xref: /titanic_50/usr/src/cmd/sgs/crle/common/hash.c (revision 174bc6499d233e329ecd3d98a880a7b07df16bfa)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include	<stdio.h>
29 #include	<stdlib.h>
30 #include	<string.h>
31 #include	<libelf.h>
32 #include	"_crle.h"
33 
34 Hash_tbl *
35 make_hash(int size, Hash_type type, ulong_t ident)
36 {
37 	Hash_tbl *	tbl;
38 
39 	if ((tbl = malloc(sizeof (Hash_tbl))) == 0)
40 		return (0);
41 
42 	if ((tbl->t_entry = calloc((unsigned)(sizeof (Hash_ent *)), size)) == 0)
43 		return (0);
44 
45 	tbl->t_ident = ident;
46 	tbl->t_type = type;
47 	tbl->t_size = size;
48 
49 	return (tbl);
50 }
51 
52 
53 Hash_ent *
54 get_hash(Hash_tbl * tbl, Addr key, Half id, int mode)
55 {
56 	int		bucket;
57 	Hash_ent *	ent;
58 	Word		hashval;
59 
60 	if (tbl->t_type == HASH_STR)
61 		hashval = elf_hash((const char *)key);
62 	else
63 		hashval = key;
64 
65 	bucket = hashval % tbl->t_size;
66 
67 	if (mode & HASH_FND_ENT) {
68 		for (ent = tbl->t_entry[bucket]; ent != NULL;
69 		    ent = ent->e_next) {
70 			if (tbl->t_type == HASH_STR) {
71 				if ((strcmp((const char *)ent->e_key,
72 				    (const char *)key) == 0) && ((id == 0) ||
73 				    (id == ent->e_id)))
74 					return (ent);
75 			} else {
76 				if (ent->e_key == key)
77 					return (ent);
78 			}
79 		}
80 	}
81 	if (!(mode & HASH_ADD_ENT))
82 		return (0);
83 
84 	/*
85 	 * Key not found in this hash table ... insert new entry into bucket.
86 	 */
87 	if ((ent = calloc(sizeof (Hash_ent), 1)) == 0)
88 		return (0);
89 
90 	ent->e_key = key;
91 	ent->e_hash = hashval;
92 
93 	/*
94 	 * Hook into bucket chain
95 	 */
96 	ent->e_next = tbl->t_entry[bucket];
97 	tbl->t_entry[bucket] = ent;
98 
99 	return (ent);
100 }
101