xref: /illumos-gate/usr/src/cmd/sgs/crle/common/hash.c (revision 8285fe28)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (c) 2000 by Sun Microsystems, Inc.
24  * All rights reserved.
25  */
26 
27 #include	<stdio.h>
28 #include	<stdlib.h>
29 #include	<string.h>
30 #include	<libelf.h>
31 #include	"_crle.h"
32 
33 Hash_tbl *
make_hash(int size,Hash_type type,ulong_t ident)34 make_hash(int size, Hash_type type, ulong_t ident)
35 {
36 	Hash_tbl *	tbl;
37 
38 	if ((tbl = malloc(sizeof (Hash_tbl))) == 0)
39 		return (0);
40 
41 	tbl->t_entry = calloc(size, (unsigned)(sizeof (Hash_ent *)));
42 	if (tbl->t_entry == NULL) {
43 		free(tbl);
44 		return (0);
45 	}
46 
47 	tbl->t_ident = ident;
48 	tbl->t_type = type;
49 	tbl->t_size = size;
50 
51 	return (tbl);
52 }
53 
54 
55 Hash_ent *
get_hash(Hash_tbl * tbl,Addr key,Half id,int mode)56 get_hash(Hash_tbl * tbl, Addr key, Half id, int mode)
57 {
58 	int		bucket;
59 	Hash_ent *	ent;
60 	Word		hashval;
61 
62 	if (tbl->t_type == HASH_STR)
63 		hashval = elf_hash((const char *)key);
64 	else
65 		hashval = key;
66 
67 	bucket = hashval % tbl->t_size;
68 
69 	if (mode & HASH_FND_ENT) {
70 		for (ent = tbl->t_entry[bucket]; ent != NULL;
71 		    ent = ent->e_next) {
72 			if (tbl->t_type == HASH_STR) {
73 				if ((strcmp((const char *)ent->e_key,
74 				    (const char *)key) == 0) && ((id == 0) ||
75 				    (id == ent->e_id)))
76 					return (ent);
77 			} else {
78 				if (ent->e_key == key)
79 					return (ent);
80 			}
81 		}
82 	}
83 	if (!(mode & HASH_ADD_ENT))
84 		return (0);
85 
86 	/*
87 	 * Key not found in this hash table ... insert new entry into bucket.
88 	 */
89 	if ((ent = calloc(1, sizeof (Hash_ent))) == NULL)
90 		return (0);
91 
92 	ent->e_key = key;
93 	ent->e_hash = hashval;
94 
95 	/*
96 	 * Hook into bucket chain
97 	 */
98 	ent->e_next = tbl->t_entry[bucket];
99 	tbl->t_entry[bucket] = ent;
100 
101 	return (ent);
102 }
103