hashtable.c 25 KB

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