hashtable.c 25 KB

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