hashtable.c 24 KB

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