xref: /openbmc/u-boot/lib/hashtable.c (revision e35171e9)
183d290c5STom Rini // SPDX-License-Identifier: LGPL-2.1+
2a6826fbcSWolfgang Denk /*
3a6826fbcSWolfgang Denk  * This implementation is based on code from uClibc-0.9.30.3 but was
4a6826fbcSWolfgang Denk  * modified and extended for use within U-Boot.
5a6826fbcSWolfgang Denk  *
6ea009d47SWolfgang Denk  * Copyright (C) 2010-2013 Wolfgang Denk <wd@denx.de>
7a6826fbcSWolfgang Denk  *
8a6826fbcSWolfgang Denk  * Original license header:
9a6826fbcSWolfgang Denk  *
10a6826fbcSWolfgang Denk  * Copyright (C) 1993, 1995, 1996, 1997, 2002 Free Software Foundation, Inc.
11a6826fbcSWolfgang Denk  * This file is part of the GNU C Library.
12a6826fbcSWolfgang Denk  * Contributed by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1993.
13a6826fbcSWolfgang Denk  */
14a6826fbcSWolfgang Denk 
15a6826fbcSWolfgang Denk #include <errno.h>
16a6826fbcSWolfgang Denk #include <malloc.h>
17a6826fbcSWolfgang Denk 
18a6826fbcSWolfgang Denk #ifdef USE_HOSTCC		/* HOST build */
19a6826fbcSWolfgang Denk # include <string.h>
20a6826fbcSWolfgang Denk # include <assert.h>
214d91a6ecSJason Hobbs # include <ctype.h>
22a6826fbcSWolfgang Denk 
23a6826fbcSWolfgang Denk # ifndef debug
24a6826fbcSWolfgang Denk #  ifdef DEBUG
25a6826fbcSWolfgang Denk #   define debug(fmt,args...)	printf(fmt ,##args)
26a6826fbcSWolfgang Denk #  else
27a6826fbcSWolfgang Denk #   define debug(fmt,args...)
28a6826fbcSWolfgang Denk #  endif
29a6826fbcSWolfgang Denk # endif
30a6826fbcSWolfgang Denk #else				/* U-Boot build */
31a6826fbcSWolfgang Denk # include <common.h>
32a6826fbcSWolfgang Denk # include <linux/string.h>
334d91a6ecSJason Hobbs # include <linux/ctype.h>
34a6826fbcSWolfgang Denk #endif
35a6826fbcSWolfgang Denk 
36fc5fc76bSAndreas Bießmann #ifndef	CONFIG_ENV_MIN_ENTRIES	/* minimum number of entries */
37fc5fc76bSAndreas Bießmann #define	CONFIG_ENV_MIN_ENTRIES 64
38fc5fc76bSAndreas Bießmann #endif
39ea882bafSWolfgang Denk #ifndef	CONFIG_ENV_MAX_ENTRIES	/* maximum number of entries */
40ea882bafSWolfgang Denk #define	CONFIG_ENV_MAX_ENTRIES 512
41ea882bafSWolfgang Denk #endif
42ea882bafSWolfgang Denk 
43*9dfdbd9fSRoman Kapl #define USED_FREE 0
44*9dfdbd9fSRoman Kapl #define USED_DELETED -1
45*9dfdbd9fSRoman Kapl 
46170ab110SJoe Hershberger #include <env_callback.h>
472598090bSJoe Hershberger #include <env_flags.h>
48170ab110SJoe Hershberger #include <search.h>
49be29df6aSWolfgang Denk #include <slre.h>
50a6826fbcSWolfgang Denk 
51a6826fbcSWolfgang Denk /*
52a6826fbcSWolfgang Denk  * [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
53a6826fbcSWolfgang Denk  * [Knuth]	      The Art of Computer Programming, part 3 (6.4)
54a6826fbcSWolfgang Denk  */
55a6826fbcSWolfgang Denk 
56a6826fbcSWolfgang Denk /*
57a6826fbcSWolfgang Denk  * The reentrant version has no static variables to maintain the state.
58a6826fbcSWolfgang Denk  * Instead the interface of all functions is extended to take an argument
59a6826fbcSWolfgang Denk  * which describes the current status.
60a6826fbcSWolfgang Denk  */
617afcf3a5SJoe Hershberger 
62a6826fbcSWolfgang Denk typedef struct _ENTRY {
63c81c1222SPeter Barada 	int used;
64a6826fbcSWolfgang Denk 	ENTRY entry;
65a6826fbcSWolfgang Denk } _ENTRY;
66a6826fbcSWolfgang Denk 
67a6826fbcSWolfgang Denk 
687afcf3a5SJoe Hershberger static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
697afcf3a5SJoe Hershberger 	int idx);
707afcf3a5SJoe Hershberger 
71a6826fbcSWolfgang Denk /*
72a6826fbcSWolfgang Denk  * hcreate()
73a6826fbcSWolfgang Denk  */
74a6826fbcSWolfgang Denk 
75a6826fbcSWolfgang Denk /*
76a6826fbcSWolfgang Denk  * For the used double hash method the table size has to be a prime. To
77a6826fbcSWolfgang Denk  * correct the user given table size we need a prime test.  This trivial
78a6826fbcSWolfgang Denk  * algorithm is adequate because
79a6826fbcSWolfgang Denk  * a)  the code is (most probably) called a few times per program run and
80a6826fbcSWolfgang Denk  * b)  the number is small because the table must fit in the core
81a6826fbcSWolfgang Denk  * */
isprime(unsigned int number)82a6826fbcSWolfgang Denk static int isprime(unsigned int number)
83a6826fbcSWolfgang Denk {
84a6826fbcSWolfgang Denk 	/* no even number will be passed */
85a6826fbcSWolfgang Denk 	unsigned int div = 3;
86a6826fbcSWolfgang Denk 
87a6826fbcSWolfgang Denk 	while (div * div < number && number % div != 0)
88a6826fbcSWolfgang Denk 		div += 2;
89a6826fbcSWolfgang Denk 
90a6826fbcSWolfgang Denk 	return number % div != 0;
91a6826fbcSWolfgang Denk }
92a6826fbcSWolfgang Denk 
93a6826fbcSWolfgang Denk /*
94a6826fbcSWolfgang Denk  * Before using the hash table we must allocate memory for it.
95a6826fbcSWolfgang Denk  * Test for an existing table are done. We allocate one element
96a6826fbcSWolfgang Denk  * more as the found prime number says. This is done for more effective
97a6826fbcSWolfgang Denk  * indexing as explained in the comment for the hsearch function.
98a6826fbcSWolfgang Denk  * The contents of the table is zeroed, especially the field used
99a6826fbcSWolfgang Denk  * becomes zero.
100a6826fbcSWolfgang Denk  */
1012eb1573fSMike Frysinger 
hcreate_r(size_t nel,struct hsearch_data * htab)102a6826fbcSWolfgang Denk int hcreate_r(size_t nel, struct hsearch_data *htab)
103a6826fbcSWolfgang Denk {
104a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
105a6826fbcSWolfgang Denk 	if (htab == NULL) {
106a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
107a6826fbcSWolfgang Denk 		return 0;
108a6826fbcSWolfgang Denk 	}
109a6826fbcSWolfgang Denk 
110a6826fbcSWolfgang Denk 	/* There is still another table active. Return with error. */
111a6826fbcSWolfgang Denk 	if (htab->table != NULL)
112a6826fbcSWolfgang Denk 		return 0;
113a6826fbcSWolfgang Denk 
114a6826fbcSWolfgang Denk 	/* Change nel to the first prime number not smaller as nel. */
115a6826fbcSWolfgang Denk 	nel |= 1;		/* make odd */
116a6826fbcSWolfgang Denk 	while (!isprime(nel))
117a6826fbcSWolfgang Denk 		nel += 2;
118a6826fbcSWolfgang Denk 
119a6826fbcSWolfgang Denk 	htab->size = nel;
120a6826fbcSWolfgang Denk 	htab->filled = 0;
121a6826fbcSWolfgang Denk 
122a6826fbcSWolfgang Denk 	/* allocate memory and zero out */
123a6826fbcSWolfgang Denk 	htab->table = (_ENTRY *) calloc(htab->size + 1, sizeof(_ENTRY));
124a6826fbcSWolfgang Denk 	if (htab->table == NULL)
125a6826fbcSWolfgang Denk 		return 0;
126a6826fbcSWolfgang Denk 
127a6826fbcSWolfgang Denk 	/* everything went alright */
128a6826fbcSWolfgang Denk 	return 1;
129a6826fbcSWolfgang Denk }
130a6826fbcSWolfgang Denk 
131a6826fbcSWolfgang Denk 
132a6826fbcSWolfgang Denk /*
133a6826fbcSWolfgang Denk  * hdestroy()
134a6826fbcSWolfgang Denk  */
135a6826fbcSWolfgang Denk 
136a6826fbcSWolfgang Denk /*
137a6826fbcSWolfgang Denk  * After using the hash table it has to be destroyed. The used memory can
138a6826fbcSWolfgang Denk  * be freed and the local static variable can be marked as not used.
139a6826fbcSWolfgang Denk  */
1402eb1573fSMike Frysinger 
hdestroy_r(struct hsearch_data * htab)141c4e0057fSJoe Hershberger void hdestroy_r(struct hsearch_data *htab)
142a6826fbcSWolfgang Denk {
143a6826fbcSWolfgang Denk 	int i;
144a6826fbcSWolfgang Denk 
145a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
146a6826fbcSWolfgang Denk 	if (htab == NULL) {
147a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
148a6826fbcSWolfgang Denk 		return;
149a6826fbcSWolfgang Denk 	}
150a6826fbcSWolfgang Denk 
151a6826fbcSWolfgang Denk 	/* free used memory */
152a6826fbcSWolfgang Denk 	for (i = 1; i <= htab->size; ++i) {
153c81c1222SPeter Barada 		if (htab->table[i].used > 0) {
154a6826fbcSWolfgang Denk 			ENTRY *ep = &htab->table[i].entry;
155c4e0057fSJoe Hershberger 
15684b5e802SWolfgang Denk 			free((void *)ep->key);
157a6826fbcSWolfgang Denk 			free(ep->data);
158a6826fbcSWolfgang Denk 		}
159a6826fbcSWolfgang Denk 	}
160a6826fbcSWolfgang Denk 	free(htab->table);
161a6826fbcSWolfgang Denk 
162a6826fbcSWolfgang Denk 	/* the sign for an existing table is an value != NULL in htable */
163a6826fbcSWolfgang Denk 	htab->table = NULL;
164a6826fbcSWolfgang Denk }
165a6826fbcSWolfgang Denk 
166a6826fbcSWolfgang Denk /*
167a6826fbcSWolfgang Denk  * hsearch()
168a6826fbcSWolfgang Denk  */
169a6826fbcSWolfgang Denk 
170a6826fbcSWolfgang Denk /*
171a6826fbcSWolfgang Denk  * This is the search function. It uses double hashing with open addressing.
172a6826fbcSWolfgang Denk  * The argument item.key has to be a pointer to an zero terminated, most
173a6826fbcSWolfgang Denk  * probably strings of chars. The function for generating a number of the
174a6826fbcSWolfgang Denk  * strings is simple but fast. It can be replaced by a more complex function
175a6826fbcSWolfgang Denk  * like ajw (see [Aho,Sethi,Ullman]) if the needs are shown.
176a6826fbcSWolfgang Denk  *
177a6826fbcSWolfgang Denk  * We use an trick to speed up the lookup. The table is created by hcreate
178a6826fbcSWolfgang Denk  * with one more element available. This enables us to use the index zero
179a6826fbcSWolfgang Denk  * special. This index will never be used because we store the first hash
180a6826fbcSWolfgang Denk  * index in the field used where zero means not used. Every other value
181a6826fbcSWolfgang Denk  * means used. The used field can be used as a first fast comparison for
182a6826fbcSWolfgang Denk  * equality of the stored and the parameter value. This helps to prevent
183a6826fbcSWolfgang Denk  * unnecessary expensive calls of strcmp.
184a6826fbcSWolfgang Denk  *
185a6826fbcSWolfgang Denk  * This implementation differs from the standard library version of
186a6826fbcSWolfgang Denk  * this function in a number of ways:
187a6826fbcSWolfgang Denk  *
188a6826fbcSWolfgang Denk  * - While the standard version does not make any assumptions about
189a6826fbcSWolfgang Denk  *   the type of the stored data objects at all, this implementation
190a6826fbcSWolfgang Denk  *   works with NUL terminated strings only.
191a6826fbcSWolfgang Denk  * - Instead of storing just pointers to the original objects, we
192a6826fbcSWolfgang Denk  *   create local copies so the caller does not need to care about the
193a6826fbcSWolfgang Denk  *   data any more.
194a6826fbcSWolfgang Denk  * - The standard implementation does not provide a way to update an
195a6826fbcSWolfgang Denk  *   existing entry.  This version will create a new entry or update an
196a6826fbcSWolfgang Denk  *   existing one when both "action == ENTER" and "item.data != NULL".
197a6826fbcSWolfgang Denk  * - Instead of returning 1 on success, we return the index into the
198a6826fbcSWolfgang Denk  *   internal hash table, which is also guaranteed to be positive.
199a6826fbcSWolfgang Denk  *   This allows us direct access to the found hash table slot for
200a6826fbcSWolfgang Denk  *   example for functions like hdelete().
201a6826fbcSWolfgang Denk  */
202a6826fbcSWolfgang Denk 
hmatch_r(const char * match,int last_idx,ENTRY ** retval,struct hsearch_data * htab)203560d424bSMike Frysinger int hmatch_r(const char *match, int last_idx, ENTRY ** retval,
204560d424bSMike Frysinger 	     struct hsearch_data *htab)
205560d424bSMike Frysinger {
206560d424bSMike Frysinger 	unsigned int idx;
207560d424bSMike Frysinger 	size_t key_len = strlen(match);
208560d424bSMike Frysinger 
209560d424bSMike Frysinger 	for (idx = last_idx + 1; idx < htab->size; ++idx) {
210af4d9074SKim Phillips 		if (htab->table[idx].used <= 0)
211560d424bSMike Frysinger 			continue;
212560d424bSMike Frysinger 		if (!strncmp(match, htab->table[idx].entry.key, key_len)) {
213560d424bSMike Frysinger 			*retval = &htab->table[idx].entry;
214560d424bSMike Frysinger 			return idx;
215560d424bSMike Frysinger 		}
216560d424bSMike Frysinger 	}
217560d424bSMike Frysinger 
218560d424bSMike Frysinger 	__set_errno(ESRCH);
219560d424bSMike Frysinger 	*retval = NULL;
220560d424bSMike Frysinger 	return 0;
221560d424bSMike Frysinger }
222560d424bSMike Frysinger 
2233d3b52f2SJoe Hershberger /*
2243d3b52f2SJoe Hershberger  * Compare an existing entry with the desired key, and overwrite if the action
2253d3b52f2SJoe Hershberger  * is ENTER.  This is simply a helper function for hsearch_r().
2263d3b52f2SJoe Hershberger  */
_compare_and_overwrite_entry(ENTRY item,ACTION action,ENTRY ** retval,struct hsearch_data * htab,int flag,unsigned int hval,unsigned int idx)2273d3b52f2SJoe Hershberger static inline int _compare_and_overwrite_entry(ENTRY item, ACTION action,
2283d3b52f2SJoe Hershberger 	ENTRY **retval, struct hsearch_data *htab, int flag,
2293d3b52f2SJoe Hershberger 	unsigned int hval, unsigned int idx)
2303d3b52f2SJoe Hershberger {
2313d3b52f2SJoe Hershberger 	if (htab->table[idx].used == hval
2323d3b52f2SJoe Hershberger 	    && strcmp(item.key, htab->table[idx].entry.key) == 0) {
2333d3b52f2SJoe Hershberger 		/* Overwrite existing value? */
2343d3b52f2SJoe Hershberger 		if ((action == ENTER) && (item.data != NULL)) {
2357afcf3a5SJoe Hershberger 			/* check for permission */
2367afcf3a5SJoe Hershberger 			if (htab->change_ok != NULL && htab->change_ok(
2377afcf3a5SJoe Hershberger 			    &htab->table[idx].entry, item.data,
2387afcf3a5SJoe Hershberger 			    env_op_overwrite, flag)) {
2397afcf3a5SJoe Hershberger 				debug("change_ok() rejected setting variable "
2407afcf3a5SJoe Hershberger 					"%s, skipping it!\n", item.key);
2417afcf3a5SJoe Hershberger 				__set_errno(EPERM);
2427afcf3a5SJoe Hershberger 				*retval = NULL;
2437afcf3a5SJoe Hershberger 				return 0;
2447afcf3a5SJoe Hershberger 			}
2457afcf3a5SJoe Hershberger 
246170ab110SJoe Hershberger 			/* If there is a callback, call it */
247170ab110SJoe Hershberger 			if (htab->table[idx].entry.callback &&
248170ab110SJoe Hershberger 			    htab->table[idx].entry.callback(item.key,
249170ab110SJoe Hershberger 			    item.data, env_op_overwrite, flag)) {
250170ab110SJoe Hershberger 				debug("callback() rejected setting variable "
251170ab110SJoe Hershberger 					"%s, skipping it!\n", item.key);
252170ab110SJoe Hershberger 				__set_errno(EINVAL);
253170ab110SJoe Hershberger 				*retval = NULL;
254170ab110SJoe Hershberger 				return 0;
255170ab110SJoe Hershberger 			}
256170ab110SJoe Hershberger 
2573d3b52f2SJoe Hershberger 			free(htab->table[idx].entry.data);
2583d3b52f2SJoe Hershberger 			htab->table[idx].entry.data = strdup(item.data);
2593d3b52f2SJoe Hershberger 			if (!htab->table[idx].entry.data) {
2603d3b52f2SJoe Hershberger 				__set_errno(ENOMEM);
2613d3b52f2SJoe Hershberger 				*retval = NULL;
2623d3b52f2SJoe Hershberger 				return 0;
2633d3b52f2SJoe Hershberger 			}
2643d3b52f2SJoe Hershberger 		}
2653d3b52f2SJoe Hershberger 		/* return found entry */
2663d3b52f2SJoe Hershberger 		*retval = &htab->table[idx].entry;
2673d3b52f2SJoe Hershberger 		return idx;
2683d3b52f2SJoe Hershberger 	}
2693d3b52f2SJoe Hershberger 	/* keep searching */
2703d3b52f2SJoe Hershberger 	return -1;
2713d3b52f2SJoe Hershberger }
2723d3b52f2SJoe Hershberger 
hsearch_r(ENTRY item,ACTION action,ENTRY ** retval,struct hsearch_data * htab,int flag)273a6826fbcSWolfgang Denk int hsearch_r(ENTRY item, ACTION action, ENTRY ** retval,
274c4e0057fSJoe Hershberger 	      struct hsearch_data *htab, int flag)
275a6826fbcSWolfgang Denk {
276a6826fbcSWolfgang Denk 	unsigned int hval;
277a6826fbcSWolfgang Denk 	unsigned int count;
278a6826fbcSWolfgang Denk 	unsigned int len = strlen(item.key);
279a6826fbcSWolfgang Denk 	unsigned int idx;
280c81c1222SPeter Barada 	unsigned int first_deleted = 0;
2813d3b52f2SJoe Hershberger 	int ret;
282a6826fbcSWolfgang Denk 
283a6826fbcSWolfgang Denk 	/* Compute an value for the given string. Perhaps use a better method. */
284a6826fbcSWolfgang Denk 	hval = len;
285a6826fbcSWolfgang Denk 	count = len;
286a6826fbcSWolfgang Denk 	while (count-- > 0) {
287a6826fbcSWolfgang Denk 		hval <<= 4;
288a6826fbcSWolfgang Denk 		hval += item.key[count];
289a6826fbcSWolfgang Denk 	}
290a6826fbcSWolfgang Denk 
291a6826fbcSWolfgang Denk 	/*
292a6826fbcSWolfgang Denk 	 * First hash function:
293a6826fbcSWolfgang Denk 	 * simply take the modul but prevent zero.
294a6826fbcSWolfgang Denk 	 */
295a6826fbcSWolfgang Denk 	hval %= htab->size;
296a6826fbcSWolfgang Denk 	if (hval == 0)
297a6826fbcSWolfgang Denk 		++hval;
298a6826fbcSWolfgang Denk 
299a6826fbcSWolfgang Denk 	/* The first index tried. */
300a6826fbcSWolfgang Denk 	idx = hval;
301a6826fbcSWolfgang Denk 
302a6826fbcSWolfgang Denk 	if (htab->table[idx].used) {
303a6826fbcSWolfgang Denk 		/*
304a6826fbcSWolfgang Denk 		 * Further action might be required according to the
305a6826fbcSWolfgang Denk 		 * action value.
306a6826fbcSWolfgang Denk 		 */
307a6826fbcSWolfgang Denk 		unsigned hval2;
308a6826fbcSWolfgang Denk 
309*9dfdbd9fSRoman Kapl 		if (htab->table[idx].used == USED_DELETED
310c81c1222SPeter Barada 		    && !first_deleted)
311c81c1222SPeter Barada 			first_deleted = idx;
312c81c1222SPeter Barada 
3133d3b52f2SJoe Hershberger 		ret = _compare_and_overwrite_entry(item, action, retval, htab,
3143d3b52f2SJoe Hershberger 			flag, hval, idx);
3153d3b52f2SJoe Hershberger 		if (ret != -1)
3163d3b52f2SJoe Hershberger 			return ret;
317a6826fbcSWolfgang Denk 
318a6826fbcSWolfgang Denk 		/*
319a6826fbcSWolfgang Denk 		 * Second hash function:
320a6826fbcSWolfgang Denk 		 * as suggested in [Knuth]
321a6826fbcSWolfgang Denk 		 */
322a6826fbcSWolfgang Denk 		hval2 = 1 + hval % (htab->size - 2);
323a6826fbcSWolfgang Denk 
324a6826fbcSWolfgang Denk 		do {
325a6826fbcSWolfgang Denk 			/*
326a6826fbcSWolfgang Denk 			 * Because SIZE is prime this guarantees to
327a6826fbcSWolfgang Denk 			 * step through all available indices.
328a6826fbcSWolfgang Denk 			 */
329a6826fbcSWolfgang Denk 			if (idx <= hval2)
330a6826fbcSWolfgang Denk 				idx = htab->size + idx - hval2;
331a6826fbcSWolfgang Denk 			else
332a6826fbcSWolfgang Denk 				idx -= hval2;
333a6826fbcSWolfgang Denk 
334a6826fbcSWolfgang Denk 			/*
335a6826fbcSWolfgang Denk 			 * If we visited all entries leave the loop
336a6826fbcSWolfgang Denk 			 * unsuccessfully.
337a6826fbcSWolfgang Denk 			 */
338a6826fbcSWolfgang Denk 			if (idx == hval)
339a6826fbcSWolfgang Denk 				break;
340a6826fbcSWolfgang Denk 
341*9dfdbd9fSRoman Kapl 			if (htab->table[idx].used == USED_DELETED
342*9dfdbd9fSRoman Kapl 			    && !first_deleted)
343*9dfdbd9fSRoman Kapl 				first_deleted = idx;
344*9dfdbd9fSRoman Kapl 
345a6826fbcSWolfgang Denk 			/* If entry is found use it. */
3463d3b52f2SJoe Hershberger 			ret = _compare_and_overwrite_entry(item, action, retval,
3473d3b52f2SJoe Hershberger 				htab, flag, hval, idx);
3483d3b52f2SJoe Hershberger 			if (ret != -1)
3493d3b52f2SJoe Hershberger 				return ret;
350a6826fbcSWolfgang Denk 		}
351*9dfdbd9fSRoman Kapl 		while (htab->table[idx].used != USED_FREE);
352a6826fbcSWolfgang Denk 	}
353a6826fbcSWolfgang Denk 
354a6826fbcSWolfgang Denk 	/* An empty bucket has been found. */
355a6826fbcSWolfgang Denk 	if (action == ENTER) {
356a6826fbcSWolfgang Denk 		/*
357a6826fbcSWolfgang Denk 		 * If table is full and another entry should be
358a6826fbcSWolfgang Denk 		 * entered return with error.
359a6826fbcSWolfgang Denk 		 */
360a6826fbcSWolfgang Denk 		if (htab->filled == htab->size) {
361a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
362a6826fbcSWolfgang Denk 			*retval = NULL;
363a6826fbcSWolfgang Denk 			return 0;
364a6826fbcSWolfgang Denk 		}
365a6826fbcSWolfgang Denk 
366a6826fbcSWolfgang Denk 		/*
367a6826fbcSWolfgang Denk 		 * Create new entry;
368a6826fbcSWolfgang Denk 		 * create copies of item.key and item.data
369a6826fbcSWolfgang Denk 		 */
370c81c1222SPeter Barada 		if (first_deleted)
371c81c1222SPeter Barada 			idx = first_deleted;
372c81c1222SPeter Barada 
373a6826fbcSWolfgang Denk 		htab->table[idx].used = hval;
374a6826fbcSWolfgang Denk 		htab->table[idx].entry.key = strdup(item.key);
375a6826fbcSWolfgang Denk 		htab->table[idx].entry.data = strdup(item.data);
376a6826fbcSWolfgang Denk 		if (!htab->table[idx].entry.key ||
377a6826fbcSWolfgang Denk 		    !htab->table[idx].entry.data) {
378a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
379a6826fbcSWolfgang Denk 			*retval = NULL;
380a6826fbcSWolfgang Denk 			return 0;
381a6826fbcSWolfgang Denk 		}
382a6826fbcSWolfgang Denk 
383a6826fbcSWolfgang Denk 		++htab->filled;
384a6826fbcSWolfgang Denk 
385170ab110SJoe Hershberger 		/* This is a new entry, so look up a possible callback */
386170ab110SJoe Hershberger 		env_callback_init(&htab->table[idx].entry);
3872598090bSJoe Hershberger 		/* Also look for flags */
3882598090bSJoe Hershberger 		env_flags_init(&htab->table[idx].entry);
389170ab110SJoe Hershberger 
3907afcf3a5SJoe Hershberger 		/* check for permission */
3917afcf3a5SJoe Hershberger 		if (htab->change_ok != NULL && htab->change_ok(
3927afcf3a5SJoe Hershberger 		    &htab->table[idx].entry, item.data, env_op_create, flag)) {
3937afcf3a5SJoe Hershberger 			debug("change_ok() rejected setting variable "
3947afcf3a5SJoe Hershberger 				"%s, skipping it!\n", item.key);
3957afcf3a5SJoe Hershberger 			_hdelete(item.key, htab, &htab->table[idx].entry, idx);
3967afcf3a5SJoe Hershberger 			__set_errno(EPERM);
3977afcf3a5SJoe Hershberger 			*retval = NULL;
3987afcf3a5SJoe Hershberger 			return 0;
3997afcf3a5SJoe Hershberger 		}
4007afcf3a5SJoe Hershberger 
401170ab110SJoe Hershberger 		/* If there is a callback, call it */
402170ab110SJoe Hershberger 		if (htab->table[idx].entry.callback &&
403170ab110SJoe Hershberger 		    htab->table[idx].entry.callback(item.key, item.data,
404170ab110SJoe Hershberger 		    env_op_create, flag)) {
405170ab110SJoe Hershberger 			debug("callback() rejected setting variable "
406170ab110SJoe Hershberger 				"%s, skipping it!\n", item.key);
407170ab110SJoe Hershberger 			_hdelete(item.key, htab, &htab->table[idx].entry, idx);
408170ab110SJoe Hershberger 			__set_errno(EINVAL);
409170ab110SJoe Hershberger 			*retval = NULL;
410170ab110SJoe Hershberger 			return 0;
411170ab110SJoe Hershberger 		}
412170ab110SJoe Hershberger 
413a6826fbcSWolfgang Denk 		/* return new entry */
414a6826fbcSWolfgang Denk 		*retval = &htab->table[idx].entry;
415a6826fbcSWolfgang Denk 		return 1;
416a6826fbcSWolfgang Denk 	}
417a6826fbcSWolfgang Denk 
418a6826fbcSWolfgang Denk 	__set_errno(ESRCH);
419a6826fbcSWolfgang Denk 	*retval = NULL;
420a6826fbcSWolfgang Denk 	return 0;
421a6826fbcSWolfgang Denk }
422a6826fbcSWolfgang Denk 
423a6826fbcSWolfgang Denk 
424a6826fbcSWolfgang Denk /*
425a6826fbcSWolfgang Denk  * hdelete()
426a6826fbcSWolfgang Denk  */
427a6826fbcSWolfgang Denk 
428a6826fbcSWolfgang Denk /*
429a6826fbcSWolfgang Denk  * The standard implementation of hsearch(3) does not provide any way
430a6826fbcSWolfgang Denk  * to delete any entries from the hash table.  We extend the code to
431a6826fbcSWolfgang Denk  * do that.
432a6826fbcSWolfgang Denk  */
433a6826fbcSWolfgang Denk 
_hdelete(const char * key,struct hsearch_data * htab,ENTRY * ep,int idx)4347afcf3a5SJoe Hershberger static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
4357afcf3a5SJoe Hershberger 	int idx)
4367afcf3a5SJoe Hershberger {
4377afcf3a5SJoe Hershberger 	/* free used ENTRY */
4387afcf3a5SJoe Hershberger 	debug("hdelete: DELETING key \"%s\"\n", key);
4397afcf3a5SJoe Hershberger 	free((void *)ep->key);
4407afcf3a5SJoe Hershberger 	free(ep->data);
441170ab110SJoe Hershberger 	ep->callback = NULL;
4422598090bSJoe Hershberger 	ep->flags = 0;
443*9dfdbd9fSRoman Kapl 	htab->table[idx].used = USED_DELETED;
4447afcf3a5SJoe Hershberger 
4457afcf3a5SJoe Hershberger 	--htab->filled;
4467afcf3a5SJoe Hershberger }
4477afcf3a5SJoe Hershberger 
hdelete_r(const char * key,struct hsearch_data * htab,int flag)448c4e0057fSJoe Hershberger int hdelete_r(const char *key, struct hsearch_data *htab, int flag)
449a6826fbcSWolfgang Denk {
450a6826fbcSWolfgang Denk 	ENTRY e, *ep;
451a6826fbcSWolfgang Denk 	int idx;
452a6826fbcSWolfgang Denk 
453a6826fbcSWolfgang Denk 	debug("hdelete: DELETE key \"%s\"\n", key);
454a6826fbcSWolfgang Denk 
455a6826fbcSWolfgang Denk 	e.key = (char *)key;
456a6826fbcSWolfgang Denk 
457c4e0057fSJoe Hershberger 	idx = hsearch_r(e, FIND, &ep, htab, 0);
458c4e0057fSJoe Hershberger 	if (idx == 0) {
459a6826fbcSWolfgang Denk 		__set_errno(ESRCH);
460a6826fbcSWolfgang Denk 		return 0;	/* not found */
461a6826fbcSWolfgang Denk 	}
462a6826fbcSWolfgang Denk 
463c4e0057fSJoe Hershberger 	/* Check for permission */
4647afcf3a5SJoe Hershberger 	if (htab->change_ok != NULL &&
4657afcf3a5SJoe Hershberger 	    htab->change_ok(ep, NULL, env_op_delete, flag)) {
4667afcf3a5SJoe Hershberger 		debug("change_ok() rejected deleting variable "
4677afcf3a5SJoe Hershberger 			"%s, skipping it!\n", key);
468c4e0057fSJoe Hershberger 		__set_errno(EPERM);
469c4e0057fSJoe Hershberger 		return 0;
470c4e0057fSJoe Hershberger 	}
471c4e0057fSJoe Hershberger 
472170ab110SJoe Hershberger 	/* If there is a callback, call it */
473170ab110SJoe Hershberger 	if (htab->table[idx].entry.callback &&
474170ab110SJoe Hershberger 	    htab->table[idx].entry.callback(key, NULL, env_op_delete, flag)) {
475170ab110SJoe Hershberger 		debug("callback() rejected deleting variable "
476170ab110SJoe Hershberger 			"%s, skipping it!\n", key);
477170ab110SJoe Hershberger 		__set_errno(EINVAL);
478170ab110SJoe Hershberger 		return 0;
479170ab110SJoe Hershberger 	}
480170ab110SJoe Hershberger 
4817afcf3a5SJoe Hershberger 	_hdelete(key, htab, ep, idx);
482a6826fbcSWolfgang Denk 
483a6826fbcSWolfgang Denk 	return 1;
484a6826fbcSWolfgang Denk }
485a6826fbcSWolfgang Denk 
486d2d9bdfcSB, Ravi #if !(defined(CONFIG_SPL_BUILD) && !defined(CONFIG_SPL_SAVEENV))
487a6826fbcSWolfgang Denk /*
488a6826fbcSWolfgang Denk  * hexport()
489a6826fbcSWolfgang Denk  */
490a6826fbcSWolfgang Denk 
491a6826fbcSWolfgang Denk /*
492a6826fbcSWolfgang Denk  * Export the data stored in the hash table in linearized form.
493a6826fbcSWolfgang Denk  *
494a6826fbcSWolfgang Denk  * Entries are exported as "name=value" strings, separated by an
495a6826fbcSWolfgang Denk  * arbitrary (non-NUL, of course) separator character. This allows to
496a6826fbcSWolfgang Denk  * use this function both when formatting the U-Boot environment for
497a6826fbcSWolfgang Denk  * external storage (using '\0' as separator), but also when using it
498a6826fbcSWolfgang Denk  * for the "printenv" command to print all variables, simply by using
499a6826fbcSWolfgang Denk  * as '\n" as separator. This can also be used for new features like
500a6826fbcSWolfgang Denk  * exporting the environment data as text file, including the option
501a6826fbcSWolfgang Denk  * for later re-import.
502a6826fbcSWolfgang Denk  *
503a6826fbcSWolfgang Denk  * The entries in the result list will be sorted by ascending key
504a6826fbcSWolfgang Denk  * values.
505a6826fbcSWolfgang Denk  *
506a6826fbcSWolfgang Denk  * If the separator character is different from NUL, then any
507a6826fbcSWolfgang Denk  * separator characters and backslash characters in the values will
508fc0b5948SRobert P. J. Day  * be escaped by a preceding backslash in output. This is needed for
509a6826fbcSWolfgang Denk  * example to enable multi-line values, especially when the output
510a6826fbcSWolfgang Denk  * shall later be parsed (for example, for re-import).
511a6826fbcSWolfgang Denk  *
512a6826fbcSWolfgang Denk  * There are several options how the result buffer is handled:
513a6826fbcSWolfgang Denk  *
514a6826fbcSWolfgang Denk  * *resp  size
515a6826fbcSWolfgang Denk  * -----------
516a6826fbcSWolfgang Denk  *  NULL    0	A string of sufficient length will be allocated.
517a6826fbcSWolfgang Denk  *  NULL   >0	A string of the size given will be
518a6826fbcSWolfgang Denk  *		allocated. An error will be returned if the size is
519a6826fbcSWolfgang Denk  *		not sufficient.  Any unused bytes in the string will
520a6826fbcSWolfgang Denk  *		be '\0'-padded.
521a6826fbcSWolfgang Denk  * !NULL    0	The user-supplied buffer will be used. No length
522a6826fbcSWolfgang Denk  *		checking will be performed, i. e. it is assumed that
523a6826fbcSWolfgang Denk  *		the buffer size will always be big enough. DANGEROUS.
524a6826fbcSWolfgang Denk  * !NULL   >0	The user-supplied buffer will be used. An error will
525a6826fbcSWolfgang Denk  *		be returned if the size is not sufficient.  Any unused
526a6826fbcSWolfgang Denk  *		bytes in the string will be '\0'-padded.
527a6826fbcSWolfgang Denk  */
528a6826fbcSWolfgang Denk 
cmpkey(const void * p1,const void * p2)529a6826fbcSWolfgang Denk static int cmpkey(const void *p1, const void *p2)
530a6826fbcSWolfgang Denk {
531a6826fbcSWolfgang Denk 	ENTRY *e1 = *(ENTRY **) p1;
532a6826fbcSWolfgang Denk 	ENTRY *e2 = *(ENTRY **) p2;
533a6826fbcSWolfgang Denk 
534a6826fbcSWolfgang Denk 	return (strcmp(e1->key, e2->key));
535a6826fbcSWolfgang Denk }
536a6826fbcSWolfgang Denk 
match_string(int flag,const char * str,const char * pat,void * priv)537be29df6aSWolfgang Denk static int match_string(int flag, const char *str, const char *pat, void *priv)
538ea009d47SWolfgang Denk {
539ea009d47SWolfgang Denk 	switch (flag & H_MATCH_METHOD) {
540ea009d47SWolfgang Denk 	case H_MATCH_IDENT:
5415a31ea04SWolfgang Denk 		if (strcmp(str, pat) == 0)
5425a31ea04SWolfgang Denk 			return 1;
5435a31ea04SWolfgang Denk 		break;
5445a31ea04SWolfgang Denk 	case H_MATCH_SUBSTR:
5455a31ea04SWolfgang Denk 		if (strstr(str, pat))
546ea009d47SWolfgang Denk 			return 1;
547ea009d47SWolfgang Denk 		break;
548be29df6aSWolfgang Denk #ifdef CONFIG_REGEX
549be29df6aSWolfgang Denk 	case H_MATCH_REGEX:
550be29df6aSWolfgang Denk 		{
551be29df6aSWolfgang Denk 			struct slre *slrep = (struct slre *)priv;
552be29df6aSWolfgang Denk 
553320194aeSHeinrich Schuchardt 			if (slre_match(slrep, str, strlen(str), NULL))
554be29df6aSWolfgang Denk 				return 1;
555be29df6aSWolfgang Denk 		}
556be29df6aSWolfgang Denk 		break;
557be29df6aSWolfgang Denk #endif
558ea009d47SWolfgang Denk 	default:
559ea009d47SWolfgang Denk 		printf("## ERROR: unsupported match method: 0x%02x\n",
560ea009d47SWolfgang Denk 			flag & H_MATCH_METHOD);
561ea009d47SWolfgang Denk 		break;
562ea009d47SWolfgang Denk 	}
5635a31ea04SWolfgang Denk 	return 0;
5645a31ea04SWolfgang Denk }
5655a31ea04SWolfgang Denk 
match_entry(ENTRY * ep,int flag,int argc,char * const argv[])5665a31ea04SWolfgang Denk static int match_entry(ENTRY *ep, int flag,
5675a31ea04SWolfgang Denk 		 int argc, char * const argv[])
5685a31ea04SWolfgang Denk {
5695a31ea04SWolfgang Denk 	int arg;
570be29df6aSWolfgang Denk 	void *priv = NULL;
5715a31ea04SWolfgang Denk 
5729a832331SPierre Aubert 	for (arg = 0; arg < argc; ++arg) {
573be29df6aSWolfgang Denk #ifdef CONFIG_REGEX
574be29df6aSWolfgang Denk 		struct slre slre;
575be29df6aSWolfgang Denk 
576be29df6aSWolfgang Denk 		if (slre_compile(&slre, argv[arg]) == 0) {
577be29df6aSWolfgang Denk 			printf("Error compiling regex: %s\n", slre.err_str);
578be29df6aSWolfgang Denk 			return 0;
579be29df6aSWolfgang Denk 		}
580be29df6aSWolfgang Denk 
581be29df6aSWolfgang Denk 		priv = (void *)&slre;
582be29df6aSWolfgang Denk #endif
5835a31ea04SWolfgang Denk 		if (flag & H_MATCH_KEY) {
584be29df6aSWolfgang Denk 			if (match_string(flag, ep->key, argv[arg], priv))
5855a31ea04SWolfgang Denk 				return 1;
5865a31ea04SWolfgang Denk 		}
5875a31ea04SWolfgang Denk 		if (flag & H_MATCH_DATA) {
588be29df6aSWolfgang Denk 			if (match_string(flag, ep->data, argv[arg], priv))
5895a31ea04SWolfgang Denk 				return 1;
590ea009d47SWolfgang Denk 		}
591ea009d47SWolfgang Denk 	}
592ea009d47SWolfgang Denk 	return 0;
593ea009d47SWolfgang Denk }
594ea009d47SWolfgang Denk 
hexport_r(struct hsearch_data * htab,const char sep,int flag,char ** resp,size_t size,int argc,char * const argv[])595be11235aSJoe Hershberger ssize_t hexport_r(struct hsearch_data *htab, const char sep, int flag,
59637f2fe74SWolfgang Denk 		 char **resp, size_t size,
59737f2fe74SWolfgang Denk 		 int argc, char * const argv[])
598a6826fbcSWolfgang Denk {
599a6826fbcSWolfgang Denk 	ENTRY *list[htab->size];
600a6826fbcSWolfgang Denk 	char *res, *p;
601a6826fbcSWolfgang Denk 	size_t totlen;
602a6826fbcSWolfgang Denk 	int i, n;
603a6826fbcSWolfgang Denk 
604a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
605a6826fbcSWolfgang Denk 	if ((resp == NULL) || (htab == NULL)) {
606a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
607a6826fbcSWolfgang Denk 		return (-1);
608a6826fbcSWolfgang Denk 	}
609a6826fbcSWolfgang Denk 
610c55d02b2SSimon Glass 	debug("EXPORT  table = %p, htab.size = %d, htab.filled = %d, size = %lu\n",
611c55d02b2SSimon Glass 	      htab, htab->size, htab->filled, (ulong)size);
612a6826fbcSWolfgang Denk 	/*
613a6826fbcSWolfgang Denk 	 * Pass 1:
614a6826fbcSWolfgang Denk 	 * search used entries,
615a6826fbcSWolfgang Denk 	 * save addresses and compute total length
616a6826fbcSWolfgang Denk 	 */
617a6826fbcSWolfgang Denk 	for (i = 1, n = 0, totlen = 0; i <= htab->size; ++i) {
618a6826fbcSWolfgang Denk 
619c81c1222SPeter Barada 		if (htab->table[i].used > 0) {
620a6826fbcSWolfgang Denk 			ENTRY *ep = &htab->table[i].entry;
6215a31ea04SWolfgang Denk 			int found = match_entry(ep, flag, argc, argv);
62237f2fe74SWolfgang Denk 
62337f2fe74SWolfgang Denk 			if ((argc > 0) && (found == 0))
62437f2fe74SWolfgang Denk 				continue;
625a6826fbcSWolfgang Denk 
626be11235aSJoe Hershberger 			if ((flag & H_HIDE_DOT) && ep->key[0] == '.')
627be11235aSJoe Hershberger 				continue;
628be11235aSJoe Hershberger 
629a6826fbcSWolfgang Denk 			list[n++] = ep;
630a6826fbcSWolfgang Denk 
631f1b20acbSZubair Lutfullah Kakakhel 			totlen += strlen(ep->key);
632a6826fbcSWolfgang Denk 
633a6826fbcSWolfgang Denk 			if (sep == '\0') {
634a6826fbcSWolfgang Denk 				totlen += strlen(ep->data);
635a6826fbcSWolfgang Denk 			} else {	/* check if escapes are needed */
636a6826fbcSWolfgang Denk 				char *s = ep->data;
637a6826fbcSWolfgang Denk 
638a6826fbcSWolfgang Denk 				while (*s) {
639a6826fbcSWolfgang Denk 					++totlen;
640a6826fbcSWolfgang Denk 					/* add room for needed escape chars */
641a6826fbcSWolfgang Denk 					if ((*s == sep) || (*s == '\\'))
642a6826fbcSWolfgang Denk 						++totlen;
643a6826fbcSWolfgang Denk 					++s;
644a6826fbcSWolfgang Denk 				}
645a6826fbcSWolfgang Denk 			}
646a6826fbcSWolfgang Denk 			totlen += 2;	/* for '=' and 'sep' char */
647a6826fbcSWolfgang Denk 		}
648a6826fbcSWolfgang Denk 	}
649a6826fbcSWolfgang Denk 
650a6826fbcSWolfgang Denk #ifdef DEBUG
651a6826fbcSWolfgang Denk 	/* Pass 1a: print unsorted list */
652a6826fbcSWolfgang Denk 	printf("Unsorted: n=%d\n", n);
653a6826fbcSWolfgang Denk 	for (i = 0; i < n; ++i) {
654a6826fbcSWolfgang Denk 		printf("\t%3d: %p ==> %-10s => %s\n",
655a6826fbcSWolfgang Denk 		       i, list[i], list[i]->key, list[i]->data);
656a6826fbcSWolfgang Denk 	}
657a6826fbcSWolfgang Denk #endif
658a6826fbcSWolfgang Denk 
659a6826fbcSWolfgang Denk 	/* Sort list by keys */
660a6826fbcSWolfgang Denk 	qsort(list, n, sizeof(ENTRY *), cmpkey);
661a6826fbcSWolfgang Denk 
662a6826fbcSWolfgang Denk 	/* Check if the user supplied buffer size is sufficient */
663a6826fbcSWolfgang Denk 	if (size) {
664a6826fbcSWolfgang Denk 		if (size < totlen + 1) {	/* provided buffer too small */
665c55d02b2SSimon Glass 			printf("Env export buffer too small: %lu, but need %lu\n",
666c55d02b2SSimon Glass 			       (ulong)size, (ulong)totlen + 1);
667a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
668a6826fbcSWolfgang Denk 			return (-1);
669a6826fbcSWolfgang Denk 		}
670a6826fbcSWolfgang Denk 	} else {
6714bca3249SAKASHI Takahiro 		size = totlen + 1;
672a6826fbcSWolfgang Denk 	}
673a6826fbcSWolfgang Denk 
674a6826fbcSWolfgang Denk 	/* Check if the user provided a buffer */
675a6826fbcSWolfgang Denk 	if (*resp) {
676a6826fbcSWolfgang Denk 		/* yes; clear it */
677a6826fbcSWolfgang Denk 		res = *resp;
678a6826fbcSWolfgang Denk 		memset(res, '\0', size);
679a6826fbcSWolfgang Denk 	} else {
680a6826fbcSWolfgang Denk 		/* no, allocate and clear one */
681a6826fbcSWolfgang Denk 		*resp = res = calloc(1, size);
682a6826fbcSWolfgang Denk 		if (res == NULL) {
683a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
684a6826fbcSWolfgang Denk 			return (-1);
685a6826fbcSWolfgang Denk 		}
686a6826fbcSWolfgang Denk 	}
687a6826fbcSWolfgang Denk 	/*
688a6826fbcSWolfgang Denk 	 * Pass 2:
689a6826fbcSWolfgang Denk 	 * export sorted list of result data
690a6826fbcSWolfgang Denk 	 */
691a6826fbcSWolfgang Denk 	for (i = 0, p = res; i < n; ++i) {
69284b5e802SWolfgang Denk 		const char *s;
693a6826fbcSWolfgang Denk 
694a6826fbcSWolfgang Denk 		s = list[i]->key;
695a6826fbcSWolfgang Denk 		while (*s)
696a6826fbcSWolfgang Denk 			*p++ = *s++;
697a6826fbcSWolfgang Denk 		*p++ = '=';
698a6826fbcSWolfgang Denk 
699a6826fbcSWolfgang Denk 		s = list[i]->data;
700a6826fbcSWolfgang Denk 
701a6826fbcSWolfgang Denk 		while (*s) {
702a6826fbcSWolfgang Denk 			if ((*s == sep) || (*s == '\\'))
703a6826fbcSWolfgang Denk 				*p++ = '\\';	/* escape */
704a6826fbcSWolfgang Denk 			*p++ = *s++;
705a6826fbcSWolfgang Denk 		}
706a6826fbcSWolfgang Denk 		*p++ = sep;
707a6826fbcSWolfgang Denk 	}
708a6826fbcSWolfgang Denk 	*p = '\0';		/* terminate result */
709a6826fbcSWolfgang Denk 
710a6826fbcSWolfgang Denk 	return size;
711a6826fbcSWolfgang Denk }
7127ac2fe2dSIlya Yanok #endif
713a6826fbcSWolfgang Denk 
714a6826fbcSWolfgang Denk 
715a6826fbcSWolfgang Denk /*
716a6826fbcSWolfgang Denk  * himport()
717a6826fbcSWolfgang Denk  */
718a6826fbcSWolfgang Denk 
719d5370febSGerlando Falauto /*
720d5370febSGerlando Falauto  * Check whether variable 'name' is amongst vars[],
721d5370febSGerlando Falauto  * and remove all instances by setting the pointer to NULL
722d5370febSGerlando Falauto  */
drop_var_from_set(const char * name,int nvars,char * vars[])723d5370febSGerlando Falauto static int drop_var_from_set(const char *name, int nvars, char * vars[])
724348b1f1cSGerlando Falauto {
725348b1f1cSGerlando Falauto 	int i = 0;
726d5370febSGerlando Falauto 	int res = 0;
727348b1f1cSGerlando Falauto 
728348b1f1cSGerlando Falauto 	/* No variables specified means process all of them */
729348b1f1cSGerlando Falauto 	if (nvars == 0)
730348b1f1cSGerlando Falauto 		return 1;
731348b1f1cSGerlando Falauto 
732348b1f1cSGerlando Falauto 	for (i = 0; i < nvars; i++) {
733d5370febSGerlando Falauto 		if (vars[i] == NULL)
734d5370febSGerlando Falauto 			continue;
735d5370febSGerlando Falauto 		/* If we found it, delete all of them */
736d5370febSGerlando Falauto 		if (!strcmp(name, vars[i])) {
737d5370febSGerlando Falauto 			vars[i] = NULL;
738d5370febSGerlando Falauto 			res = 1;
739348b1f1cSGerlando Falauto 		}
740d5370febSGerlando Falauto 	}
741d5370febSGerlando Falauto 	if (!res)
742348b1f1cSGerlando Falauto 		debug("Skipping non-listed variable %s\n", name);
743348b1f1cSGerlando Falauto 
744d5370febSGerlando Falauto 	return res;
745348b1f1cSGerlando Falauto }
746348b1f1cSGerlando Falauto 
747a6826fbcSWolfgang Denk /*
748a6826fbcSWolfgang Denk  * Import linearized data into hash table.
749a6826fbcSWolfgang Denk  *
750a6826fbcSWolfgang Denk  * This is the inverse function to hexport(): it takes a linear list
751a6826fbcSWolfgang Denk  * of "name=value" pairs and creates hash table entries from it.
752a6826fbcSWolfgang Denk  *
753a6826fbcSWolfgang Denk  * Entries without "value", i. e. consisting of only "name" or
754a6826fbcSWolfgang Denk  * "name=", will cause this entry to be deleted from the hash table.
755a6826fbcSWolfgang Denk  *
756a6826fbcSWolfgang Denk  * The "flag" argument can be used to control the behaviour: when the
757a6826fbcSWolfgang Denk  * H_NOCLEAR bit is set, then an existing hash table will kept, i. e.
758d9fc9077SQuentin Schulz  * new data will be added to an existing hash table; otherwise, if no
759d9fc9077SQuentin Schulz  * vars are passed, old data will be discarded and a new hash table
760d9fc9077SQuentin Schulz  * will be created. If vars are passed, passed vars that are not in
761d9fc9077SQuentin Schulz  * the linear list of "name=value" pairs will be removed from the
762d9fc9077SQuentin Schulz  * current hash table.
763a6826fbcSWolfgang Denk  *
764a6826fbcSWolfgang Denk  * The separator character for the "name=value" pairs can be selected,
765a6826fbcSWolfgang Denk  * so we both support importing from externally stored environment
766a6826fbcSWolfgang Denk  * data (separated by NUL characters) and from plain text files
767a6826fbcSWolfgang Denk  * (entries separated by newline characters).
768a6826fbcSWolfgang Denk  *
769a6826fbcSWolfgang Denk  * To allow for nicely formatted text input, leading white space
770a6826fbcSWolfgang Denk  * (sequences of SPACE and TAB chars) is ignored, and entries starting
771a6826fbcSWolfgang Denk  * (after removal of any leading white space) with a '#' character are
772a6826fbcSWolfgang Denk  * considered comments and ignored.
773a6826fbcSWolfgang Denk  *
774a6826fbcSWolfgang Denk  * [NOTE: this means that a variable name cannot start with a '#'
775a6826fbcSWolfgang Denk  * character.]
776a6826fbcSWolfgang Denk  *
777a6826fbcSWolfgang Denk  * When using a non-NUL separator character, backslash is used as
778a6826fbcSWolfgang Denk  * escape character in the value part, allowing for example for
779a6826fbcSWolfgang Denk  * multi-line values.
780a6826fbcSWolfgang Denk  *
781a6826fbcSWolfgang Denk  * In theory, arbitrary separator characters can be used, but only
782a6826fbcSWolfgang Denk  * '\0' and '\n' have really been tested.
783a6826fbcSWolfgang Denk  */
784a6826fbcSWolfgang Denk 
himport_r(struct hsearch_data * htab,const char * env,size_t size,const char sep,int flag,int crlf_is_lf,int nvars,char * const vars[])785a6826fbcSWolfgang Denk int himport_r(struct hsearch_data *htab,
786348b1f1cSGerlando Falauto 		const char *env, size_t size, const char sep, int flag,
787ecd1446fSAlexander Holler 		int crlf_is_lf, int nvars, char * const vars[])
788a6826fbcSWolfgang Denk {
789a6826fbcSWolfgang Denk 	char *data, *sp, *dp, *name, *value;
790d5370febSGerlando Falauto 	char *localvars[nvars];
791d5370febSGerlando Falauto 	int i;
792a6826fbcSWolfgang Denk 
793a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
794a6826fbcSWolfgang Denk 	if (htab == NULL) {
795a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
796a6826fbcSWolfgang Denk 		return 0;
797a6826fbcSWolfgang Denk 	}
798a6826fbcSWolfgang Denk 
799a6826fbcSWolfgang Denk 	/* we allocate new space to make sure we can write to the array */
800817e48d8SLukasz Majewski 	if ((data = malloc(size + 1)) == NULL) {
801c55d02b2SSimon Glass 		debug("himport_r: can't malloc %lu bytes\n", (ulong)size + 1);
802a6826fbcSWolfgang Denk 		__set_errno(ENOMEM);
803a6826fbcSWolfgang Denk 		return 0;
804a6826fbcSWolfgang Denk 	}
805a6826fbcSWolfgang Denk 	memcpy(data, env, size);
806817e48d8SLukasz Majewski 	data[size] = '\0';
807a6826fbcSWolfgang Denk 	dp = data;
808a6826fbcSWolfgang Denk 
809d5370febSGerlando Falauto 	/* make a local copy of the list of variables */
810d5370febSGerlando Falauto 	if (nvars)
811d5370febSGerlando Falauto 		memcpy(localvars, vars, sizeof(vars[0]) * nvars);
812d5370febSGerlando Falauto 
813d9fc9077SQuentin Schulz 	if ((flag & H_NOCLEAR) == 0 && !nvars) {
814a6826fbcSWolfgang Denk 		/* Destroy old hash table if one exists */
815a6826fbcSWolfgang Denk 		debug("Destroy Hash Table: %p table = %p\n", htab,
816a6826fbcSWolfgang Denk 		       htab->table);
817a6826fbcSWolfgang Denk 		if (htab->table)
818c4e0057fSJoe Hershberger 			hdestroy_r(htab);
819a6826fbcSWolfgang Denk 	}
820a6826fbcSWolfgang Denk 
821a6826fbcSWolfgang Denk 	/*
822a6826fbcSWolfgang Denk 	 * Create new hash table (if needed).  The computation of the hash
823a6826fbcSWolfgang Denk 	 * table size is based on heuristics: in a sample of some 70+
824a6826fbcSWolfgang Denk 	 * existing systems we found an average size of 39+ bytes per entry
825a6826fbcSWolfgang Denk 	 * in the environment (for the whole key=value pair). Assuming a
826ea882bafSWolfgang Denk 	 * size of 8 per entry (= safety factor of ~5) should provide enough
827ea882bafSWolfgang Denk 	 * safety margin for any existing environment definitions and still
828a6826fbcSWolfgang Denk 	 * allow for more than enough dynamic additions. Note that the
8291bce2aebSRobert P. J. Day 	 * "size" argument is supposed to give the maximum environment size
830ea882bafSWolfgang Denk 	 * (CONFIG_ENV_SIZE).  This heuristics will result in
831ea882bafSWolfgang Denk 	 * unreasonably large numbers (and thus memory footprint) for
832ea882bafSWolfgang Denk 	 * big flash environments (>8,000 entries for 64 KB
83362a3b7ddSRobert P. J. Day 	 * environment size), so we clip it to a reasonable value.
834fc5fc76bSAndreas Bießmann 	 * On the other hand we need to add some more entries for free
835fc5fc76bSAndreas Bießmann 	 * space when importing very small buffers. Both boundaries can
836fc5fc76bSAndreas Bießmann 	 * be overwritten in the board config file if needed.
837a6826fbcSWolfgang Denk 	 */
838a6826fbcSWolfgang Denk 
839a6826fbcSWolfgang Denk 	if (!htab->table) {
840fc5fc76bSAndreas Bießmann 		int nent = CONFIG_ENV_MIN_ENTRIES + size / 8;
841ea882bafSWolfgang Denk 
842ea882bafSWolfgang Denk 		if (nent > CONFIG_ENV_MAX_ENTRIES)
843ea882bafSWolfgang Denk 			nent = CONFIG_ENV_MAX_ENTRIES;
844a6826fbcSWolfgang Denk 
845a6826fbcSWolfgang Denk 		debug("Create Hash Table: N=%d\n", nent);
846a6826fbcSWolfgang Denk 
847a6826fbcSWolfgang Denk 		if (hcreate_r(nent, htab) == 0) {
848a6826fbcSWolfgang Denk 			free(data);
849a6826fbcSWolfgang Denk 			return 0;
850a6826fbcSWolfgang Denk 		}
851a6826fbcSWolfgang Denk 	}
852a6826fbcSWolfgang Denk 
8530226d878SLukasz Majewski 	if (!size) {
8540226d878SLukasz Majewski 		free(data);
855ecd1446fSAlexander Holler 		return 1;		/* everything OK */
8560226d878SLukasz Majewski 	}
857ecd1446fSAlexander Holler 	if(crlf_is_lf) {
858ecd1446fSAlexander Holler 		/* Remove Carriage Returns in front of Line Feeds */
859ecd1446fSAlexander Holler 		unsigned ignored_crs = 0;
860ecd1446fSAlexander Holler 		for(;dp < data + size && *dp; ++dp) {
861ecd1446fSAlexander Holler 			if(*dp == '\r' &&
862ecd1446fSAlexander Holler 			   dp < data + size - 1 && *(dp+1) == '\n')
863ecd1446fSAlexander Holler 				++ignored_crs;
864ecd1446fSAlexander Holler 			else
865ecd1446fSAlexander Holler 				*(dp-ignored_crs) = *dp;
866ecd1446fSAlexander Holler 		}
867ecd1446fSAlexander Holler 		size -= ignored_crs;
868ecd1446fSAlexander Holler 		dp = data;
869ecd1446fSAlexander Holler 	}
870a6826fbcSWolfgang Denk 	/* Parse environment; allow for '\0' and 'sep' as separators */
871a6826fbcSWolfgang Denk 	do {
872a6826fbcSWolfgang Denk 		ENTRY e, *rv;
873a6826fbcSWolfgang Denk 
874a6826fbcSWolfgang Denk 		/* skip leading white space */
8754d91a6ecSJason Hobbs 		while (isblank(*dp))
876a6826fbcSWolfgang Denk 			++dp;
877a6826fbcSWolfgang Denk 
878a6826fbcSWolfgang Denk 		/* skip comment lines */
879a6826fbcSWolfgang Denk 		if (*dp == '#') {
880a6826fbcSWolfgang Denk 			while (*dp && (*dp != sep))
881a6826fbcSWolfgang Denk 				++dp;
882a6826fbcSWolfgang Denk 			++dp;
883a6826fbcSWolfgang Denk 			continue;
884a6826fbcSWolfgang Denk 		}
885a6826fbcSWolfgang Denk 
886a6826fbcSWolfgang Denk 		/* parse name */
887a6826fbcSWolfgang Denk 		for (name = dp; *dp != '=' && *dp && *dp != sep; ++dp)
888a6826fbcSWolfgang Denk 			;
889a6826fbcSWolfgang Denk 
890a6826fbcSWolfgang Denk 		/* deal with "name" and "name=" entries (delete var) */
891a6826fbcSWolfgang Denk 		if (*dp == '\0' || *(dp + 1) == '\0' ||
892a6826fbcSWolfgang Denk 		    *dp == sep || *(dp + 1) == sep) {
893a6826fbcSWolfgang Denk 			if (*dp == '=')
894a6826fbcSWolfgang Denk 				*dp++ = '\0';
895a6826fbcSWolfgang Denk 			*dp++ = '\0';	/* terminate name */
896a6826fbcSWolfgang Denk 
897a6826fbcSWolfgang Denk 			debug("DELETE CANDIDATE: \"%s\"\n", name);
898d5370febSGerlando Falauto 			if (!drop_var_from_set(name, nvars, localvars))
899348b1f1cSGerlando Falauto 				continue;
900a6826fbcSWolfgang Denk 
901c4e0057fSJoe Hershberger 			if (hdelete_r(name, htab, flag) == 0)
902a6826fbcSWolfgang Denk 				debug("DELETE ERROR ##############################\n");
903a6826fbcSWolfgang Denk 
904a6826fbcSWolfgang Denk 			continue;
905a6826fbcSWolfgang Denk 		}
906a6826fbcSWolfgang Denk 		*dp++ = '\0';	/* terminate name */
907a6826fbcSWolfgang Denk 
908a6826fbcSWolfgang Denk 		/* parse value; deal with escapes */
909a6826fbcSWolfgang Denk 		for (value = sp = dp; *dp && (*dp != sep); ++dp) {
910a6826fbcSWolfgang Denk 			if ((*dp == '\\') && *(dp + 1))
911a6826fbcSWolfgang Denk 				++dp;
912a6826fbcSWolfgang Denk 			*sp++ = *dp;
913a6826fbcSWolfgang Denk 		}
914a6826fbcSWolfgang Denk 		*sp++ = '\0';	/* terminate value */
915a6826fbcSWolfgang Denk 		++dp;
916a6826fbcSWolfgang Denk 
917e4fdcaddSLucian Cojocar 		if (*name == 0) {
918e4fdcaddSLucian Cojocar 			debug("INSERT: unable to use an empty key\n");
919e4fdcaddSLucian Cojocar 			__set_errno(EINVAL);
9200226d878SLukasz Majewski 			free(data);
921e4fdcaddSLucian Cojocar 			return 0;
922e4fdcaddSLucian Cojocar 		}
923e4fdcaddSLucian Cojocar 
924348b1f1cSGerlando Falauto 		/* Skip variables which are not supposed to be processed */
925d5370febSGerlando Falauto 		if (!drop_var_from_set(name, nvars, localvars))
926348b1f1cSGerlando Falauto 			continue;
927348b1f1cSGerlando Falauto 
928a6826fbcSWolfgang Denk 		/* enter into hash table */
929a6826fbcSWolfgang Denk 		e.key = name;
930a6826fbcSWolfgang Denk 		e.data = value;
931a6826fbcSWolfgang Denk 
932c4e0057fSJoe Hershberger 		hsearch_r(e, ENTER, &rv, htab, flag);
933170ab110SJoe Hershberger 		if (rv == NULL)
934ea882bafSWolfgang Denk 			printf("himport_r: can't insert \"%s=%s\" into hash table\n",
935ea882bafSWolfgang Denk 				name, value);
936a6826fbcSWolfgang Denk 
937ea882bafSWolfgang Denk 		debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"\n",
938ea882bafSWolfgang Denk 			htab, htab->filled, htab->size,
939ea882bafSWolfgang Denk 			rv, name, value);
940a6826fbcSWolfgang Denk 	} while ((dp < data + size) && *dp);	/* size check needed for text */
941a6826fbcSWolfgang Denk 						/* without '\0' termination */
942ea882bafSWolfgang Denk 	debug("INSERT: free(data = %p)\n", data);
943a6826fbcSWolfgang Denk 	free(data);
944a6826fbcSWolfgang Denk 
945d9fc9077SQuentin Schulz 	if (flag & H_NOCLEAR)
946d9fc9077SQuentin Schulz 		goto end;
947d9fc9077SQuentin Schulz 
948d5370febSGerlando Falauto 	/* process variables which were not considered */
949d5370febSGerlando Falauto 	for (i = 0; i < nvars; i++) {
950d5370febSGerlando Falauto 		if (localvars[i] == NULL)
951d5370febSGerlando Falauto 			continue;
952d5370febSGerlando Falauto 		/*
953d5370febSGerlando Falauto 		 * All variables which were not deleted from the variable list
954d5370febSGerlando Falauto 		 * were not present in the imported env
955d5370febSGerlando Falauto 		 * This could mean two things:
956d5370febSGerlando Falauto 		 * a) if the variable was present in current env, we delete it
957d5370febSGerlando Falauto 		 * b) if the variable was not present in current env, we notify
958d5370febSGerlando Falauto 		 *    it might be a typo
959d5370febSGerlando Falauto 		 */
960c4e0057fSJoe Hershberger 		if (hdelete_r(localvars[i], htab, flag) == 0)
961d5370febSGerlando Falauto 			printf("WARNING: '%s' neither in running nor in imported env!\n", localvars[i]);
962d5370febSGerlando Falauto 		else
963d5370febSGerlando Falauto 			printf("WARNING: '%s' not in imported env, deleting it!\n", localvars[i]);
964d5370febSGerlando Falauto 	}
965d5370febSGerlando Falauto 
966d9fc9077SQuentin Schulz end:
967ea882bafSWolfgang Denk 	debug("INSERT: done\n");
968a6826fbcSWolfgang Denk 	return 1;		/* everything OK */
969a6826fbcSWolfgang Denk }
970170ab110SJoe Hershberger 
971170ab110SJoe Hershberger /*
972170ab110SJoe Hershberger  * hwalk_r()
973170ab110SJoe Hershberger  */
974170ab110SJoe Hershberger 
975170ab110SJoe Hershberger /*
976170ab110SJoe Hershberger  * Walk all of the entries in the hash, calling the callback for each one.
977170ab110SJoe Hershberger  * this allows some generic operation to be performed on each element.
978170ab110SJoe Hershberger  */
hwalk_r(struct hsearch_data * htab,int (* callback)(ENTRY *))979170ab110SJoe Hershberger int hwalk_r(struct hsearch_data *htab, int (*callback)(ENTRY *))
980170ab110SJoe Hershberger {
981170ab110SJoe Hershberger 	int i;
982170ab110SJoe Hershberger 	int retval;
983170ab110SJoe Hershberger 
984170ab110SJoe Hershberger 	for (i = 1; i <= htab->size; ++i) {
985170ab110SJoe Hershberger 		if (htab->table[i].used > 0) {
986170ab110SJoe Hershberger 			retval = callback(&htab->table[i].entry);
987170ab110SJoe Hershberger 			if (retval)
988170ab110SJoe Hershberger 				return retval;
989170ab110SJoe Hershberger 		}
990170ab110SJoe Hershberger 	}
991170ab110SJoe Hershberger 
992170ab110SJoe Hershberger 	return 0;
993170ab110SJoe Hershberger }
994