2 * Wireshark memory management and garbage collection functions
7 * Wireshark - Network traffic analyzer
8 * By Gerald Combs <gerald@wireshark.org>
9 * Copyright 1998 Gerald Combs
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License
13 * as published by the Free Software Foundation; either version 2
14 * of the License, or (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
34 #ifdef HAVE_SYS_TIME_H
48 #include <windows.h> /* VirtualAlloc, VirtualProtect */
49 #include <process.h> /* getpid */
52 /* Print out statistics about our memory allocations? */
53 /*#define SHOW_EMEM_STATS*/
55 /* Do we want to use guardpages? if available */
56 #define WANT_GUARD_PAGES 1
58 #ifdef WANT_GUARD_PAGES
59 /* Add guard pages at each end of our allocated memory */
61 #if defined(HAVE_SYSCONF) && defined(HAVE_MMAP) && defined(HAVE_MPROTECT) && defined(HAVE_STDINT_H)
64 #ifdef HAVE_SYS_TYPES_H
65 #include <sys/types.h>
66 #endif /* HAVE_SYS_TYPES_H */
70 #if defined(MAP_ANONYMOUS)
71 #define ANON_PAGE_MODE (MAP_ANONYMOUS|MAP_PRIVATE)
72 #elif defined(MAP_ANON)
73 #define ANON_PAGE_MODE (MAP_ANON|MAP_PRIVATE)
75 #define ANON_PAGE_MODE (MAP_PRIVATE) /* have to map /dev/zero */
77 #endif /* defined(MAP_ANONYMOUS) */
81 static int dev_zero_fd;
82 #define ANON_FD dev_zero_fd
85 #endif /* NEED_DEV_ZERO */
87 #define USE_GUARD_PAGES 1
88 #endif /* defined(HAVE_SYSCONF) && defined(HAVE_MMAP) && defined(HAVE_MPROTECT) && defined(HAVE_STDINT_H) */
89 #endif /* WANT_GUARD_PAGES */
91 /* When required, allocate more memory from the OS in this size chunks */
92 #define EMEM_PACKET_CHUNK_SIZE (10 * 1024 * 1024)
94 /* The canary between allocations is at least 8 bytes and up to 16 bytes to
95 * allow future allocations to be 4- or 8-byte aligned.
96 * All but the last byte of the canary are randomly generated; the last byte is
97 * NULL to separate the canary and the pointer to the next canary.
99 * For example, if the allocation is a multiple of 8 bytes, the canary and
100 * pointer would look like:
101 * |0|1|2|3|4|5|6|7||0|1|2|3|4|5|6|7|
102 * |c|c|c|c|c|c|c|0||p|p|p|p|p|p|p|p| (64-bit), or:
103 * |c|c|c|c|c|c|c|0||p|p|p|p| (32-bit)
105 * If the allocation was, for example, 12 bytes, the canary would look like:
106 * |0|1|2|3|4|5|6|7||0|1|2|3|4|5|6|7|
107 * [...]|a|a|a|a|c|c|c|c||c|c|c|c|c|c|c|0| (followed by the pointer)
109 #define EMEM_CANARY_SIZE 8
110 #define EMEM_CANARY_DATA_SIZE (EMEM_CANARY_SIZE * 2 - 1)
112 typedef struct _emem_chunk_t {
113 struct _emem_chunk_t *next;
117 unsigned int amount_free_init;
118 unsigned int amount_free;
119 unsigned int free_offset_init;
120 unsigned int free_offset;
124 typedef struct _emem_pool_t {
125 emem_chunk_t *free_list;
126 emem_chunk_t *used_list;
128 emem_tree_t *trees; /* only used by se_mem allocator */
130 guint8 canary[EMEM_CANARY_DATA_SIZE];
131 void *(*memory_alloc)(size_t size, struct _emem_pool_t *);
134 * Tools like Valgrind and ElectricFence don't work well with memchunks.
135 * Export the following environment variables to make {ep|se}_alloc() allocate each
136 * object individually.
138 * WIRESHARK_DEBUG_EP_NO_CHUNKS
139 * WIRESHARK_DEBUG_SE_NO_CHUNKS
141 gboolean debug_use_chunks;
143 /* Do we want to use canaries?
144 * Export the following environment variables to disable/enable canaries
146 * WIRESHARK_DEBUG_EP_NO_CANARY
147 * For SE memory use of canary is default off as the memory overhead
149 * WIRESHARK_DEBUG_SE_USE_CANARY
151 gboolean debug_use_canary;
153 /* Do we want to verify no one is using a pointer to an ep_ or se_
154 * allocated thing where they shouldn't be?
156 * Export WIRESHARK_EP_VERIFY_POINTERS or WIRESHARK_SE_VERIFY_POINTERS
159 gboolean debug_verify_pointers;
163 static emem_pool_t ep_packet_mem;
164 static emem_pool_t se_packet_mem;
167 * Memory scrubbing is expensive but can be useful to ensure we don't:
168 * - use memory before initializing it
169 * - use memory after freeing it
170 * Export WIRESHARK_DEBUG_SCRUB_MEMORY to turn it on.
172 static gboolean debug_use_memory_scrubber = FALSE;
175 static SYSTEM_INFO sysinfo;
176 static OSVERSIONINFO versinfo;
178 #elif defined(USE_GUARD_PAGES)
179 static intptr_t pagesize;
180 #endif /* _WIN32 / USE_GUARD_PAGES */
182 static void *emem_alloc_chunk(size_t size, emem_pool_t *mem);
183 static void *emem_alloc_glib(size_t size, emem_pool_t *mem);
186 * Set a canary value to be placed between memchunks.
189 emem_canary_init(guint8 *canary)
192 static GRand *rand_state = NULL;
194 if (rand_state == NULL) {
195 rand_state = g_rand_new();
197 for (i = 0; i < EMEM_CANARY_DATA_SIZE; i ++) {
198 canary[i] = (guint8) g_rand_int_range(rand_state, 1, 0x100);
204 emem_canary_next(guint8 *mem_canary, guint8 *canary, int *len)
209 for (i = 0; i < EMEM_CANARY_SIZE-1; i++)
210 if (mem_canary[i] != canary[i])
213 for (; i < EMEM_CANARY_DATA_SIZE; i++) {
214 if (canary[i] == '\0') {
215 memcpy(&ptr, &canary[i+1], sizeof(void *));
218 *len = i + 1 + sizeof(void *);
222 if (mem_canary[i] != canary[i])
230 * Given an allocation size, return the amount of room needed for the canary
231 * (with a minimum of 8 bytes) while using the canary to pad to an 8-byte
235 emem_canary_pad (size_t allocation)
239 pad = EMEM_CANARY_SIZE - (allocation % EMEM_CANARY_SIZE);
240 if (pad < EMEM_CANARY_SIZE)
241 pad += EMEM_CANARY_SIZE;
246 /* used for debugging canaries, will block */
247 #ifdef DEBUG_INTENSE_CANARY_CHECKS
248 gboolean intense_canary_checking = FALSE;
250 /* used to intensivelly check ep canaries
253 ep_check_canary_integrity(const char* fmt, ...)
256 static gchar there[128] = {
257 'L','a','u','n','c','h',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
258 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
259 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
260 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
262 emem_chunk_t* npc = NULL;
264 if (! intense_canary_checking ) return;
267 g_vsnprintf(here, sizeof(here), fmt, ap);
270 for (npc = ep_packet_mem.free_list; npc != NULL; npc = npc->next) {
271 void *canary_next = npc->canary_last;
273 while (canary_next != NULL) {
274 canary_next = emem_canary_next(ep_packet_mem.canary, canary_next, NULL);
275 /* XXX, check if canary_next is inside allocated memory? */
277 if (canary_next == (void *) -1)
278 g_error("Per-packet memory corrupted\nbetween: %s\nand: %s", there, here);
282 g_strlcpy(there, here, sizeof(there));
287 emem_init_chunk(emem_pool_t *mem)
289 if (mem->debug_use_canary)
290 emem_canary_init(mem->canary);
292 if (mem->debug_use_chunks)
293 mem->memory_alloc = emem_alloc_chunk;
295 mem->memory_alloc = emem_alloc_glib;
299 /* Initialize the packet-lifetime memory allocation pool.
300 * This function should be called only once when Wireshark or TShark starts
306 ep_packet_mem.free_list=NULL;
307 ep_packet_mem.used_list=NULL;
308 ep_packet_mem.trees=NULL; /* not used by this allocator */
310 ep_packet_mem.debug_use_chunks = (getenv("WIRESHARK_DEBUG_EP_NO_CHUNKS") == NULL);
311 ep_packet_mem.debug_use_canary = ep_packet_mem.debug_use_chunks && (getenv("WIRESHARK_DEBUG_EP_NO_CANARY") == NULL);
312 ep_packet_mem.debug_verify_pointers = (getenv("WIRESHARK_EP_VERIFY_POINTERS") != NULL);
314 #ifdef DEBUG_INTENSE_CANARY_CHECKS
315 intense_canary_checking = (getenv("WIRESHARK_DEBUG_EP_INTENSE_CANARY") != NULL);
318 emem_init_chunk(&ep_packet_mem);
321 /* Initialize the capture-lifetime memory allocation pool.
322 * This function should be called only once when Wireshark or TShark starts
328 se_packet_mem.free_list = NULL;
329 se_packet_mem.used_list = NULL;
330 se_packet_mem.trees = NULL;
332 se_packet_mem.debug_use_chunks = (getenv("WIRESHARK_DEBUG_SE_NO_CHUNKS") == NULL);
333 se_packet_mem.debug_use_canary = se_packet_mem.debug_use_chunks && (getenv("WIRESHARK_DEBUG_SE_USE_CANARY") != NULL);
334 se_packet_mem.debug_verify_pointers = (getenv("WIRESHARK_SE_VERIFY_POINTERS") != NULL);
336 emem_init_chunk(&se_packet_mem);
339 /* Initialize all the allocators here.
340 * This function should be called only once when Wireshark or TShark starts
349 if (getenv("WIRESHARK_DEBUG_SCRUB_MEMORY"))
350 debug_use_memory_scrubber = TRUE;
353 /* Set up our guard page info for Win32 */
354 GetSystemInfo(&sysinfo);
355 pagesize = sysinfo.dwPageSize;
357 /* calling GetVersionEx using the OSVERSIONINFO structure.
358 * OSVERSIONINFOEX requires Win NT4 with SP6 or newer NT Versions.
359 * OSVERSIONINFOEX will fail on Win9x and older NT Versions.
361 * http://msdn.microsoft.com/library/en-us/sysinfo/base/getversionex.asp
362 * http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
363 * http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfoex_str.asp
365 versinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
366 GetVersionEx(&versinfo);
368 #elif defined(USE_GUARD_PAGES)
369 pagesize = sysconf(_SC_PAGESIZE);
371 fprintf(stderr, "Warning: call to sysconf() for _SC_PAGESIZE has failed...\n");
373 dev_zero_fd = ws_open("/dev/zero", O_RDWR);
374 g_assert(dev_zero_fd != -1);
376 #endif /* _WIN32 / USE_GUARD_PAGES */
379 #ifdef SHOW_EMEM_STATS
380 #define NUM_ALLOC_DIST 10
381 static guint allocations[NUM_ALLOC_DIST] = { 0 };
382 static guint total_no_chunks = 0;
387 guint num_chunks = 0;
388 guint num_allocs = 0;
389 guint total_used = 0;
390 guint total_allocation = 0;
391 guint used_for_canaries = 0;
395 guint total_space_allocated_from_os, total_space_wasted;
396 gboolean ep_stat=TRUE;
398 fprintf(stderr, "\n-------- EP allocator statistics --------\n");
399 fprintf(stderr, "%s chunks, %s canaries, %s memory scrubber\n",
400 ep_packet_mem.debug_use_chunks ? "Using" : "Not using",
401 ep_packet_mem.debug_use_canary ? "using" : "not using",
402 debug_use_memory_scrubber ? "using" : "not using");
404 if (! (ep_packet_mem.free_list || !ep_packet_mem.used_list)) {
405 fprintf(stderr, "No memory allocated\n");
408 if (ep_packet_mem.debug_use_chunks && ep_stat) {
409 /* Nothing interesting without chunks */
410 /* Only look at the used_list since those chunks are fully
411 * used. Looking at the free list would skew our view of what
414 for (chunk = ep_packet_mem.used_list; chunk; chunk = chunk->next) {
416 total_used += (chunk->amount_free_init - chunk->amount_free);
417 total_allocation += chunk->amount_free_init;
419 if (num_chunks > 0) {
420 fprintf (stderr, "\n");
421 fprintf (stderr, "\n---- Buffer space ----\n");
422 fprintf (stderr, "\tChunk allocation size: %10u\n", EMEM_PACKET_CHUNK_SIZE);
423 fprintf (stderr, "\t* Number of chunks: %10u\n", num_chunks);
424 fprintf (stderr, "\t-------------------------------------------\n");
425 fprintf (stderr, "\t= %u (%u including guard pages) total space used for buffers\n",
426 total_allocation, EMEM_PACKET_CHUNK_SIZE * num_chunks);
427 fprintf (stderr, "\t-------------------------------------------\n");
428 total_space_allocated_from_os = total_allocation
429 + sizeof(emem_chunk_t) * num_chunks;
430 fprintf (stderr, "Total allocated from OS: %u\n\n",
431 total_space_allocated_from_os);
433 fprintf (stderr, "No fully used chunks, nothing to do\n");
439 total_allocation = 0;
440 used_for_canaries = 0;
444 fprintf(stderr, "\n-------- SE allocator statistics --------\n");
445 fprintf(stderr, "Total number of chunk allocations %u\n",
447 fprintf(stderr, "%s chunks, %s canaries\n",
448 se_packet_mem.debug_use_chunks ? "Using" : "Not using",
449 se_packet_mem.debug_use_canary ? "using" : "not using");
451 if (! (se_packet_mem.free_list || !se_packet_mem.used_list)) {
452 fprintf(stderr, "No memory allocated\n");
456 if (!se_packet_mem.debug_use_chunks )
457 return; /* Nothing interesting without chunks?? */
459 /* Only look at the used_list since those chunks are fully used.
460 * Looking at the free list would skew our view of what we have wasted.
462 for (chunk = se_packet_mem.used_list; chunk; chunk = chunk->next) {
464 total_used += (chunk->amount_free_init - chunk->amount_free);
465 total_allocation += chunk->amount_free_init;
467 if (se_packet_mem.debug_use_canary){
468 void *ptr = chunk->canary_last;
471 while (ptr != NULL) {
472 ptr = emem_canary_next(se_packet_mem.canary, ptr, &len);
474 if (ptr == (void *) -1)
475 g_error("Memory corrupted");
476 used_for_canaries += len;
481 if (num_chunks == 0) {
483 fprintf (stderr, "No fully used chunks, nothing to do\n");
487 fprintf (stderr, "\n");
488 fprintf (stderr, "---------- Allocations from the OS ----------\n");
489 fprintf (stderr, "---- Headers ----\n");
490 fprintf (stderr, "\t( Chunk header size: %10lu\n",
491 sizeof(emem_chunk_t));
492 fprintf (stderr, "\t* Number of chunks: %10u\n", num_chunks);
493 fprintf (stderr, "\t-------------------------------------------\n");
495 total_headers = sizeof(emem_chunk_t) * num_chunks;
496 fprintf (stderr, "\t= %u bytes used for headers\n", total_headers);
497 fprintf (stderr, "\n---- Buffer space ----\n");
498 fprintf (stderr, "\tChunk allocation size: %10u\n",
499 EMEM_PACKET_CHUNK_SIZE);
500 fprintf (stderr, "\t* Number of chunks: %10u\n", num_chunks);
501 fprintf (stderr, "\t-------------------------------------------\n");
502 fprintf (stderr, "\t= %u (%u including guard pages) bytes used for buffers\n",
503 total_allocation, EMEM_PACKET_CHUNK_SIZE * num_chunks);
504 fprintf (stderr, "\t-------------------------------------------\n");
505 total_space_allocated_from_os = (EMEM_PACKET_CHUNK_SIZE * num_chunks)
507 fprintf (stderr, "Total bytes allocated from the OS: %u\n\n",
508 total_space_allocated_from_os);
510 for (i = 0; i < NUM_ALLOC_DIST; i++)
511 num_allocs += allocations[i];
513 fprintf (stderr, "---------- Allocations from the SE pool ----------\n");
514 fprintf (stderr, " Number of SE allocations: %10u\n",
516 fprintf (stderr, " Bytes used (incl. canaries): %10u\n",
518 fprintf (stderr, " Bytes used for canaries: %10u\n",
520 fprintf (stderr, "Bytes unused (wasted, excl. guard pages): %10u\n",
521 total_allocation - total_used);
522 fprintf (stderr, "Bytes unused (wasted, incl. guard pages): %10u\n\n",
523 total_space_allocated_from_os - total_used);
525 fprintf (stderr, "---------- Statistics ----------\n");
526 fprintf (stderr, "Average SE allocation size (incl. canaries): %6.2f\n",
527 (float)total_used/(float)num_allocs);
528 fprintf (stderr, "Average SE allocation size (excl. canaries): %6.2f\n",
529 (float)(total_used - used_for_canaries)/(float)num_allocs);
530 fprintf (stderr, " Average wasted bytes per allocation: %6.2f\n",
531 (total_allocation - total_used)/(float)num_allocs);
532 total_space_wasted = (total_allocation - total_used)
533 + (sizeof(emem_chunk_t));
534 fprintf (stderr, " Space used for headers + unused allocation: %8u\n",
536 fprintf (stderr, "--> %% overhead/waste: %4.2f\n",
537 100 * (float)total_space_wasted/(float)total_space_allocated_from_os);
539 fprintf (stderr, "\nAllocation distribution (sizes include canaries):\n");
540 for (i = 0; i < (NUM_ALLOC_DIST-1); i++)
541 fprintf (stderr, "size < %5d: %8u\n", 32<<i, allocations[i]);
542 fprintf (stderr, "size > %5d: %8u\n", 32<<i, allocations[i]);
547 emem_verify_pointer_list(const emem_chunk_t *chunk_list, const void *ptr)
549 const gchar *cptr = ptr;
550 const emem_chunk_t *chunk;
552 for (chunk = chunk_list; chunk; chunk = chunk->next) {
553 if (cptr >= (chunk->buf + chunk->free_offset_init) && cptr < (chunk->buf + chunk->free_offset))
560 emem_verify_pointer(const emem_pool_t *hdr, const void *ptr)
562 return emem_verify_pointer_list(hdr->free_list, ptr) || emem_verify_pointer_list(hdr->used_list, ptr);
566 ep_verify_pointer(const void *ptr)
568 if (ep_packet_mem.debug_verify_pointers)
569 return emem_verify_pointer(&ep_packet_mem, ptr);
575 se_verify_pointer(const void *ptr)
577 if (se_packet_mem.debug_verify_pointers)
578 return emem_verify_pointer(&se_packet_mem, ptr);
584 emem_scrub_memory(char *buf, size_t size, gboolean alloc)
586 guint scrubbed_value;
589 if (!debug_use_memory_scrubber)
592 if (alloc) /* this memory is being allocated */
593 scrubbed_value = 0xBADDCAFE;
594 else /* this memory is being freed */
595 scrubbed_value = 0xDEADBEEF;
597 /* We shouldn't need to check the alignment of the starting address
598 * since this is malloc'd memory (or 'pagesize' bytes into malloc'd
602 /* XXX - if the above is *NOT* true, we should use memcpy here,
603 * in order to avoid problems on alignment-sensitive platforms, e.g.
604 * http://stackoverflow.com/questions/108866/is-there-memset-that-accepts-integers-larger-than-char
607 for (offset = 0; offset + sizeof(guint) <= size; offset += sizeof(guint))
608 *(guint*)(void*)(buf+offset) = scrubbed_value;
610 /* Initialize the last bytes, if any */
612 *(guint8*)(buf+offset) = scrubbed_value >> 24;
615 *(guint8*)(buf+offset) = (scrubbed_value >> 16) & 0xFF;
618 *(guint8*)(buf+offset) = (scrubbed_value >> 8) & 0xFF;
626 static emem_chunk_t *
627 emem_create_chunk(size_t size)
631 npc = g_new(emem_chunk_t, 1);
633 npc->canary_last = NULL;
637 * MSDN documents VirtualAlloc/VirtualProtect at
638 * http://msdn.microsoft.com/library/en-us/memory/base/creating_guard_pages.asp
641 /* XXX - is MEM_COMMIT|MEM_RESERVE correct? */
642 npc->buf = VirtualAlloc(NULL, size,
643 MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE);
645 if (npc->buf == NULL) {
647 if (getenv("WIRESHARK_ABORT_ON_OUT_OF_MEMORY"))
650 THROW(OutOfMemoryError);
653 #elif defined(USE_GUARD_PAGES)
654 npc->buf = mmap(NULL, size,
655 PROT_READ|PROT_WRITE, ANON_PAGE_MODE, ANON_FD, 0);
657 if (npc->buf == MAP_FAILED) {
659 if (getenv("WIRESHARK_ABORT_ON_OUT_OF_MEMORY"))
662 THROW(OutOfMemoryError);
665 #else /* Is there a draft in here? */
666 npc->buf = g_malloc(size);
667 /* g_malloc() can't fail */
670 #ifdef SHOW_EMEM_STATS
674 npc->amount_free = npc->amount_free_init = (unsigned int) size;
675 npc->free_offset = npc->free_offset_init = 0;
680 emem_destroy_chunk(emem_chunk_t *npc)
683 VirtualFree(npc->buf, 0, MEM_RELEASE);
684 #elif defined(USE_GUARD_PAGES)
686 /* we cannot recover from a munmap() failure, but we */
687 /* can print an informative error message to stderr */
689 if (munmap(npc->buf, npc->amount_free_init) != 0)
690 fprintf(stderr, "Warning: Unable to unmap memory chunk which has address %p and size %u\n",
691 npc->buf, npc->amount_free_init);
695 #ifdef SHOW_EMEM_STATS
701 static emem_chunk_t *
702 emem_create_chunk_gp(size_t size)
706 char *buf_end, *prot1, *prot2;
708 #elif defined(USE_GUARD_PAGES)
710 char *buf_end, *prot1, *prot2;
711 #endif /* _WIN32 / USE_GUARD_PAGES */
714 npc = emem_create_chunk(size);
717 buf_end = npc->buf + size;
719 /* Align our guard pages on page-sized boundaries */
720 prot1 = (char *) ((((intptr_t) npc->buf + pagesize - 1) / pagesize) * pagesize);
721 prot2 = (char *) ((((intptr_t) buf_end - (1 * pagesize)) / pagesize) * pagesize);
723 ret = VirtualProtect(prot1, pagesize, PAGE_NOACCESS, &oldprot);
724 g_assert(ret != 0 || versinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
725 ret = VirtualProtect(prot2, pagesize, PAGE_NOACCESS, &oldprot);
726 g_assert(ret != 0 || versinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
728 npc->amount_free_init = (unsigned int) (prot2 - prot1 - pagesize);
729 npc->free_offset_init = (unsigned int) (prot1 - npc->buf) + pagesize;
730 #elif defined(USE_GUARD_PAGES)
731 buf_end = npc->buf + size;
733 /* Align our guard pages on page-sized boundaries */
734 prot1 = (char *) ((((intptr_t) npc->buf + pagesize - 1) / pagesize) * pagesize);
735 prot2 = (char *) ((((intptr_t) buf_end - (1 * pagesize)) / pagesize) * pagesize);
737 ret = mprotect(prot1, pagesize, PROT_NONE);
739 ret = mprotect(prot2, pagesize, PROT_NONE);
742 npc->amount_free_init = prot2 - prot1 - pagesize;
743 npc->free_offset_init = (prot1 - npc->buf) + pagesize;
745 npc->amount_free_init = size;
746 npc->free_offset_init = 0;
747 #endif /* USE_GUARD_PAGES */
749 npc->amount_free = npc->amount_free_init;
750 npc->free_offset = npc->free_offset_init;
755 emem_alloc_chunk(size_t size, emem_pool_t *mem)
760 gboolean use_canary = mem->debug_use_canary;
762 emem_chunk_t *free_list;
764 /* Allocate room for at least 8 bytes of canary plus some padding
765 * so the canary ends on an 8-byte boundary.
766 * But first add the room needed for the pointer to the next canary
767 * (so the entire allocation will end on an 8-byte boundary).
770 asize += sizeof(void *);
771 pad = emem_canary_pad(asize);
773 pad = (WS_MEM_ALIGN - (asize & (WS_MEM_ALIGN-1))) & (WS_MEM_ALIGN-1);
777 #ifdef SHOW_EMEM_STATS
778 /* Do this check here so we can include the canary size */
779 if (mem == &se_packet_mem) {
784 else if (asize < 128)
786 else if (asize < 256)
788 else if (asize < 512)
790 else if (asize < 1024)
792 else if (asize < 2048)
794 else if (asize < 4096)
796 else if (asize < 8192)
798 else if (asize < 16384)
801 allocations[(NUM_ALLOC_DIST-1)]++;
805 /* make sure we dont try to allocate too much (arbitrary limit) */
806 DISSECTOR_ASSERT(size<(EMEM_PACKET_CHUNK_SIZE>>2));
809 mem->free_list = emem_create_chunk_gp(EMEM_PACKET_CHUNK_SIZE);
811 /* oops, we need to allocate more memory to serve this request
812 * than we have free. move this node to the used list and try again
814 if(asize > mem->free_list->amount_free) {
817 mem->free_list=mem->free_list->next;
818 npc->next=mem->used_list;
822 mem->free_list = emem_create_chunk_gp(EMEM_PACKET_CHUNK_SIZE);
825 free_list = mem->free_list;
827 buf = free_list->buf + free_list->free_offset;
829 free_list->amount_free -= (unsigned int) asize;
830 free_list->free_offset += (unsigned int) asize;
833 char *cptr = (char *)buf + size;
835 memcpy(cptr, mem->canary, pad-1);
837 memcpy(cptr + pad, &free_list->canary_last, sizeof(void *));
839 free_list->canary_last = cptr;
846 emem_alloc_glib(size_t size, emem_pool_t *mem)
850 npc=g_new(emem_chunk_t, 1);
851 npc->next=mem->used_list;
852 npc->buf=g_malloc(size);
853 npc->canary_last = NULL;
855 /* There's no padding/alignment involved (from our point of view) when
856 * we fetch the memory directly from the system pool, so WYSIWYG */
857 npc->free_offset = npc->free_offset_init = 0;
858 npc->amount_free = npc->amount_free_init = (unsigned int) size;
863 /* allocate 'size' amount of memory. */
865 emem_alloc(size_t size, emem_pool_t *mem)
867 void *buf = mem->memory_alloc(size, mem);
869 /* XXX - this is a waste of time if the allocator function is going to
870 * memset this straight back to 0.
872 emem_scrub_memory(buf, size, TRUE);
877 /* allocate 'size' amount of memory with an allocation lifetime until the
881 ep_alloc(size_t size)
883 return emem_alloc(size, &ep_packet_mem);
886 /* allocate 'size' amount of memory with an allocation lifetime until the
890 se_alloc(size_t size)
892 return emem_alloc(size, &se_packet_mem);
896 sl_alloc(struct ws_memory_slab *mem_chunk)
901 /* XXX, debug_use_slices -> fallback to g_slice_alloc0 */
903 if ((mem_chunk->freed != NULL)) {
904 ptr = mem_chunk->freed;
905 memcpy(&mem_chunk->freed, ptr, sizeof(void *));
909 if (!(chunk = mem_chunk->chunk_list) || chunk->amount_free < (guint) mem_chunk->item_size) {
910 size_t alloc_size = mem_chunk->item_size * mem_chunk->count;
912 /* align to page-size */
913 #if defined (_WIN32) || defined(USE_GUARD_PAGES)
914 alloc_size = (alloc_size + (pagesize - 1)) & ~(pagesize - 1);
917 chunk = emem_create_chunk(alloc_size); /* NOTE: using version without guard pages! */
918 chunk->next = mem_chunk->chunk_list;
919 mem_chunk->chunk_list = chunk;
922 ptr = chunk->buf + chunk->free_offset;
923 chunk->free_offset += mem_chunk->item_size;
924 chunk->amount_free -= mem_chunk->item_size;
930 sl_free(struct ws_memory_slab *mem_chunk, gpointer ptr)
932 /* XXX, debug_use_slices -> fallback to g_slice_free1 */
934 /* XXX, abort if ptr not found in emem_verify_pointer_list()? */
935 if (ptr != NULL /* && emem_verify_pointer_list(mem_chunk->chunk_list, ptr) */) {
936 memcpy(ptr, &(mem_chunk->freed), sizeof(void *));
937 mem_chunk->freed = ptr;
942 ep_alloc0(size_t size)
944 return memset(ep_alloc(size),'\0',size);
948 se_alloc0(size_t size)
950 return memset(se_alloc(size),'\0',size);
954 sl_alloc0(struct ws_memory_slab *mem_chunk)
956 return memset(sl_alloc(mem_chunk), '\0', mem_chunk->item_size);
960 emem_strdup(const gchar *src, void *allocator(size_t))
965 /* If str is NULL, just return the string "<NULL>" so that the callers don't
966 * have to bother checking it.
971 len = (guint) strlen(src);
972 dst = memcpy(allocator(len+1), src, len+1);
978 ep_strdup(const gchar *src)
980 return emem_strdup(src, ep_alloc);
984 se_strdup(const gchar *src)
986 return emem_strdup(src, se_alloc);
990 emem_strndup(const gchar *src, size_t len, void *allocator(size_t))
992 gchar *dst = allocator(len+1);
995 for (i = 0; (i < len) && src[i]; i++)
1004 ep_strndup(const gchar *src, size_t len)
1006 return emem_strndup(src, len, ep_alloc);
1010 se_strndup(const gchar *src, size_t len)
1012 return emem_strndup(src, len, se_alloc);
1018 ep_memdup(const void* src, size_t len)
1020 return memcpy(ep_alloc(len), src, len);
1024 se_memdup(const void* src, size_t len)
1026 return memcpy(se_alloc(len), src, len);
1030 emem_strdup_vprintf(const gchar *fmt, va_list ap, void *allocator(size_t))
1038 len = g_printf_string_upper_bound(fmt, ap);
1040 dst = allocator(len+1);
1041 g_vsnprintf (dst, (gulong) len, fmt, ap2);
1048 ep_strdup_vprintf(const gchar *fmt, va_list ap)
1050 return emem_strdup_vprintf(fmt, ap, ep_alloc);
1054 se_strdup_vprintf(const gchar* fmt, va_list ap)
1056 return emem_strdup_vprintf(fmt, ap, se_alloc);
1060 ep_strdup_printf(const gchar *fmt, ...)
1066 dst = ep_strdup_vprintf(fmt, ap);
1072 se_strdup_printf(const gchar *fmt, ...)
1078 dst = se_strdup_vprintf(fmt, ap);
1084 ep_strsplit(const gchar* string, const gchar* sep, int max_tokens)
1093 enum { AT_START, IN_PAD, IN_TOKEN } state;
1101 s = splitted = ep_strdup(string);
1102 str_len = (guint) strlen(splitted);
1103 sep_len = (guint) strlen(sep);
1105 if (max_tokens < 1) max_tokens = INT_MAX;
1110 while (tokens <= (guint)max_tokens && ( s = strstr(s,sep) )) {
1113 for(i=0; i < sep_len; i++ )
1120 vec = ep_alloc_array(gchar*,tokens+1);
1123 for (i=0; i< str_len; i++) {
1126 switch(splitted[i]) {
1131 vec[curr_tok] = &(splitted[i]);
1137 switch(splitted[i]) {
1144 switch(splitted[i]) {
1146 vec[curr_tok] = &(splitted[i]);
1155 vec[curr_tok] = NULL;
1161 ep_strconcat(const gchar *string1, ...)
1172 l = 1 + strlen(string1);
1173 va_start(args, string1);
1174 s = va_arg(args, gchar*);
1177 s = va_arg(args, gchar*);
1181 concat = ep_alloc(l);
1184 ptr = g_stpcpy(ptr, string1);
1185 va_start(args, string1);
1186 s = va_arg(args, gchar*);
1188 ptr = g_stpcpy(ptr, s);
1189 s = va_arg(args, gchar*);
1198 /* release all allocated memory back to the pool. */
1200 emem_free_all(emem_pool_t *mem)
1202 gboolean use_chunks = mem->debug_use_chunks;
1205 emem_tree_t *tree_list;
1207 /* move all used chunks over to the free list */
1208 while(mem->used_list){
1210 mem->used_list=mem->used_list->next;
1211 npc->next=mem->free_list;
1215 /* clear them all out */
1216 npc = mem->free_list;
1217 while (npc != NULL) {
1219 while (npc->canary_last != NULL) {
1220 npc->canary_last = emem_canary_next(mem->canary, npc->canary_last, NULL);
1221 /* XXX, check if canary_last is inside allocated memory? */
1223 if (npc->canary_last == (void *) -1)
1224 g_error("Memory corrupted");
1227 emem_scrub_memory((npc->buf + npc->free_offset_init),
1228 (npc->free_offset - npc->free_offset_init),
1231 npc->amount_free = npc->amount_free_init;
1232 npc->free_offset = npc->free_offset_init;
1235 emem_chunk_t *next = npc->next;
1237 emem_scrub_memory(npc->buf, npc->amount_free_init, FALSE);
1246 /* We've freed all this memory already */
1247 mem->free_list = NULL;
1250 /* release/reset all allocated trees */
1251 for(tree_list=mem->trees;tree_list;tree_list=tree_list->next){
1252 tree_list->tree=NULL;
1256 /* release all allocated memory back to the pool. */
1260 emem_free_all(&ep_packet_mem);
1263 /* release all allocated memory back to the pool. */
1267 #ifdef SHOW_EMEM_STATS
1268 print_alloc_stats();
1271 emem_free_all(&se_packet_mem);
1275 sl_free_all(struct ws_memory_slab *mem_chunk)
1277 emem_chunk_t *chunk_list = mem_chunk->chunk_list;
1279 mem_chunk->chunk_list = NULL;
1280 mem_chunk->freed = NULL;
1281 while (chunk_list) {
1282 emem_chunk_t *chunk = chunk_list;
1284 chunk_list = chunk_list->next;
1285 emem_destroy_chunk(chunk);
1290 ep_stack_new(void) {
1291 ep_stack_t s = ep_new(struct _ep_stack_frame_t*);
1292 *s = ep_new0(struct _ep_stack_frame_t);
1296 /* for ep_stack_t we'll keep the popped frames so we reuse them instead
1297 of allocating new ones.
1301 ep_stack_push(ep_stack_t stack, void* data)
1303 struct _ep_stack_frame_t* frame;
1304 struct _ep_stack_frame_t* head = (*stack);
1307 frame = head->above;
1309 frame = ep_new(struct _ep_stack_frame_t);
1310 head->above = frame;
1311 frame->below = head;
1312 frame->above = NULL;
1315 frame->payload = data;
1322 ep_stack_pop(ep_stack_t stack)
1325 if ((*stack)->below) {
1326 (*stack) = (*stack)->below;
1327 return (*stack)->above->payload;
1334 se_tree_create(int type, const char *name)
1336 emem_tree_t *tree_list;
1338 tree_list=g_malloc(sizeof(emem_tree_t));
1339 tree_list->next=se_packet_mem.trees;
1340 tree_list->type=type;
1341 tree_list->tree=NULL;
1342 tree_list->name=name;
1343 tree_list->malloc=se_alloc;
1344 se_packet_mem.trees=tree_list;
1350 emem_tree_lookup32(emem_tree_t *se_tree, guint32 key)
1352 emem_tree_node_t *node;
1357 if(key==node->key32){
1360 if(key<node->key32){
1364 if(key>node->key32){
1373 emem_tree_lookup32_le(emem_tree_t *se_tree, guint32 key)
1375 emem_tree_node_t *node;
1385 if(key==node->key32){
1388 if(key<node->key32){
1396 if(key>node->key32){
1411 /* If we are still at the root of the tree this means that this node
1412 * is either smaller than the search key and then we return this
1413 * node or else there is no smaller key available and then
1417 if(key>node->key32){
1424 if(node->parent->left==node){
1427 if(key>node->key32){
1428 /* if this is a left child and its key is smaller than
1429 * the search key, then this is the node we want.
1433 /* if this is a left child and its key is bigger than
1434 * the search key, we have to check if any
1435 * of our ancestors are smaller than the search key.
1438 if(key>node->key32){
1448 if(node->key32<key){
1449 /* if this is the right child and its key is smaller
1450 * than the search key then this is the one we want.
1454 /* if this is the right child and its key is larger
1455 * than the search key then our parent is the one we
1458 return node->parent->data;
1465 static inline emem_tree_node_t *
1466 emem_tree_parent(emem_tree_node_t *node)
1468 return node->parent;
1471 static inline emem_tree_node_t *
1472 emem_tree_grandparent(emem_tree_node_t *node)
1474 emem_tree_node_t *parent;
1476 parent=emem_tree_parent(node);
1478 return parent->parent;
1483 static inline emem_tree_node_t *
1484 emem_tree_uncle(emem_tree_node_t *node)
1486 emem_tree_node_t *parent, *grandparent;
1488 parent=emem_tree_parent(node);
1492 grandparent=emem_tree_parent(parent);
1496 if(parent==grandparent->left){
1497 return grandparent->right;
1499 return grandparent->left;
1502 static inline void rb_insert_case1(emem_tree_t *se_tree, emem_tree_node_t *node);
1503 static inline void rb_insert_case2(emem_tree_t *se_tree, emem_tree_node_t *node);
1506 rotate_left(emem_tree_t *se_tree, emem_tree_node_t *node)
1509 if(node->parent->left==node){
1510 node->parent->left=node->right;
1512 node->parent->right=node->right;
1515 se_tree->tree=node->right;
1517 node->right->parent=node->parent;
1518 node->parent=node->right;
1519 node->right=node->right->left;
1521 node->right->parent=node;
1523 node->parent->left=node;
1527 rotate_right(emem_tree_t *se_tree, emem_tree_node_t *node)
1530 if(node->parent->left==node){
1531 node->parent->left=node->left;
1533 node->parent->right=node->left;
1536 se_tree->tree=node->left;
1538 node->left->parent=node->parent;
1539 node->parent=node->left;
1540 node->left=node->left->right;
1542 node->left->parent=node;
1544 node->parent->right=node;
1548 rb_insert_case5(emem_tree_t *se_tree, emem_tree_node_t *node)
1550 emem_tree_node_t *grandparent;
1551 emem_tree_node_t *parent;
1553 parent=emem_tree_parent(node);
1554 grandparent=emem_tree_parent(parent);
1555 parent->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1556 grandparent->u.rb_color=EMEM_TREE_RB_COLOR_RED;
1557 if( (node==parent->left) && (parent==grandparent->left) ){
1558 rotate_right(se_tree, grandparent);
1560 rotate_left(se_tree, grandparent);
1565 rb_insert_case4(emem_tree_t *se_tree, emem_tree_node_t *node)
1567 emem_tree_node_t *grandparent;
1568 emem_tree_node_t *parent;
1570 parent=emem_tree_parent(node);
1571 grandparent=emem_tree_parent(parent);
1575 if( (node==parent->right) && (parent==grandparent->left) ){
1576 rotate_left(se_tree, parent);
1578 } else if( (node==parent->left) && (parent==grandparent->right) ){
1579 rotate_right(se_tree, parent);
1582 rb_insert_case5(se_tree, node);
1586 rb_insert_case3(emem_tree_t *se_tree, emem_tree_node_t *node)
1588 emem_tree_node_t *grandparent;
1589 emem_tree_node_t *parent;
1590 emem_tree_node_t *uncle;
1592 uncle=emem_tree_uncle(node);
1593 if(uncle && (uncle->u.rb_color==EMEM_TREE_RB_COLOR_RED)){
1594 parent=emem_tree_parent(node);
1595 parent->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1596 uncle->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1597 grandparent=emem_tree_grandparent(node);
1598 grandparent->u.rb_color=EMEM_TREE_RB_COLOR_RED;
1599 rb_insert_case1(se_tree, grandparent);
1601 rb_insert_case4(se_tree, node);
1606 rb_insert_case2(emem_tree_t *se_tree, emem_tree_node_t *node)
1608 emem_tree_node_t *parent;
1610 parent=emem_tree_parent(node);
1611 /* parent is always non-NULL here */
1612 if(parent->u.rb_color==EMEM_TREE_RB_COLOR_BLACK){
1615 rb_insert_case3(se_tree, node);
1619 rb_insert_case1(emem_tree_t *se_tree, emem_tree_node_t *node)
1621 emem_tree_node_t *parent;
1623 parent=emem_tree_parent(node);
1625 node->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1628 rb_insert_case2(se_tree, node);
1631 /* insert a new node in the tree. if this node matches an already existing node
1632 * then just replace the data for that node */
1634 emem_tree_insert32(emem_tree_t *se_tree, guint32 key, void *data)
1636 emem_tree_node_t *node;
1640 /* is this the first node ?*/
1642 node=se_tree->malloc(sizeof(emem_tree_node_t));
1643 switch(se_tree->type){
1644 case EMEM_TREE_TYPE_RED_BLACK:
1645 node->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1653 node->u.is_subtree = EMEM_TREE_NODE_IS_DATA;
1658 /* it was not the new root so walk the tree until we find where to
1659 * insert this new leaf.
1662 /* this node already exists, so just replace the data pointer*/
1663 if(key==node->key32){
1667 if(key<node->key32) {
1669 /* new node to the left */
1670 emem_tree_node_t *new_node;
1671 new_node=se_tree->malloc(sizeof(emem_tree_node_t));
1672 node->left=new_node;
1673 new_node->parent=node;
1674 new_node->left=NULL;
1675 new_node->right=NULL;
1676 new_node->key32=key;
1677 new_node->data=data;
1678 new_node->u.is_subtree=EMEM_TREE_NODE_IS_DATA;
1685 if(key>node->key32) {
1687 /* new node to the right */
1688 emem_tree_node_t *new_node;
1689 new_node=se_tree->malloc(sizeof(emem_tree_node_t));
1690 node->right=new_node;
1691 new_node->parent=node;
1692 new_node->left=NULL;
1693 new_node->right=NULL;
1694 new_node->key32=key;
1695 new_node->data=data;
1696 new_node->u.is_subtree=EMEM_TREE_NODE_IS_DATA;
1705 /* node will now point to the newly created node */
1706 switch(se_tree->type){
1707 case EMEM_TREE_TYPE_RED_BLACK:
1708 node->u.rb_color=EMEM_TREE_RB_COLOR_RED;
1709 rb_insert_case1(se_tree, node);
1715 lookup_or_insert32(emem_tree_t *se_tree, guint32 key, void*(*func)(void*),void* ud, int is_subtree)
1717 emem_tree_node_t *node;
1721 /* is this the first node ?*/
1723 node=se_tree->malloc(sizeof(emem_tree_node_t));
1724 switch(se_tree->type){
1725 case EMEM_TREE_TYPE_RED_BLACK:
1726 node->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1733 node->data= func(ud);
1734 node->u.is_subtree = is_subtree;
1739 /* it was not the new root so walk the tree until we find where to
1740 * insert this new leaf.
1743 /* this node already exists, so just return the data pointer*/
1744 if(key==node->key32){
1747 if(key<node->key32) {
1749 /* new node to the left */
1750 emem_tree_node_t *new_node;
1751 new_node=se_tree->malloc(sizeof(emem_tree_node_t));
1752 node->left=new_node;
1753 new_node->parent=node;
1754 new_node->left=NULL;
1755 new_node->right=NULL;
1756 new_node->key32=key;
1757 new_node->data= func(ud);
1758 new_node->u.is_subtree = is_subtree;
1765 if(key>node->key32) {
1767 /* new node to the right */
1768 emem_tree_node_t *new_node;
1769 new_node=se_tree->malloc(sizeof(emem_tree_node_t));
1770 node->right=new_node;
1771 new_node->parent=node;
1772 new_node->left=NULL;
1773 new_node->right=NULL;
1774 new_node->key32=key;
1775 new_node->data= func(ud);
1776 new_node->u.is_subtree = is_subtree;
1785 /* node will now point to the newly created node */
1786 switch(se_tree->type){
1787 case EMEM_TREE_TYPE_RED_BLACK:
1788 node->u.rb_color=EMEM_TREE_RB_COLOR_RED;
1789 rb_insert_case1(se_tree, node);
1796 /* When the se data is released, this entire tree will dissapear as if it
1797 * never existed including all metadata associated with the tree.
1800 se_tree_create_non_persistent(int type, const char *name)
1802 emem_tree_t *tree_list;
1804 tree_list=se_alloc(sizeof(emem_tree_t));
1805 tree_list->next=NULL;
1806 tree_list->type=type;
1807 tree_list->tree=NULL;
1808 tree_list->name=name;
1809 tree_list->malloc=se_alloc;
1814 /* This tree is PErmanent and will never be released
1817 pe_tree_create(int type, const char *name)
1819 emem_tree_t *tree_list;
1821 tree_list=g_new(emem_tree_t, 1);
1822 tree_list->next=NULL;
1823 tree_list->type=type;
1824 tree_list->tree=NULL;
1825 tree_list->name=name;
1826 tree_list->malloc=(void *(*)(size_t)) g_malloc;
1831 /* create another (sub)tree using the same memory allocation scope
1832 * as the parent tree.
1834 static emem_tree_t *
1835 emem_tree_create_subtree(emem_tree_t *parent_tree, const char *name)
1837 emem_tree_t *tree_list;
1839 tree_list=parent_tree->malloc(sizeof(emem_tree_t));
1840 tree_list->next=NULL;
1841 tree_list->type=parent_tree->type;
1842 tree_list->tree=NULL;
1843 tree_list->name=name;
1844 tree_list->malloc=parent_tree->malloc;
1850 create_sub_tree(void* d)
1852 emem_tree_t *se_tree = d;
1853 return emem_tree_create_subtree(se_tree, "subtree");
1856 /* insert a new node in the tree. if this node matches an already existing node
1857 * then just replace the data for that node */
1860 emem_tree_insert32_array(emem_tree_t *se_tree, emem_tree_key_t *key, void *data)
1862 emem_tree_t *insert_tree = NULL;
1863 emem_tree_key_t *cur_key;
1864 guint32 i, insert_key32 = 0;
1866 if(!se_tree || !key) return;
1868 for (cur_key = key; cur_key->length > 0; cur_key++) {
1869 if(cur_key->length > 100) {
1870 DISSECTOR_ASSERT_NOT_REACHED();
1873 for (i = 0; i < cur_key->length; i++) {
1874 /* Insert using the previous key32 */
1876 insert_tree = se_tree;
1878 insert_tree = lookup_or_insert32(insert_tree, insert_key32, create_sub_tree, se_tree, EMEM_TREE_NODE_IS_SUBTREE);
1880 insert_key32 = cur_key->key[i];
1885 /* We didn't get a valid key. Should we return NULL instead? */
1886 DISSECTOR_ASSERT_NOT_REACHED();
1889 emem_tree_insert32(insert_tree, insert_key32, data);
1894 emem_tree_lookup32_array(emem_tree_t *se_tree, emem_tree_key_t *key)
1896 emem_tree_t *lookup_tree = NULL;
1897 emem_tree_key_t *cur_key;
1898 guint32 i, lookup_key32 = 0;
1900 if(!se_tree || !key) return NULL; /* prevent searching on NULL pointer */
1902 for (cur_key = key; cur_key->length > 0; cur_key++) {
1903 if(cur_key->length > 100) {
1904 DISSECTOR_ASSERT_NOT_REACHED();
1907 for (i = 0; i < cur_key->length; i++) {
1908 /* Lookup using the previous key32 */
1910 lookup_tree = se_tree;
1912 lookup_tree = emem_tree_lookup32(lookup_tree, lookup_key32);
1917 lookup_key32 = cur_key->key[i];
1922 /* We didn't get a valid key. Should we return NULL instead? */
1923 DISSECTOR_ASSERT_NOT_REACHED();
1926 return emem_tree_lookup32(lookup_tree, lookup_key32);
1930 emem_tree_lookup32_array_le(emem_tree_t *se_tree, emem_tree_key_t *key)
1932 emem_tree_t *lookup_tree = NULL;
1933 emem_tree_key_t *cur_key;
1934 guint32 i, lookup_key32 = 0;
1936 if(!se_tree || !key) return NULL; /* prevent searching on NULL pointer */
1938 for (cur_key = key; cur_key->length > 0; cur_key++) {
1939 if(cur_key->length > 100) {
1940 DISSECTOR_ASSERT_NOT_REACHED();
1943 for (i = 0; i < cur_key->length; i++) {
1944 /* Lookup using the previous key32 */
1946 lookup_tree = se_tree;
1948 lookup_tree = emem_tree_lookup32_le(lookup_tree, lookup_key32);
1953 lookup_key32 = cur_key->key[i];
1958 /* We didn't get a valid key. Should we return NULL instead? */
1959 DISSECTOR_ASSERT_NOT_REACHED();
1962 return emem_tree_lookup32_le(lookup_tree, lookup_key32);
1966 /* Strings are stored as an array of uint32 containing the string characters
1967 with 4 characters in each uint32.
1968 The first byte of the string is stored as the most significant byte.
1969 If the string is not a multiple of 4 characters in length the last
1970 uint32 containing the string bytes are padded with 0 bytes.
1971 After the uint32's containing the string, there is one final terminator
1972 uint32 with the value 0x00000001
1975 emem_tree_insert_string(emem_tree_t* se_tree, const gchar* k, void* v, guint32 flags)
1977 emem_tree_key_t key[2];
1978 guint32 *aligned=NULL;
1979 guint32 len = (guint32) strlen(k);
1980 guint32 divx = (len+3)/4+1;
1984 aligned = g_malloc(divx * sizeof (guint32));
1986 /* pack the bytes one one by one into guint32s */
1988 for (i = 0;i < len;i++) {
1991 ch = (unsigned char)k[i];
1992 if (flags & EMEM_TREE_STRING_NOCASE) {
2004 /* add required padding to the last uint32 */
2010 aligned[i/4-1] = tmp;
2013 /* add the terminator */
2014 aligned[divx-1] = 0x00000001;
2016 key[0].length = divx;
2017 key[0].key = aligned;
2022 emem_tree_insert32_array(se_tree, key, v);
2027 emem_tree_lookup_string(emem_tree_t* se_tree, const gchar* k, guint32 flags)
2029 emem_tree_key_t key[2];
2030 guint32 *aligned=NULL;
2031 guint32 len = (guint) strlen(k);
2032 guint32 divx = (len+3)/4+1;
2037 aligned = g_malloc(divx * sizeof (guint32));
2039 /* pack the bytes one one by one into guint32s */
2041 for (i = 0;i < len;i++) {
2044 ch = (unsigned char)k[i];
2045 if (flags & EMEM_TREE_STRING_NOCASE) {
2057 /* add required padding to the last uint32 */
2063 aligned[i/4-1] = tmp;
2066 /* add the terminator */
2067 aligned[divx-1] = 0x00000001;
2069 key[0].length = divx;
2070 key[0].key = aligned;
2075 ret = emem_tree_lookup32_array(se_tree, key);
2081 emem_tree_foreach_nodes(emem_tree_node_t* node, tree_foreach_func callback, void *user_data)
2083 gboolean stop_traverse = FALSE;
2089 stop_traverse = emem_tree_foreach_nodes(node->left, callback, user_data);
2090 if (stop_traverse) {
2095 if (node->u.is_subtree == EMEM_TREE_NODE_IS_SUBTREE) {
2096 stop_traverse = emem_tree_foreach(node->data, callback, user_data);
2098 stop_traverse = callback(node->data, user_data);
2101 if (stop_traverse) {
2106 stop_traverse = emem_tree_foreach_nodes(node->right, callback, user_data);
2107 if (stop_traverse) {
2116 emem_tree_foreach(emem_tree_t* emem_tree, tree_foreach_func callback, void *user_data)
2121 if(!emem_tree->tree)
2124 return emem_tree_foreach_nodes(emem_tree->tree, callback, user_data);
2127 static void emem_print_subtree(emem_tree_t* emem_tree, guint32 level);
2130 emem_tree_print_nodes(const char *prefix, emem_tree_node_t* node, guint32 level)
2137 for(i=0;i<level;i++){
2141 printf("%sNODE:%p parent:%p left:%p right:%p colour:%s key:%u %s:%p\n", prefix,
2142 (void *)node,(void *)(node->parent),(void *)(node->left),(void *)(node->right),
2143 (node->u.rb_color)?"Black":"Red",(node->key32),(node->u.is_subtree)?"tree":"data",node->data);
2145 emem_tree_print_nodes("L-", node->left, level+1);
2147 emem_tree_print_nodes("R-", node->right, level+1);
2149 if (node->u.is_subtree)
2150 emem_print_subtree(node->data, level+1);
2154 emem_print_subtree(emem_tree_t* emem_tree, guint32 level)
2161 for(i=0;i<level;i++){
2165 printf("EMEM tree:%p type:%s name:%s root:%p\n",emem_tree,(emem_tree->type==1)?"RedBlack":"unknown",emem_tree->name,(void *)(emem_tree->tree));
2167 emem_tree_print_nodes("Root-", emem_tree->tree, level);
2171 emem_print_tree(emem_tree_t* emem_tree)
2173 emem_print_subtree(emem_tree, 0);
2181 * Presumably we're using these routines for building strings for the tree.
2182 * Use ITEM_LABEL_LENGTH as the basis for our default lengths.
2185 #define DEFAULT_STRBUF_LEN (ITEM_LABEL_LENGTH / 10)
2186 #define MAX_STRBUF_LEN 65536
2189 next_size(gsize cur_alloc_len, gsize wanted_alloc_len, gsize max_alloc_len)
2191 if (max_alloc_len < 1 || max_alloc_len > MAX_STRBUF_LEN) {
2192 max_alloc_len = MAX_STRBUF_LEN;
2195 if (cur_alloc_len < 1) {
2196 cur_alloc_len = DEFAULT_STRBUF_LEN;
2199 while (cur_alloc_len < wanted_alloc_len) {
2203 return cur_alloc_len < max_alloc_len ? cur_alloc_len : max_alloc_len;
2207 ep_strbuf_grow(emem_strbuf_t *strbuf, gsize wanted_alloc_len)
2209 gsize new_alloc_len;
2212 if (!strbuf || (wanted_alloc_len <= strbuf->alloc_len) || (strbuf->alloc_len >= strbuf->max_alloc_len)) {
2216 new_alloc_len = next_size(strbuf->alloc_len, wanted_alloc_len, strbuf->max_alloc_len);
2217 new_str = ep_alloc(new_alloc_len);
2218 g_strlcpy(new_str, strbuf->str, new_alloc_len);
2220 strbuf->alloc_len = new_alloc_len;
2221 strbuf->str = new_str;
2225 ep_strbuf_sized_new(gsize alloc_len, gsize max_alloc_len)
2227 emem_strbuf_t *strbuf;
2229 strbuf = ep_alloc(sizeof(emem_strbuf_t));
2231 if ((max_alloc_len == 0) || (max_alloc_len > MAX_STRBUF_LEN))
2232 max_alloc_len = MAX_STRBUF_LEN;
2235 else if (alloc_len > max_alloc_len)
2236 alloc_len = max_alloc_len;
2238 strbuf->str = ep_alloc(alloc_len);
2239 strbuf->str[0] = '\0';
2242 strbuf->alloc_len = alloc_len;
2243 strbuf->max_alloc_len = max_alloc_len;
2249 ep_strbuf_new(const gchar *init)
2251 emem_strbuf_t *strbuf;
2253 strbuf = ep_strbuf_sized_new(next_size(0, init?strlen(init)+1:0, 0), 0); /* +1 for NULL terminator */
2256 full_len = g_strlcpy(strbuf->str, init, strbuf->alloc_len);
2257 strbuf->len = MIN(full_len, strbuf->alloc_len-1);
2264 ep_strbuf_new_label(const gchar *init)
2266 emem_strbuf_t *strbuf;
2269 /* Be optimistic: Allocate default size strbuf string and only */
2270 /* request an increase if needed. */
2271 /* XXX: Is it reasonable to assume that much of the usage of */
2272 /* ep_strbuf_new_label will have init==NULL or */
2273 /* strlen(init) < DEFAULT_STRBUF_LEN) ??? */
2274 strbuf = ep_strbuf_sized_new(DEFAULT_STRBUF_LEN, ITEM_LABEL_LENGTH);
2279 /* full_len does not count the trailing '\0'. */
2280 full_len = g_strlcpy(strbuf->str, init, strbuf->alloc_len);
2281 if (full_len < strbuf->alloc_len) {
2282 strbuf->len += full_len;
2284 strbuf = ep_strbuf_sized_new(full_len+1, ITEM_LABEL_LENGTH);
2285 full_len = g_strlcpy(strbuf->str, init, strbuf->alloc_len);
2286 strbuf->len = MIN(full_len, strbuf->alloc_len-1);
2293 ep_strbuf_append(emem_strbuf_t *strbuf, const gchar *str)
2295 gsize add_len, full_len;
2297 if (!strbuf || !str || str[0] == '\0') {
2301 /* Be optimistic; try the g_strlcpy first & see if enough room. */
2302 /* Note: full_len doesn't count the trailing '\0'; add_len does allow for same */
2303 add_len = strbuf->alloc_len - strbuf->len;
2304 full_len = g_strlcpy(&strbuf->str[strbuf->len], str, add_len);
2305 if (full_len < add_len) {
2306 strbuf->len += full_len;
2308 strbuf->str[strbuf->len] = '\0'; /* end string at original length again */
2309 ep_strbuf_grow(strbuf, strbuf->len + full_len + 1);
2310 add_len = strbuf->alloc_len - strbuf->len;
2311 full_len = g_strlcpy(&strbuf->str[strbuf->len], str, add_len);
2312 strbuf->len += MIN(add_len-1, full_len);
2319 ep_strbuf_append_vprintf(emem_strbuf_t *strbuf, const gchar *format, va_list ap)
2322 gsize add_len, full_len;
2326 /* Be optimistic; try the g_vsnprintf first & see if enough room. */
2327 /* Note: full_len doesn't count the trailing '\0'; add_len does allow for same. */
2328 add_len = strbuf->alloc_len - strbuf->len;
2329 full_len = g_vsnprintf(&strbuf->str[strbuf->len], (gulong) add_len, format, ap);
2330 if (full_len < add_len) {
2331 strbuf->len += full_len;
2333 strbuf->str[strbuf->len] = '\0'; /* end string at original length again */
2334 ep_strbuf_grow(strbuf, strbuf->len + full_len + 1);
2335 add_len = strbuf->alloc_len - strbuf->len;
2336 full_len = g_vsnprintf(&strbuf->str[strbuf->len], (gulong) add_len, format, ap2);
2337 strbuf->len += MIN(add_len-1, full_len);
2344 ep_strbuf_append_printf(emem_strbuf_t *strbuf, const gchar *format, ...)
2348 va_start(ap, format);
2349 ep_strbuf_append_vprintf(strbuf, format, ap);
2354 ep_strbuf_printf(emem_strbuf_t *strbuf, const gchar *format, ...)
2363 va_start(ap, format);
2364 ep_strbuf_append_vprintf(strbuf, format, ap);
2369 ep_strbuf_append_c(emem_strbuf_t *strbuf, const gchar c)
2375 /* +1 for the new character & +1 for the trailing '\0'. */
2376 if (strbuf->alloc_len < strbuf->len + 1 + 1) {
2377 ep_strbuf_grow(strbuf, strbuf->len + 1 + 1);
2379 if (strbuf->alloc_len >= strbuf->len + 1 + 1) {
2380 strbuf->str[strbuf->len] = c;
2382 strbuf->str[strbuf->len] = '\0';
2389 ep_strbuf_append_unichar(emem_strbuf_t *strbuf, const gunichar c)
2398 charlen = g_unichar_to_utf8(c, buf);
2400 /* +charlen for the new character & +1 for the trailing '\0'. */
2401 if (strbuf->alloc_len < strbuf->len + charlen + 1) {
2402 ep_strbuf_grow(strbuf, strbuf->len + charlen + 1);
2404 if (strbuf->alloc_len >= strbuf->len + charlen + 1) {
2405 memcpy(&strbuf->str[strbuf->len], buf, charlen);
2406 strbuf->len += charlen;
2407 strbuf->str[strbuf->len] = '\0';
2414 ep_strbuf_truncate(emem_strbuf_t *strbuf, gsize len)
2416 if (!strbuf || len >= strbuf->len) {
2420 strbuf->str[len] = '\0';
2432 * indent-tabs-mode: t
2435 * ex: set shiftwidth=8 tabstop=8 noexpandtab:
2436 * :indentSize=8:tabSize=8:noTabs=false: