hashtable.c 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. // SPDX-License-Identifier: LGPL-2.1+
  2. /*
  3. * This implementation is based on code from uClibc-0.9.30.3 but was
  4. * modified and extended for use within U-Boot.
  5. *
  6. * Copyright (C) 2010-2013 Wolfgang Denk <wd@denx.de>
  7. *
  8. * Original license header:
  9. *
  10. * Copyright (C) 1993, 1995, 1996, 1997, 2002 Free Software Foundation, Inc.
  11. * This file is part of the GNU C Library.
  12. * Contributed by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1993.
  13. */
  14. #include <errno.h>
  15. #include <malloc.h>
  16. #include <sort.h>
  17. #ifdef USE_HOSTCC /* HOST build */
  18. # include <string.h>
  19. # include <assert.h>
  20. # include <ctype.h>
  21. # ifndef debug
  22. # ifdef DEBUG
  23. # define debug(fmt,args...) printf(fmt ,##args)
  24. # else
  25. # define debug(fmt,args...)
  26. # endif
  27. # endif
  28. #else /* U-Boot build */
  29. # include <common.h>
  30. # include <linux/string.h>
  31. # include <linux/ctype.h>
  32. #endif
  33. #ifndef CONFIG_ENV_MIN_ENTRIES /* minimum number of entries */
  34. #define CONFIG_ENV_MIN_ENTRIES 64
  35. #endif
  36. #ifndef CONFIG_ENV_MAX_ENTRIES /* maximum number of entries */
  37. #define CONFIG_ENV_MAX_ENTRIES 512
  38. #endif
  39. #define USED_FREE 0
  40. #define USED_DELETED -1
  41. #include <env_callback.h>
  42. #include <env_flags.h>
  43. #include <search.h>
  44. #include <slre.h>
  45. /*
  46. * [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
  47. * [Knuth] The Art of Computer Programming, part 3 (6.4)
  48. */
  49. /*
  50. * The reentrant version has no static variables to maintain the state.
  51. * Instead the interface of all functions is extended to take an argument
  52. * which describes the current status.
  53. */
  54. struct env_entry_node {
  55. int used;
  56. struct env_entry entry;
  57. };
  58. static void _hdelete(const char *key, struct hsearch_data *htab,
  59. struct env_entry *ep, int idx);
  60. /*
  61. * hcreate()
  62. */
  63. /*
  64. * For the used double hash method the table size has to be a prime. To
  65. * correct the user given table size we need a prime test. This trivial
  66. * algorithm is adequate because
  67. * a) the code is (most probably) called a few times per program run and
  68. * b) the number is small because the table must fit in the core
  69. * */
  70. static int isprime(unsigned int number)
  71. {
  72. /* no even number will be passed */
  73. unsigned int div = 3;
  74. while (div * div < number && number % div != 0)
  75. div += 2;
  76. return number % div != 0;
  77. }
  78. /*
  79. * Before using the hash table we must allocate memory for it.
  80. * Test for an existing table are done. We allocate one element
  81. * more as the found prime number says. This is done for more effective
  82. * indexing as explained in the comment for the hsearch function.
  83. * The contents of the table is zeroed, especially the field used
  84. * becomes zero.
  85. */
  86. int hcreate_r(size_t nel, struct hsearch_data *htab)
  87. {
  88. /* Test for correct arguments. */
  89. if (htab == NULL) {
  90. __set_errno(EINVAL);
  91. return 0;
  92. }
  93. /* There is still another table active. Return with error. */
  94. if (htab->table != NULL)
  95. return 0;
  96. /* Change nel to the first prime number not smaller as nel. */
  97. nel |= 1; /* make odd */
  98. while (!isprime(nel))
  99. nel += 2;
  100. htab->size = nel;
  101. htab->filled = 0;
  102. /* allocate memory and zero out */
  103. htab->table = (struct env_entry_node *)calloc(htab->size + 1,
  104. sizeof(struct env_entry_node));
  105. if (htab->table == NULL)
  106. return 0;
  107. /* everything went alright */
  108. return 1;
  109. }
  110. /*
  111. * hdestroy()
  112. */
  113. /*
  114. * After using the hash table it has to be destroyed. The used memory can
  115. * be freed and the local static variable can be marked as not used.
  116. */
  117. void hdestroy_r(struct hsearch_data *htab)
  118. {
  119. int i;
  120. /* Test for correct arguments. */
  121. if (htab == NULL) {
  122. __set_errno(EINVAL);
  123. return;
  124. }
  125. /* free used memory */
  126. for (i = 1; i <= htab->size; ++i) {
  127. if (htab->table[i].used > 0) {
  128. struct env_entry *ep = &htab->table[i].entry;
  129. free((void *)ep->key);
  130. free(ep->data);
  131. }
  132. }
  133. free(htab->table);
  134. /* the sign for an existing table is an value != NULL in htable */
  135. htab->table = NULL;
  136. }
  137. /*
  138. * hsearch()
  139. */
  140. /*
  141. * This is the search function. It uses double hashing with open addressing.
  142. * The argument item.key has to be a pointer to an zero terminated, most
  143. * probably strings of chars. The function for generating a number of the
  144. * strings is simple but fast. It can be replaced by a more complex function
  145. * like ajw (see [Aho,Sethi,Ullman]) if the needs are shown.
  146. *
  147. * We use an trick to speed up the lookup. The table is created by hcreate
  148. * with one more element available. This enables us to use the index zero
  149. * special. This index will never be used because we store the first hash
  150. * index in the field used where zero means not used. Every other value
  151. * means used. The used field can be used as a first fast comparison for
  152. * equality of the stored and the parameter value. This helps to prevent
  153. * unnecessary expensive calls of strcmp.
  154. *
  155. * This implementation differs from the standard library version of
  156. * this function in a number of ways:
  157. *
  158. * - While the standard version does not make any assumptions about
  159. * the type of the stored data objects at all, this implementation
  160. * works with NUL terminated strings only.
  161. * - Instead of storing just pointers to the original objects, we
  162. * create local copies so the caller does not need to care about the
  163. * data any more.
  164. * - The standard implementation does not provide a way to update an
  165. * existing entry. This version will create a new entry or update an
  166. * existing one when both "action == ENV_ENTER" and "item.data != NULL".
  167. * - Instead of returning 1 on success, we return the index into the
  168. * internal hash table, which is also guaranteed to be positive.
  169. * This allows us direct access to the found hash table slot for
  170. * example for functions like hdelete().
  171. */
  172. int hmatch_r(const char *match, int last_idx, struct env_entry **retval,
  173. struct hsearch_data *htab)
  174. {
  175. unsigned int idx;
  176. size_t key_len = strlen(match);
  177. for (idx = last_idx + 1; idx < htab->size; ++idx) {
  178. if (htab->table[idx].used <= 0)
  179. continue;
  180. if (!strncmp(match, htab->table[idx].entry.key, key_len)) {
  181. *retval = &htab->table[idx].entry;
  182. return idx;
  183. }
  184. }
  185. __set_errno(ESRCH);
  186. *retval = NULL;
  187. return 0;
  188. }
  189. static int
  190. do_callback(const struct env_entry *e, const char *name, const char *value,
  191. enum env_op op, int flags)
  192. {
  193. #ifndef CONFIG_SPL_BUILD
  194. if (e->callback)
  195. return e->callback(name, value, op, flags);
  196. #endif
  197. return 0;
  198. }
  199. /*
  200. * Compare an existing entry with the desired key, and overwrite if the action
  201. * is ENV_ENTER. This is simply a helper function for hsearch_r().
  202. */
  203. static inline int _compare_and_overwrite_entry(struct env_entry item,
  204. enum env_action action, struct env_entry **retval,
  205. struct hsearch_data *htab, int flag, unsigned int hval,
  206. unsigned int idx)
  207. {
  208. if (htab->table[idx].used == hval
  209. && strcmp(item.key, htab->table[idx].entry.key) == 0) {
  210. /* Overwrite existing value? */
  211. if (action == ENV_ENTER && item.data) {
  212. /* check for permission */
  213. if (htab->change_ok != NULL && htab->change_ok(
  214. &htab->table[idx].entry, item.data,
  215. env_op_overwrite, flag)) {
  216. debug("change_ok() rejected setting variable "
  217. "%s, skipping it!\n", item.key);
  218. __set_errno(EPERM);
  219. *retval = NULL;
  220. return 0;
  221. }
  222. /* If there is a callback, call it */
  223. if (do_callback(&htab->table[idx].entry, 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(struct env_entry item, enum env_action action,
  247. struct env_entry **retval, 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 == USED_DELETED
  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 (htab->table[idx].used == USED_DELETED
  305. && !first_deleted)
  306. first_deleted = idx;
  307. /* If entry is found use it. */
  308. ret = _compare_and_overwrite_entry(item, action, retval,
  309. htab, flag, hval, idx);
  310. if (ret != -1)
  311. return ret;
  312. }
  313. while (htab->table[idx].used != USED_FREE);
  314. }
  315. /* An empty bucket has been found. */
  316. if (action == ENV_ENTER) {
  317. /*
  318. * If table is full and another entry should be
  319. * entered return with error.
  320. */
  321. if (htab->filled == htab->size) {
  322. __set_errno(ENOMEM);
  323. *retval = NULL;
  324. return 0;
  325. }
  326. /*
  327. * Create new entry;
  328. * create copies of item.key and item.data
  329. */
  330. if (first_deleted)
  331. idx = first_deleted;
  332. htab->table[idx].used = hval;
  333. htab->table[idx].entry.key = strdup(item.key);
  334. htab->table[idx].entry.data = strdup(item.data);
  335. if (!htab->table[idx].entry.key ||
  336. !htab->table[idx].entry.data) {
  337. __set_errno(ENOMEM);
  338. *retval = NULL;
  339. return 0;
  340. }
  341. ++htab->filled;
  342. /* This is a new entry, so look up a possible callback */
  343. env_callback_init(&htab->table[idx].entry);
  344. /* Also look for flags */
  345. env_flags_init(&htab->table[idx].entry);
  346. /* check for permission */
  347. if (htab->change_ok != NULL && htab->change_ok(
  348. &htab->table[idx].entry, item.data, env_op_create, flag)) {
  349. debug("change_ok() rejected setting variable "
  350. "%s, skipping it!\n", item.key);
  351. _hdelete(item.key, htab, &htab->table[idx].entry, idx);
  352. __set_errno(EPERM);
  353. *retval = NULL;
  354. return 0;
  355. }
  356. /* If there is a callback, call it */
  357. if (do_callback(&htab->table[idx].entry, item.key, item.data,
  358. env_op_create, flag)) {
  359. debug("callback() rejected setting variable "
  360. "%s, skipping it!\n", item.key);
  361. _hdelete(item.key, htab, &htab->table[idx].entry, idx);
  362. __set_errno(EINVAL);
  363. *retval = NULL;
  364. return 0;
  365. }
  366. /* return new entry */
  367. *retval = &htab->table[idx].entry;
  368. return 1;
  369. }
  370. __set_errno(ESRCH);
  371. *retval = NULL;
  372. return 0;
  373. }
  374. /*
  375. * hdelete()
  376. */
  377. /*
  378. * The standard implementation of hsearch(3) does not provide any way
  379. * to delete any entries from the hash table. We extend the code to
  380. * do that.
  381. */
  382. static void _hdelete(const char *key, struct hsearch_data *htab,
  383. struct env_entry *ep, int idx)
  384. {
  385. /* free used entry */
  386. debug("hdelete: DELETING key \"%s\"\n", key);
  387. free((void *)ep->key);
  388. free(ep->data);
  389. ep->flags = 0;
  390. htab->table[idx].used = USED_DELETED;
  391. --htab->filled;
  392. }
  393. int hdelete_r(const char *key, struct hsearch_data *htab, int flag)
  394. {
  395. struct env_entry e, *ep;
  396. int idx;
  397. debug("hdelete: DELETE key \"%s\"\n", key);
  398. e.key = (char *)key;
  399. idx = hsearch_r(e, ENV_FIND, &ep, htab, 0);
  400. if (idx == 0) {
  401. __set_errno(ESRCH);
  402. return 0; /* not found */
  403. }
  404. /* Check for permission */
  405. if (htab->change_ok != NULL &&
  406. htab->change_ok(ep, NULL, env_op_delete, flag)) {
  407. debug("change_ok() rejected deleting variable "
  408. "%s, skipping it!\n", key);
  409. __set_errno(EPERM);
  410. return 0;
  411. }
  412. /* If there is a callback, call it */
  413. if (do_callback(&htab->table[idx].entry, key, NULL,
  414. env_op_delete, flag)) {
  415. debug("callback() rejected deleting variable "
  416. "%s, skipping it!\n", key);
  417. __set_errno(EINVAL);
  418. return 0;
  419. }
  420. _hdelete(key, htab, ep, idx);
  421. return 1;
  422. }
  423. #if !(defined(CONFIG_SPL_BUILD) && !defined(CONFIG_SPL_SAVEENV))
  424. /*
  425. * hexport()
  426. */
  427. /*
  428. * Export the data stored in the hash table in linearized form.
  429. *
  430. * Entries are exported as "name=value" strings, separated by an
  431. * arbitrary (non-NUL, of course) separator character. This allows to
  432. * use this function both when formatting the U-Boot environment for
  433. * external storage (using '\0' as separator), but also when using it
  434. * for the "printenv" command to print all variables, simply by using
  435. * as '\n" as separator. This can also be used for new features like
  436. * exporting the environment data as text file, including the option
  437. * for later re-import.
  438. *
  439. * The entries in the result list will be sorted by ascending key
  440. * values.
  441. *
  442. * If the separator character is different from NUL, then any
  443. * separator characters and backslash characters in the values will
  444. * be escaped by a preceding backslash in output. This is needed for
  445. * example to enable multi-line values, especially when the output
  446. * shall later be parsed (for example, for re-import).
  447. *
  448. * There are several options how the result buffer is handled:
  449. *
  450. * *resp size
  451. * -----------
  452. * NULL 0 A string of sufficient length will be allocated.
  453. * NULL >0 A string of the size given will be
  454. * allocated. An error will be returned if the size is
  455. * not sufficient. Any unused bytes in the string will
  456. * be '\0'-padded.
  457. * !NULL 0 The user-supplied buffer will be used. No length
  458. * checking will be performed, i. e. it is assumed that
  459. * the buffer size will always be big enough. DANGEROUS.
  460. * !NULL >0 The user-supplied buffer will be used. An error will
  461. * be returned if the size is not sufficient. Any unused
  462. * bytes in the string will be '\0'-padded.
  463. */
  464. static int cmpkey(const void *p1, const void *p2)
  465. {
  466. struct env_entry *e1 = *(struct env_entry **)p1;
  467. struct env_entry *e2 = *(struct env_entry **)p2;
  468. return (strcmp(e1->key, e2->key));
  469. }
  470. static int match_string(int flag, const char *str, const char *pat, void *priv)
  471. {
  472. switch (flag & H_MATCH_METHOD) {
  473. case H_MATCH_IDENT:
  474. if (strcmp(str, pat) == 0)
  475. return 1;
  476. break;
  477. case H_MATCH_SUBSTR:
  478. if (strstr(str, pat))
  479. return 1;
  480. break;
  481. #ifdef CONFIG_REGEX
  482. case H_MATCH_REGEX:
  483. {
  484. struct slre *slrep = (struct slre *)priv;
  485. if (slre_match(slrep, str, strlen(str), NULL))
  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(struct env_entry *ep, int flag, int argc,
  498. char *const argv[])
  499. {
  500. int arg;
  501. void *priv = NULL;
  502. for (arg = 0; 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. struct env_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, size = %lu\n",
  536. htab, htab->size, htab->filled, (ulong)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. struct env_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);
  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(struct env_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: %lu, but need %lu\n",
  581. (ulong)size, (ulong)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, if no
  662. * vars are passed, old data will be discarded and a new hash table
  663. * will be created. If vars are passed, passed vars that are not in
  664. * the linear list of "name=value" pairs will be removed from the
  665. * current hash table.
  666. *
  667. * The separator character for the "name=value" pairs can be selected,
  668. * so we both support importing from externally stored environment
  669. * data (separated by NUL characters) and from plain text files
  670. * (entries separated by newline characters).
  671. *
  672. * To allow for nicely formatted text input, leading white space
  673. * (sequences of SPACE and TAB chars) is ignored, and entries starting
  674. * (after removal of any leading white space) with a '#' character are
  675. * considered comments and ignored.
  676. *
  677. * [NOTE: this means that a variable name cannot start with a '#'
  678. * character.]
  679. *
  680. * When using a non-NUL separator character, backslash is used as
  681. * escape character in the value part, allowing for example for
  682. * multi-line values.
  683. *
  684. * In theory, arbitrary separator characters can be used, but only
  685. * '\0' and '\n' have really been tested.
  686. */
  687. int himport_r(struct hsearch_data *htab,
  688. const char *env, size_t size, const char sep, int flag,
  689. int crlf_is_lf, int nvars, char * const vars[])
  690. {
  691. char *data, *sp, *dp, *name, *value;
  692. char *localvars[nvars];
  693. int i;
  694. /* Test for correct arguments. */
  695. if (htab == NULL) {
  696. __set_errno(EINVAL);
  697. return 0;
  698. }
  699. /* we allocate new space to make sure we can write to the array */
  700. if ((data = malloc(size + 1)) == NULL) {
  701. debug("himport_r: can't malloc %lu bytes\n", (ulong)size + 1);
  702. __set_errno(ENOMEM);
  703. return 0;
  704. }
  705. memcpy(data, env, size);
  706. data[size] = '\0';
  707. dp = data;
  708. /* make a local copy of the list of variables */
  709. if (nvars)
  710. memcpy(localvars, vars, sizeof(vars[0]) * nvars);
  711. if ((flag & H_NOCLEAR) == 0 && !nvars) {
  712. /* Destroy old hash table if one exists */
  713. debug("Destroy Hash Table: %p table = %p\n", htab,
  714. htab->table);
  715. if (htab->table)
  716. hdestroy_r(htab);
  717. }
  718. /*
  719. * Create new hash table (if needed). The computation of the hash
  720. * table size is based on heuristics: in a sample of some 70+
  721. * existing systems we found an average size of 39+ bytes per entry
  722. * in the environment (for the whole key=value pair). Assuming a
  723. * size of 8 per entry (= safety factor of ~5) should provide enough
  724. * safety margin for any existing environment definitions and still
  725. * allow for more than enough dynamic additions. Note that the
  726. * "size" argument is supposed to give the maximum environment size
  727. * (CONFIG_ENV_SIZE). This heuristics will result in
  728. * unreasonably large numbers (and thus memory footprint) for
  729. * big flash environments (>8,000 entries for 64 KB
  730. * environment size), so we clip it to a reasonable value.
  731. * On the other hand we need to add some more entries for free
  732. * space when importing very small buffers. Both boundaries can
  733. * be overwritten in the board config file if needed.
  734. */
  735. if (!htab->table) {
  736. int nent = CONFIG_ENV_MIN_ENTRIES + size / 8;
  737. if (nent > CONFIG_ENV_MAX_ENTRIES)
  738. nent = CONFIG_ENV_MAX_ENTRIES;
  739. debug("Create Hash Table: N=%d\n", nent);
  740. if (hcreate_r(nent, htab) == 0) {
  741. free(data);
  742. return 0;
  743. }
  744. }
  745. if (!size) {
  746. free(data);
  747. return 1; /* everything OK */
  748. }
  749. if(crlf_is_lf) {
  750. /* Remove Carriage Returns in front of Line Feeds */
  751. unsigned ignored_crs = 0;
  752. for(;dp < data + size && *dp; ++dp) {
  753. if(*dp == '\r' &&
  754. dp < data + size - 1 && *(dp+1) == '\n')
  755. ++ignored_crs;
  756. else
  757. *(dp-ignored_crs) = *dp;
  758. }
  759. size -= ignored_crs;
  760. dp = data;
  761. }
  762. /* Parse environment; allow for '\0' and 'sep' as separators */
  763. do {
  764. struct env_entry e, *rv;
  765. /* skip leading white space */
  766. while (isblank(*dp))
  767. ++dp;
  768. /* skip comment lines */
  769. if (*dp == '#') {
  770. while (*dp && (*dp != sep))
  771. ++dp;
  772. ++dp;
  773. continue;
  774. }
  775. /* parse name */
  776. for (name = dp; *dp != '=' && *dp && *dp != sep; ++dp)
  777. ;
  778. /* deal with "name" and "name=" entries (delete var) */
  779. if (*dp == '\0' || *(dp + 1) == '\0' ||
  780. *dp == sep || *(dp + 1) == sep) {
  781. if (*dp == '=')
  782. *dp++ = '\0';
  783. *dp++ = '\0'; /* terminate name */
  784. debug("DELETE CANDIDATE: \"%s\"\n", name);
  785. if (!drop_var_from_set(name, nvars, localvars))
  786. continue;
  787. if (hdelete_r(name, htab, flag) == 0)
  788. debug("DELETE ERROR ##############################\n");
  789. continue;
  790. }
  791. *dp++ = '\0'; /* terminate name */
  792. /* parse value; deal with escapes */
  793. for (value = sp = dp; *dp && (*dp != sep); ++dp) {
  794. if ((*dp == '\\') && *(dp + 1))
  795. ++dp;
  796. *sp++ = *dp;
  797. }
  798. *sp++ = '\0'; /* terminate value */
  799. ++dp;
  800. if (*name == 0) {
  801. debug("INSERT: unable to use an empty key\n");
  802. __set_errno(EINVAL);
  803. free(data);
  804. return 0;
  805. }
  806. /* Skip variables which are not supposed to be processed */
  807. if (!drop_var_from_set(name, nvars, localvars))
  808. continue;
  809. /* enter into hash table */
  810. e.key = name;
  811. e.data = value;
  812. hsearch_r(e, ENV_ENTER, &rv, htab, flag);
  813. if (rv == NULL)
  814. printf("himport_r: can't insert \"%s=%s\" into hash table\n",
  815. name, value);
  816. debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"\n",
  817. htab, htab->filled, htab->size,
  818. rv, name, value);
  819. } while ((dp < data + size) && *dp); /* size check needed for text */
  820. /* without '\0' termination */
  821. debug("INSERT: free(data = %p)\n", data);
  822. free(data);
  823. if (flag & H_NOCLEAR)
  824. goto end;
  825. /* process variables which were not considered */
  826. for (i = 0; i < nvars; i++) {
  827. if (localvars[i] == NULL)
  828. continue;
  829. /*
  830. * All variables which were not deleted from the variable list
  831. * were not present in the imported env
  832. * This could mean two things:
  833. * a) if the variable was present in current env, we delete it
  834. * b) if the variable was not present in current env, we notify
  835. * it might be a typo
  836. */
  837. if (hdelete_r(localvars[i], htab, flag) == 0)
  838. printf("WARNING: '%s' neither in running nor in imported env!\n", localvars[i]);
  839. else
  840. printf("WARNING: '%s' not in imported env, deleting it!\n", localvars[i]);
  841. }
  842. end:
  843. debug("INSERT: done\n");
  844. return 1; /* everything OK */
  845. }
  846. /*
  847. * hwalk_r()
  848. */
  849. /*
  850. * Walk all of the entries in the hash, calling the callback for each one.
  851. * this allows some generic operation to be performed on each element.
  852. */
  853. int hwalk_r(struct hsearch_data *htab, int (*callback)(struct env_entry *entry))
  854. {
  855. int i;
  856. int retval;
  857. for (i = 1; i <= htab->size; ++i) {
  858. if (htab->table[i].used > 0) {
  859. retval = callback(&htab->table[i].entry);
  860. if (retval)
  861. return retval;
  862. }
  863. }
  864. return 0;
  865. }