hashtable.c 24 KB

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