]> git.saurik.com Git - redis.git/blame - dict.c
Deny EXEC under out of memory
[redis.git] / dict.c
CommitLineData
ed9b544e 1/* Hash Tables Implementation.
2 *
3 * This file implements in memory hash tables with insert/del/replace/find/
4 * get-random-element operations. Hash tables will auto resize if needed
5 * tables of power of two in size are used, collisions are handled by
6 * chaining. See the source code for more information... :)
7 *
12d090d2 8 * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
ed9b544e 9 * All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions are met:
13 *
14 * * Redistributions of source code must retain the above copyright notice,
15 * this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * * Neither the name of Redis nor the names of its contributors may be used
20 * to endorse or promote products derived from this software without
21 * specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
34 */
35
23d4709d 36#include "fmacros.h"
37
ed9b544e 38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <stdarg.h>
42#include <assert.h>
f2923bec 43#include <limits.h>
ed9b544e 44
45#include "dict.h"
46#include "zmalloc.h"
47
48/* ---------------------------- Utility funcitons --------------------------- */
49
50static void _dictPanic(const char *fmt, ...)
51{
52 va_list ap;
53
54 va_start(ap, fmt);
55 fprintf(stderr, "\nDICT LIBRARY PANIC: ");
56 vfprintf(stderr, fmt, ap);
57 fprintf(stderr, "\n\n");
58 va_end(ap);
59}
60
61/* ------------------------- Heap Management Wrappers------------------------ */
62
71aee3e9 63static void *_dictAlloc(size_t size)
ed9b544e 64{
65 void *p = zmalloc(size);
66 if (p == NULL)
67 _dictPanic("Out of memory");
68 return p;
69}
70
71static void _dictFree(void *ptr) {
72 zfree(ptr);
73}
74
75/* -------------------------- private prototypes ---------------------------- */
76
77static int _dictExpandIfNeeded(dict *ht);
f2923bec 78static unsigned long _dictNextPower(unsigned long size);
ed9b544e 79static int _dictKeyIndex(dict *ht, const void *key);
80static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
81
82/* -------------------------- hash functions -------------------------------- */
83
84/* Thomas Wang's 32 bit Mix Function */
85unsigned int dictIntHashFunction(unsigned int key)
86{
87 key += ~(key << 15);
88 key ^= (key >> 10);
89 key += (key << 3);
90 key ^= (key >> 6);
91 key += ~(key << 11);
92 key ^= (key >> 16);
93 return key;
94}
95
96/* Identity hash function for integer keys */
97unsigned int dictIdentityHashFunction(unsigned int key)
98{
99 return key;
100}
101
102/* Generic hash function (a popular one from Bernstein).
103 * I tested a few and this was the best. */
104unsigned int dictGenHashFunction(const unsigned char *buf, int len) {
105 unsigned int hash = 5381;
106
107 while (len--)
108 hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */
109 return hash;
110}
111
112/* ----------------------------- API implementation ------------------------- */
113
114/* Reset an hashtable already initialized with ht_init().
115 * NOTE: This function should only called by ht_destroy(). */
116static void _dictReset(dict *ht)
117{
118 ht->table = NULL;
119 ht->size = 0;
120 ht->sizemask = 0;
121 ht->used = 0;
122}
123
124/* Create a new hash table */
125dict *dictCreate(dictType *type,
126 void *privDataPtr)
127{
128 dict *ht = _dictAlloc(sizeof(*ht));
129
130 _dictInit(ht,type,privDataPtr);
131 return ht;
132}
133
134/* Initialize the hash table */
135int _dictInit(dict *ht, dictType *type,
136 void *privDataPtr)
137{
138 _dictReset(ht);
139 ht->type = type;
140 ht->privdata = privDataPtr;
141 return DICT_OK;
142}
143
144/* Resize the table to the minimal size that contains all the elements,
145 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
146int dictResize(dict *ht)
147{
148 int minimal = ht->used;
149
150 if (minimal < DICT_HT_INITIAL_SIZE)
151 minimal = DICT_HT_INITIAL_SIZE;
152 return dictExpand(ht, minimal);
153}
154
155/* Expand or create the hashtable */
f2923bec 156int dictExpand(dict *ht, unsigned long size)
ed9b544e 157{
158 dict n; /* the new hashtable */
f2923bec 159 unsigned long realsize = _dictNextPower(size), i;
ed9b544e 160
161 /* the size is invalid if it is smaller than the number of
162 * elements already inside the hashtable */
163 if (ht->used > size)
164 return DICT_ERR;
165
166 _dictInit(&n, ht->type, ht->privdata);
167 n.size = realsize;
168 n.sizemask = realsize-1;
169 n.table = _dictAlloc(realsize*sizeof(dictEntry*));
170
171 /* Initialize all the pointers to NULL */
172 memset(n.table, 0, realsize*sizeof(dictEntry*));
173
174 /* Copy all the elements from the old to the new table:
175 * note that if the old hash table is empty ht->size is zero,
176 * so dictExpand just creates an hash table. */
177 n.used = ht->used;
178 for (i = 0; i < ht->size && ht->used > 0; i++) {
179 dictEntry *he, *nextHe;
180
181 if (ht->table[i] == NULL) continue;
182
183 /* For each hash entry on this slot... */
184 he = ht->table[i];
185 while(he) {
186 unsigned int h;
187
188 nextHe = he->next;
189 /* Get the new element index */
190 h = dictHashKey(ht, he->key) & n.sizemask;
191 he->next = n.table[h];
192 n.table[h] = he;
193 ht->used--;
194 /* Pass to the next element */
195 he = nextHe;
196 }
197 }
198 assert(ht->used == 0);
199 _dictFree(ht->table);
200
201 /* Remap the new hashtable in the old */
202 *ht = n;
203 return DICT_OK;
204}
205
206/* Add an element to the target hash table */
207int dictAdd(dict *ht, void *key, void *val)
208{
209 int index;
210 dictEntry *entry;
211
212 /* Get the index of the new element, or -1 if
213 * the element already exists. */
214 if ((index = _dictKeyIndex(ht, key)) == -1)
215 return DICT_ERR;
216
217 /* Allocates the memory and stores key */
218 entry = _dictAlloc(sizeof(*entry));
219 entry->next = ht->table[index];
220 ht->table[index] = entry;
221
222 /* Set the hash entry fields. */
223 dictSetHashKey(ht, entry, key);
224 dictSetHashVal(ht, entry, val);
225 ht->used++;
226 return DICT_OK;
227}
228
121796f7 229/* Add an element, discarding the old if the key already exists.
230 * Return 1 if the key was added from scratch, 0 if there was already an
231 * element with such key and dictReplace() just performed a value update
232 * operation. */
ed9b544e 233int dictReplace(dict *ht, void *key, void *val)
234{
2069d06a 235 dictEntry *entry, auxentry;
ed9b544e 236
237 /* Try to add the element. If the key
238 * does not exists dictAdd will suceed. */
239 if (dictAdd(ht, key, val) == DICT_OK)
121796f7 240 return 1;
ed9b544e 241 /* It already exists, get the entry */
242 entry = dictFind(ht, key);
243 /* Free the old value and set the new one */
2069d06a 244 /* Set the new value and free the old one. Note that it is important
245 * to do that in this order, as the value may just be exactly the same
246 * as the previous one. In this context, think to reference counting,
247 * you want to increment (set), and then decrement (free), and not the
248 * reverse. */
249 auxentry = *entry;
ed9b544e 250 dictSetHashVal(ht, entry, val);
2069d06a 251 dictFreeEntryVal(ht, &auxentry);
121796f7 252 return 0;
ed9b544e 253}
254
255/* Search and remove an element */
256static int dictGenericDelete(dict *ht, const void *key, int nofree)
257{
258 unsigned int h;
259 dictEntry *he, *prevHe;
260
261 if (ht->size == 0)
262 return DICT_ERR;
263 h = dictHashKey(ht, key) & ht->sizemask;
264 he = ht->table[h];
265
266 prevHe = NULL;
267 while(he) {
268 if (dictCompareHashKeys(ht, key, he->key)) {
269 /* Unlink the element from the list */
270 if (prevHe)
271 prevHe->next = he->next;
272 else
273 ht->table[h] = he->next;
274 if (!nofree) {
275 dictFreeEntryKey(ht, he);
276 dictFreeEntryVal(ht, he);
277 }
278 _dictFree(he);
279 ht->used--;
280 return DICT_OK;
281 }
282 prevHe = he;
283 he = he->next;
284 }
285 return DICT_ERR; /* not found */
286}
287
288int dictDelete(dict *ht, const void *key) {
289 return dictGenericDelete(ht,key,0);
290}
291
292int dictDeleteNoFree(dict *ht, const void *key) {
293 return dictGenericDelete(ht,key,1);
294}
295
296/* Destroy an entire hash table */
297int _dictClear(dict *ht)
298{
f2923bec 299 unsigned long i;
ed9b544e 300
301 /* Free all the elements */
302 for (i = 0; i < ht->size && ht->used > 0; i++) {
303 dictEntry *he, *nextHe;
304
305 if ((he = ht->table[i]) == NULL) continue;
306 while(he) {
307 nextHe = he->next;
308 dictFreeEntryKey(ht, he);
309 dictFreeEntryVal(ht, he);
310 _dictFree(he);
311 ht->used--;
312 he = nextHe;
313 }
314 }
315 /* Free the table and the allocated cache structure */
316 _dictFree(ht->table);
317 /* Re-initialize the table */
318 _dictReset(ht);
319 return DICT_OK; /* never fails */
320}
321
322/* Clear & Release the hash table */
323void dictRelease(dict *ht)
324{
325 _dictClear(ht);
326 _dictFree(ht);
327}
328
329dictEntry *dictFind(dict *ht, const void *key)
330{
331 dictEntry *he;
332 unsigned int h;
333
334 if (ht->size == 0) return NULL;
335 h = dictHashKey(ht, key) & ht->sizemask;
336 he = ht->table[h];
337 while(he) {
338 if (dictCompareHashKeys(ht, key, he->key))
339 return he;
340 he = he->next;
341 }
342 return NULL;
343}
344
345dictIterator *dictGetIterator(dict *ht)
346{
347 dictIterator *iter = _dictAlloc(sizeof(*iter));
348
349 iter->ht = ht;
350 iter->index = -1;
351 iter->entry = NULL;
352 iter->nextEntry = NULL;
353 return iter;
354}
355
356dictEntry *dictNext(dictIterator *iter)
357{
358 while (1) {
359 if (iter->entry == NULL) {
360 iter->index++;
361 if (iter->index >=
362 (signed)iter->ht->size) break;
363 iter->entry = iter->ht->table[iter->index];
364 } else {
365 iter->entry = iter->nextEntry;
366 }
367 if (iter->entry) {
368 /* We need to save the 'next' here, the iterator user
369 * may delete the entry we are returning. */
370 iter->nextEntry = iter->entry->next;
371 return iter->entry;
372 }
373 }
374 return NULL;
375}
376
377void dictReleaseIterator(dictIterator *iter)
378{
379 _dictFree(iter);
380}
381
382/* Return a random entry from the hash table. Useful to
383 * implement randomized algorithms */
384dictEntry *dictGetRandomKey(dict *ht)
385{
386 dictEntry *he;
387 unsigned int h;
388 int listlen, listele;
389
6f864e62 390 if (ht->used == 0) return NULL;
ed9b544e 391 do {
392 h = random() & ht->sizemask;
393 he = ht->table[h];
394 } while(he == NULL);
395
396 /* Now we found a non empty bucket, but it is a linked
397 * list and we need to get a random element from the list.
398 * The only sane way to do so is to count the element and
399 * select a random index. */
400 listlen = 0;
401 while(he) {
402 he = he->next;
403 listlen++;
404 }
405 listele = random() % listlen;
406 he = ht->table[h];
407 while(listele--) he = he->next;
408 return he;
409}
410
411/* ------------------------- private functions ------------------------------ */
412
413/* Expand the hash table if needed */
414static int _dictExpandIfNeeded(dict *ht)
415{
416 /* If the hash table is empty expand it to the intial size,
417 * if the table is "full" dobule its size. */
418 if (ht->size == 0)
419 return dictExpand(ht, DICT_HT_INITIAL_SIZE);
420 if (ht->used == ht->size)
421 return dictExpand(ht, ht->size*2);
422 return DICT_OK;
423}
424
425/* Our hash table capability is a power of two */
f2923bec 426static unsigned long _dictNextPower(unsigned long size)
ed9b544e 427{
f2923bec 428 unsigned long i = DICT_HT_INITIAL_SIZE;
ed9b544e 429
f2923bec 430 if (size >= LONG_MAX) return LONG_MAX;
ed9b544e 431 while(1) {
432 if (i >= size)
433 return i;
434 i *= 2;
435 }
436}
437
438/* Returns the index of a free slot that can be populated with
439 * an hash entry for the given 'key'.
440 * If the key already exists, -1 is returned. */
441static int _dictKeyIndex(dict *ht, const void *key)
442{
443 unsigned int h;
444 dictEntry *he;
445
446 /* Expand the hashtable if needed */
447 if (_dictExpandIfNeeded(ht) == DICT_ERR)
448 return -1;
449 /* Compute the key hash value */
450 h = dictHashKey(ht, key) & ht->sizemask;
451 /* Search if this slot does not already contain the given key */
452 he = ht->table[h];
453 while(he) {
454 if (dictCompareHashKeys(ht, key, he->key))
455 return -1;
456 he = he->next;
457 }
458 return h;
459}
460
461void dictEmpty(dict *ht) {
462 _dictClear(ht);
463}
464
465#define DICT_STATS_VECTLEN 50
466void dictPrintStats(dict *ht) {
f2923bec 467 unsigned long i, slots = 0, chainlen, maxchainlen = 0;
468 unsigned long totchainlen = 0;
469 unsigned long clvector[DICT_STATS_VECTLEN];
ed9b544e 470
471 if (ht->used == 0) {
472 printf("No stats available for empty dictionaries\n");
473 return;
474 }
475
476 for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0;
477 for (i = 0; i < ht->size; i++) {
478 dictEntry *he;
479
480 if (ht->table[i] == NULL) {
481 clvector[0]++;
482 continue;
483 }
484 slots++;
485 /* For each hash entry on this slot... */
486 chainlen = 0;
487 he = ht->table[i];
488 while(he) {
489 chainlen++;
490 he = he->next;
491 }
492 clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++;
493 if (chainlen > maxchainlen) maxchainlen = chainlen;
494 totchainlen += chainlen;
495 }
496 printf("Hash table stats:\n");
f2923bec 497 printf(" table size: %ld\n", ht->size);
498 printf(" number of elements: %ld\n", ht->used);
499 printf(" different slots: %ld\n", slots);
500 printf(" max chain length: %ld\n", maxchainlen);
ed9b544e 501 printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots);
502 printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots);
503 printf(" Chain length distribution:\n");
504 for (i = 0; i < DICT_STATS_VECTLEN-1; i++) {
505 if (clvector[i] == 0) continue;
f2923bec 506 printf(" %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100);
ed9b544e 507 }
508}
509
510/* ----------------------- StringCopy Hash Table Type ------------------------*/
511
512static unsigned int _dictStringCopyHTHashFunction(const void *key)
513{
514 return dictGenHashFunction(key, strlen(key));
515}
516
517static void *_dictStringCopyHTKeyDup(void *privdata, const void *key)
518{
519 int len = strlen(key);
520 char *copy = _dictAlloc(len+1);
521 DICT_NOTUSED(privdata);
522
523 memcpy(copy, key, len);
524 copy[len] = '\0';
525 return copy;
526}
527
528static void *_dictStringKeyValCopyHTValDup(void *privdata, const void *val)
529{
530 int len = strlen(val);
531 char *copy = _dictAlloc(len+1);
532 DICT_NOTUSED(privdata);
533
534 memcpy(copy, val, len);
535 copy[len] = '\0';
536 return copy;
537}
538
539static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1,
540 const void *key2)
541{
542 DICT_NOTUSED(privdata);
543
544 return strcmp(key1, key2) == 0;
545}
546
547static void _dictStringCopyHTKeyDestructor(void *privdata, void *key)
548{
549 DICT_NOTUSED(privdata);
550
551 _dictFree((void*)key); /* ATTENTION: const cast */
552}
553
554static void _dictStringKeyValCopyHTValDestructor(void *privdata, void *val)
555{
556 DICT_NOTUSED(privdata);
557
558 _dictFree((void*)val); /* ATTENTION: const cast */
559}
560
561dictType dictTypeHeapStringCopyKey = {
562 _dictStringCopyHTHashFunction, /* hash function */
563 _dictStringCopyHTKeyDup, /* key dup */
564 NULL, /* val dup */
565 _dictStringCopyHTKeyCompare, /* key compare */
566 _dictStringCopyHTKeyDestructor, /* key destructor */
567 NULL /* val destructor */
568};
569
570/* This is like StringCopy but does not auto-duplicate the key.
571 * It's used for intepreter's shared strings. */
572dictType dictTypeHeapStrings = {
573 _dictStringCopyHTHashFunction, /* hash function */
574 NULL, /* key dup */
575 NULL, /* val dup */
576 _dictStringCopyHTKeyCompare, /* key compare */
577 _dictStringCopyHTKeyDestructor, /* key destructor */
578 NULL /* val destructor */
579};
580
581/* This is like StringCopy but also automatically handle dynamic
582 * allocated C strings as values. */
583dictType dictTypeHeapStringCopyKeyValue = {
584 _dictStringCopyHTHashFunction, /* hash function */
585 _dictStringCopyHTKeyDup, /* key dup */
586 _dictStringKeyValCopyHTValDup, /* val dup */
587 _dictStringCopyHTKeyCompare, /* key compare */
588 _dictStringCopyHTKeyDestructor, /* key destructor */
589 _dictStringKeyValCopyHTValDestructor, /* val destructor */
590};