xref: /rk3399_rockchip-uboot/lib/hashtable.c (revision e12b5efd268e1005d4dd24711b7aeefc0edf34bb)
1a6826fbcSWolfgang Denk /*
2a6826fbcSWolfgang Denk  * This implementation is based on code from uClibc-0.9.30.3 but was
3a6826fbcSWolfgang Denk  * modified and extended for use within U-Boot.
4a6826fbcSWolfgang Denk  *
5ea009d47SWolfgang Denk  * Copyright (C) 2010-2013 Wolfgang Denk <wd@denx.de>
6a6826fbcSWolfgang Denk  *
7a6826fbcSWolfgang Denk  * Original license header:
8a6826fbcSWolfgang Denk  *
9a6826fbcSWolfgang Denk  * Copyright (C) 1993, 1995, 1996, 1997, 2002 Free Software Foundation, Inc.
10a6826fbcSWolfgang Denk  * This file is part of the GNU C Library.
11a6826fbcSWolfgang Denk  * Contributed by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1993.
12a6826fbcSWolfgang Denk  *
13eee479cfSWolfgang Denk  * SPDX-License-Identifier:	LGPL-2.1+
14a6826fbcSWolfgang Denk  */
15a6826fbcSWolfgang Denk 
16a6826fbcSWolfgang Denk #include <errno.h>
17a6826fbcSWolfgang Denk #include <malloc.h>
18a6826fbcSWolfgang Denk 
19a6826fbcSWolfgang Denk #ifdef USE_HOSTCC		/* HOST build */
20a6826fbcSWolfgang Denk # include <string.h>
21a6826fbcSWolfgang Denk # include <assert.h>
224d91a6ecSJason Hobbs # include <ctype.h>
23a6826fbcSWolfgang Denk 
24a6826fbcSWolfgang Denk # ifndef debug
25a6826fbcSWolfgang Denk #  ifdef DEBUG
26a6826fbcSWolfgang Denk #   define debug(fmt,args...)	printf(fmt ,##args)
27a6826fbcSWolfgang Denk #  else
28a6826fbcSWolfgang Denk #   define debug(fmt,args...)
29a6826fbcSWolfgang Denk #  endif
30a6826fbcSWolfgang Denk # endif
31a6826fbcSWolfgang Denk #else				/* U-Boot build */
32a6826fbcSWolfgang Denk # include <common.h>
33a6826fbcSWolfgang Denk # include <linux/string.h>
344d91a6ecSJason Hobbs # include <linux/ctype.h>
35a6826fbcSWolfgang Denk #endif
36a6826fbcSWolfgang Denk 
37fc5fc76bSAndreas Bießmann #ifndef	CONFIG_ENV_MIN_ENTRIES	/* minimum number of entries */
38fc5fc76bSAndreas Bießmann #define	CONFIG_ENV_MIN_ENTRIES 64
39fc5fc76bSAndreas Bießmann #endif
40ea882bafSWolfgang Denk #ifndef	CONFIG_ENV_MAX_ENTRIES	/* maximum number of entries */
41ea882bafSWolfgang Denk #define	CONFIG_ENV_MAX_ENTRIES 512
42ea882bafSWolfgang Denk #endif
43ea882bafSWolfgang Denk 
44170ab110SJoe Hershberger #include <env_callback.h>
452598090bSJoe Hershberger #include <env_flags.h>
46170ab110SJoe Hershberger #include <search.h>
47be29df6aSWolfgang Denk #include <slre.h>
48a6826fbcSWolfgang Denk 
49a6826fbcSWolfgang Denk /*
50a6826fbcSWolfgang Denk  * [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
51a6826fbcSWolfgang Denk  * [Knuth]	      The Art of Computer Programming, part 3 (6.4)
52a6826fbcSWolfgang Denk  */
53a6826fbcSWolfgang Denk 
54a6826fbcSWolfgang Denk /*
55a6826fbcSWolfgang Denk  * The reentrant version has no static variables to maintain the state.
56a6826fbcSWolfgang Denk  * Instead the interface of all functions is extended to take an argument
57a6826fbcSWolfgang Denk  * which describes the current status.
58a6826fbcSWolfgang Denk  */
597afcf3a5SJoe Hershberger 
60a6826fbcSWolfgang Denk typedef struct _ENTRY {
61c81c1222SPeter Barada 	int used;
62a6826fbcSWolfgang Denk 	ENTRY entry;
63a6826fbcSWolfgang Denk } _ENTRY;
64a6826fbcSWolfgang Denk 
65a6826fbcSWolfgang Denk 
667afcf3a5SJoe Hershberger static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
677afcf3a5SJoe Hershberger 	int idx);
687afcf3a5SJoe Hershberger 
69a6826fbcSWolfgang Denk /*
70a6826fbcSWolfgang Denk  * hcreate()
71a6826fbcSWolfgang Denk  */
72a6826fbcSWolfgang Denk 
73a6826fbcSWolfgang Denk /*
74a6826fbcSWolfgang Denk  * For the used double hash method the table size has to be a prime. To
75a6826fbcSWolfgang Denk  * correct the user given table size we need a prime test.  This trivial
76a6826fbcSWolfgang Denk  * algorithm is adequate because
77a6826fbcSWolfgang Denk  * a)  the code is (most probably) called a few times per program run and
78a6826fbcSWolfgang Denk  * b)  the number is small because the table must fit in the core
79a6826fbcSWolfgang Denk  * */
isprime(unsigned int number)80a6826fbcSWolfgang Denk static int isprime(unsigned int number)
81a6826fbcSWolfgang Denk {
82a6826fbcSWolfgang Denk 	/* no even number will be passed */
83a6826fbcSWolfgang Denk 	unsigned int div = 3;
84a6826fbcSWolfgang Denk 
85a6826fbcSWolfgang Denk 	while (div * div < number && number % div != 0)
86a6826fbcSWolfgang Denk 		div += 2;
87a6826fbcSWolfgang Denk 
88a6826fbcSWolfgang Denk 	return number % div != 0;
89a6826fbcSWolfgang Denk }
90a6826fbcSWolfgang Denk 
91a6826fbcSWolfgang Denk /*
92a6826fbcSWolfgang Denk  * Before using the hash table we must allocate memory for it.
93a6826fbcSWolfgang Denk  * Test for an existing table are done. We allocate one element
94a6826fbcSWolfgang Denk  * more as the found prime number says. This is done for more effective
95a6826fbcSWolfgang Denk  * indexing as explained in the comment for the hsearch function.
96a6826fbcSWolfgang Denk  * The contents of the table is zeroed, especially the field used
97a6826fbcSWolfgang Denk  * becomes zero.
98a6826fbcSWolfgang Denk  */
992eb1573fSMike Frysinger 
hcreate_r(size_t nel,struct hsearch_data * htab)100a6826fbcSWolfgang Denk int hcreate_r(size_t nel, struct hsearch_data *htab)
101a6826fbcSWolfgang Denk {
102a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
103a6826fbcSWolfgang Denk 	if (htab == NULL) {
104a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
105a6826fbcSWolfgang Denk 		return 0;
106a6826fbcSWolfgang Denk 	}
107a6826fbcSWolfgang Denk 
108a6826fbcSWolfgang Denk 	/* There is still another table active. Return with error. */
109a6826fbcSWolfgang Denk 	if (htab->table != NULL)
110a6826fbcSWolfgang Denk 		return 0;
111a6826fbcSWolfgang Denk 
112a6826fbcSWolfgang Denk 	/* Change nel to the first prime number not smaller as nel. */
113a6826fbcSWolfgang Denk 	nel |= 1;		/* make odd */
114a6826fbcSWolfgang Denk 	while (!isprime(nel))
115a6826fbcSWolfgang Denk 		nel += 2;
116a6826fbcSWolfgang Denk 
117a6826fbcSWolfgang Denk 	htab->size = nel;
118a6826fbcSWolfgang Denk 	htab->filled = 0;
119a6826fbcSWolfgang Denk 
120a6826fbcSWolfgang Denk 	/* allocate memory and zero out */
121a6826fbcSWolfgang Denk 	htab->table = (_ENTRY *) calloc(htab->size + 1, sizeof(_ENTRY));
122a6826fbcSWolfgang Denk 	if (htab->table == NULL)
123a6826fbcSWolfgang Denk 		return 0;
124a6826fbcSWolfgang Denk 
125a6826fbcSWolfgang Denk 	/* everything went alright */
126a6826fbcSWolfgang Denk 	return 1;
127a6826fbcSWolfgang Denk }
128a6826fbcSWolfgang Denk 
129a6826fbcSWolfgang Denk 
130a6826fbcSWolfgang Denk /*
131a6826fbcSWolfgang Denk  * hdestroy()
132a6826fbcSWolfgang Denk  */
133a6826fbcSWolfgang Denk 
134a6826fbcSWolfgang Denk /*
135a6826fbcSWolfgang Denk  * After using the hash table it has to be destroyed. The used memory can
136a6826fbcSWolfgang Denk  * be freed and the local static variable can be marked as not used.
137a6826fbcSWolfgang Denk  */
1382eb1573fSMike Frysinger 
hdestroy_r(struct hsearch_data * htab)139c4e0057fSJoe Hershberger void hdestroy_r(struct hsearch_data *htab)
140a6826fbcSWolfgang Denk {
141a6826fbcSWolfgang Denk 	int i;
142a6826fbcSWolfgang Denk 
143a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
144a6826fbcSWolfgang Denk 	if (htab == NULL) {
145a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
146a6826fbcSWolfgang Denk 		return;
147a6826fbcSWolfgang Denk 	}
148a6826fbcSWolfgang Denk 
149a6826fbcSWolfgang Denk 	/* free used memory */
150a6826fbcSWolfgang Denk 	for (i = 1; i <= htab->size; ++i) {
151c81c1222SPeter Barada 		if (htab->table[i].used > 0) {
152a6826fbcSWolfgang Denk 			ENTRY *ep = &htab->table[i].entry;
153c4e0057fSJoe Hershberger 
15484b5e802SWolfgang Denk 			free((void *)ep->key);
155a6826fbcSWolfgang Denk 			free(ep->data);
156a6826fbcSWolfgang Denk 		}
157a6826fbcSWolfgang Denk 	}
158a6826fbcSWolfgang Denk 	free(htab->table);
159a6826fbcSWolfgang Denk 
160a6826fbcSWolfgang Denk 	/* the sign for an existing table is an value != NULL in htable */
161a6826fbcSWolfgang Denk 	htab->table = NULL;
162a6826fbcSWolfgang Denk }
163a6826fbcSWolfgang Denk 
164a6826fbcSWolfgang Denk /*
165a6826fbcSWolfgang Denk  * hsearch()
166a6826fbcSWolfgang Denk  */
167a6826fbcSWolfgang Denk 
168a6826fbcSWolfgang Denk /*
169a6826fbcSWolfgang Denk  * This is the search function. It uses double hashing with open addressing.
170a6826fbcSWolfgang Denk  * The argument item.key has to be a pointer to an zero terminated, most
171a6826fbcSWolfgang Denk  * probably strings of chars. The function for generating a number of the
172a6826fbcSWolfgang Denk  * strings is simple but fast. It can be replaced by a more complex function
173a6826fbcSWolfgang Denk  * like ajw (see [Aho,Sethi,Ullman]) if the needs are shown.
174a6826fbcSWolfgang Denk  *
175a6826fbcSWolfgang Denk  * We use an trick to speed up the lookup. The table is created by hcreate
176a6826fbcSWolfgang Denk  * with one more element available. This enables us to use the index zero
177a6826fbcSWolfgang Denk  * special. This index will never be used because we store the first hash
178a6826fbcSWolfgang Denk  * index in the field used where zero means not used. Every other value
179a6826fbcSWolfgang Denk  * means used. The used field can be used as a first fast comparison for
180a6826fbcSWolfgang Denk  * equality of the stored and the parameter value. This helps to prevent
181a6826fbcSWolfgang Denk  * unnecessary expensive calls of strcmp.
182a6826fbcSWolfgang Denk  *
183a6826fbcSWolfgang Denk  * This implementation differs from the standard library version of
184a6826fbcSWolfgang Denk  * this function in a number of ways:
185a6826fbcSWolfgang Denk  *
186a6826fbcSWolfgang Denk  * - While the standard version does not make any assumptions about
187a6826fbcSWolfgang Denk  *   the type of the stored data objects at all, this implementation
188a6826fbcSWolfgang Denk  *   works with NUL terminated strings only.
189a6826fbcSWolfgang Denk  * - Instead of storing just pointers to the original objects, we
190a6826fbcSWolfgang Denk  *   create local copies so the caller does not need to care about the
191a6826fbcSWolfgang Denk  *   data any more.
192a6826fbcSWolfgang Denk  * - The standard implementation does not provide a way to update an
193a6826fbcSWolfgang Denk  *   existing entry.  This version will create a new entry or update an
194a6826fbcSWolfgang Denk  *   existing one when both "action == ENTER" and "item.data != NULL".
195a6826fbcSWolfgang Denk  * - Instead of returning 1 on success, we return the index into the
196a6826fbcSWolfgang Denk  *   internal hash table, which is also guaranteed to be positive.
197a6826fbcSWolfgang Denk  *   This allows us direct access to the found hash table slot for
198a6826fbcSWolfgang Denk  *   example for functions like hdelete().
199a6826fbcSWolfgang Denk  */
200a6826fbcSWolfgang Denk 
hmatch_r(const char * match,int last_idx,ENTRY ** retval,struct hsearch_data * htab)201560d424bSMike Frysinger int hmatch_r(const char *match, int last_idx, ENTRY ** retval,
202560d424bSMike Frysinger 	     struct hsearch_data *htab)
203560d424bSMike Frysinger {
204560d424bSMike Frysinger 	unsigned int idx;
205560d424bSMike Frysinger 	size_t key_len = strlen(match);
206560d424bSMike Frysinger 
207560d424bSMike Frysinger 	for (idx = last_idx + 1; idx < htab->size; ++idx) {
208af4d9074SKim Phillips 		if (htab->table[idx].used <= 0)
209560d424bSMike Frysinger 			continue;
210560d424bSMike Frysinger 		if (!strncmp(match, htab->table[idx].entry.key, key_len)) {
211560d424bSMike Frysinger 			*retval = &htab->table[idx].entry;
212560d424bSMike Frysinger 			return idx;
213560d424bSMike Frysinger 		}
214560d424bSMike Frysinger 	}
215560d424bSMike Frysinger 
216560d424bSMike Frysinger 	__set_errno(ESRCH);
217560d424bSMike Frysinger 	*retval = NULL;
218560d424bSMike Frysinger 	return 0;
219560d424bSMike Frysinger }
220560d424bSMike Frysinger 
2213d3b52f2SJoe Hershberger /*
2223d3b52f2SJoe Hershberger  * Compare an existing entry with the desired key, and overwrite if the action
2233d3b52f2SJoe Hershberger  * is ENTER.  This is simply a helper function for hsearch_r().
2243d3b52f2SJoe Hershberger  */
_compare_and_overwrite_entry(ENTRY item,ACTION action,ENTRY ** retval,struct hsearch_data * htab,int flag,unsigned int hval,unsigned int idx)2253d3b52f2SJoe Hershberger static inline int _compare_and_overwrite_entry(ENTRY item, ACTION action,
2263d3b52f2SJoe Hershberger 	ENTRY **retval, struct hsearch_data *htab, int flag,
2273d3b52f2SJoe Hershberger 	unsigned int hval, unsigned int idx)
2283d3b52f2SJoe Hershberger {
2293d3b52f2SJoe Hershberger 	if (htab->table[idx].used == hval
2303d3b52f2SJoe Hershberger 	    && strcmp(item.key, htab->table[idx].entry.key) == 0) {
2313d3b52f2SJoe Hershberger 		/* Overwrite existing value? */
2323d3b52f2SJoe Hershberger 		if ((action == ENTER) && (item.data != NULL)) {
2337afcf3a5SJoe Hershberger 			/* check for permission */
2347afcf3a5SJoe Hershberger 			if (htab->change_ok != NULL && htab->change_ok(
2357afcf3a5SJoe Hershberger 			    &htab->table[idx].entry, item.data,
2367afcf3a5SJoe Hershberger 			    env_op_overwrite, flag)) {
2377afcf3a5SJoe Hershberger 				debug("change_ok() rejected setting variable "
2387afcf3a5SJoe Hershberger 					"%s, skipping it!\n", item.key);
2397afcf3a5SJoe Hershberger 				__set_errno(EPERM);
2407afcf3a5SJoe Hershberger 				*retval = NULL;
2417afcf3a5SJoe Hershberger 				return 0;
2427afcf3a5SJoe Hershberger 			}
2437afcf3a5SJoe Hershberger 
244170ab110SJoe Hershberger 			/* If there is a callback, call it */
245170ab110SJoe Hershberger 			if (htab->table[idx].entry.callback &&
246170ab110SJoe Hershberger 			    htab->table[idx].entry.callback(item.key,
247170ab110SJoe Hershberger 			    item.data, env_op_overwrite, flag)) {
248170ab110SJoe Hershberger 				debug("callback() rejected setting variable "
249170ab110SJoe Hershberger 					"%s, skipping it!\n", item.key);
250170ab110SJoe Hershberger 				__set_errno(EINVAL);
251170ab110SJoe Hershberger 				*retval = NULL;
252170ab110SJoe Hershberger 				return 0;
253170ab110SJoe Hershberger 			}
254170ab110SJoe Hershberger 
2553d3b52f2SJoe Hershberger 			free(htab->table[idx].entry.data);
2563d3b52f2SJoe Hershberger 			htab->table[idx].entry.data = strdup(item.data);
2573d3b52f2SJoe Hershberger 			if (!htab->table[idx].entry.data) {
2583d3b52f2SJoe Hershberger 				__set_errno(ENOMEM);
2593d3b52f2SJoe Hershberger 				*retval = NULL;
2603d3b52f2SJoe Hershberger 				return 0;
2613d3b52f2SJoe Hershberger 			}
2623d3b52f2SJoe Hershberger 		}
2633d3b52f2SJoe Hershberger 		/* return found entry */
2643d3b52f2SJoe Hershberger 		*retval = &htab->table[idx].entry;
2653d3b52f2SJoe Hershberger 		return idx;
2663d3b52f2SJoe Hershberger 	}
2673d3b52f2SJoe Hershberger 	/* keep searching */
2683d3b52f2SJoe Hershberger 	return -1;
2693d3b52f2SJoe Hershberger }
2703d3b52f2SJoe Hershberger 
hsearch_r(ENTRY item,ACTION action,ENTRY ** retval,struct hsearch_data * htab,int flag)271a6826fbcSWolfgang Denk int hsearch_r(ENTRY item, ACTION action, ENTRY ** retval,
272c4e0057fSJoe Hershberger 	      struct hsearch_data *htab, int flag)
273a6826fbcSWolfgang Denk {
274a6826fbcSWolfgang Denk 	unsigned int hval;
275a6826fbcSWolfgang Denk 	unsigned int count;
276a6826fbcSWolfgang Denk 	unsigned int len = strlen(item.key);
277a6826fbcSWolfgang Denk 	unsigned int idx;
278c81c1222SPeter Barada 	unsigned int first_deleted = 0;
2793d3b52f2SJoe Hershberger 	int ret;
280a6826fbcSWolfgang Denk 
281a6826fbcSWolfgang Denk 	/* Compute an value for the given string. Perhaps use a better method. */
282a6826fbcSWolfgang Denk 	hval = len;
283a6826fbcSWolfgang Denk 	count = len;
284a6826fbcSWolfgang Denk 	while (count-- > 0) {
285a6826fbcSWolfgang Denk 		hval <<= 4;
286a6826fbcSWolfgang Denk 		hval += item.key[count];
287a6826fbcSWolfgang Denk 	}
288a6826fbcSWolfgang Denk 
289a6826fbcSWolfgang Denk 	/*
290a6826fbcSWolfgang Denk 	 * First hash function:
291a6826fbcSWolfgang Denk 	 * simply take the modul but prevent zero.
292a6826fbcSWolfgang Denk 	 */
293a6826fbcSWolfgang Denk 	hval %= htab->size;
294a6826fbcSWolfgang Denk 	if (hval == 0)
295a6826fbcSWolfgang Denk 		++hval;
296a6826fbcSWolfgang Denk 
297a6826fbcSWolfgang Denk 	/* The first index tried. */
298a6826fbcSWolfgang Denk 	idx = hval;
299a6826fbcSWolfgang Denk 
300a6826fbcSWolfgang Denk 	if (htab->table[idx].used) {
301a6826fbcSWolfgang Denk 		/*
302a6826fbcSWolfgang Denk 		 * Further action might be required according to the
303a6826fbcSWolfgang Denk 		 * action value.
304a6826fbcSWolfgang Denk 		 */
305a6826fbcSWolfgang Denk 		unsigned hval2;
306a6826fbcSWolfgang Denk 
307c81c1222SPeter Barada 		if (htab->table[idx].used == -1
308c81c1222SPeter Barada 		    && !first_deleted)
309c81c1222SPeter Barada 			first_deleted = idx;
310c81c1222SPeter Barada 
3113d3b52f2SJoe Hershberger 		ret = _compare_and_overwrite_entry(item, action, retval, htab,
3123d3b52f2SJoe Hershberger 			flag, hval, idx);
3133d3b52f2SJoe Hershberger 		if (ret != -1)
3143d3b52f2SJoe Hershberger 			return ret;
315a6826fbcSWolfgang Denk 
316a6826fbcSWolfgang Denk 		/*
317a6826fbcSWolfgang Denk 		 * Second hash function:
318a6826fbcSWolfgang Denk 		 * as suggested in [Knuth]
319a6826fbcSWolfgang Denk 		 */
320a6826fbcSWolfgang Denk 		hval2 = 1 + hval % (htab->size - 2);
321a6826fbcSWolfgang Denk 
322a6826fbcSWolfgang Denk 		do {
323a6826fbcSWolfgang Denk 			/*
324a6826fbcSWolfgang Denk 			 * Because SIZE is prime this guarantees to
325a6826fbcSWolfgang Denk 			 * step through all available indices.
326a6826fbcSWolfgang Denk 			 */
327a6826fbcSWolfgang Denk 			if (idx <= hval2)
328a6826fbcSWolfgang Denk 				idx = htab->size + idx - hval2;
329a6826fbcSWolfgang Denk 			else
330a6826fbcSWolfgang Denk 				idx -= hval2;
331a6826fbcSWolfgang Denk 
332a6826fbcSWolfgang Denk 			/*
333a6826fbcSWolfgang Denk 			 * If we visited all entries leave the loop
334a6826fbcSWolfgang Denk 			 * unsuccessfully.
335a6826fbcSWolfgang Denk 			 */
336a6826fbcSWolfgang Denk 			if (idx == hval)
337a6826fbcSWolfgang Denk 				break;
338a6826fbcSWolfgang Denk 
339a6826fbcSWolfgang Denk 			/* If entry is found use it. */
3403d3b52f2SJoe Hershberger 			ret = _compare_and_overwrite_entry(item, action, retval,
3413d3b52f2SJoe Hershberger 				htab, flag, hval, idx);
3423d3b52f2SJoe Hershberger 			if (ret != -1)
3433d3b52f2SJoe Hershberger 				return ret;
344a6826fbcSWolfgang Denk 		}
345a6826fbcSWolfgang Denk 		while (htab->table[idx].used);
346a6826fbcSWolfgang Denk 	}
347a6826fbcSWolfgang Denk 
348a6826fbcSWolfgang Denk 	/* An empty bucket has been found. */
349a6826fbcSWolfgang Denk 	if (action == ENTER) {
350a6826fbcSWolfgang Denk 		/*
351a6826fbcSWolfgang Denk 		 * If table is full and another entry should be
352a6826fbcSWolfgang Denk 		 * entered return with error.
353a6826fbcSWolfgang Denk 		 */
354a6826fbcSWolfgang Denk 		if (htab->filled == htab->size) {
355a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
356a6826fbcSWolfgang Denk 			*retval = NULL;
357a6826fbcSWolfgang Denk 			return 0;
358a6826fbcSWolfgang Denk 		}
359a6826fbcSWolfgang Denk 
360a6826fbcSWolfgang Denk 		/*
361a6826fbcSWolfgang Denk 		 * Create new entry;
362a6826fbcSWolfgang Denk 		 * create copies of item.key and item.data
363a6826fbcSWolfgang Denk 		 */
364c81c1222SPeter Barada 		if (first_deleted)
365c81c1222SPeter Barada 			idx = first_deleted;
366c81c1222SPeter Barada 
367a6826fbcSWolfgang Denk 		htab->table[idx].used = hval;
368a6826fbcSWolfgang Denk 		htab->table[idx].entry.key = strdup(item.key);
369a6826fbcSWolfgang Denk 		htab->table[idx].entry.data = strdup(item.data);
370a6826fbcSWolfgang Denk 		if (!htab->table[idx].entry.key ||
371a6826fbcSWolfgang Denk 		    !htab->table[idx].entry.data) {
372a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
373a6826fbcSWolfgang Denk 			*retval = NULL;
374a6826fbcSWolfgang Denk 			return 0;
375a6826fbcSWolfgang Denk 		}
376a6826fbcSWolfgang Denk 
377a6826fbcSWolfgang Denk 		++htab->filled;
378a6826fbcSWolfgang Denk 
379170ab110SJoe Hershberger 		/* This is a new entry, so look up a possible callback */
380170ab110SJoe Hershberger 		env_callback_init(&htab->table[idx].entry);
3812598090bSJoe Hershberger 		/* Also look for flags */
3822598090bSJoe Hershberger 		env_flags_init(&htab->table[idx].entry);
383170ab110SJoe Hershberger 
3847afcf3a5SJoe Hershberger 		/* check for permission */
3857afcf3a5SJoe Hershberger 		if (htab->change_ok != NULL && htab->change_ok(
3867afcf3a5SJoe Hershberger 		    &htab->table[idx].entry, item.data, env_op_create, flag)) {
3877afcf3a5SJoe Hershberger 			debug("change_ok() rejected setting variable "
3887afcf3a5SJoe Hershberger 				"%s, skipping it!\n", item.key);
3897afcf3a5SJoe Hershberger 			_hdelete(item.key, htab, &htab->table[idx].entry, idx);
3907afcf3a5SJoe Hershberger 			__set_errno(EPERM);
3917afcf3a5SJoe Hershberger 			*retval = NULL;
3927afcf3a5SJoe Hershberger 			return 0;
3937afcf3a5SJoe Hershberger 		}
3947afcf3a5SJoe Hershberger 
395170ab110SJoe Hershberger 		/* If there is a callback, call it */
396170ab110SJoe Hershberger 		if (htab->table[idx].entry.callback &&
397170ab110SJoe Hershberger 		    htab->table[idx].entry.callback(item.key, item.data,
398170ab110SJoe Hershberger 		    env_op_create, flag)) {
399170ab110SJoe Hershberger 			debug("callback() rejected setting variable "
400170ab110SJoe Hershberger 				"%s, skipping it!\n", item.key);
401170ab110SJoe Hershberger 			_hdelete(item.key, htab, &htab->table[idx].entry, idx);
402170ab110SJoe Hershberger 			__set_errno(EINVAL);
403170ab110SJoe Hershberger 			*retval = NULL;
404170ab110SJoe Hershberger 			return 0;
405170ab110SJoe Hershberger 		}
406170ab110SJoe Hershberger 
407a6826fbcSWolfgang Denk 		/* return new entry */
408a6826fbcSWolfgang Denk 		*retval = &htab->table[idx].entry;
409a6826fbcSWolfgang Denk 		return 1;
410a6826fbcSWolfgang Denk 	}
411a6826fbcSWolfgang Denk 
412a6826fbcSWolfgang Denk 	__set_errno(ESRCH);
413a6826fbcSWolfgang Denk 	*retval = NULL;
414a6826fbcSWolfgang Denk 	return 0;
415a6826fbcSWolfgang Denk }
416a6826fbcSWolfgang Denk 
417a6826fbcSWolfgang Denk 
418a6826fbcSWolfgang Denk /*
419a6826fbcSWolfgang Denk  * hdelete()
420a6826fbcSWolfgang Denk  */
421a6826fbcSWolfgang Denk 
422a6826fbcSWolfgang Denk /*
423a6826fbcSWolfgang Denk  * The standard implementation of hsearch(3) does not provide any way
424a6826fbcSWolfgang Denk  * to delete any entries from the hash table.  We extend the code to
425a6826fbcSWolfgang Denk  * do that.
426a6826fbcSWolfgang Denk  */
427a6826fbcSWolfgang Denk 
_hdelete(const char * key,struct hsearch_data * htab,ENTRY * ep,int idx)4287afcf3a5SJoe Hershberger static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
4297afcf3a5SJoe Hershberger 	int idx)
4307afcf3a5SJoe Hershberger {
4317afcf3a5SJoe Hershberger 	/* free used ENTRY */
4327afcf3a5SJoe Hershberger 	debug("hdelete: DELETING key \"%s\"\n", key);
4337afcf3a5SJoe Hershberger 	free((void *)ep->key);
4347afcf3a5SJoe Hershberger 	free(ep->data);
435170ab110SJoe Hershberger 	ep->callback = NULL;
4362598090bSJoe Hershberger 	ep->flags = 0;
4377afcf3a5SJoe Hershberger 	htab->table[idx].used = -1;
4387afcf3a5SJoe Hershberger 
4397afcf3a5SJoe Hershberger 	--htab->filled;
4407afcf3a5SJoe Hershberger }
4417afcf3a5SJoe Hershberger 
hdelete_r(const char * key,struct hsearch_data * htab,int flag)442c4e0057fSJoe Hershberger int hdelete_r(const char *key, struct hsearch_data *htab, int flag)
443a6826fbcSWolfgang Denk {
444a6826fbcSWolfgang Denk 	ENTRY e, *ep;
445a6826fbcSWolfgang Denk 	int idx;
446a6826fbcSWolfgang Denk 
447a6826fbcSWolfgang Denk 	debug("hdelete: DELETE key \"%s\"\n", key);
448a6826fbcSWolfgang Denk 
449a6826fbcSWolfgang Denk 	e.key = (char *)key;
450a6826fbcSWolfgang Denk 
451c4e0057fSJoe Hershberger 	idx = hsearch_r(e, FIND, &ep, htab, 0);
452c4e0057fSJoe Hershberger 	if (idx == 0) {
453a6826fbcSWolfgang Denk 		__set_errno(ESRCH);
454a6826fbcSWolfgang Denk 		return 0;	/* not found */
455a6826fbcSWolfgang Denk 	}
456a6826fbcSWolfgang Denk 
457c4e0057fSJoe Hershberger 	/* Check for permission */
4587afcf3a5SJoe Hershberger 	if (htab->change_ok != NULL &&
4597afcf3a5SJoe Hershberger 	    htab->change_ok(ep, NULL, env_op_delete, flag)) {
4607afcf3a5SJoe Hershberger 		debug("change_ok() rejected deleting variable "
4617afcf3a5SJoe Hershberger 			"%s, skipping it!\n", key);
462c4e0057fSJoe Hershberger 		__set_errno(EPERM);
463c4e0057fSJoe Hershberger 		return 0;
464c4e0057fSJoe Hershberger 	}
465c4e0057fSJoe Hershberger 
466170ab110SJoe Hershberger 	/* If there is a callback, call it */
467170ab110SJoe Hershberger 	if (htab->table[idx].entry.callback &&
468170ab110SJoe Hershberger 	    htab->table[idx].entry.callback(key, NULL, env_op_delete, flag)) {
469170ab110SJoe Hershberger 		debug("callback() rejected deleting variable "
470170ab110SJoe Hershberger 			"%s, skipping it!\n", key);
471170ab110SJoe Hershberger 		__set_errno(EINVAL);
472170ab110SJoe Hershberger 		return 0;
473170ab110SJoe Hershberger 	}
474170ab110SJoe Hershberger 
4757afcf3a5SJoe Hershberger 	_hdelete(key, htab, ep, idx);
476a6826fbcSWolfgang Denk 
477a6826fbcSWolfgang Denk 	return 1;
478a6826fbcSWolfgang Denk }
479a6826fbcSWolfgang Denk 
480d2d9bdfcSB, Ravi #if !(defined(CONFIG_SPL_BUILD) && !defined(CONFIG_SPL_SAVEENV))
481a6826fbcSWolfgang Denk /*
482a6826fbcSWolfgang Denk  * hexport()
483a6826fbcSWolfgang Denk  */
484a6826fbcSWolfgang Denk 
485a6826fbcSWolfgang Denk /*
486a6826fbcSWolfgang Denk  * Export the data stored in the hash table in linearized form.
487a6826fbcSWolfgang Denk  *
488a6826fbcSWolfgang Denk  * Entries are exported as "name=value" strings, separated by an
489a6826fbcSWolfgang Denk  * arbitrary (non-NUL, of course) separator character. This allows to
490a6826fbcSWolfgang Denk  * use this function both when formatting the U-Boot environment for
491a6826fbcSWolfgang Denk  * external storage (using '\0' as separator), but also when using it
492a6826fbcSWolfgang Denk  * for the "printenv" command to print all variables, simply by using
493a6826fbcSWolfgang Denk  * as '\n" as separator. This can also be used for new features like
494a6826fbcSWolfgang Denk  * exporting the environment data as text file, including the option
495a6826fbcSWolfgang Denk  * for later re-import.
496a6826fbcSWolfgang Denk  *
497a6826fbcSWolfgang Denk  * The entries in the result list will be sorted by ascending key
498a6826fbcSWolfgang Denk  * values.
499a6826fbcSWolfgang Denk  *
500a6826fbcSWolfgang Denk  * If the separator character is different from NUL, then any
501a6826fbcSWolfgang Denk  * separator characters and backslash characters in the values will
502fc0b5948SRobert P. J. Day  * be escaped by a preceding backslash in output. This is needed for
503a6826fbcSWolfgang Denk  * example to enable multi-line values, especially when the output
504a6826fbcSWolfgang Denk  * shall later be parsed (for example, for re-import).
505a6826fbcSWolfgang Denk  *
506a6826fbcSWolfgang Denk  * There are several options how the result buffer is handled:
507a6826fbcSWolfgang Denk  *
508a6826fbcSWolfgang Denk  * *resp  size
509a6826fbcSWolfgang Denk  * -----------
510a6826fbcSWolfgang Denk  *  NULL    0	A string of sufficient length will be allocated.
511a6826fbcSWolfgang Denk  *  NULL   >0	A string of the size given will be
512a6826fbcSWolfgang Denk  *		allocated. An error will be returned if the size is
513a6826fbcSWolfgang Denk  *		not sufficient.  Any unused bytes in the string will
514a6826fbcSWolfgang Denk  *		be '\0'-padded.
515a6826fbcSWolfgang Denk  * !NULL    0	The user-supplied buffer will be used. No length
516a6826fbcSWolfgang Denk  *		checking will be performed, i. e. it is assumed that
517a6826fbcSWolfgang Denk  *		the buffer size will always be big enough. DANGEROUS.
518a6826fbcSWolfgang Denk  * !NULL   >0	The user-supplied buffer will be used. An error will
519a6826fbcSWolfgang Denk  *		be returned if the size is not sufficient.  Any unused
520a6826fbcSWolfgang Denk  *		bytes in the string will be '\0'-padded.
521a6826fbcSWolfgang Denk  */
522a6826fbcSWolfgang Denk 
cmpkey(const void * p1,const void * p2)523a6826fbcSWolfgang Denk static int cmpkey(const void *p1, const void *p2)
524a6826fbcSWolfgang Denk {
525a6826fbcSWolfgang Denk 	ENTRY *e1 = *(ENTRY **) p1;
526a6826fbcSWolfgang Denk 	ENTRY *e2 = *(ENTRY **) p2;
527a6826fbcSWolfgang Denk 
528a6826fbcSWolfgang Denk 	return (strcmp(e1->key, e2->key));
529a6826fbcSWolfgang Denk }
530a6826fbcSWolfgang Denk 
match_string(int flag,const char * str,const char * pat,void * priv)531be29df6aSWolfgang Denk static int match_string(int flag, const char *str, const char *pat, void *priv)
532ea009d47SWolfgang Denk {
533ea009d47SWolfgang Denk 	switch (flag & H_MATCH_METHOD) {
534ea009d47SWolfgang Denk 	case H_MATCH_IDENT:
5355a31ea04SWolfgang Denk 		if (strcmp(str, pat) == 0)
5365a31ea04SWolfgang Denk 			return 1;
5375a31ea04SWolfgang Denk 		break;
5385a31ea04SWolfgang Denk 	case H_MATCH_SUBSTR:
5395a31ea04SWolfgang Denk 		if (strstr(str, pat))
540ea009d47SWolfgang Denk 			return 1;
541ea009d47SWolfgang Denk 		break;
542be29df6aSWolfgang Denk #ifdef CONFIG_REGEX
543be29df6aSWolfgang Denk 	case H_MATCH_REGEX:
544be29df6aSWolfgang Denk 		{
545be29df6aSWolfgang Denk 			struct slre *slrep = (struct slre *)priv;
546be29df6aSWolfgang Denk 			struct cap caps[slrep->num_caps + 2];
547be29df6aSWolfgang Denk 
548be29df6aSWolfgang Denk 			if (slre_match(slrep, str, strlen(str), caps))
549be29df6aSWolfgang Denk 				return 1;
550be29df6aSWolfgang Denk 		}
551be29df6aSWolfgang Denk 		break;
552be29df6aSWolfgang Denk #endif
553ea009d47SWolfgang Denk 	default:
554ea009d47SWolfgang Denk 		printf("## ERROR: unsupported match method: 0x%02x\n",
555ea009d47SWolfgang Denk 			flag & H_MATCH_METHOD);
556ea009d47SWolfgang Denk 		break;
557ea009d47SWolfgang Denk 	}
5585a31ea04SWolfgang Denk 	return 0;
5595a31ea04SWolfgang Denk }
5605a31ea04SWolfgang Denk 
match_entry(ENTRY * ep,int flag,int argc,char * const argv[])5615a31ea04SWolfgang Denk static int match_entry(ENTRY *ep, int flag,
5625a31ea04SWolfgang Denk 		 int argc, char * const argv[])
5635a31ea04SWolfgang Denk {
5645a31ea04SWolfgang Denk 	int arg;
565be29df6aSWolfgang Denk 	void *priv = NULL;
5665a31ea04SWolfgang Denk 
5679a832331SPierre Aubert 	for (arg = 0; arg < argc; ++arg) {
568be29df6aSWolfgang Denk #ifdef CONFIG_REGEX
569be29df6aSWolfgang Denk 		struct slre slre;
570be29df6aSWolfgang Denk 
571be29df6aSWolfgang Denk 		if (slre_compile(&slre, argv[arg]) == 0) {
572be29df6aSWolfgang Denk 			printf("Error compiling regex: %s\n", slre.err_str);
573be29df6aSWolfgang Denk 			return 0;
574be29df6aSWolfgang Denk 		}
575be29df6aSWolfgang Denk 
576be29df6aSWolfgang Denk 		priv = (void *)&slre;
577be29df6aSWolfgang Denk #endif
5785a31ea04SWolfgang Denk 		if (flag & H_MATCH_KEY) {
579be29df6aSWolfgang Denk 			if (match_string(flag, ep->key, argv[arg], priv))
5805a31ea04SWolfgang Denk 				return 1;
5815a31ea04SWolfgang Denk 		}
5825a31ea04SWolfgang Denk 		if (flag & H_MATCH_DATA) {
583be29df6aSWolfgang Denk 			if (match_string(flag, ep->data, argv[arg], priv))
5845a31ea04SWolfgang Denk 				return 1;
585ea009d47SWolfgang Denk 		}
586ea009d47SWolfgang Denk 	}
587ea009d47SWolfgang Denk 	return 0;
588ea009d47SWolfgang Denk }
589ea009d47SWolfgang Denk 
hexport_r(struct hsearch_data * htab,const char sep,int flag,char ** resp,size_t size,int argc,char * const argv[])590be11235aSJoe Hershberger ssize_t hexport_r(struct hsearch_data *htab, const char sep, int flag,
59137f2fe74SWolfgang Denk 		 char **resp, size_t size,
59237f2fe74SWolfgang Denk 		 int argc, char * const argv[])
593a6826fbcSWolfgang Denk {
594a6826fbcSWolfgang Denk 	ENTRY *list[htab->size];
595a6826fbcSWolfgang Denk 	char *res, *p;
596a6826fbcSWolfgang Denk 	size_t totlen;
597a6826fbcSWolfgang Denk 	int i, n;
598a6826fbcSWolfgang Denk 
599a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
600a6826fbcSWolfgang Denk 	if ((resp == NULL) || (htab == NULL)) {
601a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
602a6826fbcSWolfgang Denk 		return (-1);
603a6826fbcSWolfgang Denk 	}
604a6826fbcSWolfgang Denk 
605c55d02b2SSimon Glass 	debug("EXPORT  table = %p, htab.size = %d, htab.filled = %d, size = %lu\n",
606c55d02b2SSimon Glass 	      htab, htab->size, htab->filled, (ulong)size);
607a6826fbcSWolfgang Denk 	/*
608a6826fbcSWolfgang Denk 	 * Pass 1:
609a6826fbcSWolfgang Denk 	 * search used entries,
610a6826fbcSWolfgang Denk 	 * save addresses and compute total length
611a6826fbcSWolfgang Denk 	 */
612a6826fbcSWolfgang Denk 	for (i = 1, n = 0, totlen = 0; i <= htab->size; ++i) {
613a6826fbcSWolfgang Denk 
614c81c1222SPeter Barada 		if (htab->table[i].used > 0) {
615a6826fbcSWolfgang Denk 			ENTRY *ep = &htab->table[i].entry;
6165a31ea04SWolfgang Denk 			int found = match_entry(ep, flag, argc, argv);
61737f2fe74SWolfgang Denk 
61837f2fe74SWolfgang Denk 			if ((argc > 0) && (found == 0))
61937f2fe74SWolfgang Denk 				continue;
620a6826fbcSWolfgang Denk 
621be11235aSJoe Hershberger 			if ((flag & H_HIDE_DOT) && ep->key[0] == '.')
622be11235aSJoe Hershberger 				continue;
623be11235aSJoe Hershberger 
624a6826fbcSWolfgang Denk 			list[n++] = ep;
625a6826fbcSWolfgang Denk 
626a6826fbcSWolfgang Denk 			totlen += strlen(ep->key) + 2;
627a6826fbcSWolfgang Denk 
628a6826fbcSWolfgang Denk 			if (sep == '\0') {
629a6826fbcSWolfgang Denk 				totlen += strlen(ep->data);
630a6826fbcSWolfgang Denk 			} else {	/* check if escapes are needed */
631a6826fbcSWolfgang Denk 				char *s = ep->data;
632a6826fbcSWolfgang Denk 
633a6826fbcSWolfgang Denk 				while (*s) {
634a6826fbcSWolfgang Denk 					++totlen;
635a6826fbcSWolfgang Denk 					/* add room for needed escape chars */
636a6826fbcSWolfgang Denk 					if ((*s == sep) || (*s == '\\'))
637a6826fbcSWolfgang Denk 						++totlen;
638a6826fbcSWolfgang Denk 					++s;
639a6826fbcSWolfgang Denk 				}
640a6826fbcSWolfgang Denk 			}
641a6826fbcSWolfgang Denk 			totlen += 2;	/* for '=' and 'sep' char */
642a6826fbcSWolfgang Denk 		}
643a6826fbcSWolfgang Denk 	}
644a6826fbcSWolfgang Denk 
645a6826fbcSWolfgang Denk #ifdef DEBUG
646a6826fbcSWolfgang Denk 	/* Pass 1a: print unsorted list */
647a6826fbcSWolfgang Denk 	printf("Unsorted: n=%d\n", n);
648a6826fbcSWolfgang Denk 	for (i = 0; i < n; ++i) {
649a6826fbcSWolfgang Denk 		printf("\t%3d: %p ==> %-10s => %s\n",
650a6826fbcSWolfgang Denk 		       i, list[i], list[i]->key, list[i]->data);
651a6826fbcSWolfgang Denk 	}
652a6826fbcSWolfgang Denk #endif
653a6826fbcSWolfgang Denk 
654a6826fbcSWolfgang Denk 	/* Sort list by keys */
655a6826fbcSWolfgang Denk 	qsort(list, n, sizeof(ENTRY *), cmpkey);
656a6826fbcSWolfgang Denk 
657a6826fbcSWolfgang Denk 	/* Check if the user supplied buffer size is sufficient */
658a6826fbcSWolfgang Denk 	if (size) {
659a6826fbcSWolfgang Denk 		if (size < totlen + 1) {	/* provided buffer too small */
660c55d02b2SSimon Glass 			printf("Env export buffer too small: %lu, but need %lu\n",
661c55d02b2SSimon Glass 			       (ulong)size, (ulong)totlen + 1);
662a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
663a6826fbcSWolfgang Denk 			return (-1);
664a6826fbcSWolfgang Denk 		}
665a6826fbcSWolfgang Denk 	} else {
666a6826fbcSWolfgang Denk 		size = totlen + 1;
667a6826fbcSWolfgang Denk 	}
668a6826fbcSWolfgang Denk 
669a6826fbcSWolfgang Denk 	/* Check if the user provided a buffer */
670a6826fbcSWolfgang Denk 	if (*resp) {
671a6826fbcSWolfgang Denk 		/* yes; clear it */
672a6826fbcSWolfgang Denk 		res = *resp;
673a6826fbcSWolfgang Denk 		memset(res, '\0', size);
674a6826fbcSWolfgang Denk 	} else {
675a6826fbcSWolfgang Denk 		/* no, allocate and clear one */
676a6826fbcSWolfgang Denk 		*resp = res = calloc(1, size);
677a6826fbcSWolfgang Denk 		if (res == NULL) {
678a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
679a6826fbcSWolfgang Denk 			return (-1);
680a6826fbcSWolfgang Denk 		}
681a6826fbcSWolfgang Denk 	}
682a6826fbcSWolfgang Denk 	/*
683a6826fbcSWolfgang Denk 	 * Pass 2:
684a6826fbcSWolfgang Denk 	 * export sorted list of result data
685a6826fbcSWolfgang Denk 	 */
686a6826fbcSWolfgang Denk 	for (i = 0, p = res; i < n; ++i) {
68784b5e802SWolfgang Denk 		const char *s;
688a6826fbcSWolfgang Denk 
689a6826fbcSWolfgang Denk 		s = list[i]->key;
690a6826fbcSWolfgang Denk 		while (*s)
691a6826fbcSWolfgang Denk 			*p++ = *s++;
692a6826fbcSWolfgang Denk 		*p++ = '=';
693a6826fbcSWolfgang Denk 
694a6826fbcSWolfgang Denk 		s = list[i]->data;
695a6826fbcSWolfgang Denk 
696a6826fbcSWolfgang Denk 		while (*s) {
697a6826fbcSWolfgang Denk 			if ((*s == sep) || (*s == '\\'))
698a6826fbcSWolfgang Denk 				*p++ = '\\';	/* escape */
699a6826fbcSWolfgang Denk 			*p++ = *s++;
700a6826fbcSWolfgang Denk 		}
701a6826fbcSWolfgang Denk 		*p++ = sep;
702a6826fbcSWolfgang Denk 	}
703a6826fbcSWolfgang Denk 	*p = '\0';		/* terminate result */
704a6826fbcSWolfgang Denk 
705a6826fbcSWolfgang Denk 	return size;
706a6826fbcSWolfgang Denk }
7077ac2fe2dSIlya Yanok #endif
708a6826fbcSWolfgang Denk 
709a6826fbcSWolfgang Denk 
710a6826fbcSWolfgang Denk /*
711a6826fbcSWolfgang Denk  * himport()
712a6826fbcSWolfgang Denk  */
713a6826fbcSWolfgang Denk 
714d5370febSGerlando Falauto /*
715d5370febSGerlando Falauto  * Check whether variable 'name' is amongst vars[],
716d5370febSGerlando Falauto  * and remove all instances by setting the pointer to NULL
717d5370febSGerlando Falauto  */
drop_var_from_set(const char * name,int nvars,char * vars[])718d5370febSGerlando Falauto static int drop_var_from_set(const char *name, int nvars, char * vars[])
719348b1f1cSGerlando Falauto {
720348b1f1cSGerlando Falauto 	int i = 0;
721d5370febSGerlando Falauto 	int res = 0;
722348b1f1cSGerlando Falauto 
723348b1f1cSGerlando Falauto 	/* No variables specified means process all of them */
724348b1f1cSGerlando Falauto 	if (nvars == 0)
725348b1f1cSGerlando Falauto 		return 1;
726348b1f1cSGerlando Falauto 
727348b1f1cSGerlando Falauto 	for (i = 0; i < nvars; i++) {
728d5370febSGerlando Falauto 		if (vars[i] == NULL)
729d5370febSGerlando Falauto 			continue;
730d5370febSGerlando Falauto 		/* If we found it, delete all of them */
731d5370febSGerlando Falauto 		if (!strcmp(name, vars[i])) {
732d5370febSGerlando Falauto 			vars[i] = NULL;
733d5370febSGerlando Falauto 			res = 1;
734348b1f1cSGerlando Falauto 		}
735d5370febSGerlando Falauto 	}
736d5370febSGerlando Falauto 	if (!res)
737348b1f1cSGerlando Falauto 		debug("Skipping non-listed variable %s\n", name);
738348b1f1cSGerlando Falauto 
739d5370febSGerlando Falauto 	return res;
740348b1f1cSGerlando Falauto }
741348b1f1cSGerlando Falauto 
742a6826fbcSWolfgang Denk /*
743a6826fbcSWolfgang Denk  * Import linearized data into hash table.
744a6826fbcSWolfgang Denk  *
745a6826fbcSWolfgang Denk  * This is the inverse function to hexport(): it takes a linear list
746a6826fbcSWolfgang Denk  * of "name=value" pairs and creates hash table entries from it.
747a6826fbcSWolfgang Denk  *
748a6826fbcSWolfgang Denk  * Entries without "value", i. e. consisting of only "name" or
749a6826fbcSWolfgang Denk  * "name=", will cause this entry to be deleted from the hash table.
750a6826fbcSWolfgang Denk  *
751a6826fbcSWolfgang Denk  * The "flag" argument can be used to control the behaviour: when the
752a6826fbcSWolfgang Denk  * H_NOCLEAR bit is set, then an existing hash table will kept, i. e.
753a6826fbcSWolfgang Denk  * new data will be added to an existing hash table; otherwise, old
754a6826fbcSWolfgang Denk  * data will be discarded and a new hash table will be created.
755a6826fbcSWolfgang Denk  *
756a6826fbcSWolfgang Denk  * The separator character for the "name=value" pairs can be selected,
757a6826fbcSWolfgang Denk  * so we both support importing from externally stored environment
758a6826fbcSWolfgang Denk  * data (separated by NUL characters) and from plain text files
759a6826fbcSWolfgang Denk  * (entries separated by newline characters).
760a6826fbcSWolfgang Denk  *
761a6826fbcSWolfgang Denk  * To allow for nicely formatted text input, leading white space
762a6826fbcSWolfgang Denk  * (sequences of SPACE and TAB chars) is ignored, and entries starting
763a6826fbcSWolfgang Denk  * (after removal of any leading white space) with a '#' character are
764a6826fbcSWolfgang Denk  * considered comments and ignored.
765a6826fbcSWolfgang Denk  *
766a6826fbcSWolfgang Denk  * [NOTE: this means that a variable name cannot start with a '#'
767a6826fbcSWolfgang Denk  * character.]
768a6826fbcSWolfgang Denk  *
769a6826fbcSWolfgang Denk  * When using a non-NUL separator character, backslash is used as
770a6826fbcSWolfgang Denk  * escape character in the value part, allowing for example for
771a6826fbcSWolfgang Denk  * multi-line values.
772a6826fbcSWolfgang Denk  *
773a6826fbcSWolfgang Denk  * In theory, arbitrary separator characters can be used, but only
774a6826fbcSWolfgang Denk  * '\0' and '\n' have really been tested.
775a6826fbcSWolfgang Denk  */
776a6826fbcSWolfgang 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[])777a6826fbcSWolfgang Denk int himport_r(struct hsearch_data *htab,
778348b1f1cSGerlando Falauto 		const char *env, size_t size, const char sep, int flag,
779ecd1446fSAlexander Holler 		int crlf_is_lf, int nvars, char * const vars[])
780a6826fbcSWolfgang Denk {
781a6826fbcSWolfgang Denk 	char *data, *sp, *dp, *name, *value;
782d5370febSGerlando Falauto 	char *localvars[nvars];
783a6826fbcSWolfgang Denk 
784a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
785a6826fbcSWolfgang Denk 	if (htab == NULL) {
786a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
787a6826fbcSWolfgang Denk 		return 0;
788a6826fbcSWolfgang Denk 	}
789a6826fbcSWolfgang Denk 
790a6826fbcSWolfgang Denk 	/* we allocate new space to make sure we can write to the array */
791817e48d8SLukasz Majewski 	if ((data = malloc(size + 1)) == NULL) {
792c55d02b2SSimon Glass 		debug("himport_r: can't malloc %lu bytes\n", (ulong)size + 1);
793a6826fbcSWolfgang Denk 		__set_errno(ENOMEM);
794a6826fbcSWolfgang Denk 		return 0;
795a6826fbcSWolfgang Denk 	}
796a6826fbcSWolfgang Denk 	memcpy(data, env, size);
797817e48d8SLukasz Majewski 	data[size] = '\0';
798a6826fbcSWolfgang Denk 	dp = data;
799a6826fbcSWolfgang Denk 
800d5370febSGerlando Falauto 	/* make a local copy of the list of variables */
801d5370febSGerlando Falauto 	if (nvars)
802d5370febSGerlando Falauto 		memcpy(localvars, vars, sizeof(vars[0]) * nvars);
803d5370febSGerlando Falauto 
804a6826fbcSWolfgang Denk 	if ((flag & H_NOCLEAR) == 0) {
805a6826fbcSWolfgang Denk 		/* Destroy old hash table if one exists */
806a6826fbcSWolfgang Denk 		debug("Destroy Hash Table: %p table = %p\n", htab,
807a6826fbcSWolfgang Denk 		       htab->table);
808a6826fbcSWolfgang Denk 		if (htab->table)
809c4e0057fSJoe Hershberger 			hdestroy_r(htab);
810a6826fbcSWolfgang Denk 	}
811a6826fbcSWolfgang Denk 
812a6826fbcSWolfgang Denk 	/*
813a6826fbcSWolfgang Denk 	 * Create new hash table (if needed).  The computation of the hash
814a6826fbcSWolfgang Denk 	 * table size is based on heuristics: in a sample of some 70+
815a6826fbcSWolfgang Denk 	 * existing systems we found an average size of 39+ bytes per entry
816a6826fbcSWolfgang Denk 	 * in the environment (for the whole key=value pair). Assuming a
817ea882bafSWolfgang Denk 	 * size of 8 per entry (= safety factor of ~5) should provide enough
818ea882bafSWolfgang Denk 	 * safety margin for any existing environment definitions and still
819a6826fbcSWolfgang Denk 	 * allow for more than enough dynamic additions. Note that the
8201bce2aebSRobert P. J. Day 	 * "size" argument is supposed to give the maximum environment size
821ea882bafSWolfgang Denk 	 * (CONFIG_ENV_SIZE).  This heuristics will result in
822ea882bafSWolfgang Denk 	 * unreasonably large numbers (and thus memory footprint) for
823ea882bafSWolfgang Denk 	 * big flash environments (>8,000 entries for 64 KB
82462a3b7ddSRobert P. J. Day 	 * environment size), so we clip it to a reasonable value.
825fc5fc76bSAndreas Bießmann 	 * On the other hand we need to add some more entries for free
826fc5fc76bSAndreas Bießmann 	 * space when importing very small buffers. Both boundaries can
827fc5fc76bSAndreas Bießmann 	 * be overwritten in the board config file if needed.
828a6826fbcSWolfgang Denk 	 */
829a6826fbcSWolfgang Denk 
830a6826fbcSWolfgang Denk 	if (!htab->table) {
831fc5fc76bSAndreas Bießmann 		int nent = CONFIG_ENV_MIN_ENTRIES + size / 8;
832ea882bafSWolfgang Denk 
833ea882bafSWolfgang Denk 		if (nent > CONFIG_ENV_MAX_ENTRIES)
834ea882bafSWolfgang Denk 			nent = CONFIG_ENV_MAX_ENTRIES;
835a6826fbcSWolfgang Denk 
836a6826fbcSWolfgang Denk 		debug("Create Hash Table: N=%d\n", nent);
837a6826fbcSWolfgang Denk 
838a6826fbcSWolfgang Denk 		if (hcreate_r(nent, htab) == 0) {
839a6826fbcSWolfgang Denk 			free(data);
840a6826fbcSWolfgang Denk 			return 0;
841a6826fbcSWolfgang Denk 		}
842a6826fbcSWolfgang Denk 	}
843a6826fbcSWolfgang Denk 
8440226d878SLukasz Majewski 	if (!size) {
8450226d878SLukasz Majewski 		free(data);
846ecd1446fSAlexander Holler 		return 1;		/* everything OK */
8470226d878SLukasz Majewski 	}
848ecd1446fSAlexander Holler 	if(crlf_is_lf) {
849ecd1446fSAlexander Holler 		/* Remove Carriage Returns in front of Line Feeds */
850ecd1446fSAlexander Holler 		unsigned ignored_crs = 0;
851ecd1446fSAlexander Holler 		for(;dp < data + size && *dp; ++dp) {
852ecd1446fSAlexander Holler 			if(*dp == '\r' &&
853ecd1446fSAlexander Holler 			   dp < data + size - 1 && *(dp+1) == '\n')
854ecd1446fSAlexander Holler 				++ignored_crs;
855ecd1446fSAlexander Holler 			else
856ecd1446fSAlexander Holler 				*(dp-ignored_crs) = *dp;
857ecd1446fSAlexander Holler 		}
858ecd1446fSAlexander Holler 		size -= ignored_crs;
859ecd1446fSAlexander Holler 		dp = data;
860ecd1446fSAlexander Holler 	}
861a6826fbcSWolfgang Denk 	/* Parse environment; allow for '\0' and 'sep' as separators */
862a6826fbcSWolfgang Denk 	do {
863a6826fbcSWolfgang Denk 		ENTRY e, *rv;
864a6826fbcSWolfgang Denk 
865a6826fbcSWolfgang Denk 		/* skip leading white space */
8664d91a6ecSJason Hobbs 		while (isblank(*dp))
867a6826fbcSWolfgang Denk 			++dp;
868a6826fbcSWolfgang Denk 
869a6826fbcSWolfgang Denk 		/* skip comment lines */
870a6826fbcSWolfgang Denk 		if (*dp == '#') {
871a6826fbcSWolfgang Denk 			while (*dp && (*dp != sep))
872a6826fbcSWolfgang Denk 				++dp;
873a6826fbcSWolfgang Denk 			++dp;
874a6826fbcSWolfgang Denk 			continue;
875a6826fbcSWolfgang Denk 		}
876a6826fbcSWolfgang Denk 
877a6826fbcSWolfgang Denk 		/* parse name */
878a6826fbcSWolfgang Denk 		for (name = dp; *dp != '=' && *dp && *dp != sep; ++dp)
879a6826fbcSWolfgang Denk 			;
880a6826fbcSWolfgang Denk 
881a6826fbcSWolfgang Denk 		/* deal with "name" and "name=" entries (delete var) */
882a6826fbcSWolfgang Denk 		if (*dp == '\0' || *(dp + 1) == '\0' ||
883a6826fbcSWolfgang Denk 		    *dp == sep || *(dp + 1) == sep) {
884a6826fbcSWolfgang Denk 			if (*dp == '=')
885a6826fbcSWolfgang Denk 				*dp++ = '\0';
886a6826fbcSWolfgang Denk 			*dp++ = '\0';	/* terminate name */
887a6826fbcSWolfgang Denk 
888a6826fbcSWolfgang Denk 			debug("DELETE CANDIDATE: \"%s\"\n", name);
889d5370febSGerlando Falauto 			if (!drop_var_from_set(name, nvars, localvars))
890348b1f1cSGerlando Falauto 				continue;
891a6826fbcSWolfgang Denk 
892c4e0057fSJoe Hershberger 			if (hdelete_r(name, htab, flag) == 0)
893a6826fbcSWolfgang Denk 				debug("DELETE ERROR ##############################\n");
894a6826fbcSWolfgang Denk 
895a6826fbcSWolfgang Denk 			continue;
896a6826fbcSWolfgang Denk 		}
897a6826fbcSWolfgang Denk 		*dp++ = '\0';	/* terminate name */
898a6826fbcSWolfgang Denk 
899a6826fbcSWolfgang Denk 		/* parse value; deal with escapes */
900a6826fbcSWolfgang Denk 		for (value = sp = dp; *dp && (*dp != sep); ++dp) {
901a6826fbcSWolfgang Denk 			if ((*dp == '\\') && *(dp + 1))
902a6826fbcSWolfgang Denk 				++dp;
903a6826fbcSWolfgang Denk 			*sp++ = *dp;
904a6826fbcSWolfgang Denk 		}
905a6826fbcSWolfgang Denk 		*sp++ = '\0';	/* terminate value */
906a6826fbcSWolfgang Denk 		++dp;
907a6826fbcSWolfgang Denk 
908e4fdcaddSLucian Cojocar 		if (*name == 0) {
909e4fdcaddSLucian Cojocar 			debug("INSERT: unable to use an empty key\n");
910e4fdcaddSLucian Cojocar 			__set_errno(EINVAL);
9110226d878SLukasz Majewski 			free(data);
912e4fdcaddSLucian Cojocar 			return 0;
913e4fdcaddSLucian Cojocar 		}
914e4fdcaddSLucian Cojocar 
915348b1f1cSGerlando Falauto 		/* Skip variables which are not supposed to be processed */
916d5370febSGerlando Falauto 		if (!drop_var_from_set(name, nvars, localvars))
917348b1f1cSGerlando Falauto 			continue;
918348b1f1cSGerlando Falauto 
919a6826fbcSWolfgang Denk 		/* enter into hash table */
920a6826fbcSWolfgang Denk 		e.key = name;
921a6826fbcSWolfgang Denk 		e.data = value;
922a6826fbcSWolfgang Denk 
923c4e0057fSJoe Hershberger 		hsearch_r(e, ENTER, &rv, htab, flag);
924170ab110SJoe Hershberger 		if (rv == NULL)
925ea882bafSWolfgang Denk 			printf("himport_r: can't insert \"%s=%s\" into hash table\n",
926ea882bafSWolfgang Denk 				name, value);
927a6826fbcSWolfgang Denk 
928ea882bafSWolfgang Denk 		debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"\n",
929ea882bafSWolfgang Denk 			htab, htab->filled, htab->size,
930ea882bafSWolfgang Denk 			rv, name, value);
931a6826fbcSWolfgang Denk 	} while ((dp < data + size) && *dp);	/* size check needed for text */
932a6826fbcSWolfgang Denk 						/* without '\0' termination */
933ea882bafSWolfgang Denk 	debug("INSERT: free(data = %p)\n", data);
934a6826fbcSWolfgang Denk 	free(data);
935a6826fbcSWolfgang Denk 
9367a38549fSJoseph Chen 	/*
9377a38549fSJoseph Chen 	 * CONFIG_ENVF=y: don't delete the default variables when they are
938*e12b5efdSJoseph Chen 	 * not present in env.img
9397a38549fSJoseph Chen 	 */
9407a38549fSJoseph Chen #ifndef CONFIG_ENVF
9417a38549fSJoseph Chen 	int i;
9427a38549fSJoseph Chen 
943d5370febSGerlando Falauto 	/* process variables which were not considered */
944d5370febSGerlando Falauto 	for (i = 0; i < nvars; i++) {
945d5370febSGerlando Falauto 		if (localvars[i] == NULL)
946d5370febSGerlando Falauto 			continue;
947d5370febSGerlando Falauto 		/*
948d5370febSGerlando Falauto 		 * All variables which were not deleted from the variable list
949d5370febSGerlando Falauto 		 * were not present in the imported env
950d5370febSGerlando Falauto 		 * This could mean two things:
951d5370febSGerlando Falauto 		 * a) if the variable was present in current env, we delete it
952d5370febSGerlando Falauto 		 * b) if the variable was not present in current env, we notify
953d5370febSGerlando Falauto 		 *    it might be a typo
954d5370febSGerlando Falauto 		 */
955c4e0057fSJoe Hershberger 		if (hdelete_r(localvars[i], htab, flag) == 0)
956d5370febSGerlando Falauto 			printf("WARNING: '%s' neither in running nor in imported env!\n", localvars[i]);
957d5370febSGerlando Falauto 		else
958d5370febSGerlando Falauto 			printf("WARNING: '%s' not in imported env, deleting it!\n", localvars[i]);
959d5370febSGerlando Falauto 	}
9607a38549fSJoseph Chen #endif
961ea882bafSWolfgang Denk 	debug("INSERT: done\n");
962a6826fbcSWolfgang Denk 	return 1;		/* everything OK */
963a6826fbcSWolfgang Denk }
964170ab110SJoe Hershberger 
965170ab110SJoe Hershberger /*
966170ab110SJoe Hershberger  * hwalk_r()
967170ab110SJoe Hershberger  */
968170ab110SJoe Hershberger 
969170ab110SJoe Hershberger /*
970170ab110SJoe Hershberger  * Walk all of the entries in the hash, calling the callback for each one.
971170ab110SJoe Hershberger  * this allows some generic operation to be performed on each element.
972170ab110SJoe Hershberger  */
hwalk_r(struct hsearch_data * htab,int (* callback)(ENTRY *))973170ab110SJoe Hershberger int hwalk_r(struct hsearch_data *htab, int (*callback)(ENTRY *))
974170ab110SJoe Hershberger {
975170ab110SJoe Hershberger 	int i;
976170ab110SJoe Hershberger 	int retval;
977170ab110SJoe Hershberger 
978170ab110SJoe Hershberger 	for (i = 1; i <= htab->size; ++i) {
979170ab110SJoe Hershberger 		if (htab->table[i].used > 0) {
980170ab110SJoe Hershberger 			retval = callback(&htab->table[i].entry);
981170ab110SJoe Hershberger 			if (retval)
982170ab110SJoe Hershberger 				return retval;
983170ab110SJoe Hershberger 		}
984170ab110SJoe Hershberger 	}
985170ab110SJoe Hershberger 
986170ab110SJoe Hershberger 	return 0;
987170ab110SJoe Hershberger }
988