hashtable.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. /*
  2. * This implementation is based on code from uClibc-0.9.30.3 but was
  3. * modified and extended for use within U-Boot.
  4. *
  5. * Copyright (C) 2010 Wolfgang Denk <wd@denx.de>
  6. *
  7. * Original license header:
  8. *
  9. * Copyright (C) 1993, 1995, 1996, 1997, 2002 Free Software Foundation, Inc.
  10. * This file is part of the GNU C Library.
  11. * Contributed by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1993.
  12. *
  13. * The GNU C Library is free software; you can redistribute it and/or
  14. * modify it under the terms of the GNU Lesser General Public
  15. * License as published by the Free Software Foundation; either
  16. * version 2.1 of the License, or (at your option) any later version.
  17. *
  18. * The GNU C Library is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  21. * Lesser General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Lesser General Public
  24. * License along with the GNU C Library; if not, write to the Free
  25. * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  26. * 02111-1307 USA.
  27. */
  28. #include <errno.h>
  29. #include <malloc.h>
  30. #ifdef USE_HOSTCC /* HOST build */
  31. # include <string.h>
  32. # include <assert.h>
  33. # include <ctype.h>
  34. # ifndef debug
  35. # ifdef DEBUG
  36. # define debug(fmt,args...) printf(fmt ,##args)
  37. # else
  38. # define debug(fmt,args...)
  39. # endif
  40. # endif
  41. #else /* U-Boot build */
  42. # include <common.h>
  43. # include <linux/string.h>
  44. # include <linux/ctype.h>
  45. #endif
  46. #ifndef CONFIG_ENV_MIN_ENTRIES /* minimum number of entries */
  47. #define CONFIG_ENV_MIN_ENTRIES 64
  48. #endif
  49. #ifndef CONFIG_ENV_MAX_ENTRIES /* maximum number of entries */
  50. #define CONFIG_ENV_MAX_ENTRIES 512
  51. #endif
  52. #include "search.h"
  53. /*
  54. * [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
  55. * [Knuth] The Art of Computer Programming, part 3 (6.4)
  56. */
  57. /*
  58. * The reentrant version has no static variables to maintain the state.
  59. * Instead the interface of all functions is extended to take an argument
  60. * which describes the current status.
  61. */
  62. typedef struct _ENTRY {
  63. int used;
  64. ENTRY entry;
  65. } _ENTRY;
  66. static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
  67. int idx);
  68. /*
  69. * hcreate()
  70. */
  71. /*
  72. * For the used double hash method the table size has to be a prime. To
  73. * correct the user given table size we need a prime test. This trivial
  74. * algorithm is adequate because
  75. * a) the code is (most probably) called a few times per program run and
  76. * b) the number is small because the table must fit in the core
  77. * */
  78. static int isprime(unsigned int number)
  79. {
  80. /* no even number will be passed */
  81. unsigned int div = 3;
  82. while (div * div < number && number % div != 0)
  83. div += 2;
  84. return number % div != 0;
  85. }
  86. /*
  87. * Before using the hash table we must allocate memory for it.
  88. * Test for an existing table are done. We allocate one element
  89. * more as the found prime number says. This is done for more effective
  90. * indexing as explained in the comment for the hsearch function.
  91. * The contents of the table is zeroed, especially the field used
  92. * becomes zero.
  93. */
  94. int hcreate_r(size_t nel, struct hsearch_data *htab)
  95. {
  96. /* Test for correct arguments. */
  97. if (htab == NULL) {
  98. __set_errno(EINVAL);
  99. return 0;
  100. }
  101. /* There is still another table active. Return with error. */
  102. if (htab->table != NULL)
  103. return 0;
  104. /* Change nel to the first prime number not smaller as nel. */
  105. nel |= 1; /* make odd */
  106. while (!isprime(nel))
  107. nel += 2;
  108. htab->size = nel;
  109. htab->filled = 0;
  110. /* allocate memory and zero out */
  111. htab->table = (_ENTRY *) calloc(htab->size + 1, sizeof(_ENTRY));
  112. if (htab->table == NULL)
  113. return 0;
  114. /* everything went alright */
  115. return 1;
  116. }
  117. /*
  118. * hdestroy()
  119. */
  120. /*
  121. * After using the hash table it has to be destroyed. The used memory can
  122. * be freed and the local static variable can be marked as not used.
  123. */
  124. void hdestroy_r(struct hsearch_data *htab)
  125. {
  126. int i;
  127. /* Test for correct arguments. */
  128. if (htab == NULL) {
  129. __set_errno(EINVAL);
  130. return;
  131. }
  132. /* free used memory */
  133. for (i = 1; i <= htab->size; ++i) {
  134. if (htab->table[i].used > 0) {
  135. ENTRY *ep = &htab->table[i].entry;
  136. free((void *)ep->key);
  137. free(ep->data);
  138. }
  139. }
  140. free(htab->table);
  141. /* the sign for an existing table is an value != NULL in htable */
  142. htab->table = NULL;
  143. }
  144. /*
  145. * hsearch()
  146. */
  147. /*
  148. * This is the search function. It uses double hashing with open addressing.
  149. * The argument item.key has to be a pointer to an zero terminated, most
  150. * probably strings of chars. The function for generating a number of the
  151. * strings is simple but fast. It can be replaced by a more complex function
  152. * like ajw (see [Aho,Sethi,Ullman]) if the needs are shown.
  153. *
  154. * We use an trick to speed up the lookup. The table is created by hcreate
  155. * with one more element available. This enables us to use the index zero
  156. * special. This index will never be used because we store the first hash
  157. * index in the field used where zero means not used. Every other value
  158. * means used. The used field can be used as a first fast comparison for
  159. * equality of the stored and the parameter value. This helps to prevent
  160. * unnecessary expensive calls of strcmp.
  161. *
  162. * This implementation differs from the standard library version of
  163. * this function in a number of ways:
  164. *
  165. * - While the standard version does not make any assumptions about
  166. * the type of the stored data objects at all, this implementation
  167. * works with NUL terminated strings only.
  168. * - Instead of storing just pointers to the original objects, we
  169. * create local copies so the caller does not need to care about the
  170. * data any more.
  171. * - The standard implementation does not provide a way to update an
  172. * existing entry. This version will create a new entry or update an
  173. * existing one when both "action == ENTER" and "item.data != NULL".
  174. * - Instead of returning 1 on success, we return the index into the
  175. * internal hash table, which is also guaranteed to be positive.
  176. * This allows us direct access to the found hash table slot for
  177. * example for functions like hdelete().
  178. */
  179. /*
  180. * hstrstr_r - return index to entry whose key and/or data contains match
  181. */
  182. int hstrstr_r(const char *match, int last_idx, ENTRY ** retval,
  183. struct hsearch_data *htab)
  184. {
  185. unsigned int idx;
  186. for (idx = last_idx + 1; idx < htab->size; ++idx) {
  187. if (htab->table[idx].used <= 0)
  188. continue;
  189. if (strstr(htab->table[idx].entry.key, match) ||
  190. strstr(htab->table[idx].entry.data, match)) {
  191. *retval = &htab->table[idx].entry;
  192. return idx;
  193. }
  194. }
  195. __set_errno(ESRCH);
  196. *retval = NULL;
  197. return 0;
  198. }
  199. int hmatch_r(const char *match, int last_idx, ENTRY ** retval,
  200. struct hsearch_data *htab)
  201. {
  202. unsigned int idx;
  203. size_t key_len = strlen(match);
  204. for (idx = last_idx + 1; idx < htab->size; ++idx) {
  205. if (htab->table[idx].used <= 0)
  206. continue;
  207. if (!strncmp(match, htab->table[idx].entry.key, key_len)) {
  208. *retval = &htab->table[idx].entry;
  209. return idx;
  210. }
  211. }
  212. __set_errno(ESRCH);
  213. *retval = NULL;
  214. return 0;
  215. }
  216. /*
  217. * Compare an existing entry with the desired key, and overwrite if the action
  218. * is ENTER. This is simply a helper function for hsearch_r().
  219. */
  220. static inline int _compare_and_overwrite_entry(ENTRY item, ACTION action,
  221. ENTRY **retval, struct hsearch_data *htab, int flag,
  222. unsigned int hval, unsigned int idx)
  223. {
  224. if (htab->table[idx].used == hval
  225. && strcmp(item.key, htab->table[idx].entry.key) == 0) {
  226. /* Overwrite existing value? */
  227. if ((action == ENTER) && (item.data != NULL)) {
  228. /* check for permission */
  229. if (htab->change_ok != NULL && htab->change_ok(
  230. &htab->table[idx].entry, item.data,
  231. env_op_overwrite, flag)) {
  232. debug("change_ok() rejected setting variable "
  233. "%s, skipping it!\n", item.key);
  234. __set_errno(EPERM);
  235. *retval = NULL;
  236. return 0;
  237. }
  238. free(htab->table[idx].entry.data);
  239. htab->table[idx].entry.data = strdup(item.data);
  240. if (!htab->table[idx].entry.data) {
  241. __set_errno(ENOMEM);
  242. *retval = NULL;
  243. return 0;
  244. }
  245. }
  246. /* return found entry */
  247. *retval = &htab->table[idx].entry;
  248. return idx;
  249. }
  250. /* keep searching */
  251. return -1;
  252. }
  253. int hsearch_r(ENTRY item, ACTION action, ENTRY ** retval,
  254. struct hsearch_data *htab, int flag)
  255. {
  256. unsigned int hval;
  257. unsigned int count;
  258. unsigned int len = strlen(item.key);
  259. unsigned int idx;
  260. unsigned int first_deleted = 0;
  261. int ret;
  262. /* Compute an value for the given string. Perhaps use a better method. */
  263. hval = len;
  264. count = len;
  265. while (count-- > 0) {
  266. hval <<= 4;
  267. hval += item.key[count];
  268. }
  269. /*
  270. * First hash function:
  271. * simply take the modul but prevent zero.
  272. */
  273. hval %= htab->size;
  274. if (hval == 0)
  275. ++hval;
  276. /* The first index tried. */
  277. idx = hval;
  278. if (htab->table[idx].used) {
  279. /*
  280. * Further action might be required according to the
  281. * action value.
  282. */
  283. unsigned hval2;
  284. if (htab->table[idx].used == -1
  285. && !first_deleted)
  286. first_deleted = idx;
  287. ret = _compare_and_overwrite_entry(item, action, retval, htab,
  288. flag, hval, idx);
  289. if (ret != -1)
  290. return ret;
  291. /*
  292. * Second hash function:
  293. * as suggested in [Knuth]
  294. */
  295. hval2 = 1 + hval % (htab->size - 2);
  296. do {
  297. /*
  298. * Because SIZE is prime this guarantees to
  299. * step through all available indices.
  300. */
  301. if (idx <= hval2)
  302. idx = htab->size + idx - hval2;
  303. else
  304. idx -= hval2;
  305. /*
  306. * If we visited all entries leave the loop
  307. * unsuccessfully.
  308. */
  309. if (idx == hval)
  310. break;
  311. /* If entry is found use it. */
  312. ret = _compare_and_overwrite_entry(item, action, retval,
  313. htab, flag, hval, idx);
  314. if (ret != -1)
  315. return ret;
  316. }
  317. while (htab->table[idx].used);
  318. }
  319. /* An empty bucket has been found. */
  320. if (action == ENTER) {
  321. /*
  322. * If table is full and another entry should be
  323. * entered return with error.
  324. */
  325. if (htab->filled == htab->size) {
  326. __set_errno(ENOMEM);
  327. *retval = NULL;
  328. return 0;
  329. }
  330. /*
  331. * Create new entry;
  332. * create copies of item.key and item.data
  333. */
  334. if (first_deleted)
  335. idx = first_deleted;
  336. htab->table[idx].used = hval;
  337. htab->table[idx].entry.key = strdup(item.key);
  338. htab->table[idx].entry.data = strdup(item.data);
  339. if (!htab->table[idx].entry.key ||
  340. !htab->table[idx].entry.data) {
  341. __set_errno(ENOMEM);
  342. *retval = NULL;
  343. return 0;
  344. }
  345. ++htab->filled;
  346. /* check for permission */
  347. if (htab->change_ok != NULL && htab->change_ok(
  348. &htab->table[idx].entry, item.data, env_op_create, flag)) {
  349. debug("change_ok() rejected setting variable "
  350. "%s, skipping it!\n", item.key);
  351. _hdelete(item.key, htab, &htab->table[idx].entry, idx);
  352. __set_errno(EPERM);
  353. *retval = NULL;
  354. return 0;
  355. }
  356. /* return new entry */
  357. *retval = &htab->table[idx].entry;
  358. return 1;
  359. }
  360. __set_errno(ESRCH);
  361. *retval = NULL;
  362. return 0;
  363. }
  364. /*
  365. * hdelete()
  366. */
  367. /*
  368. * The standard implementation of hsearch(3) does not provide any way
  369. * to delete any entries from the hash table. We extend the code to
  370. * do that.
  371. */
  372. static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
  373. int idx)
  374. {
  375. /* free used ENTRY */
  376. debug("hdelete: DELETING key \"%s\"\n", key);
  377. free((void *)ep->key);
  378. free(ep->data);
  379. htab->table[idx].used = -1;
  380. --htab->filled;
  381. }
  382. int hdelete_r(const char *key, struct hsearch_data *htab, int flag)
  383. {
  384. ENTRY e, *ep;
  385. int idx;
  386. debug("hdelete: DELETE key \"%s\"\n", key);
  387. e.key = (char *)key;
  388. idx = hsearch_r(e, FIND, &ep, htab, 0);
  389. if (idx == 0) {
  390. __set_errno(ESRCH);
  391. return 0; /* not found */
  392. }
  393. /* Check for permission */
  394. if (htab->change_ok != NULL &&
  395. htab->change_ok(ep, NULL, env_op_delete, flag)) {
  396. debug("change_ok() rejected deleting variable "
  397. "%s, skipping it!\n", key);
  398. __set_errno(EPERM);
  399. return 0;
  400. }
  401. _hdelete(key, htab, ep, idx);
  402. return 1;
  403. }
  404. /*
  405. * hexport()
  406. */
  407. #ifndef CONFIG_SPL_BUILD
  408. /*
  409. * Export the data stored in the hash table in linearized form.
  410. *
  411. * Entries are exported as "name=value" strings, separated by an
  412. * arbitrary (non-NUL, of course) separator character. This allows to
  413. * use this function both when formatting the U-Boot environment for
  414. * external storage (using '\0' as separator), but also when using it
  415. * for the "printenv" command to print all variables, simply by using
  416. * as '\n" as separator. This can also be used for new features like
  417. * exporting the environment data as text file, including the option
  418. * for later re-import.
  419. *
  420. * The entries in the result list will be sorted by ascending key
  421. * values.
  422. *
  423. * If the separator character is different from NUL, then any
  424. * separator characters and backslash characters in the values will
  425. * be escaped by a preceeding backslash in output. This is needed for
  426. * example to enable multi-line values, especially when the output
  427. * shall later be parsed (for example, for re-import).
  428. *
  429. * There are several options how the result buffer is handled:
  430. *
  431. * *resp size
  432. * -----------
  433. * NULL 0 A string of sufficient length will be allocated.
  434. * NULL >0 A string of the size given will be
  435. * allocated. An error will be returned if the size is
  436. * not sufficient. Any unused bytes in the string will
  437. * be '\0'-padded.
  438. * !NULL 0 The user-supplied buffer will be used. No length
  439. * checking will be performed, i. e. it is assumed that
  440. * the buffer size will always be big enough. DANGEROUS.
  441. * !NULL >0 The user-supplied buffer will be used. An error will
  442. * be returned if the size is not sufficient. Any unused
  443. * bytes in the string will be '\0'-padded.
  444. */
  445. static int cmpkey(const void *p1, const void *p2)
  446. {
  447. ENTRY *e1 = *(ENTRY **) p1;
  448. ENTRY *e2 = *(ENTRY **) p2;
  449. return (strcmp(e1->key, e2->key));
  450. }
  451. ssize_t hexport_r(struct hsearch_data *htab, const char sep, int flag,
  452. char **resp, size_t size,
  453. int argc, char * const argv[])
  454. {
  455. ENTRY *list[htab->size];
  456. char *res, *p;
  457. size_t totlen;
  458. int i, n;
  459. /* Test for correct arguments. */
  460. if ((resp == NULL) || (htab == NULL)) {
  461. __set_errno(EINVAL);
  462. return (-1);
  463. }
  464. debug("EXPORT table = %p, htab.size = %d, htab.filled = %d, "
  465. "size = %zu\n", htab, htab->size, htab->filled, size);
  466. /*
  467. * Pass 1:
  468. * search used entries,
  469. * save addresses and compute total length
  470. */
  471. for (i = 1, n = 0, totlen = 0; i <= htab->size; ++i) {
  472. if (htab->table[i].used > 0) {
  473. ENTRY *ep = &htab->table[i].entry;
  474. int arg, found = 0;
  475. for (arg = 0; arg < argc; ++arg) {
  476. if (strcmp(argv[arg], ep->key) == 0) {
  477. found = 1;
  478. break;
  479. }
  480. }
  481. if ((argc > 0) && (found == 0))
  482. continue;
  483. if ((flag & H_HIDE_DOT) && ep->key[0] == '.')
  484. continue;
  485. list[n++] = ep;
  486. totlen += strlen(ep->key) + 2;
  487. if (sep == '\0') {
  488. totlen += strlen(ep->data);
  489. } else { /* check if escapes are needed */
  490. char *s = ep->data;
  491. while (*s) {
  492. ++totlen;
  493. /* add room for needed escape chars */
  494. if ((*s == sep) || (*s == '\\'))
  495. ++totlen;
  496. ++s;
  497. }
  498. }
  499. totlen += 2; /* for '=' and 'sep' char */
  500. }
  501. }
  502. #ifdef DEBUG
  503. /* Pass 1a: print unsorted list */
  504. printf("Unsorted: n=%d\n", n);
  505. for (i = 0; i < n; ++i) {
  506. printf("\t%3d: %p ==> %-10s => %s\n",
  507. i, list[i], list[i]->key, list[i]->data);
  508. }
  509. #endif
  510. /* Sort list by keys */
  511. qsort(list, n, sizeof(ENTRY *), cmpkey);
  512. /* Check if the user supplied buffer size is sufficient */
  513. if (size) {
  514. if (size < totlen + 1) { /* provided buffer too small */
  515. printf("Env export buffer too small: %zu, "
  516. "but need %zu\n", size, totlen + 1);
  517. __set_errno(ENOMEM);
  518. return (-1);
  519. }
  520. } else {
  521. size = totlen + 1;
  522. }
  523. /* Check if the user provided a buffer */
  524. if (*resp) {
  525. /* yes; clear it */
  526. res = *resp;
  527. memset(res, '\0', size);
  528. } else {
  529. /* no, allocate and clear one */
  530. *resp = res = calloc(1, size);
  531. if (res == NULL) {
  532. __set_errno(ENOMEM);
  533. return (-1);
  534. }
  535. }
  536. /*
  537. * Pass 2:
  538. * export sorted list of result data
  539. */
  540. for (i = 0, p = res; i < n; ++i) {
  541. const char *s;
  542. s = list[i]->key;
  543. while (*s)
  544. *p++ = *s++;
  545. *p++ = '=';
  546. s = list[i]->data;
  547. while (*s) {
  548. if ((*s == sep) || (*s == '\\'))
  549. *p++ = '\\'; /* escape */
  550. *p++ = *s++;
  551. }
  552. *p++ = sep;
  553. }
  554. *p = '\0'; /* terminate result */
  555. return size;
  556. }
  557. #endif
  558. /*
  559. * himport()
  560. */
  561. /*
  562. * Check whether variable 'name' is amongst vars[],
  563. * and remove all instances by setting the pointer to NULL
  564. */
  565. static int drop_var_from_set(const char *name, int nvars, char * vars[])
  566. {
  567. int i = 0;
  568. int res = 0;
  569. /* No variables specified means process all of them */
  570. if (nvars == 0)
  571. return 1;
  572. for (i = 0; i < nvars; i++) {
  573. if (vars[i] == NULL)
  574. continue;
  575. /* If we found it, delete all of them */
  576. if (!strcmp(name, vars[i])) {
  577. vars[i] = NULL;
  578. res = 1;
  579. }
  580. }
  581. if (!res)
  582. debug("Skipping non-listed variable %s\n", name);
  583. return res;
  584. }
  585. /*
  586. * Import linearized data into hash table.
  587. *
  588. * This is the inverse function to hexport(): it takes a linear list
  589. * of "name=value" pairs and creates hash table entries from it.
  590. *
  591. * Entries without "value", i. e. consisting of only "name" or
  592. * "name=", will cause this entry to be deleted from the hash table.
  593. *
  594. * The "flag" argument can be used to control the behaviour: when the
  595. * H_NOCLEAR bit is set, then an existing hash table will kept, i. e.
  596. * new data will be added to an existing hash table; otherwise, old
  597. * data will be discarded and a new hash table will be created.
  598. *
  599. * The separator character for the "name=value" pairs can be selected,
  600. * so we both support importing from externally stored environment
  601. * data (separated by NUL characters) and from plain text files
  602. * (entries separated by newline characters).
  603. *
  604. * To allow for nicely formatted text input, leading white space
  605. * (sequences of SPACE and TAB chars) is ignored, and entries starting
  606. * (after removal of any leading white space) with a '#' character are
  607. * considered comments and ignored.
  608. *
  609. * [NOTE: this means that a variable name cannot start with a '#'
  610. * character.]
  611. *
  612. * When using a non-NUL separator character, backslash is used as
  613. * escape character in the value part, allowing for example for
  614. * multi-line values.
  615. *
  616. * In theory, arbitrary separator characters can be used, but only
  617. * '\0' and '\n' have really been tested.
  618. */
  619. int himport_r(struct hsearch_data *htab,
  620. const char *env, size_t size, const char sep, int flag,
  621. int nvars, char * const vars[])
  622. {
  623. char *data, *sp, *dp, *name, *value;
  624. char *localvars[nvars];
  625. int i;
  626. /* Test for correct arguments. */
  627. if (htab == NULL) {
  628. __set_errno(EINVAL);
  629. return 0;
  630. }
  631. /* we allocate new space to make sure we can write to the array */
  632. if ((data = malloc(size)) == NULL) {
  633. debug("himport_r: can't malloc %zu bytes\n", size);
  634. __set_errno(ENOMEM);
  635. return 0;
  636. }
  637. memcpy(data, env, size);
  638. dp = data;
  639. /* make a local copy of the list of variables */
  640. if (nvars)
  641. memcpy(localvars, vars, sizeof(vars[0]) * nvars);
  642. if ((flag & H_NOCLEAR) == 0) {
  643. /* Destroy old hash table if one exists */
  644. debug("Destroy Hash Table: %p table = %p\n", htab,
  645. htab->table);
  646. if (htab->table)
  647. hdestroy_r(htab);
  648. }
  649. /*
  650. * Create new hash table (if needed). The computation of the hash
  651. * table size is based on heuristics: in a sample of some 70+
  652. * existing systems we found an average size of 39+ bytes per entry
  653. * in the environment (for the whole key=value pair). Assuming a
  654. * size of 8 per entry (= safety factor of ~5) should provide enough
  655. * safety margin for any existing environment definitions and still
  656. * allow for more than enough dynamic additions. Note that the
  657. * "size" argument is supposed to give the maximum enviroment size
  658. * (CONFIG_ENV_SIZE). This heuristics will result in
  659. * unreasonably large numbers (and thus memory footprint) for
  660. * big flash environments (>8,000 entries for 64 KB
  661. * envrionment size), so we clip it to a reasonable value.
  662. * On the other hand we need to add some more entries for free
  663. * space when importing very small buffers. Both boundaries can
  664. * be overwritten in the board config file if needed.
  665. */
  666. if (!htab->table) {
  667. int nent = CONFIG_ENV_MIN_ENTRIES + size / 8;
  668. if (nent > CONFIG_ENV_MAX_ENTRIES)
  669. nent = CONFIG_ENV_MAX_ENTRIES;
  670. debug("Create Hash Table: N=%d\n", nent);
  671. if (hcreate_r(nent, htab) == 0) {
  672. free(data);
  673. return 0;
  674. }
  675. }
  676. /* Parse environment; allow for '\0' and 'sep' as separators */
  677. do {
  678. ENTRY e, *rv;
  679. /* skip leading white space */
  680. while (isblank(*dp))
  681. ++dp;
  682. /* skip comment lines */
  683. if (*dp == '#') {
  684. while (*dp && (*dp != sep))
  685. ++dp;
  686. ++dp;
  687. continue;
  688. }
  689. /* parse name */
  690. for (name = dp; *dp != '=' && *dp && *dp != sep; ++dp)
  691. ;
  692. /* deal with "name" and "name=" entries (delete var) */
  693. if (*dp == '\0' || *(dp + 1) == '\0' ||
  694. *dp == sep || *(dp + 1) == sep) {
  695. if (*dp == '=')
  696. *dp++ = '\0';
  697. *dp++ = '\0'; /* terminate name */
  698. debug("DELETE CANDIDATE: \"%s\"\n", name);
  699. if (!drop_var_from_set(name, nvars, localvars))
  700. continue;
  701. if (hdelete_r(name, htab, flag) == 0)
  702. debug("DELETE ERROR ##############################\n");
  703. continue;
  704. }
  705. *dp++ = '\0'; /* terminate name */
  706. /* parse value; deal with escapes */
  707. for (value = sp = dp; *dp && (*dp != sep); ++dp) {
  708. if ((*dp == '\\') && *(dp + 1))
  709. ++dp;
  710. *sp++ = *dp;
  711. }
  712. *sp++ = '\0'; /* terminate value */
  713. ++dp;
  714. /* Skip variables which are not supposed to be processed */
  715. if (!drop_var_from_set(name, nvars, localvars))
  716. continue;
  717. /* enter into hash table */
  718. e.key = name;
  719. e.data = value;
  720. hsearch_r(e, ENTER, &rv, htab, flag);
  721. if (rv == NULL) {
  722. printf("himport_r: can't insert \"%s=%s\" into hash table\n",
  723. name, value);
  724. return 0;
  725. }
  726. debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"\n",
  727. htab, htab->filled, htab->size,
  728. rv, name, value);
  729. } while ((dp < data + size) && *dp); /* size check needed for text */
  730. /* without '\0' termination */
  731. debug("INSERT: free(data = %p)\n", data);
  732. free(data);
  733. /* process variables which were not considered */
  734. for (i = 0; i < nvars; i++) {
  735. if (localvars[i] == NULL)
  736. continue;
  737. /*
  738. * All variables which were not deleted from the variable list
  739. * were not present in the imported env
  740. * This could mean two things:
  741. * a) if the variable was present in current env, we delete it
  742. * b) if the variable was not present in current env, we notify
  743. * it might be a typo
  744. */
  745. if (hdelete_r(localvars[i], htab, flag) == 0)
  746. printf("WARNING: '%s' neither in running nor in imported env!\n", localvars[i]);
  747. else
  748. printf("WARNING: '%s' not in imported env, deleting it!\n", localvars[i]);
  749. }
  750. debug("INSERT: done\n");
  751. return 1; /* everything OK */
  752. }