hashtable.c 25 KB

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