xref: /rk3399_rockchip-uboot/lib/hashtable.c (revision 5a31ea04c9ee5544fbb70ad7597ea4b294840eab)
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  *
13a6826fbcSWolfgang Denk  * The GNU C Library is free software; you can redistribute it and/or
14a6826fbcSWolfgang Denk  * modify it under the terms of the GNU Lesser General Public
15a6826fbcSWolfgang Denk  * License as published by the Free Software Foundation; either
16a6826fbcSWolfgang Denk  * version 2.1 of the License, or (at your option) any later version.
17a6826fbcSWolfgang Denk  *
18a6826fbcSWolfgang Denk  * The GNU C Library is distributed in the hope that it will be useful,
19a6826fbcSWolfgang Denk  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20a6826fbcSWolfgang Denk  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21a6826fbcSWolfgang Denk  * Lesser General Public License for more details.
22a6826fbcSWolfgang Denk  *
23a6826fbcSWolfgang Denk  * You should have received a copy of the GNU Lesser General Public
24a6826fbcSWolfgang Denk  * License along with the GNU C Library; if not, write to the Free
25a6826fbcSWolfgang Denk  * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26a6826fbcSWolfgang Denk  * 02111-1307 USA.
27a6826fbcSWolfgang Denk  */
28a6826fbcSWolfgang Denk 
29a6826fbcSWolfgang Denk #include <errno.h>
30a6826fbcSWolfgang Denk #include <malloc.h>
31a6826fbcSWolfgang Denk 
32a6826fbcSWolfgang Denk #ifdef USE_HOSTCC		/* HOST build */
33a6826fbcSWolfgang Denk # include <string.h>
34a6826fbcSWolfgang Denk # include <assert.h>
354d91a6ecSJason Hobbs # include <ctype.h>
36a6826fbcSWolfgang Denk 
37a6826fbcSWolfgang Denk # ifndef debug
38a6826fbcSWolfgang Denk #  ifdef DEBUG
39a6826fbcSWolfgang Denk #   define debug(fmt,args...)	printf(fmt ,##args)
40a6826fbcSWolfgang Denk #  else
41a6826fbcSWolfgang Denk #   define debug(fmt,args...)
42a6826fbcSWolfgang Denk #  endif
43a6826fbcSWolfgang Denk # endif
44a6826fbcSWolfgang Denk #else				/* U-Boot build */
45a6826fbcSWolfgang Denk # include <common.h>
46a6826fbcSWolfgang Denk # include <linux/string.h>
474d91a6ecSJason Hobbs # include <linux/ctype.h>
48a6826fbcSWolfgang Denk #endif
49a6826fbcSWolfgang Denk 
50fc5fc76bSAndreas Bießmann #ifndef	CONFIG_ENV_MIN_ENTRIES	/* minimum number of entries */
51fc5fc76bSAndreas Bießmann #define	CONFIG_ENV_MIN_ENTRIES 64
52fc5fc76bSAndreas Bießmann #endif
53ea882bafSWolfgang Denk #ifndef	CONFIG_ENV_MAX_ENTRIES	/* maximum number of entries */
54ea882bafSWolfgang Denk #define	CONFIG_ENV_MAX_ENTRIES 512
55ea882bafSWolfgang Denk #endif
56ea882bafSWolfgang Denk 
57170ab110SJoe Hershberger #include <env_callback.h>
582598090bSJoe Hershberger #include <env_flags.h>
59170ab110SJoe Hershberger #include <search.h>
60a6826fbcSWolfgang Denk 
61a6826fbcSWolfgang Denk /*
62a6826fbcSWolfgang Denk  * [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
63a6826fbcSWolfgang Denk  * [Knuth]	      The Art of Computer Programming, part 3 (6.4)
64a6826fbcSWolfgang Denk  */
65a6826fbcSWolfgang Denk 
66a6826fbcSWolfgang Denk /*
67a6826fbcSWolfgang Denk  * The reentrant version has no static variables to maintain the state.
68a6826fbcSWolfgang Denk  * Instead the interface of all functions is extended to take an argument
69a6826fbcSWolfgang Denk  * which describes the current status.
70a6826fbcSWolfgang Denk  */
717afcf3a5SJoe Hershberger 
72a6826fbcSWolfgang Denk typedef struct _ENTRY {
73c81c1222SPeter Barada 	int used;
74a6826fbcSWolfgang Denk 	ENTRY entry;
75a6826fbcSWolfgang Denk } _ENTRY;
76a6826fbcSWolfgang Denk 
77a6826fbcSWolfgang Denk 
787afcf3a5SJoe Hershberger static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
797afcf3a5SJoe Hershberger 	int idx);
807afcf3a5SJoe Hershberger 
81a6826fbcSWolfgang Denk /*
82a6826fbcSWolfgang Denk  * hcreate()
83a6826fbcSWolfgang Denk  */
84a6826fbcSWolfgang Denk 
85a6826fbcSWolfgang Denk /*
86a6826fbcSWolfgang Denk  * For the used double hash method the table size has to be a prime. To
87a6826fbcSWolfgang Denk  * correct the user given table size we need a prime test.  This trivial
88a6826fbcSWolfgang Denk  * algorithm is adequate because
89a6826fbcSWolfgang Denk  * a)  the code is (most probably) called a few times per program run and
90a6826fbcSWolfgang Denk  * b)  the number is small because the table must fit in the core
91a6826fbcSWolfgang Denk  * */
92a6826fbcSWolfgang Denk static int isprime(unsigned int number)
93a6826fbcSWolfgang Denk {
94a6826fbcSWolfgang Denk 	/* no even number will be passed */
95a6826fbcSWolfgang Denk 	unsigned int div = 3;
96a6826fbcSWolfgang Denk 
97a6826fbcSWolfgang Denk 	while (div * div < number && number % div != 0)
98a6826fbcSWolfgang Denk 		div += 2;
99a6826fbcSWolfgang Denk 
100a6826fbcSWolfgang Denk 	return number % div != 0;
101a6826fbcSWolfgang Denk }
102a6826fbcSWolfgang Denk 
103a6826fbcSWolfgang Denk /*
104a6826fbcSWolfgang Denk  * Before using the hash table we must allocate memory for it.
105a6826fbcSWolfgang Denk  * Test for an existing table are done. We allocate one element
106a6826fbcSWolfgang Denk  * more as the found prime number says. This is done for more effective
107a6826fbcSWolfgang Denk  * indexing as explained in the comment for the hsearch function.
108a6826fbcSWolfgang Denk  * The contents of the table is zeroed, especially the field used
109a6826fbcSWolfgang Denk  * becomes zero.
110a6826fbcSWolfgang Denk  */
1112eb1573fSMike Frysinger 
112a6826fbcSWolfgang Denk int hcreate_r(size_t nel, struct hsearch_data *htab)
113a6826fbcSWolfgang Denk {
114a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
115a6826fbcSWolfgang Denk 	if (htab == NULL) {
116a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
117a6826fbcSWolfgang Denk 		return 0;
118a6826fbcSWolfgang Denk 	}
119a6826fbcSWolfgang Denk 
120a6826fbcSWolfgang Denk 	/* There is still another table active. Return with error. */
121a6826fbcSWolfgang Denk 	if (htab->table != NULL)
122a6826fbcSWolfgang Denk 		return 0;
123a6826fbcSWolfgang Denk 
124a6826fbcSWolfgang Denk 	/* Change nel to the first prime number not smaller as nel. */
125a6826fbcSWolfgang Denk 	nel |= 1;		/* make odd */
126a6826fbcSWolfgang Denk 	while (!isprime(nel))
127a6826fbcSWolfgang Denk 		nel += 2;
128a6826fbcSWolfgang Denk 
129a6826fbcSWolfgang Denk 	htab->size = nel;
130a6826fbcSWolfgang Denk 	htab->filled = 0;
131a6826fbcSWolfgang Denk 
132a6826fbcSWolfgang Denk 	/* allocate memory and zero out */
133a6826fbcSWolfgang Denk 	htab->table = (_ENTRY *) calloc(htab->size + 1, sizeof(_ENTRY));
134a6826fbcSWolfgang Denk 	if (htab->table == NULL)
135a6826fbcSWolfgang Denk 		return 0;
136a6826fbcSWolfgang Denk 
137a6826fbcSWolfgang Denk 	/* everything went alright */
138a6826fbcSWolfgang Denk 	return 1;
139a6826fbcSWolfgang Denk }
140a6826fbcSWolfgang Denk 
141a6826fbcSWolfgang Denk 
142a6826fbcSWolfgang Denk /*
143a6826fbcSWolfgang Denk  * hdestroy()
144a6826fbcSWolfgang Denk  */
145a6826fbcSWolfgang Denk 
146a6826fbcSWolfgang Denk /*
147a6826fbcSWolfgang Denk  * After using the hash table it has to be destroyed. The used memory can
148a6826fbcSWolfgang Denk  * be freed and the local static variable can be marked as not used.
149a6826fbcSWolfgang Denk  */
1502eb1573fSMike Frysinger 
151c4e0057fSJoe Hershberger void hdestroy_r(struct hsearch_data *htab)
152a6826fbcSWolfgang Denk {
153a6826fbcSWolfgang Denk 	int i;
154a6826fbcSWolfgang Denk 
155a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
156a6826fbcSWolfgang Denk 	if (htab == NULL) {
157a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
158a6826fbcSWolfgang Denk 		return;
159a6826fbcSWolfgang Denk 	}
160a6826fbcSWolfgang Denk 
161a6826fbcSWolfgang Denk 	/* free used memory */
162a6826fbcSWolfgang Denk 	for (i = 1; i <= htab->size; ++i) {
163c81c1222SPeter Barada 		if (htab->table[i].used > 0) {
164a6826fbcSWolfgang Denk 			ENTRY *ep = &htab->table[i].entry;
165c4e0057fSJoe Hershberger 
16684b5e802SWolfgang Denk 			free((void *)ep->key);
167a6826fbcSWolfgang Denk 			free(ep->data);
168a6826fbcSWolfgang Denk 		}
169a6826fbcSWolfgang Denk 	}
170a6826fbcSWolfgang Denk 	free(htab->table);
171a6826fbcSWolfgang Denk 
172a6826fbcSWolfgang Denk 	/* the sign for an existing table is an value != NULL in htable */
173a6826fbcSWolfgang Denk 	htab->table = NULL;
174a6826fbcSWolfgang Denk }
175a6826fbcSWolfgang Denk 
176a6826fbcSWolfgang Denk /*
177a6826fbcSWolfgang Denk  * hsearch()
178a6826fbcSWolfgang Denk  */
179a6826fbcSWolfgang Denk 
180a6826fbcSWolfgang Denk /*
181a6826fbcSWolfgang Denk  * This is the search function. It uses double hashing with open addressing.
182a6826fbcSWolfgang Denk  * The argument item.key has to be a pointer to an zero terminated, most
183a6826fbcSWolfgang Denk  * probably strings of chars. The function for generating a number of the
184a6826fbcSWolfgang Denk  * strings is simple but fast. It can be replaced by a more complex function
185a6826fbcSWolfgang Denk  * like ajw (see [Aho,Sethi,Ullman]) if the needs are shown.
186a6826fbcSWolfgang Denk  *
187a6826fbcSWolfgang Denk  * We use an trick to speed up the lookup. The table is created by hcreate
188a6826fbcSWolfgang Denk  * with one more element available. This enables us to use the index zero
189a6826fbcSWolfgang Denk  * special. This index will never be used because we store the first hash
190a6826fbcSWolfgang Denk  * index in the field used where zero means not used. Every other value
191a6826fbcSWolfgang Denk  * means used. The used field can be used as a first fast comparison for
192a6826fbcSWolfgang Denk  * equality of the stored and the parameter value. This helps to prevent
193a6826fbcSWolfgang Denk  * unnecessary expensive calls of strcmp.
194a6826fbcSWolfgang Denk  *
195a6826fbcSWolfgang Denk  * This implementation differs from the standard library version of
196a6826fbcSWolfgang Denk  * this function in a number of ways:
197a6826fbcSWolfgang Denk  *
198a6826fbcSWolfgang Denk  * - While the standard version does not make any assumptions about
199a6826fbcSWolfgang Denk  *   the type of the stored data objects at all, this implementation
200a6826fbcSWolfgang Denk  *   works with NUL terminated strings only.
201a6826fbcSWolfgang Denk  * - Instead of storing just pointers to the original objects, we
202a6826fbcSWolfgang Denk  *   create local copies so the caller does not need to care about the
203a6826fbcSWolfgang Denk  *   data any more.
204a6826fbcSWolfgang Denk  * - The standard implementation does not provide a way to update an
205a6826fbcSWolfgang Denk  *   existing entry.  This version will create a new entry or update an
206a6826fbcSWolfgang Denk  *   existing one when both "action == ENTER" and "item.data != NULL".
207a6826fbcSWolfgang Denk  * - Instead of returning 1 on success, we return the index into the
208a6826fbcSWolfgang Denk  *   internal hash table, which is also guaranteed to be positive.
209a6826fbcSWolfgang Denk  *   This allows us direct access to the found hash table slot for
210a6826fbcSWolfgang Denk  *   example for functions like hdelete().
211a6826fbcSWolfgang Denk  */
212a6826fbcSWolfgang Denk 
213560d424bSMike Frysinger int hmatch_r(const char *match, int last_idx, ENTRY ** retval,
214560d424bSMike Frysinger 	     struct hsearch_data *htab)
215560d424bSMike Frysinger {
216560d424bSMike Frysinger 	unsigned int idx;
217560d424bSMike Frysinger 	size_t key_len = strlen(match);
218560d424bSMike Frysinger 
219560d424bSMike Frysinger 	for (idx = last_idx + 1; idx < htab->size; ++idx) {
220af4d9074SKim Phillips 		if (htab->table[idx].used <= 0)
221560d424bSMike Frysinger 			continue;
222560d424bSMike Frysinger 		if (!strncmp(match, htab->table[idx].entry.key, key_len)) {
223560d424bSMike Frysinger 			*retval = &htab->table[idx].entry;
224560d424bSMike Frysinger 			return idx;
225560d424bSMike Frysinger 		}
226560d424bSMike Frysinger 	}
227560d424bSMike Frysinger 
228560d424bSMike Frysinger 	__set_errno(ESRCH);
229560d424bSMike Frysinger 	*retval = NULL;
230560d424bSMike Frysinger 	return 0;
231560d424bSMike Frysinger }
232560d424bSMike Frysinger 
2333d3b52f2SJoe Hershberger /*
2343d3b52f2SJoe Hershberger  * Compare an existing entry with the desired key, and overwrite if the action
2353d3b52f2SJoe Hershberger  * is ENTER.  This is simply a helper function for hsearch_r().
2363d3b52f2SJoe Hershberger  */
2373d3b52f2SJoe Hershberger static inline int _compare_and_overwrite_entry(ENTRY item, ACTION action,
2383d3b52f2SJoe Hershberger 	ENTRY **retval, struct hsearch_data *htab, int flag,
2393d3b52f2SJoe Hershberger 	unsigned int hval, unsigned int idx)
2403d3b52f2SJoe Hershberger {
2413d3b52f2SJoe Hershberger 	if (htab->table[idx].used == hval
2423d3b52f2SJoe Hershberger 	    && strcmp(item.key, htab->table[idx].entry.key) == 0) {
2433d3b52f2SJoe Hershberger 		/* Overwrite existing value? */
2443d3b52f2SJoe Hershberger 		if ((action == ENTER) && (item.data != NULL)) {
2457afcf3a5SJoe Hershberger 			/* check for permission */
2467afcf3a5SJoe Hershberger 			if (htab->change_ok != NULL && htab->change_ok(
2477afcf3a5SJoe Hershberger 			    &htab->table[idx].entry, item.data,
2487afcf3a5SJoe Hershberger 			    env_op_overwrite, flag)) {
2497afcf3a5SJoe Hershberger 				debug("change_ok() rejected setting variable "
2507afcf3a5SJoe Hershberger 					"%s, skipping it!\n", item.key);
2517afcf3a5SJoe Hershberger 				__set_errno(EPERM);
2527afcf3a5SJoe Hershberger 				*retval = NULL;
2537afcf3a5SJoe Hershberger 				return 0;
2547afcf3a5SJoe Hershberger 			}
2557afcf3a5SJoe Hershberger 
256170ab110SJoe Hershberger 			/* If there is a callback, call it */
257170ab110SJoe Hershberger 			if (htab->table[idx].entry.callback &&
258170ab110SJoe Hershberger 			    htab->table[idx].entry.callback(item.key,
259170ab110SJoe Hershberger 			    item.data, env_op_overwrite, flag)) {
260170ab110SJoe Hershberger 				debug("callback() rejected setting variable "
261170ab110SJoe Hershberger 					"%s, skipping it!\n", item.key);
262170ab110SJoe Hershberger 				__set_errno(EINVAL);
263170ab110SJoe Hershberger 				*retval = NULL;
264170ab110SJoe Hershberger 				return 0;
265170ab110SJoe Hershberger 			}
266170ab110SJoe Hershberger 
2673d3b52f2SJoe Hershberger 			free(htab->table[idx].entry.data);
2683d3b52f2SJoe Hershberger 			htab->table[idx].entry.data = strdup(item.data);
2693d3b52f2SJoe Hershberger 			if (!htab->table[idx].entry.data) {
2703d3b52f2SJoe Hershberger 				__set_errno(ENOMEM);
2713d3b52f2SJoe Hershberger 				*retval = NULL;
2723d3b52f2SJoe Hershberger 				return 0;
2733d3b52f2SJoe Hershberger 			}
2743d3b52f2SJoe Hershberger 		}
2753d3b52f2SJoe Hershberger 		/* return found entry */
2763d3b52f2SJoe Hershberger 		*retval = &htab->table[idx].entry;
2773d3b52f2SJoe Hershberger 		return idx;
2783d3b52f2SJoe Hershberger 	}
2793d3b52f2SJoe Hershberger 	/* keep searching */
2803d3b52f2SJoe Hershberger 	return -1;
2813d3b52f2SJoe Hershberger }
2823d3b52f2SJoe Hershberger 
283a6826fbcSWolfgang Denk int hsearch_r(ENTRY item, ACTION action, ENTRY ** retval,
284c4e0057fSJoe Hershberger 	      struct hsearch_data *htab, int flag)
285a6826fbcSWolfgang Denk {
286a6826fbcSWolfgang Denk 	unsigned int hval;
287a6826fbcSWolfgang Denk 	unsigned int count;
288a6826fbcSWolfgang Denk 	unsigned int len = strlen(item.key);
289a6826fbcSWolfgang Denk 	unsigned int idx;
290c81c1222SPeter Barada 	unsigned int first_deleted = 0;
2913d3b52f2SJoe Hershberger 	int ret;
292a6826fbcSWolfgang Denk 
293a6826fbcSWolfgang Denk 	/* Compute an value for the given string. Perhaps use a better method. */
294a6826fbcSWolfgang Denk 	hval = len;
295a6826fbcSWolfgang Denk 	count = len;
296a6826fbcSWolfgang Denk 	while (count-- > 0) {
297a6826fbcSWolfgang Denk 		hval <<= 4;
298a6826fbcSWolfgang Denk 		hval += item.key[count];
299a6826fbcSWolfgang Denk 	}
300a6826fbcSWolfgang Denk 
301a6826fbcSWolfgang Denk 	/*
302a6826fbcSWolfgang Denk 	 * First hash function:
303a6826fbcSWolfgang Denk 	 * simply take the modul but prevent zero.
304a6826fbcSWolfgang Denk 	 */
305a6826fbcSWolfgang Denk 	hval %= htab->size;
306a6826fbcSWolfgang Denk 	if (hval == 0)
307a6826fbcSWolfgang Denk 		++hval;
308a6826fbcSWolfgang Denk 
309a6826fbcSWolfgang Denk 	/* The first index tried. */
310a6826fbcSWolfgang Denk 	idx = hval;
311a6826fbcSWolfgang Denk 
312a6826fbcSWolfgang Denk 	if (htab->table[idx].used) {
313a6826fbcSWolfgang Denk 		/*
314a6826fbcSWolfgang Denk 		 * Further action might be required according to the
315a6826fbcSWolfgang Denk 		 * action value.
316a6826fbcSWolfgang Denk 		 */
317a6826fbcSWolfgang Denk 		unsigned hval2;
318a6826fbcSWolfgang Denk 
319c81c1222SPeter Barada 		if (htab->table[idx].used == -1
320c81c1222SPeter Barada 		    && !first_deleted)
321c81c1222SPeter Barada 			first_deleted = idx;
322c81c1222SPeter Barada 
3233d3b52f2SJoe Hershberger 		ret = _compare_and_overwrite_entry(item, action, retval, htab,
3243d3b52f2SJoe Hershberger 			flag, hval, idx);
3253d3b52f2SJoe Hershberger 		if (ret != -1)
3263d3b52f2SJoe Hershberger 			return ret;
327a6826fbcSWolfgang Denk 
328a6826fbcSWolfgang Denk 		/*
329a6826fbcSWolfgang Denk 		 * Second hash function:
330a6826fbcSWolfgang Denk 		 * as suggested in [Knuth]
331a6826fbcSWolfgang Denk 		 */
332a6826fbcSWolfgang Denk 		hval2 = 1 + hval % (htab->size - 2);
333a6826fbcSWolfgang Denk 
334a6826fbcSWolfgang Denk 		do {
335a6826fbcSWolfgang Denk 			/*
336a6826fbcSWolfgang Denk 			 * Because SIZE is prime this guarantees to
337a6826fbcSWolfgang Denk 			 * step through all available indices.
338a6826fbcSWolfgang Denk 			 */
339a6826fbcSWolfgang Denk 			if (idx <= hval2)
340a6826fbcSWolfgang Denk 				idx = htab->size + idx - hval2;
341a6826fbcSWolfgang Denk 			else
342a6826fbcSWolfgang Denk 				idx -= hval2;
343a6826fbcSWolfgang Denk 
344a6826fbcSWolfgang Denk 			/*
345a6826fbcSWolfgang Denk 			 * If we visited all entries leave the loop
346a6826fbcSWolfgang Denk 			 * unsuccessfully.
347a6826fbcSWolfgang Denk 			 */
348a6826fbcSWolfgang Denk 			if (idx == hval)
349a6826fbcSWolfgang Denk 				break;
350a6826fbcSWolfgang Denk 
351a6826fbcSWolfgang Denk 			/* If entry is found use it. */
3523d3b52f2SJoe Hershberger 			ret = _compare_and_overwrite_entry(item, action, retval,
3533d3b52f2SJoe Hershberger 				htab, flag, hval, idx);
3543d3b52f2SJoe Hershberger 			if (ret != -1)
3553d3b52f2SJoe Hershberger 				return ret;
356a6826fbcSWolfgang Denk 		}
357a6826fbcSWolfgang Denk 		while (htab->table[idx].used);
358a6826fbcSWolfgang Denk 	}
359a6826fbcSWolfgang Denk 
360a6826fbcSWolfgang Denk 	/* An empty bucket has been found. */
361a6826fbcSWolfgang Denk 	if (action == ENTER) {
362a6826fbcSWolfgang Denk 		/*
363a6826fbcSWolfgang Denk 		 * If table is full and another entry should be
364a6826fbcSWolfgang Denk 		 * entered return with error.
365a6826fbcSWolfgang Denk 		 */
366a6826fbcSWolfgang Denk 		if (htab->filled == htab->size) {
367a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
368a6826fbcSWolfgang Denk 			*retval = NULL;
369a6826fbcSWolfgang Denk 			return 0;
370a6826fbcSWolfgang Denk 		}
371a6826fbcSWolfgang Denk 
372a6826fbcSWolfgang Denk 		/*
373a6826fbcSWolfgang Denk 		 * Create new entry;
374a6826fbcSWolfgang Denk 		 * create copies of item.key and item.data
375a6826fbcSWolfgang Denk 		 */
376c81c1222SPeter Barada 		if (first_deleted)
377c81c1222SPeter Barada 			idx = first_deleted;
378c81c1222SPeter Barada 
379a6826fbcSWolfgang Denk 		htab->table[idx].used = hval;
380a6826fbcSWolfgang Denk 		htab->table[idx].entry.key = strdup(item.key);
381a6826fbcSWolfgang Denk 		htab->table[idx].entry.data = strdup(item.data);
382a6826fbcSWolfgang Denk 		if (!htab->table[idx].entry.key ||
383a6826fbcSWolfgang Denk 		    !htab->table[idx].entry.data) {
384a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
385a6826fbcSWolfgang Denk 			*retval = NULL;
386a6826fbcSWolfgang Denk 			return 0;
387a6826fbcSWolfgang Denk 		}
388a6826fbcSWolfgang Denk 
389a6826fbcSWolfgang Denk 		++htab->filled;
390a6826fbcSWolfgang Denk 
391170ab110SJoe Hershberger 		/* This is a new entry, so look up a possible callback */
392170ab110SJoe Hershberger 		env_callback_init(&htab->table[idx].entry);
3932598090bSJoe Hershberger 		/* Also look for flags */
3942598090bSJoe Hershberger 		env_flags_init(&htab->table[idx].entry);
395170ab110SJoe Hershberger 
3967afcf3a5SJoe Hershberger 		/* check for permission */
3977afcf3a5SJoe Hershberger 		if (htab->change_ok != NULL && htab->change_ok(
3987afcf3a5SJoe Hershberger 		    &htab->table[idx].entry, item.data, env_op_create, flag)) {
3997afcf3a5SJoe Hershberger 			debug("change_ok() rejected setting variable "
4007afcf3a5SJoe Hershberger 				"%s, skipping it!\n", item.key);
4017afcf3a5SJoe Hershberger 			_hdelete(item.key, htab, &htab->table[idx].entry, idx);
4027afcf3a5SJoe Hershberger 			__set_errno(EPERM);
4037afcf3a5SJoe Hershberger 			*retval = NULL;
4047afcf3a5SJoe Hershberger 			return 0;
4057afcf3a5SJoe Hershberger 		}
4067afcf3a5SJoe Hershberger 
407170ab110SJoe Hershberger 		/* If there is a callback, call it */
408170ab110SJoe Hershberger 		if (htab->table[idx].entry.callback &&
409170ab110SJoe Hershberger 		    htab->table[idx].entry.callback(item.key, item.data,
410170ab110SJoe Hershberger 		    env_op_create, flag)) {
411170ab110SJoe Hershberger 			debug("callback() rejected setting variable "
412170ab110SJoe Hershberger 				"%s, skipping it!\n", item.key);
413170ab110SJoe Hershberger 			_hdelete(item.key, htab, &htab->table[idx].entry, idx);
414170ab110SJoe Hershberger 			__set_errno(EINVAL);
415170ab110SJoe Hershberger 			*retval = NULL;
416170ab110SJoe Hershberger 			return 0;
417170ab110SJoe Hershberger 		}
418170ab110SJoe Hershberger 
419a6826fbcSWolfgang Denk 		/* return new entry */
420a6826fbcSWolfgang Denk 		*retval = &htab->table[idx].entry;
421a6826fbcSWolfgang Denk 		return 1;
422a6826fbcSWolfgang Denk 	}
423a6826fbcSWolfgang Denk 
424a6826fbcSWolfgang Denk 	__set_errno(ESRCH);
425a6826fbcSWolfgang Denk 	*retval = NULL;
426a6826fbcSWolfgang Denk 	return 0;
427a6826fbcSWolfgang Denk }
428a6826fbcSWolfgang Denk 
429a6826fbcSWolfgang Denk 
430a6826fbcSWolfgang Denk /*
431a6826fbcSWolfgang Denk  * hdelete()
432a6826fbcSWolfgang Denk  */
433a6826fbcSWolfgang Denk 
434a6826fbcSWolfgang Denk /*
435a6826fbcSWolfgang Denk  * The standard implementation of hsearch(3) does not provide any way
436a6826fbcSWolfgang Denk  * to delete any entries from the hash table.  We extend the code to
437a6826fbcSWolfgang Denk  * do that.
438a6826fbcSWolfgang Denk  */
439a6826fbcSWolfgang Denk 
4407afcf3a5SJoe Hershberger static void _hdelete(const char *key, struct hsearch_data *htab, ENTRY *ep,
4417afcf3a5SJoe Hershberger 	int idx)
4427afcf3a5SJoe Hershberger {
4437afcf3a5SJoe Hershberger 	/* free used ENTRY */
4447afcf3a5SJoe Hershberger 	debug("hdelete: DELETING key \"%s\"\n", key);
4457afcf3a5SJoe Hershberger 	free((void *)ep->key);
4467afcf3a5SJoe Hershberger 	free(ep->data);
447170ab110SJoe Hershberger 	ep->callback = NULL;
4482598090bSJoe Hershberger 	ep->flags = 0;
4497afcf3a5SJoe Hershberger 	htab->table[idx].used = -1;
4507afcf3a5SJoe Hershberger 
4517afcf3a5SJoe Hershberger 	--htab->filled;
4527afcf3a5SJoe Hershberger }
4537afcf3a5SJoe Hershberger 
454c4e0057fSJoe Hershberger int hdelete_r(const char *key, struct hsearch_data *htab, int flag)
455a6826fbcSWolfgang Denk {
456a6826fbcSWolfgang Denk 	ENTRY e, *ep;
457a6826fbcSWolfgang Denk 	int idx;
458a6826fbcSWolfgang Denk 
459a6826fbcSWolfgang Denk 	debug("hdelete: DELETE key \"%s\"\n", key);
460a6826fbcSWolfgang Denk 
461a6826fbcSWolfgang Denk 	e.key = (char *)key;
462a6826fbcSWolfgang Denk 
463c4e0057fSJoe Hershberger 	idx = hsearch_r(e, FIND, &ep, htab, 0);
464c4e0057fSJoe Hershberger 	if (idx == 0) {
465a6826fbcSWolfgang Denk 		__set_errno(ESRCH);
466a6826fbcSWolfgang Denk 		return 0;	/* not found */
467a6826fbcSWolfgang Denk 	}
468a6826fbcSWolfgang Denk 
469c4e0057fSJoe Hershberger 	/* Check for permission */
4707afcf3a5SJoe Hershberger 	if (htab->change_ok != NULL &&
4717afcf3a5SJoe Hershberger 	    htab->change_ok(ep, NULL, env_op_delete, flag)) {
4727afcf3a5SJoe Hershberger 		debug("change_ok() rejected deleting variable "
4737afcf3a5SJoe Hershberger 			"%s, skipping it!\n", key);
474c4e0057fSJoe Hershberger 		__set_errno(EPERM);
475c4e0057fSJoe Hershberger 		return 0;
476c4e0057fSJoe Hershberger 	}
477c4e0057fSJoe Hershberger 
478170ab110SJoe Hershberger 	/* If there is a callback, call it */
479170ab110SJoe Hershberger 	if (htab->table[idx].entry.callback &&
480170ab110SJoe Hershberger 	    htab->table[idx].entry.callback(key, NULL, env_op_delete, flag)) {
481170ab110SJoe Hershberger 		debug("callback() rejected deleting variable "
482170ab110SJoe Hershberger 			"%s, skipping it!\n", key);
483170ab110SJoe Hershberger 		__set_errno(EINVAL);
484170ab110SJoe Hershberger 		return 0;
485170ab110SJoe Hershberger 	}
486170ab110SJoe Hershberger 
4877afcf3a5SJoe Hershberger 	_hdelete(key, htab, ep, idx);
488a6826fbcSWolfgang Denk 
489a6826fbcSWolfgang Denk 	return 1;
490a6826fbcSWolfgang Denk }
491a6826fbcSWolfgang Denk 
492a6826fbcSWolfgang Denk /*
493a6826fbcSWolfgang Denk  * hexport()
494a6826fbcSWolfgang Denk  */
495a6826fbcSWolfgang Denk 
4967ac2fe2dSIlya Yanok #ifndef CONFIG_SPL_BUILD
497a6826fbcSWolfgang Denk /*
498a6826fbcSWolfgang Denk  * Export the data stored in the hash table in linearized form.
499a6826fbcSWolfgang Denk  *
500a6826fbcSWolfgang Denk  * Entries are exported as "name=value" strings, separated by an
501a6826fbcSWolfgang Denk  * arbitrary (non-NUL, of course) separator character. This allows to
502a6826fbcSWolfgang Denk  * use this function both when formatting the U-Boot environment for
503a6826fbcSWolfgang Denk  * external storage (using '\0' as separator), but also when using it
504a6826fbcSWolfgang Denk  * for the "printenv" command to print all variables, simply by using
505a6826fbcSWolfgang Denk  * as '\n" as separator. This can also be used for new features like
506a6826fbcSWolfgang Denk  * exporting the environment data as text file, including the option
507a6826fbcSWolfgang Denk  * for later re-import.
508a6826fbcSWolfgang Denk  *
509a6826fbcSWolfgang Denk  * The entries in the result list will be sorted by ascending key
510a6826fbcSWolfgang Denk  * values.
511a6826fbcSWolfgang Denk  *
512a6826fbcSWolfgang Denk  * If the separator character is different from NUL, then any
513a6826fbcSWolfgang Denk  * separator characters and backslash characters in the values will
514a6826fbcSWolfgang Denk  * be escaped by a preceeding backslash in output. This is needed for
515a6826fbcSWolfgang Denk  * example to enable multi-line values, especially when the output
516a6826fbcSWolfgang Denk  * shall later be parsed (for example, for re-import).
517a6826fbcSWolfgang Denk  *
518a6826fbcSWolfgang Denk  * There are several options how the result buffer is handled:
519a6826fbcSWolfgang Denk  *
520a6826fbcSWolfgang Denk  * *resp  size
521a6826fbcSWolfgang Denk  * -----------
522a6826fbcSWolfgang Denk  *  NULL    0	A string of sufficient length will be allocated.
523a6826fbcSWolfgang Denk  *  NULL   >0	A string of the size given will be
524a6826fbcSWolfgang Denk  *		allocated. An error will be returned if the size is
525a6826fbcSWolfgang Denk  *		not sufficient.  Any unused bytes in the string will
526a6826fbcSWolfgang Denk  *		be '\0'-padded.
527a6826fbcSWolfgang Denk  * !NULL    0	The user-supplied buffer will be used. No length
528a6826fbcSWolfgang Denk  *		checking will be performed, i. e. it is assumed that
529a6826fbcSWolfgang Denk  *		the buffer size will always be big enough. DANGEROUS.
530a6826fbcSWolfgang Denk  * !NULL   >0	The user-supplied buffer will be used. An error will
531a6826fbcSWolfgang Denk  *		be returned if the size is not sufficient.  Any unused
532a6826fbcSWolfgang Denk  *		bytes in the string will be '\0'-padded.
533a6826fbcSWolfgang Denk  */
534a6826fbcSWolfgang Denk 
535a6826fbcSWolfgang Denk static int cmpkey(const void *p1, const void *p2)
536a6826fbcSWolfgang Denk {
537a6826fbcSWolfgang Denk 	ENTRY *e1 = *(ENTRY **) p1;
538a6826fbcSWolfgang Denk 	ENTRY *e2 = *(ENTRY **) p2;
539a6826fbcSWolfgang Denk 
540a6826fbcSWolfgang Denk 	return (strcmp(e1->key, e2->key));
541a6826fbcSWolfgang Denk }
542a6826fbcSWolfgang Denk 
543*5a31ea04SWolfgang Denk static int match_string(int flag, const char *str, const char *pat)
544ea009d47SWolfgang Denk {
545ea009d47SWolfgang Denk 	switch (flag & H_MATCH_METHOD) {
546ea009d47SWolfgang Denk 	case H_MATCH_IDENT:
547*5a31ea04SWolfgang Denk 		if (strcmp(str, pat) == 0)
548*5a31ea04SWolfgang Denk 			return 1;
549*5a31ea04SWolfgang Denk 		break;
550*5a31ea04SWolfgang Denk 	case H_MATCH_SUBSTR:
551*5a31ea04SWolfgang Denk 		if (strstr(str, pat))
552ea009d47SWolfgang Denk 			return 1;
553ea009d47SWolfgang Denk 		break;
554ea009d47SWolfgang Denk 	default:
555ea009d47SWolfgang Denk 		printf("## ERROR: unsupported match method: 0x%02x\n",
556ea009d47SWolfgang Denk 			flag & H_MATCH_METHOD);
557ea009d47SWolfgang Denk 		break;
558ea009d47SWolfgang Denk 	}
559*5a31ea04SWolfgang Denk 	return 0;
560*5a31ea04SWolfgang Denk }
561*5a31ea04SWolfgang Denk 
562*5a31ea04SWolfgang Denk static int match_entry(ENTRY *ep, int flag,
563*5a31ea04SWolfgang Denk 		 int argc, char * const argv[])
564*5a31ea04SWolfgang Denk {
565*5a31ea04SWolfgang Denk 	int arg;
566*5a31ea04SWolfgang Denk 
567*5a31ea04SWolfgang Denk 	for (arg = 1; arg < argc; ++arg) {
568*5a31ea04SWolfgang Denk 		if (flag & H_MATCH_KEY) {
569*5a31ea04SWolfgang Denk 			if (match_string(flag, ep->key, argv[arg]))
570*5a31ea04SWolfgang Denk 				return 1;
571*5a31ea04SWolfgang Denk 		}
572*5a31ea04SWolfgang Denk 		if (flag & H_MATCH_DATA) {
573*5a31ea04SWolfgang Denk 			if (match_string(flag, ep->data, argv[arg]))
574*5a31ea04SWolfgang Denk 				return 1;
575ea009d47SWolfgang Denk 		}
576ea009d47SWolfgang Denk 	}
577ea009d47SWolfgang Denk 	return 0;
578ea009d47SWolfgang Denk }
579ea009d47SWolfgang Denk 
580be11235aSJoe Hershberger ssize_t hexport_r(struct hsearch_data *htab, const char sep, int flag,
58137f2fe74SWolfgang Denk 		 char **resp, size_t size,
58237f2fe74SWolfgang Denk 		 int argc, char * const argv[])
583a6826fbcSWolfgang Denk {
584a6826fbcSWolfgang Denk 	ENTRY *list[htab->size];
585a6826fbcSWolfgang Denk 	char *res, *p;
586a6826fbcSWolfgang Denk 	size_t totlen;
587a6826fbcSWolfgang Denk 	int i, n;
588a6826fbcSWolfgang Denk 
589a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
590a6826fbcSWolfgang Denk 	if ((resp == NULL) || (htab == NULL)) {
591a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
592a6826fbcSWolfgang Denk 		return (-1);
593a6826fbcSWolfgang Denk 	}
594a6826fbcSWolfgang Denk 
595ff856286SSimon Glass 	debug("EXPORT  table = %p, htab.size = %d, htab.filled = %d, "
596ff856286SSimon Glass 		"size = %zu\n", htab, htab->size, htab->filled, size);
597a6826fbcSWolfgang Denk 	/*
598a6826fbcSWolfgang Denk 	 * Pass 1:
599a6826fbcSWolfgang Denk 	 * search used entries,
600a6826fbcSWolfgang Denk 	 * save addresses and compute total length
601a6826fbcSWolfgang Denk 	 */
602a6826fbcSWolfgang Denk 	for (i = 1, n = 0, totlen = 0; i <= htab->size; ++i) {
603a6826fbcSWolfgang Denk 
604c81c1222SPeter Barada 		if (htab->table[i].used > 0) {
605a6826fbcSWolfgang Denk 			ENTRY *ep = &htab->table[i].entry;
606*5a31ea04SWolfgang Denk 			int found = match_entry(ep, flag, argc, argv);
60737f2fe74SWolfgang Denk 
60837f2fe74SWolfgang Denk 			if ((argc > 0) && (found == 0))
60937f2fe74SWolfgang Denk 				continue;
610a6826fbcSWolfgang Denk 
611be11235aSJoe Hershberger 			if ((flag & H_HIDE_DOT) && ep->key[0] == '.')
612be11235aSJoe Hershberger 				continue;
613be11235aSJoe Hershberger 
614a6826fbcSWolfgang Denk 			list[n++] = ep;
615a6826fbcSWolfgang Denk 
616a6826fbcSWolfgang Denk 			totlen += strlen(ep->key) + 2;
617a6826fbcSWolfgang Denk 
618a6826fbcSWolfgang Denk 			if (sep == '\0') {
619a6826fbcSWolfgang Denk 				totlen += strlen(ep->data);
620a6826fbcSWolfgang Denk 			} else {	/* check if escapes are needed */
621a6826fbcSWolfgang Denk 				char *s = ep->data;
622a6826fbcSWolfgang Denk 
623a6826fbcSWolfgang Denk 				while (*s) {
624a6826fbcSWolfgang Denk 					++totlen;
625a6826fbcSWolfgang Denk 					/* add room for needed escape chars */
626a6826fbcSWolfgang Denk 					if ((*s == sep) || (*s == '\\'))
627a6826fbcSWolfgang Denk 						++totlen;
628a6826fbcSWolfgang Denk 					++s;
629a6826fbcSWolfgang Denk 				}
630a6826fbcSWolfgang Denk 			}
631a6826fbcSWolfgang Denk 			totlen += 2;	/* for '=' and 'sep' char */
632a6826fbcSWolfgang Denk 		}
633a6826fbcSWolfgang Denk 	}
634a6826fbcSWolfgang Denk 
635a6826fbcSWolfgang Denk #ifdef DEBUG
636a6826fbcSWolfgang Denk 	/* Pass 1a: print unsorted list */
637a6826fbcSWolfgang Denk 	printf("Unsorted: n=%d\n", n);
638a6826fbcSWolfgang Denk 	for (i = 0; i < n; ++i) {
639a6826fbcSWolfgang Denk 		printf("\t%3d: %p ==> %-10s => %s\n",
640a6826fbcSWolfgang Denk 		       i, list[i], list[i]->key, list[i]->data);
641a6826fbcSWolfgang Denk 	}
642a6826fbcSWolfgang Denk #endif
643a6826fbcSWolfgang Denk 
644a6826fbcSWolfgang Denk 	/* Sort list by keys */
645a6826fbcSWolfgang Denk 	qsort(list, n, sizeof(ENTRY *), cmpkey);
646a6826fbcSWolfgang Denk 
647a6826fbcSWolfgang Denk 	/* Check if the user supplied buffer size is sufficient */
648a6826fbcSWolfgang Denk 	if (size) {
649a6826fbcSWolfgang Denk 		if (size < totlen + 1) {	/* provided buffer too small */
650ff856286SSimon Glass 			printf("Env export buffer too small: %zu, "
651ff856286SSimon Glass 				"but need %zu\n", size, totlen + 1);
652a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
653a6826fbcSWolfgang Denk 			return (-1);
654a6826fbcSWolfgang Denk 		}
655a6826fbcSWolfgang Denk 	} else {
656a6826fbcSWolfgang Denk 		size = totlen + 1;
657a6826fbcSWolfgang Denk 	}
658a6826fbcSWolfgang Denk 
659a6826fbcSWolfgang Denk 	/* Check if the user provided a buffer */
660a6826fbcSWolfgang Denk 	if (*resp) {
661a6826fbcSWolfgang Denk 		/* yes; clear it */
662a6826fbcSWolfgang Denk 		res = *resp;
663a6826fbcSWolfgang Denk 		memset(res, '\0', size);
664a6826fbcSWolfgang Denk 	} else {
665a6826fbcSWolfgang Denk 		/* no, allocate and clear one */
666a6826fbcSWolfgang Denk 		*resp = res = calloc(1, size);
667a6826fbcSWolfgang Denk 		if (res == NULL) {
668a6826fbcSWolfgang Denk 			__set_errno(ENOMEM);
669a6826fbcSWolfgang Denk 			return (-1);
670a6826fbcSWolfgang Denk 		}
671a6826fbcSWolfgang Denk 	}
672a6826fbcSWolfgang Denk 	/*
673a6826fbcSWolfgang Denk 	 * Pass 2:
674a6826fbcSWolfgang Denk 	 * export sorted list of result data
675a6826fbcSWolfgang Denk 	 */
676a6826fbcSWolfgang Denk 	for (i = 0, p = res; i < n; ++i) {
67784b5e802SWolfgang Denk 		const char *s;
678a6826fbcSWolfgang Denk 
679a6826fbcSWolfgang Denk 		s = list[i]->key;
680a6826fbcSWolfgang Denk 		while (*s)
681a6826fbcSWolfgang Denk 			*p++ = *s++;
682a6826fbcSWolfgang Denk 		*p++ = '=';
683a6826fbcSWolfgang Denk 
684a6826fbcSWolfgang Denk 		s = list[i]->data;
685a6826fbcSWolfgang Denk 
686a6826fbcSWolfgang Denk 		while (*s) {
687a6826fbcSWolfgang Denk 			if ((*s == sep) || (*s == '\\'))
688a6826fbcSWolfgang Denk 				*p++ = '\\';	/* escape */
689a6826fbcSWolfgang Denk 			*p++ = *s++;
690a6826fbcSWolfgang Denk 		}
691a6826fbcSWolfgang Denk 		*p++ = sep;
692a6826fbcSWolfgang Denk 	}
693a6826fbcSWolfgang Denk 	*p = '\0';		/* terminate result */
694a6826fbcSWolfgang Denk 
695a6826fbcSWolfgang Denk 	return size;
696a6826fbcSWolfgang Denk }
6977ac2fe2dSIlya Yanok #endif
698a6826fbcSWolfgang Denk 
699a6826fbcSWolfgang Denk 
700a6826fbcSWolfgang Denk /*
701a6826fbcSWolfgang Denk  * himport()
702a6826fbcSWolfgang Denk  */
703a6826fbcSWolfgang Denk 
704d5370febSGerlando Falauto /*
705d5370febSGerlando Falauto  * Check whether variable 'name' is amongst vars[],
706d5370febSGerlando Falauto  * and remove all instances by setting the pointer to NULL
707d5370febSGerlando Falauto  */
708d5370febSGerlando Falauto static int drop_var_from_set(const char *name, int nvars, char * vars[])
709348b1f1cSGerlando Falauto {
710348b1f1cSGerlando Falauto 	int i = 0;
711d5370febSGerlando Falauto 	int res = 0;
712348b1f1cSGerlando Falauto 
713348b1f1cSGerlando Falauto 	/* No variables specified means process all of them */
714348b1f1cSGerlando Falauto 	if (nvars == 0)
715348b1f1cSGerlando Falauto 		return 1;
716348b1f1cSGerlando Falauto 
717348b1f1cSGerlando Falauto 	for (i = 0; i < nvars; i++) {
718d5370febSGerlando Falauto 		if (vars[i] == NULL)
719d5370febSGerlando Falauto 			continue;
720d5370febSGerlando Falauto 		/* If we found it, delete all of them */
721d5370febSGerlando Falauto 		if (!strcmp(name, vars[i])) {
722d5370febSGerlando Falauto 			vars[i] = NULL;
723d5370febSGerlando Falauto 			res = 1;
724348b1f1cSGerlando Falauto 		}
725d5370febSGerlando Falauto 	}
726d5370febSGerlando Falauto 	if (!res)
727348b1f1cSGerlando Falauto 		debug("Skipping non-listed variable %s\n", name);
728348b1f1cSGerlando Falauto 
729d5370febSGerlando Falauto 	return res;
730348b1f1cSGerlando Falauto }
731348b1f1cSGerlando Falauto 
732a6826fbcSWolfgang Denk /*
733a6826fbcSWolfgang Denk  * Import linearized data into hash table.
734a6826fbcSWolfgang Denk  *
735a6826fbcSWolfgang Denk  * This is the inverse function to hexport(): it takes a linear list
736a6826fbcSWolfgang Denk  * of "name=value" pairs and creates hash table entries from it.
737a6826fbcSWolfgang Denk  *
738a6826fbcSWolfgang Denk  * Entries without "value", i. e. consisting of only "name" or
739a6826fbcSWolfgang Denk  * "name=", will cause this entry to be deleted from the hash table.
740a6826fbcSWolfgang Denk  *
741a6826fbcSWolfgang Denk  * The "flag" argument can be used to control the behaviour: when the
742a6826fbcSWolfgang Denk  * H_NOCLEAR bit is set, then an existing hash table will kept, i. e.
743a6826fbcSWolfgang Denk  * new data will be added to an existing hash table; otherwise, old
744a6826fbcSWolfgang Denk  * data will be discarded and a new hash table will be created.
745a6826fbcSWolfgang Denk  *
746a6826fbcSWolfgang Denk  * The separator character for the "name=value" pairs can be selected,
747a6826fbcSWolfgang Denk  * so we both support importing from externally stored environment
748a6826fbcSWolfgang Denk  * data (separated by NUL characters) and from plain text files
749a6826fbcSWolfgang Denk  * (entries separated by newline characters).
750a6826fbcSWolfgang Denk  *
751a6826fbcSWolfgang Denk  * To allow for nicely formatted text input, leading white space
752a6826fbcSWolfgang Denk  * (sequences of SPACE and TAB chars) is ignored, and entries starting
753a6826fbcSWolfgang Denk  * (after removal of any leading white space) with a '#' character are
754a6826fbcSWolfgang Denk  * considered comments and ignored.
755a6826fbcSWolfgang Denk  *
756a6826fbcSWolfgang Denk  * [NOTE: this means that a variable name cannot start with a '#'
757a6826fbcSWolfgang Denk  * character.]
758a6826fbcSWolfgang Denk  *
759a6826fbcSWolfgang Denk  * When using a non-NUL separator character, backslash is used as
760a6826fbcSWolfgang Denk  * escape character in the value part, allowing for example for
761a6826fbcSWolfgang Denk  * multi-line values.
762a6826fbcSWolfgang Denk  *
763a6826fbcSWolfgang Denk  * In theory, arbitrary separator characters can be used, but only
764a6826fbcSWolfgang Denk  * '\0' and '\n' have really been tested.
765a6826fbcSWolfgang Denk  */
766a6826fbcSWolfgang Denk 
767a6826fbcSWolfgang Denk int himport_r(struct hsearch_data *htab,
768348b1f1cSGerlando Falauto 		const char *env, size_t size, const char sep, int flag,
769c4e0057fSJoe Hershberger 		int nvars, char * const vars[])
770a6826fbcSWolfgang Denk {
771a6826fbcSWolfgang Denk 	char *data, *sp, *dp, *name, *value;
772d5370febSGerlando Falauto 	char *localvars[nvars];
773d5370febSGerlando Falauto 	int i;
774a6826fbcSWolfgang Denk 
775a6826fbcSWolfgang Denk 	/* Test for correct arguments.  */
776a6826fbcSWolfgang Denk 	if (htab == NULL) {
777a6826fbcSWolfgang Denk 		__set_errno(EINVAL);
778a6826fbcSWolfgang Denk 		return 0;
779a6826fbcSWolfgang Denk 	}
780a6826fbcSWolfgang Denk 
781a6826fbcSWolfgang Denk 	/* we allocate new space to make sure we can write to the array */
782a6826fbcSWolfgang Denk 	if ((data = malloc(size)) == NULL) {
783ff856286SSimon Glass 		debug("himport_r: can't malloc %zu bytes\n", size);
784a6826fbcSWolfgang Denk 		__set_errno(ENOMEM);
785a6826fbcSWolfgang Denk 		return 0;
786a6826fbcSWolfgang Denk 	}
787a6826fbcSWolfgang Denk 	memcpy(data, env, size);
788a6826fbcSWolfgang Denk 	dp = data;
789a6826fbcSWolfgang Denk 
790d5370febSGerlando Falauto 	/* make a local copy of the list of variables */
791d5370febSGerlando Falauto 	if (nvars)
792d5370febSGerlando Falauto 		memcpy(localvars, vars, sizeof(vars[0]) * nvars);
793d5370febSGerlando Falauto 
794a6826fbcSWolfgang Denk 	if ((flag & H_NOCLEAR) == 0) {
795a6826fbcSWolfgang Denk 		/* Destroy old hash table if one exists */
796a6826fbcSWolfgang Denk 		debug("Destroy Hash Table: %p table = %p\n", htab,
797a6826fbcSWolfgang Denk 		       htab->table);
798a6826fbcSWolfgang Denk 		if (htab->table)
799c4e0057fSJoe Hershberger 			hdestroy_r(htab);
800a6826fbcSWolfgang Denk 	}
801a6826fbcSWolfgang Denk 
802a6826fbcSWolfgang Denk 	/*
803a6826fbcSWolfgang Denk 	 * Create new hash table (if needed).  The computation of the hash
804a6826fbcSWolfgang Denk 	 * table size is based on heuristics: in a sample of some 70+
805a6826fbcSWolfgang Denk 	 * existing systems we found an average size of 39+ bytes per entry
806a6826fbcSWolfgang Denk 	 * in the environment (for the whole key=value pair). Assuming a
807ea882bafSWolfgang Denk 	 * size of 8 per entry (= safety factor of ~5) should provide enough
808ea882bafSWolfgang Denk 	 * safety margin for any existing environment definitions and still
809a6826fbcSWolfgang Denk 	 * allow for more than enough dynamic additions. Note that the
810a6826fbcSWolfgang Denk 	 * "size" argument is supposed to give the maximum enviroment size
811ea882bafSWolfgang Denk 	 * (CONFIG_ENV_SIZE).  This heuristics will result in
812ea882bafSWolfgang Denk 	 * unreasonably large numbers (and thus memory footprint) for
813ea882bafSWolfgang Denk 	 * big flash environments (>8,000 entries for 64 KB
814fc5fc76bSAndreas Bießmann 	 * envrionment size), so we clip it to a reasonable value.
815fc5fc76bSAndreas Bießmann 	 * On the other hand we need to add some more entries for free
816fc5fc76bSAndreas Bießmann 	 * space when importing very small buffers. Both boundaries can
817fc5fc76bSAndreas Bießmann 	 * be overwritten in the board config file if needed.
818a6826fbcSWolfgang Denk 	 */
819a6826fbcSWolfgang Denk 
820a6826fbcSWolfgang Denk 	if (!htab->table) {
821fc5fc76bSAndreas Bießmann 		int nent = CONFIG_ENV_MIN_ENTRIES + size / 8;
822ea882bafSWolfgang Denk 
823ea882bafSWolfgang Denk 		if (nent > CONFIG_ENV_MAX_ENTRIES)
824ea882bafSWolfgang Denk 			nent = CONFIG_ENV_MAX_ENTRIES;
825a6826fbcSWolfgang Denk 
826a6826fbcSWolfgang Denk 		debug("Create Hash Table: N=%d\n", nent);
827a6826fbcSWolfgang Denk 
828a6826fbcSWolfgang Denk 		if (hcreate_r(nent, htab) == 0) {
829a6826fbcSWolfgang Denk 			free(data);
830a6826fbcSWolfgang Denk 			return 0;
831a6826fbcSWolfgang Denk 		}
832a6826fbcSWolfgang Denk 	}
833a6826fbcSWolfgang Denk 
834a6826fbcSWolfgang Denk 	/* Parse environment; allow for '\0' and 'sep' as separators */
835a6826fbcSWolfgang Denk 	do {
836a6826fbcSWolfgang Denk 		ENTRY e, *rv;
837a6826fbcSWolfgang Denk 
838a6826fbcSWolfgang Denk 		/* skip leading white space */
8394d91a6ecSJason Hobbs 		while (isblank(*dp))
840a6826fbcSWolfgang Denk 			++dp;
841a6826fbcSWolfgang Denk 
842a6826fbcSWolfgang Denk 		/* skip comment lines */
843a6826fbcSWolfgang Denk 		if (*dp == '#') {
844a6826fbcSWolfgang Denk 			while (*dp && (*dp != sep))
845a6826fbcSWolfgang Denk 				++dp;
846a6826fbcSWolfgang Denk 			++dp;
847a6826fbcSWolfgang Denk 			continue;
848a6826fbcSWolfgang Denk 		}
849a6826fbcSWolfgang Denk 
850a6826fbcSWolfgang Denk 		/* parse name */
851a6826fbcSWolfgang Denk 		for (name = dp; *dp != '=' && *dp && *dp != sep; ++dp)
852a6826fbcSWolfgang Denk 			;
853a6826fbcSWolfgang Denk 
854a6826fbcSWolfgang Denk 		/* deal with "name" and "name=" entries (delete var) */
855a6826fbcSWolfgang Denk 		if (*dp == '\0' || *(dp + 1) == '\0' ||
856a6826fbcSWolfgang Denk 		    *dp == sep || *(dp + 1) == sep) {
857a6826fbcSWolfgang Denk 			if (*dp == '=')
858a6826fbcSWolfgang Denk 				*dp++ = '\0';
859a6826fbcSWolfgang Denk 			*dp++ = '\0';	/* terminate name */
860a6826fbcSWolfgang Denk 
861a6826fbcSWolfgang Denk 			debug("DELETE CANDIDATE: \"%s\"\n", name);
862d5370febSGerlando Falauto 			if (!drop_var_from_set(name, nvars, localvars))
863348b1f1cSGerlando Falauto 				continue;
864a6826fbcSWolfgang Denk 
865c4e0057fSJoe Hershberger 			if (hdelete_r(name, htab, flag) == 0)
866a6826fbcSWolfgang Denk 				debug("DELETE ERROR ##############################\n");
867a6826fbcSWolfgang Denk 
868a6826fbcSWolfgang Denk 			continue;
869a6826fbcSWolfgang Denk 		}
870a6826fbcSWolfgang Denk 		*dp++ = '\0';	/* terminate name */
871a6826fbcSWolfgang Denk 
872a6826fbcSWolfgang Denk 		/* parse value; deal with escapes */
873a6826fbcSWolfgang Denk 		for (value = sp = dp; *dp && (*dp != sep); ++dp) {
874a6826fbcSWolfgang Denk 			if ((*dp == '\\') && *(dp + 1))
875a6826fbcSWolfgang Denk 				++dp;
876a6826fbcSWolfgang Denk 			*sp++ = *dp;
877a6826fbcSWolfgang Denk 		}
878a6826fbcSWolfgang Denk 		*sp++ = '\0';	/* terminate value */
879a6826fbcSWolfgang Denk 		++dp;
880a6826fbcSWolfgang Denk 
881348b1f1cSGerlando Falauto 		/* Skip variables which are not supposed to be processed */
882d5370febSGerlando Falauto 		if (!drop_var_from_set(name, nvars, localvars))
883348b1f1cSGerlando Falauto 			continue;
884348b1f1cSGerlando Falauto 
885a6826fbcSWolfgang Denk 		/* enter into hash table */
886a6826fbcSWolfgang Denk 		e.key = name;
887a6826fbcSWolfgang Denk 		e.data = value;
888a6826fbcSWolfgang Denk 
889c4e0057fSJoe Hershberger 		hsearch_r(e, ENTER, &rv, htab, flag);
890170ab110SJoe Hershberger 		if (rv == NULL)
891ea882bafSWolfgang Denk 			printf("himport_r: can't insert \"%s=%s\" into hash table\n",
892ea882bafSWolfgang Denk 				name, value);
893a6826fbcSWolfgang Denk 
894ea882bafSWolfgang Denk 		debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"\n",
895ea882bafSWolfgang Denk 			htab, htab->filled, htab->size,
896ea882bafSWolfgang Denk 			rv, name, value);
897a6826fbcSWolfgang Denk 	} while ((dp < data + size) && *dp);	/* size check needed for text */
898a6826fbcSWolfgang Denk 						/* without '\0' termination */
899ea882bafSWolfgang Denk 	debug("INSERT: free(data = %p)\n", data);
900a6826fbcSWolfgang Denk 	free(data);
901a6826fbcSWolfgang Denk 
902d5370febSGerlando Falauto 	/* process variables which were not considered */
903d5370febSGerlando Falauto 	for (i = 0; i < nvars; i++) {
904d5370febSGerlando Falauto 		if (localvars[i] == NULL)
905d5370febSGerlando Falauto 			continue;
906d5370febSGerlando Falauto 		/*
907d5370febSGerlando Falauto 		 * All variables which were not deleted from the variable list
908d5370febSGerlando Falauto 		 * were not present in the imported env
909d5370febSGerlando Falauto 		 * This could mean two things:
910d5370febSGerlando Falauto 		 * a) if the variable was present in current env, we delete it
911d5370febSGerlando Falauto 		 * b) if the variable was not present in current env, we notify
912d5370febSGerlando Falauto 		 *    it might be a typo
913d5370febSGerlando Falauto 		 */
914c4e0057fSJoe Hershberger 		if (hdelete_r(localvars[i], htab, flag) == 0)
915d5370febSGerlando Falauto 			printf("WARNING: '%s' neither in running nor in imported env!\n", localvars[i]);
916d5370febSGerlando Falauto 		else
917d5370febSGerlando Falauto 			printf("WARNING: '%s' not in imported env, deleting it!\n", localvars[i]);
918d5370febSGerlando Falauto 	}
919d5370febSGerlando Falauto 
920ea882bafSWolfgang Denk 	debug("INSERT: done\n");
921a6826fbcSWolfgang Denk 	return 1;		/* everything OK */
922a6826fbcSWolfgang Denk }
923170ab110SJoe Hershberger 
924170ab110SJoe Hershberger /*
925170ab110SJoe Hershberger  * hwalk_r()
926170ab110SJoe Hershberger  */
927170ab110SJoe Hershberger 
928170ab110SJoe Hershberger /*
929170ab110SJoe Hershberger  * Walk all of the entries in the hash, calling the callback for each one.
930170ab110SJoe Hershberger  * this allows some generic operation to be performed on each element.
931170ab110SJoe Hershberger  */
932170ab110SJoe Hershberger int hwalk_r(struct hsearch_data *htab, int (*callback)(ENTRY *))
933170ab110SJoe Hershberger {
934170ab110SJoe Hershberger 	int i;
935170ab110SJoe Hershberger 	int retval;
936170ab110SJoe Hershberger 
937170ab110SJoe Hershberger 	for (i = 1; i <= htab->size; ++i) {
938170ab110SJoe Hershberger 		if (htab->table[i].used > 0) {
939170ab110SJoe Hershberger 			retval = callback(&htab->table[i].entry);
940170ab110SJoe Hershberger 			if (retval)
941170ab110SJoe Hershberger 				return retval;
942170ab110SJoe Hershberger 		}
943170ab110SJoe Hershberger 	}
944170ab110SJoe Hershberger 
945170ab110SJoe Hershberger 	return 0;
946170ab110SJoe Hershberger }
947