hashtable.c 25 KB

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