2 * This implementation is based on code from uClibc-0.9.30.3 but was
3 * modified and extended for use within U-Boot.
5 * Copyright (C) 2010-2013 Wolfgang Denk <wd@denx.de>
7 * Original license header:
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.
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.
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.
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
32 #ifdef USE_HOSTCC /* HOST build */
39 # define debug(fmt,args...) printf(fmt ,##args)
41 # define debug(fmt,args...)
44 #else /* U-Boot build */
46 # include <linux/string.h>
47 # include <linux/ctype.h>
50 #ifndef CONFIG_ENV_MIN_ENTRIES /* minimum number of entries */
51 #define CONFIG_ENV_MIN_ENTRIES 64
53 #ifndef CONFIG_ENV_MAX_ENTRIES /* maximum number of entries */
54 #define CONFIG_ENV_MAX_ENTRIES 512
57 #include <env_callback.h>
58 #include <env_flags.h>
62 * [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
63 * [Knuth] The Art of Computer Programming, part 3 (6.4)
67 * The reentrant version has no static variables to maintain the state.
68 * Instead the interface of all functions is extended to take an argument
69 * which describes the current status.
72 typedef struct _ENTRY {
78 static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
86 * For the used double hash method the table size has to be a prime. To
87 * correct the user given table size we need a prime test. This trivial
88 * algorithm is adequate because
89 * a) the code is (most probably) called a few times per program run and
90 * b) the number is small because the table must fit in the core
92 static int isprime(unsigned int number)
94 /* no even number will be passed */
97 while (div * div < number && number % div != 0)
100 return number % div != 0;
104 * Before using the hash table we must allocate memory for it.
105 * Test for an existing table are done. We allocate one element
106 * more as the found prime number says. This is done for more effective
107 * indexing as explained in the comment for the hsearch function.
108 * The contents of the table is zeroed, especially the field used
112 int hcreate_r(size_t nel, struct hsearch_data *htab)
114 /* Test for correct arguments. */
120 /* There is still another table active. Return with error. */
121 if (htab->table != NULL)
124 /* Change nel to the first prime number not smaller as nel. */
125 nel |= 1; /* make odd */
126 while (!isprime(nel))
132 /* allocate memory and zero out */
133 htab->table = (_ENTRY *) calloc(htab->size + 1, sizeof(_ENTRY));
134 if (htab->table == NULL)
137 /* everything went alright */
147 * After using the hash table it has to be destroyed. The used memory can
148 * be freed and the local static variable can be marked as not used.
151 void hdestroy_r(struct hsearch_data *htab)
155 /* Test for correct arguments. */
161 /* free used memory */
162 for (i = 1; i <= htab->size; ++i) {
163 if (htab->table[i].used > 0) {
164 ENTRY *ep = &htab->table[i].entry;
166 free((void *)ep->key);
172 /* the sign for an existing table is an value != NULL in htable */
181 * This is the search function. It uses double hashing with open addressing.
182 * The argument item.key has to be a pointer to an zero terminated, most
183 * probably strings of chars. The function for generating a number of the
184 * strings is simple but fast. It can be replaced by a more complex function
185 * like ajw (see [Aho,Sethi,Ullman]) if the needs are shown.
187 * We use an trick to speed up the lookup. The table is created by hcreate
188 * with one more element available. This enables us to use the index zero
189 * special. This index will never be used because we store the first hash
190 * index in the field used where zero means not used. Every other value
191 * means used. The used field can be used as a first fast comparison for
192 * equality of the stored and the parameter value. This helps to prevent
193 * unnecessary expensive calls of strcmp.
195 * This implementation differs from the standard library version of
196 * this function in a number of ways:
198 * - While the standard version does not make any assumptions about
199 * the type of the stored data objects at all, this implementation
200 * works with NUL terminated strings only.
201 * - Instead of storing just pointers to the original objects, we
202 * create local copies so the caller does not need to care about the
204 * - The standard implementation does not provide a way to update an
205 * existing entry. This version will create a new entry or update an
206 * existing one when both "action == ENTER" and "item.data != NULL".
207 * - Instead of returning 1 on success, we return the index into the
208 * internal hash table, which is also guaranteed to be positive.
209 * This allows us direct access to the found hash table slot for
210 * example for functions like hdelete().
213 int hmatch_r(const char *match, int last_idx, ENTRY ** retval,
214 struct hsearch_data *htab)
217 size_t key_len = strlen(match);
219 for (idx = last_idx + 1; idx < htab->size; ++idx) {
220 if (htab->table[idx].used <= 0)
222 if (!strncmp(match, htab->table[idx].entry.key, key_len)) {
223 *retval = &htab->table[idx].entry;
234 * Compare an existing entry with the desired key, and overwrite if the action
235 * is ENTER. This is simply a helper function for hsearch_r().
237 static inline int _compare_and_overwrite_entry(ENTRY item, ACTION action,
238 ENTRY **retval, struct hsearch_data *htab, int flag,
239 unsigned int hval, unsigned int idx)
241 if (htab->table[idx].used == hval
242 && strcmp(item.key, htab->table[idx].entry.key) == 0) {
243 /* Overwrite existing value? */
244 if ((action == ENTER) && (item.data != NULL)) {
245 /* check for permission */
246 if (htab->change_ok != NULL && htab->change_ok(
247 &htab->table[idx].entry, item.data,
248 env_op_overwrite, flag)) {
249 debug("change_ok() rejected setting variable "
250 "%s, skipping it!\n", item.key);
256 /* If there is a callback, call it */
257 if (htab->table[idx].entry.callback &&
258 htab->table[idx].entry.callback(item.key,
259 item.data, env_op_overwrite, flag)) {
260 debug("callback() rejected setting variable "
261 "%s, skipping it!\n", item.key);
267 free(htab->table[idx].entry.data);
268 htab->table[idx].entry.data = strdup(item.data);
269 if (!htab->table[idx].entry.data) {
275 /* return found entry */
276 *retval = &htab->table[idx].entry;
283 int hsearch_r(ENTRY item, ACTION action, ENTRY ** retval,
284 struct hsearch_data *htab, int flag)
288 unsigned int len = strlen(item.key);
290 unsigned int first_deleted = 0;
293 /* Compute an value for the given string. Perhaps use a better method. */
296 while (count-- > 0) {
298 hval += item.key[count];
302 * First hash function:
303 * simply take the modul but prevent zero.
309 /* The first index tried. */
312 if (htab->table[idx].used) {
314 * Further action might be required according to the
319 if (htab->table[idx].used == -1
323 ret = _compare_and_overwrite_entry(item, action, retval, htab,
329 * Second hash function:
330 * as suggested in [Knuth]
332 hval2 = 1 + hval % (htab->size - 2);
336 * Because SIZE is prime this guarantees to
337 * step through all available indices.
340 idx = htab->size + idx - hval2;
345 * If we visited all entries leave the loop
351 /* If entry is found use it. */
352 ret = _compare_and_overwrite_entry(item, action, retval,
353 htab, flag, hval, idx);
357 while (htab->table[idx].used);
360 /* An empty bucket has been found. */
361 if (action == ENTER) {
363 * If table is full and another entry should be
364 * entered return with error.
366 if (htab->filled == htab->size) {
374 * create copies of item.key and item.data
379 htab->table[idx].used = hval;
380 htab->table[idx].entry.key = strdup(item.key);
381 htab->table[idx].entry.data = strdup(item.data);
382 if (!htab->table[idx].entry.key ||
383 !htab->table[idx].entry.data) {
391 /* This is a new entry, so look up a possible callback */
392 env_callback_init(&htab->table[idx].entry);
393 /* Also look for flags */
394 env_flags_init(&htab->table[idx].entry);
396 /* check for permission */
397 if (htab->change_ok != NULL && htab->change_ok(
398 &htab->table[idx].entry, item.data, env_op_create, flag)) {
399 debug("change_ok() rejected setting variable "
400 "%s, skipping it!\n", item.key);
401 _hdelete(item.key, htab, &htab->table[idx].entry, idx);
407 /* If there is a callback, call it */
408 if (htab->table[idx].entry.callback &&
409 htab->table[idx].entry.callback(item.key, item.data,
410 env_op_create, flag)) {
411 debug("callback() rejected setting variable "
412 "%s, skipping it!\n", item.key);
413 _hdelete(item.key, htab, &htab->table[idx].entry, idx);
419 /* return new entry */
420 *retval = &htab->table[idx].entry;
435 * The standard implementation of hsearch(3) does not provide any way
436 * to delete any entries from the hash table. We extend the code to
440 static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
443 /* free used ENTRY */
444 debug("hdelete: DELETING key \"%s\"\n", key);
445 free((void *)ep->key);
449 htab->table[idx].used = -1;
454 int hdelete_r(const char *key, struct hsearch_data *htab, int flag)
459 debug("hdelete: DELETE key \"%s\"\n", key);
463 idx = hsearch_r(e, FIND, &ep, htab, 0);
466 return 0; /* not found */
469 /* Check for permission */
470 if (htab->change_ok != NULL &&
471 htab->change_ok(ep, NULL, env_op_delete, flag)) {
472 debug("change_ok() rejected deleting variable "
473 "%s, skipping it!\n", key);
478 /* If there is a callback, call it */
479 if (htab->table[idx].entry.callback &&
480 htab->table[idx].entry.callback(key, NULL, env_op_delete, flag)) {
481 debug("callback() rejected deleting variable "
482 "%s, skipping it!\n", key);
487 _hdelete(key, htab, ep, idx);
496 #ifndef CONFIG_SPL_BUILD
498 * Export the data stored in the hash table in linearized form.
500 * Entries are exported as "name=value" strings, separated by an
501 * arbitrary (non-NUL, of course) separator character. This allows to
502 * use this function both when formatting the U-Boot environment for
503 * external storage (using '\0' as separator), but also when using it
504 * for the "printenv" command to print all variables, simply by using
505 * as '\n" as separator. This can also be used for new features like
506 * exporting the environment data as text file, including the option
507 * for later re-import.
509 * The entries in the result list will be sorted by ascending key
512 * If the separator character is different from NUL, then any
513 * separator characters and backslash characters in the values will
514 * be escaped by a preceeding backslash in output. This is needed for
515 * example to enable multi-line values, especially when the output
516 * shall later be parsed (for example, for re-import).
518 * There are several options how the result buffer is handled:
522 * NULL 0 A string of sufficient length will be allocated.
523 * NULL >0 A string of the size given will be
524 * allocated. An error will be returned if the size is
525 * not sufficient. Any unused bytes in the string will
527 * !NULL 0 The user-supplied buffer will be used. No length
528 * checking will be performed, i. e. it is assumed that
529 * the buffer size will always be big enough. DANGEROUS.
530 * !NULL >0 The user-supplied buffer will be used. An error will
531 * be returned if the size is not sufficient. Any unused
532 * bytes in the string will be '\0'-padded.
535 static int cmpkey(const void *p1, const void *p2)
537 ENTRY *e1 = *(ENTRY **) p1;
538 ENTRY *e2 = *(ENTRY **) p2;
540 return (strcmp(e1->key, e2->key));
543 static int match_string(int flag, const char *str, const char *pat)
545 switch (flag & H_MATCH_METHOD) {
547 if (strcmp(str, pat) == 0)
551 if (strstr(str, pat))
555 printf("## ERROR: unsupported match method: 0x%02x\n",
556 flag & H_MATCH_METHOD);
562 static int match_entry(ENTRY *ep, int flag,
563 int argc, char * const argv[])
567 for (arg = 1; arg < argc; ++arg) {
568 if (flag & H_MATCH_KEY) {
569 if (match_string(flag, ep->key, argv[arg]))
572 if (flag & H_MATCH_DATA) {
573 if (match_string(flag, ep->data, argv[arg]))
580 ssize_t hexport_r(struct hsearch_data *htab, const char sep, int flag,
581 char **resp, size_t size,
582 int argc, char * const argv[])
584 ENTRY *list[htab->size];
589 /* Test for correct arguments. */
590 if ((resp == NULL) || (htab == NULL)) {
595 debug("EXPORT table = %p, htab.size = %d, htab.filled = %d, "
596 "size = %zu\n", htab, htab->size, htab->filled, size);
599 * search used entries,
600 * save addresses and compute total length
602 for (i = 1, n = 0, totlen = 0; i <= htab->size; ++i) {
604 if (htab->table[i].used > 0) {
605 ENTRY *ep = &htab->table[i].entry;
606 int found = match_entry(ep, flag, argc, argv);
608 if ((argc > 0) && (found == 0))
611 if ((flag & H_HIDE_DOT) && ep->key[0] == '.')
616 totlen += strlen(ep->key) + 2;
619 totlen += strlen(ep->data);
620 } else { /* check if escapes are needed */
625 /* add room for needed escape chars */
626 if ((*s == sep) || (*s == '\\'))
631 totlen += 2; /* for '=' and 'sep' char */
636 /* Pass 1a: print unsorted list */
637 printf("Unsorted: n=%d\n", n);
638 for (i = 0; i < n; ++i) {
639 printf("\t%3d: %p ==> %-10s => %s\n",
640 i, list[i], list[i]->key, list[i]->data);
644 /* Sort list by keys */
645 qsort(list, n, sizeof(ENTRY *), cmpkey);
647 /* Check if the user supplied buffer size is sufficient */
649 if (size < totlen + 1) { /* provided buffer too small */
650 printf("Env export buffer too small: %zu, "
651 "but need %zu\n", size, totlen + 1);
659 /* Check if the user provided a buffer */
663 memset(res, '\0', size);
665 /* no, allocate and clear one */
666 *resp = res = calloc(1, size);
674 * export sorted list of result data
676 for (i = 0, p = res; i < n; ++i) {
687 if ((*s == sep) || (*s == '\\'))
688 *p++ = '\\'; /* escape */
693 *p = '\0'; /* terminate result */
705 * Check whether variable 'name' is amongst vars[],
706 * and remove all instances by setting the pointer to NULL
708 static int drop_var_from_set(const char *name, int nvars, char * vars[])
713 /* No variables specified means process all of them */
717 for (i = 0; i < nvars; i++) {
720 /* If we found it, delete all of them */
721 if (!strcmp(name, vars[i])) {
727 debug("Skipping non-listed variable %s\n", name);
733 * Import linearized data into hash table.
735 * This is the inverse function to hexport(): it takes a linear list
736 * of "name=value" pairs and creates hash table entries from it.
738 * Entries without "value", i. e. consisting of only "name" or
739 * "name=", will cause this entry to be deleted from the hash table.
741 * The "flag" argument can be used to control the behaviour: when the
742 * H_NOCLEAR bit is set, then an existing hash table will kept, i. e.
743 * new data will be added to an existing hash table; otherwise, old
744 * data will be discarded and a new hash table will be created.
746 * The separator character for the "name=value" pairs can be selected,
747 * so we both support importing from externally stored environment
748 * data (separated by NUL characters) and from plain text files
749 * (entries separated by newline characters).
751 * To allow for nicely formatted text input, leading white space
752 * (sequences of SPACE and TAB chars) is ignored, and entries starting
753 * (after removal of any leading white space) with a '#' character are
754 * considered comments and ignored.
756 * [NOTE: this means that a variable name cannot start with a '#'
759 * When using a non-NUL separator character, backslash is used as
760 * escape character in the value part, allowing for example for
763 * In theory, arbitrary separator characters can be used, but only
764 * '\0' and '\n' have really been tested.
767 int himport_r(struct hsearch_data *htab,
768 const char *env, size_t size, const char sep, int flag,
769 int nvars, char * const vars[])
771 char *data, *sp, *dp, *name, *value;
772 char *localvars[nvars];
775 /* Test for correct arguments. */
781 /* we allocate new space to make sure we can write to the array */
782 if ((data = malloc(size)) == NULL) {
783 debug("himport_r: can't malloc %zu bytes\n", size);
787 memcpy(data, env, size);
790 /* make a local copy of the list of variables */
792 memcpy(localvars, vars, sizeof(vars[0]) * nvars);
794 if ((flag & H_NOCLEAR) == 0) {
795 /* Destroy old hash table if one exists */
796 debug("Destroy Hash Table: %p table = %p\n", htab,
803 * Create new hash table (if needed). The computation of the hash
804 * table size is based on heuristics: in a sample of some 70+
805 * existing systems we found an average size of 39+ bytes per entry
806 * in the environment (for the whole key=value pair). Assuming a
807 * size of 8 per entry (= safety factor of ~5) should provide enough
808 * safety margin for any existing environment definitions and still
809 * allow for more than enough dynamic additions. Note that the
810 * "size" argument is supposed to give the maximum enviroment size
811 * (CONFIG_ENV_SIZE). This heuristics will result in
812 * unreasonably large numbers (and thus memory footprint) for
813 * big flash environments (>8,000 entries for 64 KB
814 * envrionment size), so we clip it to a reasonable value.
815 * On the other hand we need to add some more entries for free
816 * space when importing very small buffers. Both boundaries can
817 * be overwritten in the board config file if needed.
821 int nent = CONFIG_ENV_MIN_ENTRIES + size / 8;
823 if (nent > CONFIG_ENV_MAX_ENTRIES)
824 nent = CONFIG_ENV_MAX_ENTRIES;
826 debug("Create Hash Table: N=%d\n", nent);
828 if (hcreate_r(nent, htab) == 0) {
834 /* Parse environment; allow for '\0' and 'sep' as separators */
838 /* skip leading white space */
842 /* skip comment lines */
844 while (*dp && (*dp != sep))
851 for (name = dp; *dp != '=' && *dp && *dp != sep; ++dp)
854 /* deal with "name" and "name=" entries (delete var) */
855 if (*dp == '\0' || *(dp + 1) == '\0' ||
856 *dp == sep || *(dp + 1) == sep) {
859 *dp++ = '\0'; /* terminate name */
861 debug("DELETE CANDIDATE: \"%s\"\n", name);
862 if (!drop_var_from_set(name, nvars, localvars))
865 if (hdelete_r(name, htab, flag) == 0)
866 debug("DELETE ERROR ##############################\n");
870 *dp++ = '\0'; /* terminate name */
872 /* parse value; deal with escapes */
873 for (value = sp = dp; *dp && (*dp != sep); ++dp) {
874 if ((*dp == '\\') && *(dp + 1))
878 *sp++ = '\0'; /* terminate value */
881 /* Skip variables which are not supposed to be processed */
882 if (!drop_var_from_set(name, nvars, localvars))
885 /* enter into hash table */
889 hsearch_r(e, ENTER, &rv, htab, flag);
891 printf("himport_r: can't insert \"%s=%s\" into hash table\n",
894 debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"\n",
895 htab, htab->filled, htab->size,
897 } while ((dp < data + size) && *dp); /* size check needed for text */
898 /* without '\0' termination */
899 debug("INSERT: free(data = %p)\n", data);
902 /* process variables which were not considered */
903 for (i = 0; i < nvars; i++) {
904 if (localvars[i] == NULL)
907 * All variables which were not deleted from the variable list
908 * were not present in the imported env
909 * This could mean two things:
910 * a) if the variable was present in current env, we delete it
911 * b) if the variable was not present in current env, we notify
914 if (hdelete_r(localvars[i], htab, flag) == 0)
915 printf("WARNING: '%s' neither in running nor in imported env!\n", localvars[i]);
917 printf("WARNING: '%s' not in imported env, deleting it!\n", localvars[i]);
920 debug("INSERT: done\n");
921 return 1; /* everything OK */
929 * Walk all of the entries in the hash, calling the callback for each one.
930 * this allows some generic operation to be performed on each element.
932 int hwalk_r(struct hsearch_data *htab, int (*callback)(ENTRY *))
937 for (i = 1; i <= htab->size; ++i) {
938 if (htab->table[i].used > 0) {
939 retval = callback(&htab->table[i].entry);