hashtable.c 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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)
  284. first_deleted = idx;
  285. ret = _compare_and_overwrite_entry(item, action, retval, htab,
  286. flag, hval, idx);
  287. if (ret != -1)
  288. return ret;
  289. /*
  290. * Second hash function:
  291. * as suggested in [Knuth]
  292. */
  293. hval2 = 1 + hval % (htab->size - 2);
  294. do {
  295. /*
  296. * Because SIZE is prime this guarantees to
  297. * step through all available indices.
  298. */
  299. if (idx <= hval2)
  300. idx = htab->size + idx - hval2;
  301. else
  302. idx -= hval2;
  303. /*
  304. * If we visited all entries leave the loop
  305. * unsuccessfully.
  306. */
  307. if (idx == hval)
  308. break;
  309. if (htab->table[idx].used == USED_DELETED
  310. && !first_deleted)
  311. first_deleted = idx;
  312. /* If entry is found use it. */
  313. ret = _compare_and_overwrite_entry(item, action, retval,
  314. htab, flag, hval, idx);
  315. if (ret != -1)
  316. return ret;
  317. }
  318. while (htab->table[idx].used != USED_FREE);
  319. }
  320. /* An empty bucket has been found. */
  321. if (action == ENV_ENTER) {
  322. /*
  323. * If table is full and another entry should be
  324. * entered return with error.
  325. */
  326. if (htab->filled == htab->size) {
  327. __set_errno(ENOMEM);
  328. *retval = NULL;
  329. return 0;
  330. }
  331. /*
  332. * Create new entry;
  333. * create copies of item.key and item.data
  334. */
  335. if (first_deleted)
  336. idx = first_deleted;
  337. htab->table[idx].used = hval;
  338. htab->table[idx].entry.key = strdup(item.key);
  339. htab->table[idx].entry.data = strdup(item.data);
  340. if (!htab->table[idx].entry.key ||
  341. !htab->table[idx].entry.data) {
  342. __set_errno(ENOMEM);
  343. *retval = NULL;
  344. return 0;
  345. }
  346. ++htab->filled;
  347. /* This is a new entry, so look up a possible callback */
  348. env_callback_init(&htab->table[idx].entry);
  349. /* Also look for flags */
  350. env_flags_init(&htab->table[idx].entry);
  351. /* check for permission */
  352. if (htab->change_ok != NULL && htab->change_ok(
  353. &htab->table[idx].entry, item.data, env_op_create, flag)) {
  354. debug("change_ok() rejected setting variable "
  355. "%s, skipping it!\n", item.key);
  356. _hdelete(item.key, htab, &htab->table[idx].entry, idx);
  357. __set_errno(EPERM);
  358. *retval = NULL;
  359. return 0;
  360. }
  361. /* If there is a callback, call it */
  362. if (do_callback(&htab->table[idx].entry, item.key, item.data,
  363. env_op_create, flag)) {
  364. debug("callback() rejected setting variable "
  365. "%s, skipping it!\n", item.key);
  366. _hdelete(item.key, htab, &htab->table[idx].entry, idx);
  367. __set_errno(EINVAL);
  368. *retval = NULL;
  369. return 0;
  370. }
  371. /* return new entry */
  372. *retval = &htab->table[idx].entry;
  373. return 1;
  374. }
  375. __set_errno(ESRCH);
  376. *retval = NULL;
  377. return 0;
  378. }
  379. /*
  380. * hdelete()
  381. */
  382. /*
  383. * The standard implementation of hsearch(3) does not provide any way
  384. * to delete any entries from the hash table. We extend the code to
  385. * do that.
  386. */
  387. static void _hdelete(const char *key, struct hsearch_data *htab,
  388. struct env_entry *ep, int idx)
  389. {
  390. /* free used entry */
  391. debug("hdelete: DELETING key \"%s\"\n", key);
  392. free((void *)ep->key);
  393. free(ep->data);
  394. ep->flags = 0;
  395. htab->table[idx].used = USED_DELETED;
  396. --htab->filled;
  397. }
  398. int hdelete_r(const char *key, struct hsearch_data *htab, int flag)
  399. {
  400. struct env_entry e, *ep;
  401. int idx;
  402. debug("hdelete: DELETE key \"%s\"\n", key);
  403. e.key = (char *)key;
  404. idx = hsearch_r(e, ENV_FIND, &ep, htab, 0);
  405. if (idx == 0) {
  406. __set_errno(ESRCH);
  407. return 0; /* not found */
  408. }
  409. /* Check for permission */
  410. if (htab->change_ok != NULL &&
  411. htab->change_ok(ep, NULL, env_op_delete, flag)) {
  412. debug("change_ok() rejected deleting variable "
  413. "%s, skipping it!\n", key);
  414. __set_errno(EPERM);
  415. return 0;
  416. }
  417. /* If there is a callback, call it */
  418. if (do_callback(&htab->table[idx].entry, key, NULL,
  419. env_op_delete, flag)) {
  420. debug("callback() rejected deleting variable "
  421. "%s, skipping it!\n", key);
  422. __set_errno(EINVAL);
  423. return 0;
  424. }
  425. _hdelete(key, htab, ep, idx);
  426. return 1;
  427. }
  428. #if !(defined(CONFIG_SPL_BUILD) && !defined(CONFIG_SPL_SAVEENV))
  429. /*
  430. * hexport()
  431. */
  432. /*
  433. * Export the data stored in the hash table in linearized form.
  434. *
  435. * Entries are exported as "name=value" strings, separated by an
  436. * arbitrary (non-NUL, of course) separator character. This allows to
  437. * use this function both when formatting the U-Boot environment for
  438. * external storage (using '\0' as separator), but also when using it
  439. * for the "printenv" command to print all variables, simply by using
  440. * as '\n" as separator. This can also be used for new features like
  441. * exporting the environment data as text file, including the option
  442. * for later re-import.
  443. *
  444. * The entries in the result list will be sorted by ascending key
  445. * values.
  446. *
  447. * If the separator character is different from NUL, then any
  448. * separator characters and backslash characters in the values will
  449. * be escaped by a preceding backslash in output. This is needed for
  450. * example to enable multi-line values, especially when the output
  451. * shall later be parsed (for example, for re-import).
  452. *
  453. * There are several options how the result buffer is handled:
  454. *
  455. * *resp size
  456. * -----------
  457. * NULL 0 A string of sufficient length will be allocated.
  458. * NULL >0 A string of the size given will be
  459. * allocated. An error will be returned if the size is
  460. * not sufficient. Any unused bytes in the string will
  461. * be '\0'-padded.
  462. * !NULL 0 The user-supplied buffer will be used. No length
  463. * checking will be performed, i. e. it is assumed that
  464. * the buffer size will always be big enough. DANGEROUS.
  465. * !NULL >0 The user-supplied buffer will be used. An error will
  466. * be returned if the size is not sufficient. Any unused
  467. * bytes in the string will be '\0'-padded.
  468. */
  469. static int cmpkey(const void *p1, const void *p2)
  470. {
  471. struct env_entry *e1 = *(struct env_entry **)p1;
  472. struct env_entry *e2 = *(struct env_entry **)p2;
  473. return (strcmp(e1->key, e2->key));
  474. }
  475. static int match_string(int flag, const char *str, const char *pat, void *priv)
  476. {
  477. switch (flag & H_MATCH_METHOD) {
  478. case H_MATCH_IDENT:
  479. if (strcmp(str, pat) == 0)
  480. return 1;
  481. break;
  482. case H_MATCH_SUBSTR:
  483. if (strstr(str, pat))
  484. return 1;
  485. break;
  486. #ifdef CONFIG_REGEX
  487. case H_MATCH_REGEX:
  488. {
  489. struct slre *slrep = (struct slre *)priv;
  490. if (slre_match(slrep, str, strlen(str), NULL))
  491. return 1;
  492. }
  493. break;
  494. #endif
  495. default:
  496. printf("## ERROR: unsupported match method: 0x%02x\n",
  497. flag & H_MATCH_METHOD);
  498. break;
  499. }
  500. return 0;
  501. }
  502. static int match_entry(struct env_entry *ep, int flag, int argc,
  503. char *const argv[])
  504. {
  505. int arg;
  506. void *priv = NULL;
  507. for (arg = 0; arg < argc; ++arg) {
  508. #ifdef CONFIG_REGEX
  509. struct slre slre;
  510. if (slre_compile(&slre, argv[arg]) == 0) {
  511. printf("Error compiling regex: %s\n", slre.err_str);
  512. return 0;
  513. }
  514. priv = (void *)&slre;
  515. #endif
  516. if (flag & H_MATCH_KEY) {
  517. if (match_string(flag, ep->key, argv[arg], priv))
  518. return 1;
  519. }
  520. if (flag & H_MATCH_DATA) {
  521. if (match_string(flag, ep->data, argv[arg], priv))
  522. return 1;
  523. }
  524. }
  525. return 0;
  526. }
  527. ssize_t hexport_r(struct hsearch_data *htab, const char sep, int flag,
  528. char **resp, size_t size,
  529. int argc, char *const argv[])
  530. {
  531. struct env_entry *list[htab->size];
  532. char *res, *p;
  533. size_t totlen;
  534. int i, n;
  535. /* Test for correct arguments. */
  536. if ((resp == NULL) || (htab == NULL)) {
  537. __set_errno(EINVAL);
  538. return (-1);
  539. }
  540. debug("EXPORT table = %p, htab.size = %d, htab.filled = %d, size = %lu\n",
  541. htab, htab->size, htab->filled, (ulong)size);
  542. /*
  543. * Pass 1:
  544. * search used entries,
  545. * save addresses and compute total length
  546. */
  547. for (i = 1, n = 0, totlen = 0; i <= htab->size; ++i) {
  548. if (htab->table[i].used > 0) {
  549. struct env_entry *ep = &htab->table[i].entry;
  550. int found = match_entry(ep, flag, argc, argv);
  551. if ((argc > 0) && (found == 0))
  552. continue;
  553. if ((flag & H_HIDE_DOT) && ep->key[0] == '.')
  554. continue;
  555. list[n++] = ep;
  556. totlen += strlen(ep->key);
  557. if (sep == '\0') {
  558. totlen += strlen(ep->data);
  559. } else { /* check if escapes are needed */
  560. char *s = ep->data;
  561. while (*s) {
  562. ++totlen;
  563. /* add room for needed escape chars */
  564. if ((*s == sep) || (*s == '\\'))
  565. ++totlen;
  566. ++s;
  567. }
  568. }
  569. totlen += 2; /* for '=' and 'sep' char */
  570. }
  571. }
  572. #ifdef DEBUG
  573. /* Pass 1a: print unsorted list */
  574. printf("Unsorted: n=%d\n", n);
  575. for (i = 0; i < n; ++i) {
  576. printf("\t%3d: %p ==> %-10s => %s\n",
  577. i, list[i], list[i]->key, list[i]->data);
  578. }
  579. #endif
  580. /* Sort list by keys */
  581. qsort(list, n, sizeof(struct env_entry *), cmpkey);
  582. /* Check if the user supplied buffer size is sufficient */
  583. if (size) {
  584. if (size < totlen + 1) { /* provided buffer too small */
  585. printf("Env export buffer too small: %lu, but need %lu\n",
  586. (ulong)size, (ulong)totlen + 1);
  587. __set_errno(ENOMEM);
  588. return (-1);
  589. }
  590. } else {
  591. size = totlen + 1;
  592. }
  593. /* Check if the user provided a buffer */
  594. if (*resp) {
  595. /* yes; clear it */
  596. res = *resp;
  597. memset(res, '\0', size);
  598. } else {
  599. /* no, allocate and clear one */
  600. *resp = res = calloc(1, size);
  601. if (res == NULL) {
  602. __set_errno(ENOMEM);
  603. return (-1);
  604. }
  605. }
  606. /*
  607. * Pass 2:
  608. * export sorted list of result data
  609. */
  610. for (i = 0, p = res; i < n; ++i) {
  611. const char *s;
  612. s = list[i]->key;
  613. while (*s)
  614. *p++ = *s++;
  615. *p++ = '=';
  616. s = list[i]->data;
  617. while (*s) {
  618. if ((*s == sep) || (*s == '\\'))
  619. *p++ = '\\'; /* escape */
  620. *p++ = *s++;
  621. }
  622. *p++ = sep;
  623. }
  624. *p = '\0'; /* terminate result */
  625. return size;
  626. }
  627. #endif
  628. /*
  629. * himport()
  630. */
  631. /*
  632. * Check whether variable 'name' is amongst vars[],
  633. * and remove all instances by setting the pointer to NULL
  634. */
  635. static int drop_var_from_set(const char *name, int nvars, char * vars[])
  636. {
  637. int i = 0;
  638. int res = 0;
  639. /* No variables specified means process all of them */
  640. if (nvars == 0)
  641. return 1;
  642. for (i = 0; i < nvars; i++) {
  643. if (vars[i] == NULL)
  644. continue;
  645. /* If we found it, delete all of them */
  646. if (!strcmp(name, vars[i])) {
  647. vars[i] = NULL;
  648. res = 1;
  649. }
  650. }
  651. if (!res)
  652. debug("Skipping non-listed variable %s\n", name);
  653. return res;
  654. }
  655. /*
  656. * Import linearized data into hash table.
  657. *
  658. * This is the inverse function to hexport(): it takes a linear list
  659. * of "name=value" pairs and creates hash table entries from it.
  660. *
  661. * Entries without "value", i. e. consisting of only "name" or
  662. * "name=", will cause this entry to be deleted from the hash table.
  663. *
  664. * The "flag" argument can be used to control the behaviour: when the
  665. * H_NOCLEAR bit is set, then an existing hash table will kept, i. e.
  666. * new data will be added to an existing hash table; otherwise, if no
  667. * vars are passed, old data will be discarded and a new hash table
  668. * will be created. If vars are passed, passed vars that are not in
  669. * the linear list of "name=value" pairs will be removed from the
  670. * current hash table.
  671. *
  672. * The separator character for the "name=value" pairs can be selected,
  673. * so we both support importing from externally stored environment
  674. * data (separated by NUL characters) and from plain text files
  675. * (entries separated by newline characters).
  676. *
  677. * To allow for nicely formatted text input, leading white space
  678. * (sequences of SPACE and TAB chars) is ignored, and entries starting
  679. * (after removal of any leading white space) with a '#' character are
  680. * considered comments and ignored.
  681. *
  682. * [NOTE: this means that a variable name cannot start with a '#'
  683. * character.]
  684. *
  685. * When using a non-NUL separator character, backslash is used as
  686. * escape character in the value part, allowing for example for
  687. * multi-line values.
  688. *
  689. * In theory, arbitrary separator characters can be used, but only
  690. * '\0' and '\n' have really been tested.
  691. */
  692. int himport_r(struct hsearch_data *htab,
  693. const char *env, size_t size, const char sep, int flag,
  694. int crlf_is_lf, int nvars, char * const vars[])
  695. {
  696. char *data, *sp, *dp, *name, *value;
  697. char *localvars[nvars];
  698. int i;
  699. /* Test for correct arguments. */
  700. if (htab == NULL) {
  701. __set_errno(EINVAL);
  702. return 0;
  703. }
  704. /* we allocate new space to make sure we can write to the array */
  705. if ((data = malloc(size + 1)) == NULL) {
  706. debug("himport_r: can't malloc %lu bytes\n", (ulong)size + 1);
  707. __set_errno(ENOMEM);
  708. return 0;
  709. }
  710. memcpy(data, env, size);
  711. data[size] = '\0';
  712. dp = data;
  713. /* make a local copy of the list of variables */
  714. if (nvars)
  715. memcpy(localvars, vars, sizeof(vars[0]) * nvars);
  716. #if CONFIG_IS_ENABLED(ENV_APPEND)
  717. flag |= H_NOCLEAR;
  718. #endif
  719. if ((flag & H_NOCLEAR) == 0 && !nvars) {
  720. /* Destroy old hash table if one exists */
  721. debug("Destroy Hash Table: %p table = %p\n", htab,
  722. htab->table);
  723. if (htab->table)
  724. hdestroy_r(htab);
  725. }
  726. /*
  727. * Create new hash table (if needed). The computation of the hash
  728. * table size is based on heuristics: in a sample of some 70+
  729. * existing systems we found an average size of 39+ bytes per entry
  730. * in the environment (for the whole key=value pair). Assuming a
  731. * size of 8 per entry (= safety factor of ~5) should provide enough
  732. * safety margin for any existing environment definitions and still
  733. * allow for more than enough dynamic additions. Note that the
  734. * "size" argument is supposed to give the maximum environment size
  735. * (CONFIG_ENV_SIZE). This heuristics will result in
  736. * unreasonably large numbers (and thus memory footprint) for
  737. * big flash environments (>8,000 entries for 64 KB
  738. * environment size), so we clip it to a reasonable value.
  739. * On the other hand we need to add some more entries for free
  740. * space when importing very small buffers. Both boundaries can
  741. * be overwritten in the board config file if needed.
  742. */
  743. if (!htab->table) {
  744. int nent = CONFIG_ENV_MIN_ENTRIES + size / 8;
  745. if (nent > CONFIG_ENV_MAX_ENTRIES)
  746. nent = CONFIG_ENV_MAX_ENTRIES;
  747. debug("Create Hash Table: N=%d\n", nent);
  748. if (hcreate_r(nent, htab) == 0) {
  749. free(data);
  750. return 0;
  751. }
  752. }
  753. if (!size) {
  754. free(data);
  755. return 1; /* everything OK */
  756. }
  757. if(crlf_is_lf) {
  758. /* Remove Carriage Returns in front of Line Feeds */
  759. unsigned ignored_crs = 0;
  760. for(;dp < data + size && *dp; ++dp) {
  761. if(*dp == '\r' &&
  762. dp < data + size - 1 && *(dp+1) == '\n')
  763. ++ignored_crs;
  764. else
  765. *(dp-ignored_crs) = *dp;
  766. }
  767. size -= ignored_crs;
  768. dp = data;
  769. }
  770. /* Parse environment; allow for '\0' and 'sep' as separators */
  771. do {
  772. struct env_entry e, *rv;
  773. /* skip leading white space */
  774. while (isblank(*dp))
  775. ++dp;
  776. /* skip comment lines */
  777. if (*dp == '#') {
  778. while (*dp && (*dp != sep))
  779. ++dp;
  780. ++dp;
  781. continue;
  782. }
  783. /* parse name */
  784. for (name = dp; *dp != '=' && *dp && *dp != sep; ++dp)
  785. ;
  786. /* deal with "name" and "name=" entries (delete var) */
  787. if (*dp == '\0' || *(dp + 1) == '\0' ||
  788. *dp == sep || *(dp + 1) == sep) {
  789. if (*dp == '=')
  790. *dp++ = '\0';
  791. *dp++ = '\0'; /* terminate name */
  792. debug("DELETE CANDIDATE: \"%s\"\n", name);
  793. if (!drop_var_from_set(name, nvars, localvars))
  794. continue;
  795. if (hdelete_r(name, htab, flag) == 0)
  796. debug("DELETE ERROR ##############################\n");
  797. continue;
  798. }
  799. *dp++ = '\0'; /* terminate name */
  800. /* parse value; deal with escapes */
  801. for (value = sp = dp; *dp && (*dp != sep); ++dp) {
  802. if ((*dp == '\\') && *(dp + 1))
  803. ++dp;
  804. *sp++ = *dp;
  805. }
  806. *sp++ = '\0'; /* terminate value */
  807. ++dp;
  808. if (*name == 0) {
  809. debug("INSERT: unable to use an empty key\n");
  810. __set_errno(EINVAL);
  811. free(data);
  812. return 0;
  813. }
  814. /* Skip variables which are not supposed to be processed */
  815. if (!drop_var_from_set(name, nvars, localvars))
  816. continue;
  817. /* enter into hash table */
  818. e.key = name;
  819. e.data = value;
  820. hsearch_r(e, ENV_ENTER, &rv, htab, flag);
  821. #if !CONFIG_IS_ENABLED(ENV_WRITEABLE_LIST)
  822. if (rv == NULL) {
  823. printf("himport_r: can't insert \"%s=%s\" into hash table\n",
  824. name, value);
  825. }
  826. #endif
  827. debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"\n",
  828. htab, htab->filled, htab->size,
  829. rv, name, value);
  830. } while ((dp < data + size) && *dp); /* size check needed for text */
  831. /* without '\0' termination */
  832. debug("INSERT: free(data = %p)\n", data);
  833. free(data);
  834. if (flag & H_NOCLEAR)
  835. goto end;
  836. /* process variables which were not considered */
  837. for (i = 0; i < nvars; i++) {
  838. if (localvars[i] == NULL)
  839. continue;
  840. /*
  841. * All variables which were not deleted from the variable list
  842. * were not present in the imported env
  843. * This could mean two things:
  844. * a) if the variable was present in current env, we delete it
  845. * b) if the variable was not present in current env, we notify
  846. * it might be a typo
  847. */
  848. if (hdelete_r(localvars[i], htab, flag) == 0)
  849. printf("WARNING: '%s' neither in running nor in imported env!\n", localvars[i]);
  850. else
  851. printf("WARNING: '%s' not in imported env, deleting it!\n", localvars[i]);
  852. }
  853. end:
  854. debug("INSERT: done\n");
  855. return 1; /* everything OK */
  856. }
  857. /*
  858. * hwalk_r()
  859. */
  860. /*
  861. * Walk all of the entries in the hash, calling the callback for each one.
  862. * this allows some generic operation to be performed on each element.
  863. */
  864. int hwalk_r(struct hsearch_data *htab, int (*callback)(struct env_entry *entry))
  865. {
  866. int i;
  867. int retval;
  868. for (i = 1; i <= htab->size; ++i) {
  869. if (htab->table[i].used > 0) {
  870. retval = callback(&htab->table[i].entry);
  871. if (retval)
  872. return retval;
  873. }
  874. }
  875. return 0;
  876. }