Debian Codegraph @

src/lib/libdwarf/dwarf_tsearchhash.c

raw
1 /* Copyright (c) 2013-2022, David Anderson
2 All rights reserved.
3
4 Redistribution and use in source and binary forms, with
5 or without modification, are permitted provided that the
6 following conditions are met:
7
8 Redistributions of source code must retain the above
9 copyright notice, this list of conditions and the following
10 disclaimer.
11
12 Redistributions in binary form must reproduce the above
13 copyright notice, this list of conditions and the following
14 disclaimer in the documentation and/or other materials
15 provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18 CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
22 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
28 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
29 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 */
32
33 /* The interfaces follow tsearch (See the Single
34 Unix Specification) but the implementation is
35 written without reference to the source of any
36 version of tsearch or any hashing code.
37
38 An additional interface is added (compared to
39 a real tsearch) to let the caller identify a
40 'hash' function with each hash table (called
41 a tree below, but that is a misnomer).
42
43 So read 'tree' below as hash table.
44
45 See http://www.prevanders.net/tsearch.html
46 for information and an example of use.
47
48 Based on Knuth, chapter 6.4
49
50 This uses a hash based on the key.
51 Collision resolution is by chaining.
52
53 twalk() and tdestroy() walk in a random order.
54 The 'preorder' etc labels mean nothing in a hash, so everything
55 is called a leaf.
56
57 Since libdwarf never calls dwarf_tdump we
58 never define BUILD_TDUMP
59
60 */
61
62 #include <config.h>
63
64 #include <stddef.h> /* NULL */
65 #include <stdio.h> /* printf() */
66 #include <stdlib.h> /* calloc() free() malloc() */
67
68 #ifdef HAVE_STDINT_H
69 #include <stdint.h> /* uintptr_t */
70 #endif /* HAVE_STDINT_H */
71
72 #include "libdwarf.h"
73 #include "libdwarf_private.h"
74 #include "dwarf_tsearch.h"
75
76 /* A table of primes used to size and resize the hash table.
77 From public sources of prime numbers, arbitrarily chosen
78 to approximately double in size at each step.
79 */
80 static unsigned long primes[] =
81 {
82 #if 0 /* for testing only */
83 5,11, 17,23, 31, 47, 53,
84 79,
85 #endif /*0*/
86 521,
87 1009,
88 5591,
89 10007,
90 21839,
91 41413,
92 99907,
93 199967,
94 400009,
95 800029,
96 1600141,
97 3000089,
98 6000121,
99 12000257,
100 24000143,
101 48000203,
102 100000127,
103 200001611,
104 400000669,
105 800000573,
106 0 /* Here we are giving up */
107 };
108
109 static unsigned long allowed_fill_percent = 90;
110
111 struct hs_base {
112 unsigned long tablesize_;
113 unsigned long tablesize_entry_index_;
114 unsigned long allowed_fill_;
115 /* Record_count means number of active records,
116 counting all records on chains.
117 When the record_count is > 90% of a full
118 tablesize_ we redo the table before adding
119 a new entry. */
120 unsigned long record_count_;
121 /* hashtab_ is an array of hs_entry,
122 indexes 0 through tablesize_ -1. */
123 struct ts_entry * hashtab_;
124 DW_TSHASHTYPE (*hashfunc_)(const void *key);
125 };
126
127 struct ts_entry {
128 const void * keyptr;
129 /* So that a keyptr of 0 (if added) is
130 not confused with an empty hash slot,
131 we must mark used slots as used in the hash tab */
132 unsigned char entryused;
133 struct ts_entry *next;
134 };
135
136 enum search_intent_t
137 {
138 want_insert,
139 only_find,
140 want_delete
141 };
142
143 static struct ts_entry *
144 _tsearch_inner( const void *key, struct hs_base* head,
145 int (*compar)(const void *, const void *),
146 const enum search_intent_t intent, int*inserted,
147 struct ts_entry **parent_ptr);
148 static void
149 _dwarf_tdestroy_inner(struct hs_base*h,
150 void (*free_node)(void *nodep));
151
152 /* A trivial integer-based percentage calculation.
153 Percents >100 are reasonable for a hash-with-chains
154 situation (even if they might not be the best choice
155 for performance). */
156 static unsigned long
157 calculate_allowed_fill(unsigned long fill_percent, unsigned long ct)
158 {
159 unsigned long v = 0;
160 if (ct < 100000) {
161 unsigned long v2 = (ct *fill_percent)/100;
162 return v2;
163 }
164 v = (ct /100)*fill_percent;
165 return v;
166 }
167
168 /* Initialize the hash and pass in the hash function.
169 If the entry count needed is unknown, pass in
170 0 as a count estimate,
171 but if the number of hash entries needed can be estimated,
172 pass in the estimate (which need not be prime,
173 we actually use
174 the nearest higher prime from the above table).
175 If the estimated count is
176 Return the tree base, or return NULL if insufficient
177 memory. */
178 void *
179 dwarf_initialize_search_hash( void **treeptr,
180 DW_TSHASHTYPE(*hashfunc)(const void *key),
181 unsigned long size_estimate)
182 {
183 unsigned long prime_to_use = primes[0];
184 unsigned entry_index = 0;
185 unsigned k = 0;
186 struct hs_base *base = 0;
187
188 base = *(struct hs_base **)treeptr;
189 if (base) {
190 /* initialized already. */
191 return base ;
192 }
193 base = calloc(1, sizeof(struct hs_base));
194 if (!base) {
195 /* Out of memory. */
196 return NULL ;
197 }
198 prime_to_use = primes[0];
199 while(size_estimate && (size_estimate > prime_to_use)) {
200 k = k +1;
201 prime_to_use = primes[k];
202 if (prime_to_use == 0) {
203 /* Oops. Too large. */
204 free(base);
205 return NULL;
206 }
207 entry_index = k;
208 }
209 #ifdef TESTINGHASHTAB
210 printf("debugging: initial alloc size estimate %lu\n",size_estimate);
211 printf("debugging: initial alloc prime to use %lu\n",prime_to_use);
212 #endif
213 base->tablesize_ = prime_to_use;
214 base->allowed_fill_ = calculate_allowed_fill(allowed_fill_percent,
215 prime_to_use);
216 if (base->allowed_fill_< (base->tablesize_/2)) {
217 free(base);
218 /* Oops. We are in trouble. Coding mistake here. */
219 return NULL;
220 }
221 base->record_count_ = 0;
222 base->tablesize_entry_index_ = entry_index;
223 /* hashtab_ is an array of hs_entry,
224 indexes 0 through tablesize_ -1. */
225 base->hashfunc_ = hashfunc;
226 base->hashtab_ = calloc(base->tablesize_,
227 sizeof(struct ts_entry));
228 if (!base->hashtab_) {
229 free(base);
230 return NULL;
231 }
232 *treeptr = base;
233 return base;
234 }
235
236 #ifdef BUILD_TDUMP
237 /* We don't really care whether hashpos or chainpos
238 are 32 or 64 bits. 32 suffices. */
239 static void print_entry(struct ts_entry *t,const char *descr,
240 char *(* keyprint)(const void *),
241 unsigned long hashpos,
242 unsigned long chainpos)
243 {
244 char *v = 0;
245 if (!t->entryused) {
246 return;
247 }
248 v = keyprint(t->keyptr);
249 printf("[%4lu.%02lu] 0x%08" DW_PR_DUx
250 " <keyptr 0x%08" DW_PR_DUx
251 "> <key %s> %s\n",
252 hashpos,chainpos,
253 (Dwarf_Unsigned)(uintptr_t)t,
254 (Dwarf_Unsigned)(uintptr_t)t->keyptr,
255 v,
256 descr);
257 }
258
259 /* For debugging */
260 static void
261 dumptree_inner(const struct hs_base *h,
262 char *(* keyprint)(const void *),
263 const char *descr, int printdetails)
264 {
265 unsigned long ix = 0;
266 unsigned long tsize = h->tablesize_;
267 struct ts_entry *p = &h->hashtab_[0];
268 unsigned long hashused = 0;
269 unsigned long maxchainlength = 0;
270 unsigned long chainsgt1 = 0;
271 printf("dumptree head ptr : 0x%08" DW_PR_DUx
272 " size %" DW_PR_DUu
273 " entries %" DW_PR_DUu
274 " allowed %" DW_PR_DUu " %s\n",
275 (Dwarf_Unsigned)(uintptr_t)h,
276 (Dwarf_Unsigned)h->tablesize_,
277 (Dwarf_Unsigned)h->record_count_,
278 (Dwarf_Unsigned)h->allowed_fill_,
279 descr);
280 for ( ; ix < tsize; ix++,p++) {
281 unsigned long chainlength = 0;
282 struct ts_entry*n = 0;
283 int chainpos = 0;
284 if (p->entryused) {
285 ++hashused;
286 chainlength = 1;
287 if (printdetails) {
288 print_entry(p,"head",keyprint,ix,chainpos);
289 }
290 }
291 chainpos++;
292 for (n = p->next; n ; n = n->next) {
293 chainlength++;
294 if (printdetails) {
295 print_entry(n,"chain",keyprint,ix,chainpos);
296 }
297 }
298 if (chainlength > maxchainlength) {
299 maxchainlength = chainlength;
300 }
301 if (chainlength > 1) {
302 chainsgt1++;
303 }
304 }
305 printf("Hashtable: %lu of %lu hash entries used.\n",
306 hashused,tsize);
307 printf("Hashtable: %lu chains length longer than 1. \n",
308 chainsgt1);
309 printf("Hashtable: %lu is maximum chain length.\n",
310 maxchainlength);
311 }
312
313 /* Dumping the tree.
314 */
315 void
316 dwarf_tdump(const void*headp_in,
317 char *(* keyprint)(const void *),
318 const char *msg)
319 {
320 const struct hs_base *head = (const struct hs_base *)headp_in;
321 if (!head) {
322 printf("dumptree null tree ptr : %s\n",msg);
323 return;
324 }
325 dumptree_inner(head,keyprint,msg,1);
326 }
327 #endif /* BUILD_TDUMP */
328
329 static struct ts_entry *
330 allocate_ts_entry(const void *key)
331 {
332 struct ts_entry *e = 0;
333
334 e = (struct ts_entry *) malloc(sizeof(struct ts_entry));
335 if (!e) {
336 return NULL;
337 }
338 e->keyptr = key;
339 e->entryused = 1;
340 e->next = 0;
341 return e;
342 }
343
344 static void
345 resize_table(struct hs_base *head,
346 int (*compar)(const void *, const void *))
347 {
348 struct hs_base newhead;
349 unsigned new_entry_index = 0;
350 unsigned long prime_to_use = 0;
351
352 /* Copy the values we have. */
353 newhead = *head;
354 /* But drop the hashtab_ from new. calloc below. */
355 newhead.hashtab_ = 0;
356 newhead.record_count_ = 0;
357 new_entry_index = head->tablesize_entry_index_ +1;
358 prime_to_use = primes[new_entry_index];
359 if (!prime_to_use) {
360 /* Oops, too large. Leave table size as is, though
361 it will get slow as it overfills. */
362 return;
363 }
364 newhead.tablesize_ = prime_to_use;
365 newhead.allowed_fill_ = calculate_allowed_fill(
366 allowed_fill_percent, prime_to_use);
367 if (newhead.allowed_fill_< (newhead.tablesize_/2)) {
368 /* Oops. We are in trouble. */
369 return;
370 }
371 newhead.tablesize_entry_index_ = new_entry_index;
372 newhead.hashtab_ = calloc(newhead.tablesize_,
373 sizeof(struct ts_entry));
374 if (!newhead.hashtab_) {
375 /* Oops, too large. Leave table size as is, though
376 things will get slow as it overfills. */
377 free(newhead.hashtab_);
378 return;
379 }
380 {
381 /* Insert all the records from the old table into
382 the new table. */
383 int fillnewfail = 0;
384 unsigned long ix = 0;
385 unsigned long tsize = head->tablesize_;
386 struct ts_entry *p = &head->hashtab_[0];
387 #ifdef TESTINGHASHTAB
388 printf("debugging: Resize %lu to %lu\n",tsize,prime_to_use);
389 #endif
390 for ( ; ix < tsize; ix++,p++) {
391 int inserted = 0;
392 struct ts_entry*n = 0;
393 if (fillnewfail) {
394 break;
395 }
396 if (p->keyptr) {
397 _tsearch_inner(p->keyptr,
398 &newhead,compar,
399 want_insert,
400 &inserted,
401 0);
402 if (!inserted) {
403 fillnewfail = 1;
404 break;
405 }
406 }
407 for (n = p->next; n ; n = n->next) {
408 inserted = 0;
409 _tsearch_inner(n->keyptr,
410 &newhead,compar,
411 want_insert,
412 &inserted,
413 0);
414 if (!inserted) {
415 fillnewfail = 1;
416 break;
417 }
418 }
419 }
420 if (fillnewfail) {
421 free(newhead.hashtab_);
422 return;
423 }
424 }
425 /* Now get rid of the chain entries of the old table. */
426 _dwarf_tdestroy_inner(head,0);
427 /* Now get rid of the old table itself. */
428 free(head->hashtab_);
429 head->hashtab_ = 0;
430 *head = newhead;
431 return;
432 }
433
434 /* Inner search of the hash and synonym chains. */
435 static struct ts_entry *
436 _tsearch_inner( const void *key, struct hs_base* head,
437 int (*compar)(const void *, const void *),
438 const enum search_intent_t intent, int*inserted,
439 /* owner_ptr used for delete. Only set
440 if the to-be-deleted item is on a chain,
441 not in the hashtab. Points to the item
442 pointing to the to-be-deleted-item.*/
443 struct ts_entry **owner_ptr)
444 {
445 struct ts_entry *s =0;
446 struct ts_entry *c =0;
447 struct ts_entry *q =0;
448 int kc = 0;
449 DW_TSHASHTYPE keyhash = 0;
450 DW_TSHASHTYPE hindx = 0;
451 struct ts_entry *chain_parent = 0;
452
453 if (! head->hashfunc_) {
454 /* Not fully initialized. */
455 return NULL;
456 }
457 keyhash = head->hashfunc_(key);
458 if (intent == want_insert) {
459 if (head->record_count_ > head->allowed_fill_) {
460 resize_table(head,compar);
461 }
462 }
463 hindx = keyhash%head->tablesize_;
464 s = &head->hashtab_[hindx];
465 if (!s->entryused) {
466 /* Not found. */
467 if (intent != want_insert) {
468 return NULL;
469 }
470 /* Insert in the base hash table in an
471 empty slot. */
472 *inserted = 1;
473 head->record_count_++;
474 s->keyptr = (const void *)key;
475 s->entryused = 1;
476 s->next = 0;
477 return s;
478 }
479 kc = compar(key,s->keyptr);
480 if (kc == 0 ) {
481 /* found! */
482 if (intent == want_delete) {
483 *owner_ptr = 0;
484 }
485 return (void *)&(s->keyptr);
486 }
487 chain_parent = s;
488 for (c = s->next; c; c = c->next) {
489 kc = compar(key,c->keyptr);
490 if (kc == 0 ) {
491 /* found! */
492 if (intent == want_delete) {
493 *owner_ptr = chain_parent;
494 }
495 return (void *)&(c->keyptr);
496 }
497 chain_parent = c;
498 }
499 if (intent != want_insert) {
500 return NULL;
501 }
502 /* Insert following head record of the chain. */
503 q = allocate_ts_entry(key);
504 if (!q) {
505 return q;
506 }
507 q->next = s->next;
508 s->next = q;
509 head->record_count_++;
510 *inserted = 1;
511 return q;
512 }
513 /* Search and, if missing, insert. */
514 void *
515 dwarf_tsearch(const void *key, void **headin,
516 int (*compar)(const void *, const void *))
517 {
518 struct hs_base **rootp = (struct hs_base **)headin;
519 struct hs_base *head = *rootp;
520 struct ts_entry *r = 0;
521 int inserted = 0;
522 /* nullme won't be set. */
523 struct ts_entry *nullme = 0;
524
525 if (!head) {
526 /* something is wrong here, not initialized. */
527 return NULL;
528 }
529 r = _tsearch_inner(key,head,compar,want_insert,&inserted,&nullme);
530 if (!r) {
531 return NULL;
532 }
533 return (void *)&(r->keyptr);
534 }
535
536 /* Search. */
537 void *
538 dwarf_tfind(const void *key, void *const *rootp,
539 int (*compar)(const void *, const void *))
540 {
541 /* Nothing will change, but we discard const
542 so we can use tsearch_inner(). */
543 struct hs_base **proot = (struct hs_base **)rootp;
544 struct hs_base *head = *proot;
545 struct ts_entry *r = 0;
546 /* inserted flag won't be set. */
547 int inserted = 0;
548 /* nullme won't be set. */
549 struct ts_entry * nullme = 0;
550 /* Get to actual tree. */
551
552 if (!head) {
553 return NULL;
554 }
555
556 r = _tsearch_inner(key,head,compar,only_find,&inserted,&nullme);
557 if (!r) {
558 return NULL;
559 }
560 return (void *)(&(r->keyptr));
561 }
562
563 /* Unlike the simple binary tree case,
564 a fully-empty hash situation does not null the *rootp
565 */
566 void *
567 dwarf_tdelete(const void *key, void **rootp,
568 int (*compar)(const void *, const void *))
569 {
570 struct hs_base **proot = (struct hs_base **)rootp;
571 struct hs_base *head = *proot;
572 struct ts_entry *found = 0;
573 /* inserted flag won't be set. */
574 int inserted = 0;
575 struct ts_entry * parentp = 0;
576
577 if (!head) {
578 return NULL;
579 }
580
581 found = _tsearch_inner(key,head,compar,want_delete,&inserted,
582 &parentp);
583 if (found) {
584 if (parentp) {
585 /* Delete a chain entry. */
586 head->record_count_--;
587 parentp->next = found->next;
588 /* We free our storage. It would be up
589 to caller to do a tfind to find
590 a record and delete content if necessary. */
591 free(found);
592 return (void *)&(parentp->keyptr);
593 }
594 /* So found is the head of a chain. */
595 if (found->next) {
596 /* Delete a chain entry, pull up to hash tab, freeing
597 up the chain entry. */
598 struct ts_entry *pullup = found->next;
599 *found = *pullup;
600 free(pullup);
601 head->record_count_--;
602 return (void *)&(found->keyptr);
603 } else {
604 /* Delete a main hash table entry.
605 Problem: what the heck to return as a keyptr pointer?
606 Well, we return NULL. As in the standard
607 tsearch, returning NULL does not mean
608 failure! Here it just means 'empty chain somewhere'.
609 */
610 head->record_count_--;
611 found->next = 0;
612 found->keyptr = 0;
613 found->entryused = 0;
614 return NULL;
615 }
616 }
617 return NULL;
618 }
619
620 static void
621 _dwarf_twalk_inner(const struct hs_base *h,
622 struct ts_entry *p,
623 void (*action)(const void *nodep, const DW_VISIT which,
624 const int depth )
625 )
626 {
627 unsigned long ix = 0;
628 int depth = 0;
629 unsigned long tsize = h->tablesize_;
630 for ( ; ix < tsize; ix++,p++) {
631 struct ts_entry*n = 0;
632 if (p->keyptr) {
633 action((void *)(&(p->keyptr)),dwarf_leaf,depth);
634 }
635 for (n = p->next; n ; n = n->next) {
636 action((void *)(&(n->keyptr)),dwarf_leaf,depth);
637 }
638 }
639 }
640
641 void
642 dwarf_twalk(const void *rootp,
643 void (*action)(const void *nodep, const DW_VISIT which,
644 const int depth))
645 {
646 const struct hs_base *head = (const struct hs_base *)rootp;
647 struct ts_entry *root = 0;
648 if (!head) {
649 return;
650 }
651 root = head->hashtab_;
652 /* Get to actual tree. */
653 _dwarf_twalk_inner(head,root,action);
654 }
655
656 static void
657 _dwarf_tdestroy_inner(struct hs_base*h,
658 void (*free_node)(void *nodep))
659 {
660 unsigned long ix = 0;
661 unsigned long tsize = h->tablesize_;
662 struct ts_entry *p = &h->hashtab_[0];
663 #ifdef TESTINGHASHTAB
664 printf("debugging: destroyhashtable blocks %lu\n",tsize);
665 printf("debugging: destroyhashtable recordcount %lu\n",
666 h->record_count_);
667 #endif
668 for ( ; ix < tsize; ix++,p++) {
669 struct ts_entry*n = 0;
670 struct ts_entry*prev = 0;
671 if (p->keyptr && p->entryused) {
672 if (free_node) {
673 free_node((void *)(p->keyptr));
674 }
675 --h->record_count_;
676 }
677 /* Now walk and free up the chain entries. */
678 for (n = p->next; n ; ) {
679 if (free_node) {
680 free_node((void *)(n->keyptr));
681 }
682 --h->record_count_;
683 prev = n;
684 n = n->next;
685 free(prev);
686 }
687 }
688 }
689
690 /* Walk the tree, freeing all space in the tree
691 and calling the user's callback function on each node.
692
693 It is up to the caller to zero out anything pointing to
694 head (ie, that has the value rootp holds) after this
695 returns.
696 */
697 void
698 dwarf_tdestroy(void *rootp, void (*free_node)(void *nodep))
699 {
700 struct hs_base *head = (struct hs_base *)rootp;
701 struct ts_entry *root = 0;
702 if (!head) {
703 return;
704 }
705 root = head->hashtab_;
706 _dwarf_tdestroy_inner(head,free_node);
707 free(root);
708 free(head);
709 }