]>
git.ipfire.org Git - people/ms/u-boot.git/blob - lib/hashtable.c
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 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().
214 * hstrstr_r - return index to entry whose key and/or data contains match
216 int hstrstr_r(const char *match
, int last_idx
, ENTRY
** retval
,
217 struct hsearch_data
*htab
)
221 for (idx
= last_idx
+ 1; idx
< htab
->size
; ++idx
) {
222 if (htab
->table
[idx
].used
<= 0)
224 if (strstr(htab
->table
[idx
].entry
.key
, match
) ||
225 strstr(htab
->table
[idx
].entry
.data
, match
)) {
226 *retval
= &htab
->table
[idx
].entry
;
236 int hmatch_r(const char *match
, int last_idx
, ENTRY
** retval
,
237 struct hsearch_data
*htab
)
240 size_t key_len
= strlen(match
);
242 for (idx
= last_idx
+ 1; idx
< htab
->size
; ++idx
) {
243 if (htab
->table
[idx
].used
<= 0)
245 if (!strncmp(match
, htab
->table
[idx
].entry
.key
, key_len
)) {
246 *retval
= &htab
->table
[idx
].entry
;
257 * Compare an existing entry with the desired key, and overwrite if the action
258 * is ENTER. This is simply a helper function for hsearch_r().
260 static inline int _compare_and_overwrite_entry(ENTRY item
, ACTION action
,
261 ENTRY
**retval
, struct hsearch_data
*htab
, int flag
,
262 unsigned int hval
, unsigned int idx
)
264 if (htab
->table
[idx
].used
== hval
265 && strcmp(item
.key
, htab
->table
[idx
].entry
.key
) == 0) {
266 /* Overwrite existing value? */
267 if ((action
== ENTER
) && (item
.data
!= NULL
)) {
268 /* check for permission */
269 if (htab
->change_ok
!= NULL
&& htab
->change_ok(
270 &htab
->table
[idx
].entry
, item
.data
,
271 env_op_overwrite
, flag
)) {
272 debug("change_ok() rejected setting variable "
273 "%s, skipping it!\n", item
.key
);
279 /* If there is a callback, call it */
280 if (htab
->table
[idx
].entry
.callback
&&
281 htab
->table
[idx
].entry
.callback(item
.key
,
282 item
.data
, env_op_overwrite
, flag
)) {
283 debug("callback() rejected setting variable "
284 "%s, skipping it!\n", item
.key
);
290 free(htab
->table
[idx
].entry
.data
);
291 htab
->table
[idx
].entry
.data
= strdup(item
.data
);
292 if (!htab
->table
[idx
].entry
.data
) {
298 /* return found entry */
299 *retval
= &htab
->table
[idx
].entry
;
306 int hsearch_r(ENTRY item
, ACTION action
, ENTRY
** retval
,
307 struct hsearch_data
*htab
, int flag
)
311 unsigned int len
= strlen(item
.key
);
313 unsigned int first_deleted
= 0;
316 /* Compute an value for the given string. Perhaps use a better method. */
319 while (count
-- > 0) {
321 hval
+= item
.key
[count
];
325 * First hash function:
326 * simply take the modul but prevent zero.
332 /* The first index tried. */
335 if (htab
->table
[idx
].used
) {
337 * Further action might be required according to the
342 if (htab
->table
[idx
].used
== -1
346 ret
= _compare_and_overwrite_entry(item
, action
, retval
, htab
,
352 * Second hash function:
353 * as suggested in [Knuth]
355 hval2
= 1 + hval
% (htab
->size
- 2);
359 * Because SIZE is prime this guarantees to
360 * step through all available indices.
363 idx
= htab
->size
+ idx
- hval2
;
368 * If we visited all entries leave the loop
374 /* If entry is found use it. */
375 ret
= _compare_and_overwrite_entry(item
, action
, retval
,
376 htab
, flag
, hval
, idx
);
380 while (htab
->table
[idx
].used
);
383 /* An empty bucket has been found. */
384 if (action
== ENTER
) {
386 * If table is full and another entry should be
387 * entered return with error.
389 if (htab
->filled
== htab
->size
) {
397 * create copies of item.key and item.data
402 htab
->table
[idx
].used
= hval
;
403 htab
->table
[idx
].entry
.key
= strdup(item
.key
);
404 htab
->table
[idx
].entry
.data
= strdup(item
.data
);
405 if (!htab
->table
[idx
].entry
.key
||
406 !htab
->table
[idx
].entry
.data
) {
414 /* This is a new entry, so look up a possible callback */
415 env_callback_init(&htab
->table
[idx
].entry
);
416 /* Also look for flags */
417 env_flags_init(&htab
->table
[idx
].entry
);
419 /* check for permission */
420 if (htab
->change_ok
!= NULL
&& htab
->change_ok(
421 &htab
->table
[idx
].entry
, item
.data
, env_op_create
, flag
)) {
422 debug("change_ok() rejected setting variable "
423 "%s, skipping it!\n", item
.key
);
424 _hdelete(item
.key
, htab
, &htab
->table
[idx
].entry
, idx
);
430 /* If there is a callback, call it */
431 if (htab
->table
[idx
].entry
.callback
&&
432 htab
->table
[idx
].entry
.callback(item
.key
, item
.data
,
433 env_op_create
, flag
)) {
434 debug("callback() rejected setting variable "
435 "%s, skipping it!\n", item
.key
);
436 _hdelete(item
.key
, htab
, &htab
->table
[idx
].entry
, idx
);
442 /* return new entry */
443 *retval
= &htab
->table
[idx
].entry
;
458 * The standard implementation of hsearch(3) does not provide any way
459 * to delete any entries from the hash table. We extend the code to
463 static void _hdelete(const char *key
, struct hsearch_data
*htab
, ENTRY
*ep
,
466 /* free used ENTRY */
467 debug("hdelete: DELETING key \"%s\"\n", key
);
468 free((void *)ep
->key
);
472 htab
->table
[idx
].used
= -1;
477 int hdelete_r(const char *key
, struct hsearch_data
*htab
, int flag
)
482 debug("hdelete: DELETE key \"%s\"\n", key
);
486 idx
= hsearch_r(e
, FIND
, &ep
, htab
, 0);
489 return 0; /* not found */
492 /* Check for permission */
493 if (htab
->change_ok
!= NULL
&&
494 htab
->change_ok(ep
, NULL
, env_op_delete
, flag
)) {
495 debug("change_ok() rejected deleting variable "
496 "%s, skipping it!\n", key
);
501 /* If there is a callback, call it */
502 if (htab
->table
[idx
].entry
.callback
&&
503 htab
->table
[idx
].entry
.callback(key
, NULL
, env_op_delete
, flag
)) {
504 debug("callback() rejected deleting variable "
505 "%s, skipping it!\n", key
);
510 _hdelete(key
, htab
, ep
, idx
);
519 #ifndef CONFIG_SPL_BUILD
521 * Export the data stored in the hash table in linearized form.
523 * Entries are exported as "name=value" strings, separated by an
524 * arbitrary (non-NUL, of course) separator character. This allows to
525 * use this function both when formatting the U-Boot environment for
526 * external storage (using '\0' as separator), but also when using it
527 * for the "printenv" command to print all variables, simply by using
528 * as '\n" as separator. This can also be used for new features like
529 * exporting the environment data as text file, including the option
530 * for later re-import.
532 * The entries in the result list will be sorted by ascending key
535 * If the separator character is different from NUL, then any
536 * separator characters and backslash characters in the values will
537 * be escaped by a preceeding backslash in output. This is needed for
538 * example to enable multi-line values, especially when the output
539 * shall later be parsed (for example, for re-import).
541 * There are several options how the result buffer is handled:
545 * NULL 0 A string of sufficient length will be allocated.
546 * NULL >0 A string of the size given will be
547 * allocated. An error will be returned if the size is
548 * not sufficient. Any unused bytes in the string will
550 * !NULL 0 The user-supplied buffer will be used. No length
551 * checking will be performed, i. e. it is assumed that
552 * the buffer size will always be big enough. DANGEROUS.
553 * !NULL >0 The user-supplied buffer will be used. An error will
554 * be returned if the size is not sufficient. Any unused
555 * bytes in the string will be '\0'-padded.
558 static int cmpkey(const void *p1
, const void *p2
)
560 ENTRY
*e1
= *(ENTRY
**) p1
;
561 ENTRY
*e2
= *(ENTRY
**) p2
;
563 return (strcmp(e1
->key
, e2
->key
));
566 ssize_t
hexport_r(struct hsearch_data
*htab
, const char sep
, int flag
,
567 char **resp
, size_t size
,
568 int argc
, char * const argv
[])
570 ENTRY
*list
[htab
->size
];
575 /* Test for correct arguments. */
576 if ((resp
== NULL
) || (htab
== NULL
)) {
581 debug("EXPORT table = %p, htab.size = %d, htab.filled = %d, "
582 "size = %zu\n", htab
, htab
->size
, htab
->filled
, size
);
585 * search used entries,
586 * save addresses and compute total length
588 for (i
= 1, n
= 0, totlen
= 0; i
<= htab
->size
; ++i
) {
590 if (htab
->table
[i
].used
> 0) {
591 ENTRY
*ep
= &htab
->table
[i
].entry
;
594 for (arg
= 0; arg
< argc
; ++arg
) {
595 if (strcmp(argv
[arg
], ep
->key
) == 0) {
600 if ((argc
> 0) && (found
== 0))
603 if ((flag
& H_HIDE_DOT
) && ep
->key
[0] == '.')
608 totlen
+= strlen(ep
->key
) + 2;
611 totlen
+= strlen(ep
->data
);
612 } else { /* check if escapes are needed */
617 /* add room for needed escape chars */
618 if ((*s
== sep
) || (*s
== '\\'))
623 totlen
+= 2; /* for '=' and 'sep' char */
628 /* Pass 1a: print unsorted list */
629 printf("Unsorted: n=%d\n", n
);
630 for (i
= 0; i
< n
; ++i
) {
631 printf("\t%3d: %p ==> %-10s => %s\n",
632 i
, list
[i
], list
[i
]->key
, list
[i
]->data
);
636 /* Sort list by keys */
637 qsort(list
, n
, sizeof(ENTRY
*), cmpkey
);
639 /* Check if the user supplied buffer size is sufficient */
641 if (size
< totlen
+ 1) { /* provided buffer too small */
642 printf("Env export buffer too small: %zu, "
643 "but need %zu\n", size
, totlen
+ 1);
651 /* Check if the user provided a buffer */
655 memset(res
, '\0', size
);
657 /* no, allocate and clear one */
658 *resp
= res
= calloc(1, size
);
666 * export sorted list of result data
668 for (i
= 0, p
= res
; i
< n
; ++i
) {
679 if ((*s
== sep
) || (*s
== '\\'))
680 *p
++ = '\\'; /* escape */
685 *p
= '\0'; /* terminate result */
697 * Check whether variable 'name' is amongst vars[],
698 * and remove all instances by setting the pointer to NULL
700 static int drop_var_from_set(const char *name
, int nvars
, char * vars
[])
705 /* No variables specified means process all of them */
709 for (i
= 0; i
< nvars
; i
++) {
712 /* If we found it, delete all of them */
713 if (!strcmp(name
, vars
[i
])) {
719 debug("Skipping non-listed variable %s\n", name
);
725 * Import linearized data into hash table.
727 * This is the inverse function to hexport(): it takes a linear list
728 * of "name=value" pairs and creates hash table entries from it.
730 * Entries without "value", i. e. consisting of only "name" or
731 * "name=", will cause this entry to be deleted from the hash table.
733 * The "flag" argument can be used to control the behaviour: when the
734 * H_NOCLEAR bit is set, then an existing hash table will kept, i. e.
735 * new data will be added to an existing hash table; otherwise, old
736 * data will be discarded and a new hash table will be created.
738 * The separator character for the "name=value" pairs can be selected,
739 * so we both support importing from externally stored environment
740 * data (separated by NUL characters) and from plain text files
741 * (entries separated by newline characters).
743 * To allow for nicely formatted text input, leading white space
744 * (sequences of SPACE and TAB chars) is ignored, and entries starting
745 * (after removal of any leading white space) with a '#' character are
746 * considered comments and ignored.
748 * [NOTE: this means that a variable name cannot start with a '#'
751 * When using a non-NUL separator character, backslash is used as
752 * escape character in the value part, allowing for example for
755 * In theory, arbitrary separator characters can be used, but only
756 * '\0' and '\n' have really been tested.
759 int himport_r(struct hsearch_data
*htab
,
760 const char *env
, size_t size
, const char sep
, int flag
,
761 int nvars
, char * const vars
[])
763 char *data
, *sp
, *dp
, *name
, *value
;
764 char *localvars
[nvars
];
767 /* Test for correct arguments. */
773 /* we allocate new space to make sure we can write to the array */
774 if ((data
= malloc(size
)) == NULL
) {
775 debug("himport_r: can't malloc %zu bytes\n", size
);
779 memcpy(data
, env
, size
);
782 /* make a local copy of the list of variables */
784 memcpy(localvars
, vars
, sizeof(vars
[0]) * nvars
);
786 if ((flag
& H_NOCLEAR
) == 0) {
787 /* Destroy old hash table if one exists */
788 debug("Destroy Hash Table: %p table = %p\n", htab
,
795 * Create new hash table (if needed). The computation of the hash
796 * table size is based on heuristics: in a sample of some 70+
797 * existing systems we found an average size of 39+ bytes per entry
798 * in the environment (for the whole key=value pair). Assuming a
799 * size of 8 per entry (= safety factor of ~5) should provide enough
800 * safety margin for any existing environment definitions and still
801 * allow for more than enough dynamic additions. Note that the
802 * "size" argument is supposed to give the maximum enviroment size
803 * (CONFIG_ENV_SIZE). This heuristics will result in
804 * unreasonably large numbers (and thus memory footprint) for
805 * big flash environments (>8,000 entries for 64 KB
806 * envrionment size), so we clip it to a reasonable value.
807 * On the other hand we need to add some more entries for free
808 * space when importing very small buffers. Both boundaries can
809 * be overwritten in the board config file if needed.
813 int nent
= CONFIG_ENV_MIN_ENTRIES
+ size
/ 8;
815 if (nent
> CONFIG_ENV_MAX_ENTRIES
)
816 nent
= CONFIG_ENV_MAX_ENTRIES
;
818 debug("Create Hash Table: N=%d\n", nent
);
820 if (hcreate_r(nent
, htab
) == 0) {
826 /* Parse environment; allow for '\0' and 'sep' as separators */
830 /* skip leading white space */
834 /* skip comment lines */
836 while (*dp
&& (*dp
!= sep
))
843 for (name
= dp
; *dp
!= '=' && *dp
&& *dp
!= sep
; ++dp
)
846 /* deal with "name" and "name=" entries (delete var) */
847 if (*dp
== '\0' || *(dp
+ 1) == '\0' ||
848 *dp
== sep
|| *(dp
+ 1) == sep
) {
851 *dp
++ = '\0'; /* terminate name */
853 debug("DELETE CANDIDATE: \"%s\"\n", name
);
854 if (!drop_var_from_set(name
, nvars
, localvars
))
857 if (hdelete_r(name
, htab
, flag
) == 0)
858 debug("DELETE ERROR ##############################\n");
862 *dp
++ = '\0'; /* terminate name */
864 /* parse value; deal with escapes */
865 for (value
= sp
= dp
; *dp
&& (*dp
!= sep
); ++dp
) {
866 if ((*dp
== '\\') && *(dp
+ 1))
870 *sp
++ = '\0'; /* terminate value */
873 /* Skip variables which are not supposed to be processed */
874 if (!drop_var_from_set(name
, nvars
, localvars
))
877 /* enter into hash table */
881 hsearch_r(e
, ENTER
, &rv
, htab
, flag
);
883 printf("himport_r: can't insert \"%s=%s\" into hash table\n",
886 debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"\n",
887 htab
, htab
->filled
, htab
->size
,
889 } while ((dp
< data
+ size
) && *dp
); /* size check needed for text */
890 /* without '\0' termination */
891 debug("INSERT: free(data = %p)\n", data
);
894 /* process variables which were not considered */
895 for (i
= 0; i
< nvars
; i
++) {
896 if (localvars
[i
] == NULL
)
899 * All variables which were not deleted from the variable list
900 * were not present in the imported env
901 * This could mean two things:
902 * a) if the variable was present in current env, we delete it
903 * b) if the variable was not present in current env, we notify
906 if (hdelete_r(localvars
[i
], htab
, flag
) == 0)
907 printf("WARNING: '%s' neither in running nor in imported env!\n", localvars
[i
]);
909 printf("WARNING: '%s' not in imported env, deleting it!\n", localvars
[i
]);
912 debug("INSERT: done\n");
913 return 1; /* everything OK */
921 * Walk all of the entries in the hash, calling the callback for each one.
922 * this allows some generic operation to be performed on each element.
924 int hwalk_r(struct hsearch_data
*htab
, int (*callback
)(ENTRY
*))
929 for (i
= 1; i
<= htab
->size
; ++i
) {
930 if (htab
->table
[i
].used
> 0) {
931 retval
= callback(&htab
->table
[i
].entry
);