1 /* hash.c - hash table lookup strings -
2 Copyright (C) 1987, 1990, 1991 Free Software Foundation, Inc.
4 This file is part of GAS, the GNU Assembler.
6 GAS is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GAS is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GAS; see the file COPYING. If not, write to
18 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
21 * BUGS, GRIPES, APOLOGIA etc.
23 * A typical user doesn't need ALL this: I intend to make a library out
24 * of it one day - Dean Elsner.
25 * Also, I want to change the definition of a symbol to (address,length)
26 * so I can put arbitrary binary in the names stored. [see hsh.c for that]
28 * This slime is common coupled inside the module. Com-coupling (and other
29 * vandalism) was done to speed running time. The interfaces at the
30 * module's edges are adequately clean.
32 * There is no way to (a) run a test script through this heap and (b)
33 * compare results with previous scripts, to see if we have broken any
34 * code. Use GNU (f)utilities to do this. A few commands assist test.
35 * The testing is awkward: it tries to be both batch & interactive.
36 * For now, interactive rules!
40 * The idea is to implement a symbol table. A test jig is here.
41 * Symbols are arbitrary strings; they can't contain '\0'.
42 * [See hsh.c for a more general symbol flavour.]
43 * Each symbol is associated with a char*, which can point to anything
44 * you want, allowing an arbitrary property list for each symbol.
46 * The basic operations are:
48 * new creates symbol table, returns handle
49 * find (symbol) returns char*
50 * insert (symbol,char*) error if symbol already in table
51 * delete (symbol) returns char* if symbol was in table
52 * apply so you can delete all symbols before die()
53 * die destroy symbol table (free up memory)
55 * Supplementary functions include:
57 * say how big? what % full?
58 * replace (symbol,newval) report previous value
59 * jam (symbol,value) assert symbol:=value
61 * You, the caller, have control over errors: this just reports them.
63 * This package requires malloc(), free().
64 * Malloc(size) returns NULL or address of char[size].
65 * Free(address) frees same.
69 * The code and its structures are re-enterent.
70 * Before you do anything else, you must call hash_new() which will
71 * return the address of a hash-table-control-block (or NULL if there
72 * is not enough memory). You then use this address as a handle of the
73 * symbol table by passing it to all the other hash_...() functions.
74 * The only approved way to recover the memory used by the symbol table
75 * is to call hash_die() with the handle of the symbol table.
77 * Before you call hash_die() you normally delete anything pointed to
78 * by individual symbols. After hash_die() you can't use that symbol
81 * The char* you associate with a symbol may not be NULL (0) because
82 * NULL is returned whenever a symbol is not in the table. Any other
83 * value is OK, except DELETED, #defined below.
85 * When you supply a symbol string for insertion, YOU MUST PRESERVE THE
86 * STRING until that symbol is deleted from the table. The reason is that
87 * only the address you supply, NOT the symbol string itself, is stored
88 * in the symbol table.
90 * You may delete and add symbols arbitrarily.
91 * Any or all symbols may have the same 'value' (char *). In fact, these
92 * routines don't do anything with your symbol values.
94 * You have no right to know where the symbol:char* mapping is stored,
95 * because it moves around in memory; also because we may change how it
96 * works and we don't want to break your code do we? However the handle
97 * (address of struct hash_control) is never changed in
98 * the life of the symbol table.
100 * What you CAN find out about a symbol table is:
101 * how many slots are in the hash table?
102 * how many slots are filled with symbols?
103 * (total hashes,collisions) for (reads,writes) (*)
104 * All of the above values vary in time.
105 * (*) some of these numbers will not be meaningful if we change the
112 * Hash table is an array of hash_entries; each entry is a pointer to a
113 * a string and a user-supplied value 1 char* wide.
115 * The array always has 2 ** n elements, n>0, n integer.
116 * There is also a 'wall' entry after the array, which is always empty
117 * and acts as a sentinel to stop running off the end of the array.
118 * When the array gets too full, we create a new array twice as large
119 * and re-hash the symbols into the new array, then forget the old array.
120 * (Of course, we copy the values into the new array before we junk the
129 #define TRUE (!FALSE)
130 #endif /* no FALSE yet */
133 #define min(a, b) ((a) < (b) ? (a) : (b))
137 #define error as_fatal
139 #define DELETED ((char *)1) /* guarenteed invalid address */
140 #define START_POWER (11) /* power of two: size of new hash table *//* JF was 6 */
141 /* JF These next two aren't used any more. */
142 /* #define START_SIZE (64) / * 2 ** START_POWER */
143 /* #define START_FULL (32) / * number of entries before table expands */
144 #define islive(ptr) (ptr->hash_string && ptr->hash_string!=DELETED)
145 /* above TRUE if a symbol is in entry @ ptr */
147 #define STAT_SIZE (0) /* number of slots in hash table */
148 /* the wall does not count here */
149 /* we expect this is always a power of 2 */
150 #define STAT_ACCESS (1) /* number of hash_ask()s */
151 #define STAT__READ (0) /* reading */
152 #define STAT__WRITE (1) /* writing */
153 #define STAT_COLLIDE (3) /* number of collisions (total) */
154 /* this may exceed STAT_ACCESS if we have */
155 /* lots of collisions/access */
156 #define STAT_USED (5) /* slots used right now */
157 #define STATLENGTH (6) /* size of statistics block */
158 #if STATLENGTH != HASH_STATLENGTH
159 Panic! Please make #include "stat.h" agree with previous definitions!
162 /* #define SUSPECT to do runtime checks */
163 /* #define TEST to be a test jig for hash...() */
165 #ifdef TEST /* TEST: use smaller hash table */
167 #define START_POWER (3)
169 #define START_SIZE (8)
171 #define START_FULL (4)
174 /*------------------ plan ---------------------------------- i = internal
176 struct hash_control * c;
177 struct hash_entry * e; i
178 int b[z]; buffer for statistics
180 char * s; symbol string (address) [ key ]
181 char * v; value string (address) [datum]
182 boolean f; TRUE if we found s in hash table i
183 char * t; error string; "" means OK
184 int a; access type [0...n) i
186 c=hash_new () create new hash_control
188 hash_die (c) destroy hash_control (and hash table)
189 table should be empty.
190 doesn't check if table is empty.
191 c has no meaning after this.
193 hash_say (c,b,z) report statistics of hash_control.
194 also report number of available statistics.
196 v=hash_delete (c,s) delete symbol, return old value if any.
197 ask() NULL means no old value.
200 v=hash_replace (c,s,v) replace old value of s with v.
201 ask() NULL means no old value: no table change.
204 t=hash_insert (c,s,v) insert (s,v) in c.
205 ask() return error string.
206 f it is an error to insert if s is already
208 if any error, c is unchanged.
210 t=hash_jam (c,s,v) assert that new value of s will be v. i
211 ask() it may decide to GROW the table. i
214 t=hash_grow (c) grow the hash table. i
215 jam() will invoke JAM. i
217 ?=hash_apply (c,y) apply y() to every symbol in c.
218 y evtries visited in 'unspecified' order.
220 v=hash_find (c,s) return value of s, or NULL if s not in c.
224 f,e=hash_ask() (c,s,a) return slot where s SHOULD live. i
225 code() maintain collision stats in c. i
227 .=hash_code (c,s) compute hash-code for s, i
228 from parameters of c. i
232 static char hash_found; /* returned by hash_ask() to stop extra */
233 /* testing. hash_ask() wants to return both */
234 /* a slot and a status. This is the status. */
235 /* TRUE: found symbol */
236 /* FALSE: absent: empty or deleted slot */
237 /* Also returned by hash_jam(). */
238 /* TRUE: we replaced a value */
239 /* FALSE: we inserted a value */
241 static struct hash_entry * hash_ask();
242 static int hash_code ();
243 static char * hash_grow();
246 * h a s h _ n e w ( )
249 struct hash_control *
250 hash_new() /* create a new hash table */
251 /* return NULL if failed */
252 /* return handle (address of struct hash) */
254 register struct hash_control * retval;
255 register struct hash_entry * room; /* points to hash table */
256 register struct hash_entry * wall;
257 register struct hash_entry * entry;
258 register int * ip; /* scan stats block of struct hash_control */
259 register int * nd; /* limit of stats block */
261 if (( room = (struct hash_entry *) malloc( sizeof(struct
262 hash_entry)*((1<<START_POWER) + 1) ) ) != NULL)
263 /* +1 for the wall entry */
265 if (( retval = (struct hash_control *) malloc(sizeof(struct
266 hash_control)) ) != NULL)
268 nd = retval->hash_stat + STATLENGTH;
269 for (ip=retval->hash_stat; ip<nd; ip++)
274 retval -> hash_stat[STAT_SIZE] = 1<<START_POWER;
275 retval -> hash_mask = (1<<START_POWER) - 1;
276 retval -> hash_sizelog = START_POWER;
277 /* works for 1's compl ok */
278 retval -> hash_where = room;
279 retval -> hash_wall =
280 wall = room + (1<<START_POWER);
281 retval -> hash_full = (1<<START_POWER)/2;
282 for (entry=room; entry<=wall; entry++)
284 entry->hash_string = NULL;
290 retval = NULL; /* no room for table: fake a failure */
292 return(retval); /* return NULL or set-up structs */
296 * h a s h _ d i e ( )
298 * Table should be empty, but this is not checked.
299 * To empty the table, try hash_apply()ing a symbol deleter.
300 * Return to free memory both the hash table and it's control
302 * 'handle' has no meaning after this function.
303 * No errors are recoverable.
307 struct hash_control * handle;
309 free((char *)handle->hash_where);
310 free((char *)handle);
314 * h a s h _ s a y ( )
316 * Return the size of the statistics table, and as many statistics as
317 * we can until either (a) we have run out of statistics or (b) caller
318 * has run out of buffer.
319 * NOTE: hash_say treats all statistics alike.
320 * These numbers may change with time, due to insertions, deletions
321 * and expansions of the table.
322 * The first "statistic" returned is the length of hash_stat[].
323 * Then contents of hash_stat[] are read out (in ascending order)
324 * until your buffer or hash_stat[] is exausted.
327 hash_say(handle,buffer,bufsiz)
328 register struct hash_control * handle;
329 register int buffer[/*bufsiz*/];
332 register int * nd; /* limit of statistics block */
333 register int * ip; /* scan statistics */
335 ip = handle -> hash_stat;
336 nd = ip + min(bufsiz-1,STATLENGTH);
337 if (bufsiz>0) /* trust nothing! bufsiz<=0 is dangerous */
339 *buffer++ = STATLENGTH;
340 for (; ip<nd; ip++,buffer++)
348 * h a s h _ d e l e t e ( )
350 * Try to delete a symbol from the table.
351 * If it was there, return its value (and adjust STAT_USED).
352 * Otherwise, return NULL.
353 * Anyway, the symbol is not present after this function.
356 char * /* NULL if string not in table, else */
357 /* returns value of deleted symbol */
358 hash_delete(handle,string)
359 register struct hash_control * handle;
360 register char * string;
362 register char * retval; /* NULL if string not in table */
363 register struct hash_entry * entry; /* NULL or entry of this symbol */
365 entry = hash_ask(handle,string,STAT__WRITE);
368 retval = entry -> hash_value;
369 entry -> hash_string = DELETED; /* mark as deleted */
370 handle -> hash_stat[STAT_USED] -= 1; /* slots-in-use count */
372 if (handle->hash_stat[STAT_USED]<0)
374 error("hash_delete");
376 #endif /* def SUSPECT */
386 * h a s h _ r e p l a c e ( )
388 * Try to replace the old value of a symbol with a new value.
389 * Normally return the old value.
390 * Return NULL and don't change the table if the symbol is not already
394 hash_replace(handle,string,value)
395 register struct hash_control * handle;
396 register char * string;
397 register char * value;
399 register struct hash_entry * entry;
400 register char * retval;
402 entry = hash_ask(handle,string,STAT__WRITE);
405 retval = entry -> hash_value;
406 entry -> hash_value = value;
417 * h a s h _ i n s e r t ( )
419 * Insert a (symbol-string, value) into the hash table.
420 * Return an error string, "" means OK.
421 * It is an 'error' to insert an existing symbol.
424 char * /* return error string */
425 hash_insert(handle,string,value)
426 register struct hash_control * handle;
427 register char * string;
428 register char * value;
430 register struct hash_entry * entry;
431 register char * retval;
434 if (handle->hash_stat[STAT_USED] > handle->hash_full)
436 retval = hash_grow(handle);
440 entry = hash_ask(handle,string,STAT__WRITE);
447 entry -> hash_value = value;
448 entry -> hash_string = string;
449 handle-> hash_stat[STAT_USED] += 1;
456 * h a s h _ j a m ( )
458 * Regardless of what was in the symbol table before, after hash_jam()
459 * the named symbol has the given value. The symbol is either inserted or
460 * (its value is) relpaced.
461 * An error message string is returned, "" means OK.
463 * WARNING: this may decide to grow the hashed symbol table.
464 * To do this, we call hash_grow(), WHICH WILL recursively CALL US.
466 * We report status internally: hash_found is TRUE if we replaced, but
467 * false if we inserted.
470 hash_jam(handle,string,value)
471 register struct hash_control * handle;
472 register char * string;
473 register char * value;
475 register char * retval;
476 register struct hash_entry * entry;
479 if (handle->hash_stat[STAT_USED] > handle->hash_full)
481 retval = hash_grow(handle);
485 entry = hash_ask(handle,string,STAT__WRITE);
488 entry -> hash_string = string;
489 handle->hash_stat[STAT_USED] += 1;
491 entry -> hash_value = value;
497 * h a s h _ g r o w ( )
499 * Grow a new (bigger) hash table from the old one.
500 * We choose to double the hash table's size.
501 * Return a human-scrutible error string: "" if OK.
502 * Warning! This uses hash_jam(), which had better not recurse
503 * back here! Hash_jam() conditionally calls us, but we ALWAYS
508 hash_grow(handle) /* make a hash table grow */
509 struct hash_control * handle;
511 register struct hash_entry * newwall;
512 register struct hash_entry * newwhere;
513 struct hash_entry * newtrack;
514 register struct hash_entry * oldtrack;
515 register struct hash_entry * oldwhere;
516 register struct hash_entry * oldwall;
526 * capture info about old hash table
528 oldwhere = handle -> hash_where;
529 oldwall = handle -> hash_wall;
531 oldused = handle -> hash_stat[STAT_USED];
534 * attempt to get enough room for a hash table twice as big
536 temp = handle->hash_stat[STAT_SIZE];
537 if (( newwhere = (struct hash_entry *)
538 xmalloc((long)((temp+temp+1)*sizeof(struct hash_entry)))) != NULL)
539 /* +1 for wall slot */
541 retval = ""; /* assume success until proven otherwise */
543 * have enough room: now we do all the work.
544 * double the size of everything in handle,
545 * note: hash_mask frob works for 1's & for 2's complement machines
547 handle->hash_mask = handle->hash_mask + handle->hash_mask + 1;
548 handle->hash_stat[STAT_SIZE] <<= 1;
549 newsize = handle->hash_stat[STAT_SIZE];
550 handle->hash_where = newwhere;
551 handle->hash_full <<= 1;
552 handle->hash_sizelog += 1;
553 handle->hash_stat[STAT_USED] = 0;
555 newwall = newwhere + newsize;
557 * set all those pesky new slots to vacant.
559 for (newtrack=newwhere; newtrack <= newwall; newtrack++)
561 newtrack -> hash_string = NULL;
564 * we will do a scan of the old table, the hard way, using the
565 * new control block to re-insert the data into new hash table.
567 handle -> hash_stat[STAT_USED] = 0; /* inserts will bump it up to correct */
568 for (oldtrack=oldwhere; oldtrack < oldwall; oldtrack++)
570 if ( ((string=oldtrack->hash_string) != NULL) && string!=DELETED )
572 if ( * (retval = hash_jam(handle,string,oldtrack->hash_value) ) )
579 if ( !*retval && handle->hash_stat[STAT_USED] != oldused)
581 retval = "hash_used";
587 * we have a completely faked up control block.
588 * return the old hash table.
590 free((char *)oldwhere);
592 * Here with success. retval is already "".
604 * h a s h _ a p p l y ( )
606 * Use this to scan each entry in symbol table.
607 * For each symbol, this calls (applys) a nominated function supplying the
608 * symbol's value (and the symbol's name).
609 * The idea is you use this to destroy whatever is associted with
610 * any values in the table BEFORE you destroy the table with hash_die.
611 * Of course, you can use it for other jobs; whenever you need to
612 * visit all extant symbols in the table.
614 * We choose to have a call-you-back idea for two reasons:
615 * asthetic: it is a neater idea to use apply than an explicit loop
616 * sensible: if we ever had to grow the symbol table (due to insertions)
617 * then we would lose our place in the table when we re-hashed
618 * symbols into the new table in a different order.
620 * The order symbols are visited depends entirely on the hashing function.
621 * Whenever you insert a (symbol, value) you risk expanding the table. If
622 * you do expand the table, then the hashing function WILL change, so you
623 * MIGHT get a different order of symbols visited. In other words, if you
624 * want the same order of visiting symbols as the last time you used
625 * hash_apply() then you better not have done any hash_insert()s or
626 * hash_jam()s since the last time you used hash_apply().
628 * In future we may use the value returned by your nominated function.
629 * One idea is to abort the scan if, after applying the function to a
630 * certain node, the function returns a certain code.
631 * To be safe, please make your functions of type char *. If you always
632 * return NULL, then the scan will complete, visiting every symbol in
633 * the table exactly once. ALL OTHER RETURNED VALUES have no meaning yet!
636 * The function you supply should be of the form:
637 * char * myfunct(string,value)
638 * char * string; |* the symbol's name *|
639 * char * value; |* the symbol's value *|
645 * The returned value of hash_apply() is (char*)NULL. In future it may return
646 * other values. NULL means "completed scan OK". Other values have no meaning
647 * yet. (The function has no graceful failures.)
650 hash_apply(handle,function)
651 struct hash_control * handle;
654 register struct hash_entry * entry;
655 register struct hash_entry * wall;
657 wall = handle->hash_wall;
658 for (entry = handle->hash_where; entry < wall; entry++)
660 if (islive(entry)) /* silly code: tests entry->string twice! */
662 (*function)(entry->hash_string,entry->hash_value);
669 * h a s h _ f i n d ( )
671 * Given symbol string, find value (if any).
672 * Return found value or NULL.
675 hash_find(handle,string) /* return char* or NULL */
676 struct hash_control * handle;
679 register struct hash_entry * entry;
680 register char * retval;
682 entry = hash_ask(handle,string,STAT__READ);
685 retval = entry->hash_value;
695 * h a s h _ a s k ( )
697 * Searches for given symbol string.
698 * Return the slot where it OUGHT to live. It may be there.
699 * Return hash_found: TRUE only if symbol is in that slot.
700 * Access argument is to help keep statistics in control block.
703 static struct hash_entry * /* string slot, may be empty or deleted */
704 hash_ask(handle,string,access)
705 struct hash_control * handle;
707 int access; /* access type */
709 register char *string1; /* JF avoid strcmp calls */
712 register struct hash_entry * slot;
713 register int collision; /* count collisions */
715 slot = handle->hash_where + hash_code(handle,string); /* start looking here */
716 handle->hash_stat[STAT_ACCESS+access] += 1;
719 while ( ((s = slot->hash_string) != NULL) && s!=DELETED )
721 for(string1=string;;) {
737 * in use: we found string slot
739 * at wall: we fell off: wrap round ????
740 * in table: dig here slot
741 * at DELETED: dig here slot
743 if (slot==handle->hash_wall)
745 slot = handle->hash_where; /* now look again */
746 while( ((s = slot->hash_string) != NULL) && s!=DELETED )
748 for(string1=string;*s;string1++,s++) {
761 * in use: we found it slot
762 * empty: wall: ERROR IMPOSSIBLE !!!!
763 * in table: dig here slot
764 * DELETED:dig here slot
767 /* fprintf(stderr,"hash_ask(%s)->%d(%d)\n",string,hash_code(handle,string),collision); */
768 handle -> hash_stat[STAT_COLLIDE+access] += collision;
769 return(slot); /* also return hash_found */
775 * Does hashing of symbol string to hash number.
779 hash_code(handle,string)
780 struct hash_control * handle;
781 register char * string;
783 register long h; /* hash code built here */
784 register long c; /* each character lands here */
785 register int n; /* Amount to shift h by */
787 n = (handle->hash_sizelog - 3);
789 while ((c = *string++) != 0)
792 h = (h<<3) + (h>>n) + c;
794 return (h & handle->hash_mask);
798 * Here is a test program to exercise above.
802 #define TABLES (6) /* number of hash tables to maintain */
803 /* (at once) in any testing */
804 #define STATBUFSIZE (12) /* we can have 12 statistics */
806 int statbuf[STATBUFSIZE]; /* display statistics here */
807 char answer[100]; /* human farts here */
808 char * hashtable[TABLES]; /* we test many hash tables at once */
809 char * h; /* points to curent hash_control */
817 int number; /* number 0:TABLES-1 of current hashed */
822 char (*applicatee());
826 struct hash_control * hash_new();
827 char * hash_replace();
832 printf("type h <RETURN> for help\n");
835 printf("hash_test command: ");
838 if (isupper(command)) command = tolower(command); /* ecch! */
842 printf("old hash table #=%d.\n",number);
846 for (pp=hashtable; pp<hashtable+TABLES; pp++)
848 printf("address of hash table #%d control block is %xx\n"
853 hash_apply(h,applicatee);
856 hash_apply(h,destroy);
860 p = hash_find(h,name=what("symbol"));
861 printf("value of \"%s\" is \"%s\"\n",name,p?p:"NOT-PRESENT");
864 printf("# show old, select new default hash table number\n");
865 printf("? display all hashtable control block addresses\n");
866 printf("a apply a simple display-er to each symbol in table\n");
867 printf("d die: destroy hashtable\n");
868 printf("f find value of nominated symbol\n");
869 printf("h this help\n");
870 printf("i insert value into symbol\n");
871 printf("j jam value into symbol\n");
872 printf("n new hashtable\n");
873 printf("r replace a value with another\n");
874 printf("s say what %% of table is used\n");
875 printf("q exit this program\n");
876 printf("x delete a symbol from table, report its value\n");
879 p = hash_insert(h,name=what("symbol"),value=what("value"));
882 printf("symbol=\"%s\" value=\"%s\" error=%s\n",name,value,p);
886 p = hash_jam(h,name=what("symbol"),value=what("value"));
889 printf("symbol=\"%s\" value=\"%s\" error=%s\n",name,value,p);
893 h = hashtable[number] = (char *) hash_new();
898 p = hash_replace(h,name=what("symbol"),value=what("value"));
899 printf("old value was \"%s\"\n",p?p:"{}");
902 hash_say(h,statbuf,STATBUFSIZE);
903 for (ip=statbuf; ip<statbuf+STATBUFSIZE; ip++)
910 p = hash_delete(h,name=what("symbol"));
911 printf("old value was \"%s\"\n",p?p:"{}");
914 printf("I can't understand command \"%c\"\n",command);
927 printf(" %s : ",description);
929 /* will one day clean up answer here */
930 retval = malloc(strlen(answer)+1);
935 (void)strcpy(retval,answer);
940 destroy(string,value)
951 applicatee(string,value)
955 printf("%.20s-%.20s\n",string,value);
959 whattable() /* determine number: what hash table to use */
960 /* also determine h: points to hash_control */
965 printf(" what hash table (%d:%d) ? ",0,TABLES-1);
967 sscanf(answer,"%d",&number);
968 if (number>=0 && number<TABLES)
970 h = hashtable[number];
973 printf("warning: current hash-table-#%d. has no hash-control\n",number);
979 printf("invalid hash table number: %d\n",number);
986 #endif /* #ifdef TEST */