Blame view

lib/hashtable.c 25 KB
83d290c56   Tom Rini   SPDX: Convert all...
1
  // SPDX-License-Identifier: LGPL-2.1+
a6826fbc5   Wolfgang Denk   Add hash table su...
2
3
4
5
  /*
   * This implementation is based on code from uClibc-0.9.30.3 but was
   * modified and extended for use within U-Boot.
   *
ea009d474   Wolfgang Denk   hashtable: prepar...
6
   * Copyright (C) 2010-2013 Wolfgang Denk <wd@denx.de>
a6826fbc5   Wolfgang Denk   Add hash table su...
7
8
9
10
11
12
   *
   * Original license header:
   *
   * Copyright (C) 1993, 1995, 1996, 1997, 2002 Free Software Foundation, Inc.
   * This file is part of the GNU C Library.
   * Contributed by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1993.
a6826fbc5   Wolfgang Denk   Add hash table su...
13
14
15
16
   */
  
  #include <errno.h>
  #include <malloc.h>
8bef79bf3   Simon Glass   common: Move sort...
17
  #include <sort.h>
a6826fbc5   Wolfgang Denk   Add hash table su...
18
19
20
21
  
  #ifdef USE_HOSTCC		/* HOST build */
  # include <string.h>
  # include <assert.h>
4d91a6eca   Jason Hobbs   Replace space and...
22
  # include <ctype.h>
a6826fbc5   Wolfgang Denk   Add hash table su...
23
24
25
26
27
28
29
30
31
32
33
  
  # ifndef debug
  #  ifdef DEBUG
  #   define debug(fmt,args...)	printf(fmt ,##args)
  #  else
  #   define debug(fmt,args...)
  #  endif
  # endif
  #else				/* U-Boot build */
  # include <common.h>
  # include <linux/string.h>
4d91a6eca   Jason Hobbs   Replace space and...
34
  # include <linux/ctype.h>
a6826fbc5   Wolfgang Denk   Add hash table su...
35
  #endif
fc5fc76bd   Andreas Bießmann   lib/hashtable.c: ...
36
37
38
  #ifndef	CONFIG_ENV_MIN_ENTRIES	/* minimum number of entries */
  #define	CONFIG_ENV_MIN_ENTRIES 64
  #endif
ea882baf9   Wolfgang Denk   New implementatio...
39
40
41
  #ifndef	CONFIG_ENV_MAX_ENTRIES	/* maximum number of entries */
  #define	CONFIG_ENV_MAX_ENTRIES 512
  #endif
9dfdbd9f0   Roman Kapl   hashtable: fix en...
42
43
  #define USED_FREE 0
  #define USED_DELETED -1
170ab1107   Joe Hershberger   env: Add support ...
44
  #include <env_callback.h>
2598090b7   Joe Hershberger   env: Add environm...
45
  #include <env_flags.h>
170ab1107   Joe Hershberger   env: Add support ...
46
  #include <search.h>
be29df6a1   Wolfgang Denk   "env grep" - add ...
47
  #include <slre.h>
a6826fbc5   Wolfgang Denk   Add hash table su...
48
49
50
  
  /*
   * [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
071bc9233   Wolfgang Denk   Coding Style cleanup
51
   * [Knuth]	      The Art of Computer Programming, part 3 (6.4)
a6826fbc5   Wolfgang Denk   Add hash table su...
52
53
54
   */
  
  /*
a6826fbc5   Wolfgang Denk   Add hash table su...
55
56
57
58
   * The reentrant version has no static variables to maintain the state.
   * Instead the interface of all functions is extended to take an argument
   * which describes the current status.
   */
7afcf3a55   Joe Hershberger   env: Refactor app...
59

25e51e90f   Simon Glass   env: Drop _ENTRY
60
  struct env_entry_node {
c81c12224   Peter Barada   Fix hash table de...
61
  	int used;
dd2408cac   Simon Glass   env: Drop the ENT...
62
  	struct env_entry entry;
25e51e90f   Simon Glass   env: Drop _ENTRY
63
  };
a6826fbc5   Wolfgang Denk   Add hash table su...
64

dd2408cac   Simon Glass   env: Drop the ENT...
65
66
  static void _hdelete(const char *key, struct hsearch_data *htab,
  		     struct env_entry *ep, int idx);
7afcf3a55   Joe Hershberger   env: Refactor app...
67

a6826fbc5   Wolfgang Denk   Add hash table su...
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
  /*
   * hcreate()
   */
  
  /*
   * For the used double hash method the table size has to be a prime. To
   * correct the user given table size we need a prime test.  This trivial
   * algorithm is adequate because
   * a)  the code is (most probably) called a few times per program run and
   * b)  the number is small because the table must fit in the core
   * */
  static int isprime(unsigned int number)
  {
  	/* no even number will be passed */
  	unsigned int div = 3;
  
  	while (div * div < number && number % div != 0)
  		div += 2;
  
  	return number % div != 0;
  }
a6826fbc5   Wolfgang Denk   Add hash table su...
89
90
91
92
93
94
95
96
  /*
   * Before using the hash table we must allocate memory for it.
   * Test for an existing table are done. We allocate one element
   * more as the found prime number says. This is done for more effective
   * indexing as explained in the comment for the hsearch function.
   * The contents of the table is zeroed, especially the field used
   * becomes zero.
   */
2eb1573f0   Mike Frysinger   hashtable: drop a...
97

a6826fbc5   Wolfgang Denk   Add hash table su...
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
  int hcreate_r(size_t nel, struct hsearch_data *htab)
  {
  	/* Test for correct arguments.  */
  	if (htab == NULL) {
  		__set_errno(EINVAL);
  		return 0;
  	}
  
  	/* There is still another table active. Return with error. */
  	if (htab->table != NULL)
  		return 0;
  
  	/* Change nel to the first prime number not smaller as nel. */
  	nel |= 1;		/* make odd */
  	while (!isprime(nel))
  		nel += 2;
  
  	htab->size = nel;
  	htab->filled = 0;
  
  	/* allocate memory and zero out */
25e51e90f   Simon Glass   env: Drop _ENTRY
119
120
  	htab->table = (struct env_entry_node *)calloc(htab->size + 1,
  						sizeof(struct env_entry_node));
a6826fbc5   Wolfgang Denk   Add hash table su...
121
122
123
124
125
126
127
128
129
130
131
  	if (htab->table == NULL)
  		return 0;
  
  	/* everything went alright */
  	return 1;
  }
  
  
  /*
   * hdestroy()
   */
a6826fbc5   Wolfgang Denk   Add hash table su...
132
133
134
135
136
  
  /*
   * After using the hash table it has to be destroyed. The used memory can
   * be freed and the local static variable can be marked as not used.
   */
2eb1573f0   Mike Frysinger   hashtable: drop a...
137

c4e0057fa   Joe Hershberger   env: Refactor do_...
138
  void hdestroy_r(struct hsearch_data *htab)
a6826fbc5   Wolfgang Denk   Add hash table su...
139
140
141
142
143
144
145
146
147
148
149
  {
  	int i;
  
  	/* Test for correct arguments.  */
  	if (htab == NULL) {
  		__set_errno(EINVAL);
  		return;
  	}
  
  	/* free used memory */
  	for (i = 1; i <= htab->size; ++i) {
c81c12224   Peter Barada   Fix hash table de...
150
  		if (htab->table[i].used > 0) {
dd2408cac   Simon Glass   env: Drop the ENT...
151
  			struct env_entry *ep = &htab->table[i].entry;
c4e0057fa   Joe Hershberger   env: Refactor do_...
152

84b5e8022   Wolfgang Denk   Constify getenv()...
153
  			free((void *)ep->key);
a6826fbc5   Wolfgang Denk   Add hash table su...
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
  			free(ep->data);
  		}
  	}
  	free(htab->table);
  
  	/* the sign for an existing table is an value != NULL in htable */
  	htab->table = NULL;
  }
  
  /*
   * hsearch()
   */
  
  /*
   * This is the search function. It uses double hashing with open addressing.
   * The argument item.key has to be a pointer to an zero terminated, most
   * probably strings of chars. The function for generating a number of the
   * strings is simple but fast. It can be replaced by a more complex function
   * like ajw (see [Aho,Sethi,Ullman]) if the needs are shown.
   *
   * We use an trick to speed up the lookup. The table is created by hcreate
   * with one more element available. This enables us to use the index zero
   * special. This index will never be used because we store the first hash
   * index in the field used where zero means not used. Every other value
   * means used. The used field can be used as a first fast comparison for
   * equality of the stored and the parameter value. This helps to prevent
   * unnecessary expensive calls of strcmp.
   *
   * This implementation differs from the standard library version of
   * this function in a number of ways:
   *
   * - While the standard version does not make any assumptions about
   *   the type of the stored data objects at all, this implementation
   *   works with NUL terminated strings only.
   * - Instead of storing just pointers to the original objects, we
   *   create local copies so the caller does not need to care about the
   *   data any more.
   * - The standard implementation does not provide a way to update an
   *   existing entry.  This version will create a new entry or update an
3f0d68074   Simon Glass   env: Drop the ACT...
193
   *   existing one when both "action == ENV_ENTER" and "item.data != NULL".
a6826fbc5   Wolfgang Denk   Add hash table su...
194
195
196
197
198
   * - Instead of returning 1 on success, we return the index into the
   *   internal hash table, which is also guaranteed to be positive.
   *   This allows us direct access to the found hash table slot for
   *   example for functions like hdelete().
   */
dd2408cac   Simon Glass   env: Drop the ENT...
199
  int hmatch_r(const char *match, int last_idx, struct env_entry **retval,
560d424b6   Mike Frysinger   env: re-add suppo...
200
201
202
203
204
205
  	     struct hsearch_data *htab)
  {
  	unsigned int idx;
  	size_t key_len = strlen(match);
  
  	for (idx = last_idx + 1; idx < htab->size; ++idx) {
af4d9074a   Kim Phillips   env: fix env var ...
206
  		if (htab->table[idx].used <= 0)
560d424b6   Mike Frysinger   env: re-add suppo...
207
208
209
210
211
212
213
214
215
216
217
  			continue;
  		if (!strncmp(match, htab->table[idx].entry.key, key_len)) {
  			*retval = &htab->table[idx].entry;
  			return idx;
  		}
  	}
  
  	__set_errno(ESRCH);
  	*retval = NULL;
  	return 0;
  }
3d3b52f25   Joe Hershberger   env: Consolidate ...
218
219
  /*
   * Compare an existing entry with the desired key, and overwrite if the action
3f0d68074   Simon Glass   env: Drop the ACT...
220
   * is ENV_ENTER.  This is simply a helper function for hsearch_r().
3d3b52f25   Joe Hershberger   env: Consolidate ...
221
   */
dd2408cac   Simon Glass   env: Drop the ENT...
222
  static inline int _compare_and_overwrite_entry(struct env_entry item,
3f0d68074   Simon Glass   env: Drop the ACT...
223
  		enum env_action action, struct env_entry **retval,
dd2408cac   Simon Glass   env: Drop the ENT...
224
225
  		struct hsearch_data *htab, int flag, unsigned int hval,
  		unsigned int idx)
3d3b52f25   Joe Hershberger   env: Consolidate ...
226
227
228
229
  {
  	if (htab->table[idx].used == hval
  	    && strcmp(item.key, htab->table[idx].entry.key) == 0) {
  		/* Overwrite existing value? */
3f0d68074   Simon Glass   env: Drop the ACT...
230
  		if (action == ENV_ENTER && item.data) {
7afcf3a55   Joe Hershberger   env: Refactor app...
231
232
233
234
235
236
237
238
239
240
241
  			/* check for permission */
  			if (htab->change_ok != NULL && htab->change_ok(
  			    &htab->table[idx].entry, item.data,
  			    env_op_overwrite, flag)) {
  				debug("change_ok() rejected setting variable "
  					"%s, skipping it!
  ", item.key);
  				__set_errno(EPERM);
  				*retval = NULL;
  				return 0;
  			}
170ab1107   Joe Hershberger   env: Add support ...
242
243
244
245
246
247
248
249
250
251
252
  			/* If there is a callback, call it */
  			if (htab->table[idx].entry.callback &&
  			    htab->table[idx].entry.callback(item.key,
  			    item.data, env_op_overwrite, flag)) {
  				debug("callback() rejected setting variable "
  					"%s, skipping it!
  ", item.key);
  				__set_errno(EINVAL);
  				*retval = NULL;
  				return 0;
  			}
3d3b52f25   Joe Hershberger   env: Consolidate ...
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
  			free(htab->table[idx].entry.data);
  			htab->table[idx].entry.data = strdup(item.data);
  			if (!htab->table[idx].entry.data) {
  				__set_errno(ENOMEM);
  				*retval = NULL;
  				return 0;
  			}
  		}
  		/* return found entry */
  		*retval = &htab->table[idx].entry;
  		return idx;
  	}
  	/* keep searching */
  	return -1;
  }
3f0d68074   Simon Glass   env: Drop the ACT...
268
269
  int hsearch_r(struct env_entry item, enum env_action action,
  	      struct env_entry **retval, struct hsearch_data *htab, int flag)
a6826fbc5   Wolfgang Denk   Add hash table su...
270
271
272
273
274
  {
  	unsigned int hval;
  	unsigned int count;
  	unsigned int len = strlen(item.key);
  	unsigned int idx;
c81c12224   Peter Barada   Fix hash table de...
275
  	unsigned int first_deleted = 0;
3d3b52f25   Joe Hershberger   env: Consolidate ...
276
  	int ret;
a6826fbc5   Wolfgang Denk   Add hash table su...
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
  
  	/* Compute an value for the given string. Perhaps use a better method. */
  	hval = len;
  	count = len;
  	while (count-- > 0) {
  		hval <<= 4;
  		hval += item.key[count];
  	}
  
  	/*
  	 * First hash function:
  	 * simply take the modul but prevent zero.
  	 */
  	hval %= htab->size;
  	if (hval == 0)
  		++hval;
  
  	/* The first index tried. */
  	idx = hval;
  
  	if (htab->table[idx].used) {
  		/*
071bc9233   Wolfgang Denk   Coding Style cleanup
299
  		 * Further action might be required according to the
a6826fbc5   Wolfgang Denk   Add hash table su...
300
301
302
  		 * action value.
  		 */
  		unsigned hval2;
9dfdbd9f0   Roman Kapl   hashtable: fix en...
303
  		if (htab->table[idx].used == USED_DELETED
c81c12224   Peter Barada   Fix hash table de...
304
305
  		    && !first_deleted)
  			first_deleted = idx;
3d3b52f25   Joe Hershberger   env: Consolidate ...
306
307
308
309
  		ret = _compare_and_overwrite_entry(item, action, retval, htab,
  			flag, hval, idx);
  		if (ret != -1)
  			return ret;
a6826fbc5   Wolfgang Denk   Add hash table su...
310
311
312
313
314
315
316
317
318
  
  		/*
  		 * Second hash function:
  		 * as suggested in [Knuth]
  		 */
  		hval2 = 1 + hval % (htab->size - 2);
  
  		do {
  			/*
071bc9233   Wolfgang Denk   Coding Style cleanup
319
320
  			 * Because SIZE is prime this guarantees to
  			 * step through all available indices.
a6826fbc5   Wolfgang Denk   Add hash table su...
321
322
323
324
325
326
327
328
329
330
331
332
  			 */
  			if (idx <= hval2)
  				idx = htab->size + idx - hval2;
  			else
  				idx -= hval2;
  
  			/*
  			 * If we visited all entries leave the loop
  			 * unsuccessfully.
  			 */
  			if (idx == hval)
  				break;
9dfdbd9f0   Roman Kapl   hashtable: fix en...
333
334
335
  			if (htab->table[idx].used == USED_DELETED
  			    && !first_deleted)
  				first_deleted = idx;
a6826fbc5   Wolfgang Denk   Add hash table su...
336
  			/* If entry is found use it. */
3d3b52f25   Joe Hershberger   env: Consolidate ...
337
338
339
340
  			ret = _compare_and_overwrite_entry(item, action, retval,
  				htab, flag, hval, idx);
  			if (ret != -1)
  				return ret;
a6826fbc5   Wolfgang Denk   Add hash table su...
341
  		}
9dfdbd9f0   Roman Kapl   hashtable: fix en...
342
  		while (htab->table[idx].used != USED_FREE);
a6826fbc5   Wolfgang Denk   Add hash table su...
343
344
345
  	}
  
  	/* An empty bucket has been found. */
3f0d68074   Simon Glass   env: Drop the ACT...
346
  	if (action == ENV_ENTER) {
a6826fbc5   Wolfgang Denk   Add hash table su...
347
  		/*
071bc9233   Wolfgang Denk   Coding Style cleanup
348
349
  		 * If table is full and another entry should be
  		 * entered return with error.
a6826fbc5   Wolfgang Denk   Add hash table su...
350
351
352
353
354
355
356
357
358
359
360
  		 */
  		if (htab->filled == htab->size) {
  			__set_errno(ENOMEM);
  			*retval = NULL;
  			return 0;
  		}
  
  		/*
  		 * Create new entry;
  		 * create copies of item.key and item.data
  		 */
c81c12224   Peter Barada   Fix hash table de...
361
362
  		if (first_deleted)
  			idx = first_deleted;
a6826fbc5   Wolfgang Denk   Add hash table su...
363
364
365
366
367
368
369
370
371
372
373
  		htab->table[idx].used = hval;
  		htab->table[idx].entry.key = strdup(item.key);
  		htab->table[idx].entry.data = strdup(item.data);
  		if (!htab->table[idx].entry.key ||
  		    !htab->table[idx].entry.data) {
  			__set_errno(ENOMEM);
  			*retval = NULL;
  			return 0;
  		}
  
  		++htab->filled;
170ab1107   Joe Hershberger   env: Add support ...
374
375
  		/* This is a new entry, so look up a possible callback */
  		env_callback_init(&htab->table[idx].entry);
2598090b7   Joe Hershberger   env: Add environm...
376
377
  		/* Also look for flags */
  		env_flags_init(&htab->table[idx].entry);
170ab1107   Joe Hershberger   env: Add support ...
378

7afcf3a55   Joe Hershberger   env: Refactor app...
379
380
381
382
383
384
385
386
387
388
389
  		/* check for permission */
  		if (htab->change_ok != NULL && htab->change_ok(
  		    &htab->table[idx].entry, item.data, env_op_create, flag)) {
  			debug("change_ok() rejected setting variable "
  				"%s, skipping it!
  ", item.key);
  			_hdelete(item.key, htab, &htab->table[idx].entry, idx);
  			__set_errno(EPERM);
  			*retval = NULL;
  			return 0;
  		}
170ab1107   Joe Hershberger   env: Add support ...
390
391
392
393
394
395
396
397
398
399
400
401
  		/* If there is a callback, call it */
  		if (htab->table[idx].entry.callback &&
  		    htab->table[idx].entry.callback(item.key, item.data,
  		    env_op_create, flag)) {
  			debug("callback() rejected setting variable "
  				"%s, skipping it!
  ", item.key);
  			_hdelete(item.key, htab, &htab->table[idx].entry, idx);
  			__set_errno(EINVAL);
  			*retval = NULL;
  			return 0;
  		}
a6826fbc5   Wolfgang Denk   Add hash table su...
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  		/* return new entry */
  		*retval = &htab->table[idx].entry;
  		return 1;
  	}
  
  	__set_errno(ESRCH);
  	*retval = NULL;
  	return 0;
  }
  
  
  /*
   * hdelete()
   */
  
  /*
   * The standard implementation of hsearch(3) does not provide any way
   * to delete any entries from the hash table.  We extend the code to
   * do that.
   */
dd2408cac   Simon Glass   env: Drop the ENT...
422
423
  static void _hdelete(const char *key, struct hsearch_data *htab,
  		     struct env_entry *ep, int idx)
7afcf3a55   Joe Hershberger   env: Refactor app...
424
  {
dd2408cac   Simon Glass   env: Drop the ENT...
425
  	/* free used entry */
7afcf3a55   Joe Hershberger   env: Refactor app...
426
427
428
429
  	debug("hdelete: DELETING key \"%s\"
  ", key);
  	free((void *)ep->key);
  	free(ep->data);
170ab1107   Joe Hershberger   env: Add support ...
430
  	ep->callback = NULL;
2598090b7   Joe Hershberger   env: Add environm...
431
  	ep->flags = 0;
9dfdbd9f0   Roman Kapl   hashtable: fix en...
432
  	htab->table[idx].used = USED_DELETED;
7afcf3a55   Joe Hershberger   env: Refactor app...
433
434
435
  
  	--htab->filled;
  }
c4e0057fa   Joe Hershberger   env: Refactor do_...
436
  int hdelete_r(const char *key, struct hsearch_data *htab, int flag)
a6826fbc5   Wolfgang Denk   Add hash table su...
437
  {
dd2408cac   Simon Glass   env: Drop the ENT...
438
  	struct env_entry e, *ep;
a6826fbc5   Wolfgang Denk   Add hash table su...
439
440
441
442
443
444
  	int idx;
  
  	debug("hdelete: DELETE key \"%s\"
  ", key);
  
  	e.key = (char *)key;
3f0d68074   Simon Glass   env: Drop the ACT...
445
  	idx = hsearch_r(e, ENV_FIND, &ep, htab, 0);
c4e0057fa   Joe Hershberger   env: Refactor do_...
446
  	if (idx == 0) {
a6826fbc5   Wolfgang Denk   Add hash table su...
447
448
449
  		__set_errno(ESRCH);
  		return 0;	/* not found */
  	}
c4e0057fa   Joe Hershberger   env: Refactor do_...
450
  	/* Check for permission */
7afcf3a55   Joe Hershberger   env: Refactor app...
451
452
453
454
455
  	if (htab->change_ok != NULL &&
  	    htab->change_ok(ep, NULL, env_op_delete, flag)) {
  		debug("change_ok() rejected deleting variable "
  			"%s, skipping it!
  ", key);
c4e0057fa   Joe Hershberger   env: Refactor do_...
456
457
458
  		__set_errno(EPERM);
  		return 0;
  	}
170ab1107   Joe Hershberger   env: Add support ...
459
460
461
462
463
464
465
466
467
  	/* If there is a callback, call it */
  	if (htab->table[idx].entry.callback &&
  	    htab->table[idx].entry.callback(key, NULL, env_op_delete, flag)) {
  		debug("callback() rejected deleting variable "
  			"%s, skipping it!
  ", key);
  		__set_errno(EINVAL);
  		return 0;
  	}
7afcf3a55   Joe Hershberger   env: Refactor app...
468
  	_hdelete(key, htab, ep, idx);
a6826fbc5   Wolfgang Denk   Add hash table su...
469
470
471
  
  	return 1;
  }
d2d9bdfcf   B, Ravi   spl: saveenv: add...
472
  #if !(defined(CONFIG_SPL_BUILD) && !defined(CONFIG_SPL_SAVEENV))
a6826fbc5   Wolfgang Denk   Add hash table su...
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
  /*
   * hexport()
   */
  
  /*
   * Export the data stored in the hash table in linearized form.
   *
   * Entries are exported as "name=value" strings, separated by an
   * arbitrary (non-NUL, of course) separator character. This allows to
   * use this function both when formatting the U-Boot environment for
   * external storage (using '\0' as separator), but also when using it
   * for the "printenv" command to print all variables, simply by using
   * as '
  " as separator. This can also be used for new features like
   * exporting the environment data as text file, including the option
   * for later re-import.
   *
   * The entries in the result list will be sorted by ascending key
   * values.
   *
   * If the separator character is different from NUL, then any
   * separator characters and backslash characters in the values will
fc0b5948e   Robert P. J. Day   Various, accumula...
495
   * be escaped by a preceding backslash in output. This is needed for
a6826fbc5   Wolfgang Denk   Add hash table su...
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
   * example to enable multi-line values, especially when the output
   * shall later be parsed (for example, for re-import).
   *
   * There are several options how the result buffer is handled:
   *
   * *resp  size
   * -----------
   *  NULL    0	A string of sufficient length will be allocated.
   *  NULL   >0	A string of the size given will be
   *		allocated. An error will be returned if the size is
   *		not sufficient.  Any unused bytes in the string will
   *		be '\0'-padded.
   * !NULL    0	The user-supplied buffer will be used. No length
   *		checking will be performed, i. e. it is assumed that
   *		the buffer size will always be big enough. DANGEROUS.
   * !NULL   >0	The user-supplied buffer will be used. An error will
   *		be returned if the size is not sufficient.  Any unused
   *		bytes in the string will be '\0'-padded.
   */
a6826fbc5   Wolfgang Denk   Add hash table su...
515
516
  static int cmpkey(const void *p1, const void *p2)
  {
dd2408cac   Simon Glass   env: Drop the ENT...
517
518
  	struct env_entry *e1 = *(struct env_entry **)p1;
  	struct env_entry *e2 = *(struct env_entry **)p2;
a6826fbc5   Wolfgang Denk   Add hash table su...
519
520
521
  
  	return (strcmp(e1->key, e2->key));
  }
be29df6a1   Wolfgang Denk   "env grep" - add ...
522
  static int match_string(int flag, const char *str, const char *pat, void *priv)
5a31ea04c   Wolfgang Denk   "env grep" - reim...
523
524
525
526
527
528
529
530
531
532
  {
  	switch (flag & H_MATCH_METHOD) {
  	case H_MATCH_IDENT:
  		if (strcmp(str, pat) == 0)
  			return 1;
  		break;
  	case H_MATCH_SUBSTR:
  		if (strstr(str, pat))
  			return 1;
  		break;
be29df6a1   Wolfgang Denk   "env grep" - add ...
533
534
535
536
  #ifdef CONFIG_REGEX
  	case H_MATCH_REGEX:
  		{
  			struct slre *slrep = (struct slre *)priv;
be29df6a1   Wolfgang Denk   "env grep" - add ...
537

320194ae3   Heinrich Schuchardt   hashtable: remove...
538
  			if (slre_match(slrep, str, strlen(str), NULL))
be29df6a1   Wolfgang Denk   "env grep" - add ...
539
540
541
542
  				return 1;
  		}
  		break;
  #endif
5a31ea04c   Wolfgang Denk   "env grep" - reim...
543
544
545
546
547
548
549
550
  	default:
  		printf("## ERROR: unsupported match method: 0x%02x
  ",
  			flag & H_MATCH_METHOD);
  		break;
  	}
  	return 0;
  }
dd2408cac   Simon Glass   env: Drop the ENT...
551
552
  static int match_entry(struct env_entry *ep, int flag, int argc,
  		       char *const argv[])
ea009d474   Wolfgang Denk   hashtable: prepar...
553
554
  {
  	int arg;
be29df6a1   Wolfgang Denk   "env grep" - add ...
555
  	void *priv = NULL;
ea009d474   Wolfgang Denk   hashtable: prepar...
556

9a8323311   Pierre Aubert   env: fix the env ...
557
  	for (arg = 0; arg < argc; ++arg) {
be29df6a1   Wolfgang Denk   "env grep" - add ...
558
559
560
561
562
563
564
565
566
567
568
  #ifdef CONFIG_REGEX
  		struct slre slre;
  
  		if (slre_compile(&slre, argv[arg]) == 0) {
  			printf("Error compiling regex: %s
  ", slre.err_str);
  			return 0;
  		}
  
  		priv = (void *)&slre;
  #endif
ea009d474   Wolfgang Denk   hashtable: prepar...
569
  		if (flag & H_MATCH_KEY) {
be29df6a1   Wolfgang Denk   "env grep" - add ...
570
  			if (match_string(flag, ep->key, argv[arg], priv))
5a31ea04c   Wolfgang Denk   "env grep" - reim...
571
572
573
  				return 1;
  		}
  		if (flag & H_MATCH_DATA) {
be29df6a1   Wolfgang Denk   "env grep" - add ...
574
  			if (match_string(flag, ep->data, argv[arg], priv))
5a31ea04c   Wolfgang Denk   "env grep" - reim...
575
  				return 1;
ea009d474   Wolfgang Denk   hashtable: prepar...
576
577
578
579
  		}
  	}
  	return 0;
  }
be11235ab   Joe Hershberger   env: Hide '.' var...
580
  ssize_t hexport_r(struct hsearch_data *htab, const char sep, int flag,
37f2fe747   Wolfgang Denk   env: allow to exp...
581
582
  		 char **resp, size_t size,
  		 int argc, char * const argv[])
a6826fbc5   Wolfgang Denk   Add hash table su...
583
  {
dd2408cac   Simon Glass   env: Drop the ENT...
584
  	struct env_entry *list[htab->size];
a6826fbc5   Wolfgang Denk   Add hash table su...
585
586
587
588
589
590
591
592
593
  	char *res, *p;
  	size_t totlen;
  	int i, n;
  
  	/* Test for correct arguments.  */
  	if ((resp == NULL) || (htab == NULL)) {
  		__set_errno(EINVAL);
  		return (-1);
  	}
c55d02b2a   Simon Glass   hashtable: Fix co...
594
595
596
  	debug("EXPORT  table = %p, htab.size = %d, htab.filled = %d, size = %lu
  ",
  	      htab, htab->size, htab->filled, (ulong)size);
a6826fbc5   Wolfgang Denk   Add hash table su...
597
598
599
600
601
602
  	/*
  	 * Pass 1:
  	 * search used entries,
  	 * save addresses and compute total length
  	 */
  	for (i = 1, n = 0, totlen = 0; i <= htab->size; ++i) {
c81c12224   Peter Barada   Fix hash table de...
603
  		if (htab->table[i].used > 0) {
dd2408cac   Simon Glass   env: Drop the ENT...
604
  			struct env_entry *ep = &htab->table[i].entry;
5a31ea04c   Wolfgang Denk   "env grep" - reim...
605
  			int found = match_entry(ep, flag, argc, argv);
37f2fe747   Wolfgang Denk   env: allow to exp...
606

37f2fe747   Wolfgang Denk   env: allow to exp...
607
608
  			if ((argc > 0) && (found == 0))
  				continue;
a6826fbc5   Wolfgang Denk   Add hash table su...
609

be11235ab   Joe Hershberger   env: Hide '.' var...
610
611
  			if ((flag & H_HIDE_DOT) && ep->key[0] == '.')
  				continue;
a6826fbc5   Wolfgang Denk   Add hash table su...
612
  			list[n++] = ep;
f1b20acb4   Zubair Lutfullah Kakakhel   hashtable: Fix le...
613
  			totlen += strlen(ep->key);
a6826fbc5   Wolfgang Denk   Add hash table su...
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
  
  			if (sep == '\0') {
  				totlen += strlen(ep->data);
  			} else {	/* check if escapes are needed */
  				char *s = ep->data;
  
  				while (*s) {
  					++totlen;
  					/* add room for needed escape chars */
  					if ((*s == sep) || (*s == '\\'))
  						++totlen;
  					++s;
  				}
  			}
  			totlen += 2;	/* for '=' and 'sep' char */
  		}
  	}
  
  #ifdef DEBUG
  	/* Pass 1a: print unsorted list */
  	printf("Unsorted: n=%d
  ", n);
  	for (i = 0; i < n; ++i) {
  		printf("\t%3d: %p ==> %-10s => %s
  ",
  		       i, list[i], list[i]->key, list[i]->data);
  	}
  #endif
  
  	/* Sort list by keys */
dd2408cac   Simon Glass   env: Drop the ENT...
644
  	qsort(list, n, sizeof(struct env_entry *), cmpkey);
a6826fbc5   Wolfgang Denk   Add hash table su...
645
646
647
648
  
  	/* Check if the user supplied buffer size is sufficient */
  	if (size) {
  		if (size < totlen + 1) {	/* provided buffer too small */
c55d02b2a   Simon Glass   hashtable: Fix co...
649
650
651
  			printf("Env export buffer too small: %lu, but need %lu
  ",
  			       (ulong)size, (ulong)totlen + 1);
a6826fbc5   Wolfgang Denk   Add hash table su...
652
653
654
655
  			__set_errno(ENOMEM);
  			return (-1);
  		}
  	} else {
4bca32497   AKASHI Takahiro   hashtable: fix le...
656
  		size = totlen + 1;
a6826fbc5   Wolfgang Denk   Add hash table su...
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
  	}
  
  	/* Check if the user provided a buffer */
  	if (*resp) {
  		/* yes; clear it */
  		res = *resp;
  		memset(res, '\0', size);
  	} else {
  		/* no, allocate and clear one */
  		*resp = res = calloc(1, size);
  		if (res == NULL) {
  			__set_errno(ENOMEM);
  			return (-1);
  		}
  	}
  	/*
  	 * Pass 2:
  	 * export sorted list of result data
  	 */
  	for (i = 0, p = res; i < n; ++i) {
84b5e8022   Wolfgang Denk   Constify getenv()...
677
  		const char *s;
a6826fbc5   Wolfgang Denk   Add hash table su...
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
  
  		s = list[i]->key;
  		while (*s)
  			*p++ = *s++;
  		*p++ = '=';
  
  		s = list[i]->data;
  
  		while (*s) {
  			if ((*s == sep) || (*s == '\\'))
  				*p++ = '\\';	/* escape */
  			*p++ = *s++;
  		}
  		*p++ = sep;
  	}
  	*p = '\0';		/* terminate result */
  
  	return size;
  }
7ac2fe2da   Ilya Yanok   OMAP: networking ...
697
  #endif
a6826fbc5   Wolfgang Denk   Add hash table su...
698
699
700
701
702
  
  
  /*
   * himport()
   */
d5370febb   Gerlando Falauto   env: delete selec...
703
704
705
706
707
  /*
   * Check whether variable 'name' is amongst vars[],
   * and remove all instances by setting the pointer to NULL
   */
  static int drop_var_from_set(const char *name, int nvars, char * vars[])
348b1f1c6   Gerlando Falauto   env: make himport...
708
709
  {
  	int i = 0;
d5370febb   Gerlando Falauto   env: delete selec...
710
  	int res = 0;
348b1f1c6   Gerlando Falauto   env: make himport...
711
712
713
714
715
716
  
  	/* No variables specified means process all of them */
  	if (nvars == 0)
  		return 1;
  
  	for (i = 0; i < nvars; i++) {
d5370febb   Gerlando Falauto   env: delete selec...
717
718
719
720
721
722
723
  		if (vars[i] == NULL)
  			continue;
  		/* If we found it, delete all of them */
  		if (!strcmp(name, vars[i])) {
  			vars[i] = NULL;
  			res = 1;
  		}
348b1f1c6   Gerlando Falauto   env: make himport...
724
  	}
d5370febb   Gerlando Falauto   env: delete selec...
725
726
727
  	if (!res)
  		debug("Skipping non-listed variable %s
  ", name);
348b1f1c6   Gerlando Falauto   env: make himport...
728

d5370febb   Gerlando Falauto   env: delete selec...
729
  	return res;
348b1f1c6   Gerlando Falauto   env: make himport...
730
  }
a6826fbc5   Wolfgang Denk   Add hash table su...
731
732
733
734
735
736
737
738
739
740
741
  /*
   * Import linearized data into hash table.
   *
   * This is the inverse function to hexport(): it takes a linear list
   * of "name=value" pairs and creates hash table entries from it.
   *
   * Entries without "value", i. e. consisting of only "name" or
   * "name=", will cause this entry to be deleted from the hash table.
   *
   * The "flag" argument can be used to control the behaviour: when the
   * H_NOCLEAR bit is set, then an existing hash table will kept, i. e.
d9fc9077e   Quentin Schulz   hashtable: do not...
742
743
744
745
746
   * new data will be added to an existing hash table; otherwise, if no
   * vars are passed, old data will be discarded and a new hash table
   * will be created. If vars are passed, passed vars that are not in
   * the linear list of "name=value" pairs will be removed from the
   * current hash table.
a6826fbc5   Wolfgang Denk   Add hash table su...
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
   *
   * The separator character for the "name=value" pairs can be selected,
   * so we both support importing from externally stored environment
   * data (separated by NUL characters) and from plain text files
   * (entries separated by newline characters).
   *
   * To allow for nicely formatted text input, leading white space
   * (sequences of SPACE and TAB chars) is ignored, and entries starting
   * (after removal of any leading white space) with a '#' character are
   * considered comments and ignored.
   *
   * [NOTE: this means that a variable name cannot start with a '#'
   * character.]
   *
   * When using a non-NUL separator character, backslash is used as
   * escape character in the value part, allowing for example for
   * multi-line values.
   *
   * In theory, arbitrary separator characters can be used, but only
   * '\0' and '
  ' have really been tested.
   */
a6826fbc5   Wolfgang Denk   Add hash table su...
769
  int himport_r(struct hsearch_data *htab,
348b1f1c6   Gerlando Falauto   env: make himport...
770
  		const char *env, size_t size, const char sep, int flag,
ecd1446fe   Alexander Holler   Add option -r to ...
771
  		int crlf_is_lf, int nvars, char * const vars[])
a6826fbc5   Wolfgang Denk   Add hash table su...
772
773
  {
  	char *data, *sp, *dp, *name, *value;
d5370febb   Gerlando Falauto   env: delete selec...
774
775
  	char *localvars[nvars];
  	int i;
a6826fbc5   Wolfgang Denk   Add hash table su...
776
777
778
779
780
781
782
783
  
  	/* Test for correct arguments.  */
  	if (htab == NULL) {
  		__set_errno(EINVAL);
  		return 0;
  	}
  
  	/* we allocate new space to make sure we can write to the array */
817e48d8a   Lukasz Majewski   env: import: hash...
784
  	if ((data = malloc(size + 1)) == NULL) {
c55d02b2a   Simon Glass   hashtable: Fix co...
785
786
  		debug("himport_r: can't malloc %lu bytes
  ", (ulong)size + 1);
a6826fbc5   Wolfgang Denk   Add hash table su...
787
788
789
790
  		__set_errno(ENOMEM);
  		return 0;
  	}
  	memcpy(data, env, size);
817e48d8a   Lukasz Majewski   env: import: hash...
791
  	data[size] = '\0';
a6826fbc5   Wolfgang Denk   Add hash table su...
792
  	dp = data;
d5370febb   Gerlando Falauto   env: delete selec...
793
794
795
  	/* make a local copy of the list of variables */
  	if (nvars)
  		memcpy(localvars, vars, sizeof(vars[0]) * nvars);
d9fc9077e   Quentin Schulz   hashtable: do not...
796
  	if ((flag & H_NOCLEAR) == 0 && !nvars) {
a6826fbc5   Wolfgang Denk   Add hash table su...
797
798
799
800
801
  		/* Destroy old hash table if one exists */
  		debug("Destroy Hash Table: %p table = %p
  ", htab,
  		       htab->table);
  		if (htab->table)
c4e0057fa   Joe Hershberger   env: Refactor do_...
802
  			hdestroy_r(htab);
a6826fbc5   Wolfgang Denk   Add hash table su...
803
804
805
806
807
808
809
  	}
  
  	/*
  	 * Create new hash table (if needed).  The computation of the hash
  	 * table size is based on heuristics: in a sample of some 70+
  	 * existing systems we found an average size of 39+ bytes per entry
  	 * in the environment (for the whole key=value pair). Assuming a
ea882baf9   Wolfgang Denk   New implementatio...
810
811
  	 * size of 8 per entry (= safety factor of ~5) should provide enough
  	 * safety margin for any existing environment definitions and still
a6826fbc5   Wolfgang Denk   Add hash table su...
812
  	 * allow for more than enough dynamic additions. Note that the
1bce2aeb6   Robert P. J. Day   Cosmetic: Fix a n...
813
  	 * "size" argument is supposed to give the maximum environment size
ea882baf9   Wolfgang Denk   New implementatio...
814
815
816
  	 * (CONFIG_ENV_SIZE).  This heuristics will result in
  	 * unreasonably large numbers (and thus memory footprint) for
  	 * big flash environments (>8,000 entries for 64 KB
62a3b7dd0   Robert P. J. Day   Various, unrelate...
817
  	 * environment size), so we clip it to a reasonable value.
fc5fc76bd   Andreas Bießmann   lib/hashtable.c: ...
818
819
820
  	 * On the other hand we need to add some more entries for free
  	 * space when importing very small buffers. Both boundaries can
  	 * be overwritten in the board config file if needed.
a6826fbc5   Wolfgang Denk   Add hash table su...
821
822
823
  	 */
  
  	if (!htab->table) {
fc5fc76bd   Andreas Bießmann   lib/hashtable.c: ...
824
  		int nent = CONFIG_ENV_MIN_ENTRIES + size / 8;
ea882baf9   Wolfgang Denk   New implementatio...
825
826
827
  
  		if (nent > CONFIG_ENV_MAX_ENTRIES)
  			nent = CONFIG_ENV_MAX_ENTRIES;
a6826fbc5   Wolfgang Denk   Add hash table su...
828
829
830
831
832
833
834
835
836
  
  		debug("Create Hash Table: N=%d
  ", nent);
  
  		if (hcreate_r(nent, htab) == 0) {
  			free(data);
  			return 0;
  		}
  	}
0226d8780   Lukasz Majewski   env: import: hash...
837
838
  	if (!size) {
  		free(data);
ecd1446fe   Alexander Holler   Add option -r to ...
839
  		return 1;		/* everything OK */
0226d8780   Lukasz Majewski   env: import: hash...
840
  	}
ecd1446fe   Alexander Holler   Add option -r to ...
841
842
843
844
845
846
847
848
849
850
851
852
853
854
  	if(crlf_is_lf) {
  		/* Remove Carriage Returns in front of Line Feeds */
  		unsigned ignored_crs = 0;
  		for(;dp < data + size && *dp; ++dp) {
  			if(*dp == '\r' &&
  			   dp < data + size - 1 && *(dp+1) == '
  ')
  				++ignored_crs;
  			else
  				*(dp-ignored_crs) = *dp;
  		}
  		size -= ignored_crs;
  		dp = data;
  	}
a6826fbc5   Wolfgang Denk   Add hash table su...
855
856
  	/* Parse environment; allow for '\0' and 'sep' as separators */
  	do {
dd2408cac   Simon Glass   env: Drop the ENT...
857
  		struct env_entry e, *rv;
a6826fbc5   Wolfgang Denk   Add hash table su...
858
859
  
  		/* skip leading white space */
4d91a6eca   Jason Hobbs   Replace space and...
860
  		while (isblank(*dp))
a6826fbc5   Wolfgang Denk   Add hash table su...
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
  			++dp;
  
  		/* skip comment lines */
  		if (*dp == '#') {
  			while (*dp && (*dp != sep))
  				++dp;
  			++dp;
  			continue;
  		}
  
  		/* parse name */
  		for (name = dp; *dp != '=' && *dp && *dp != sep; ++dp)
  			;
  
  		/* deal with "name" and "name=" entries (delete var) */
  		if (*dp == '\0' || *(dp + 1) == '\0' ||
  		    *dp == sep || *(dp + 1) == sep) {
  			if (*dp == '=')
  				*dp++ = '\0';
  			*dp++ = '\0';	/* terminate name */
  
  			debug("DELETE CANDIDATE: \"%s\"
  ", name);
d5370febb   Gerlando Falauto   env: delete selec...
884
  			if (!drop_var_from_set(name, nvars, localvars))
348b1f1c6   Gerlando Falauto   env: make himport...
885
  				continue;
a6826fbc5   Wolfgang Denk   Add hash table su...
886

c4e0057fa   Joe Hershberger   env: Refactor do_...
887
  			if (hdelete_r(name, htab, flag) == 0)
a6826fbc5   Wolfgang Denk   Add hash table su...
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
  				debug("DELETE ERROR ##############################
  ");
  
  			continue;
  		}
  		*dp++ = '\0';	/* terminate name */
  
  		/* parse value; deal with escapes */
  		for (value = sp = dp; *dp && (*dp != sep); ++dp) {
  			if ((*dp == '\\') && *(dp + 1))
  				++dp;
  			*sp++ = *dp;
  		}
  		*sp++ = '\0';	/* terminate value */
  		++dp;
e4fdcadd8   Lucian Cojocar   env: throw an err...
903
904
905
906
  		if (*name == 0) {
  			debug("INSERT: unable to use an empty key
  ");
  			__set_errno(EINVAL);
0226d8780   Lukasz Majewski   env: import: hash...
907
  			free(data);
e4fdcadd8   Lucian Cojocar   env: throw an err...
908
909
  			return 0;
  		}
348b1f1c6   Gerlando Falauto   env: make himport...
910
  		/* Skip variables which are not supposed to be processed */
d5370febb   Gerlando Falauto   env: delete selec...
911
  		if (!drop_var_from_set(name, nvars, localvars))
348b1f1c6   Gerlando Falauto   env: make himport...
912
  			continue;
a6826fbc5   Wolfgang Denk   Add hash table su...
913
914
915
  		/* enter into hash table */
  		e.key = name;
  		e.data = value;
3f0d68074   Simon Glass   env: Drop the ACT...
916
  		hsearch_r(e, ENV_ENTER, &rv, htab, flag);
170ab1107   Joe Hershberger   env: Add support ...
917
  		if (rv == NULL)
ea882baf9   Wolfgang Denk   New implementatio...
918
919
920
  			printf("himport_r: can't insert \"%s=%s\" into hash table
  ",
  				name, value);
a6826fbc5   Wolfgang Denk   Add hash table su...
921

ea882baf9   Wolfgang Denk   New implementatio...
922
923
924
925
  		debug("INSERT: table %p, filled %d/%d rv %p ==> name=\"%s\" value=\"%s\"
  ",
  			htab, htab->filled, htab->size,
  			rv, name, value);
a6826fbc5   Wolfgang Denk   Add hash table su...
926
927
  	} while ((dp < data + size) && *dp);	/* size check needed for text */
  						/* without '\0' termination */
ea882baf9   Wolfgang Denk   New implementatio...
928
929
  	debug("INSERT: free(data = %p)
  ", data);
a6826fbc5   Wolfgang Denk   Add hash table su...
930
  	free(data);
d9fc9077e   Quentin Schulz   hashtable: do not...
931
932
  	if (flag & H_NOCLEAR)
  		goto end;
d5370febb   Gerlando Falauto   env: delete selec...
933
934
935
936
937
938
939
940
941
942
943
944
  	/* process variables which were not considered */
  	for (i = 0; i < nvars; i++) {
  		if (localvars[i] == NULL)
  			continue;
  		/*
  		 * All variables which were not deleted from the variable list
  		 * were not present in the imported env
  		 * This could mean two things:
  		 * a) if the variable was present in current env, we delete it
  		 * b) if the variable was not present in current env, we notify
  		 *    it might be a typo
  		 */
c4e0057fa   Joe Hershberger   env: Refactor do_...
945
  		if (hdelete_r(localvars[i], htab, flag) == 0)
d5370febb   Gerlando Falauto   env: delete selec...
946
947
948
949
950
951
  			printf("WARNING: '%s' neither in running nor in imported env!
  ", localvars[i]);
  		else
  			printf("WARNING: '%s' not in imported env, deleting it!
  ", localvars[i]);
  	}
d9fc9077e   Quentin Schulz   hashtable: do not...
952
  end:
ea882baf9   Wolfgang Denk   New implementatio...
953
954
  	debug("INSERT: done
  ");
a6826fbc5   Wolfgang Denk   Add hash table su...
955
956
  	return 1;		/* everything OK */
  }
170ab1107   Joe Hershberger   env: Add support ...
957
958
959
960
961
962
963
964
965
  
  /*
   * hwalk_r()
   */
  
  /*
   * Walk all of the entries in the hash, calling the callback for each one.
   * this allows some generic operation to be performed on each element.
   */
dd2408cac   Simon Glass   env: Drop the ENT...
966
  int hwalk_r(struct hsearch_data *htab, int (*callback)(struct env_entry *entry))
170ab1107   Joe Hershberger   env: Add support ...
967
968
969
970
971
972
973
974
975
976
977
978
979
980
  {
  	int i;
  	int retval;
  
  	for (i = 1; i <= htab->size; ++i) {
  		if (htab->table[i].used > 0) {
  			retval = callback(&htab->table[i].entry);
  			if (retval)
  				return retval;
  		}
  	}
  
  	return 0;
  }