From Tyson Key:
[obnox/wireshark/wip.git] / epan / emem.c
1 /* emem.c
2  * Wireshark memory management and garbage collection functions
3  * Ronnie Sahlberg 2005
4  *
5  * $Id$
6  *
7  * Wireshark - Network traffic analyzer
8  * By Gerald Combs <gerald@wireshark.org>
9  * Copyright 1998 Gerald Combs
10  *
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.
15  *
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.
20  *
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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  */
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdarg.h>
33 #include <ctype.h>
34
35 #include <time.h>
36 #ifdef HAVE_SYS_TIME_H
37 #include <sys/time.h>
38 #endif
39
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43
44 #include <glib.h>
45
46 #include "proto.h"
47 #include "emem.h"
48
49 #ifdef _WIN32
50 #include <windows.h>    /* VirtualAlloc, VirtualProtect */
51 #include <process.h>    /* getpid */
52 #endif
53
54 /* Print out statistics about our memory allocations? */
55 /*#define SHOW_EMEM_STATS*/
56
57 /* Do we want to use guardpages? if available */
58 #define WANT_GUARD_PAGES 1
59
60 #ifdef WANT_GUARD_PAGES
61 /* Add guard pages at each end of our allocated memory */
62 #if defined(HAVE_SYSCONF) && defined(HAVE_MMAP) && defined(HAVE_MPROTECT) && defined(HAVE_STDINT_H)
63 #include <stdint.h>
64 #ifdef HAVE_SYS_TYPES_H
65 #include <sys/types.h>
66 #endif
67 #include <sys/mman.h>
68 #if defined(MAP_ANONYMOUS)
69 #define ANON_PAGE_MODE  (MAP_ANONYMOUS|MAP_PRIVATE)
70 #elif defined(MAP_ANON)
71 #define ANON_PAGE_MODE  (MAP_ANON|MAP_PRIVATE)
72 #else
73 #define ANON_PAGE_MODE  (MAP_PRIVATE)   /* have to map /dev/zero */
74 #define NEED_DEV_ZERO
75 #endif
76 #ifdef NEED_DEV_ZERO
77 #include <fcntl.h>
78 static int dev_zero_fd;
79 #define ANON_FD dev_zero_fd
80 #else
81 #define ANON_FD -1
82 #endif
83 #define USE_GUARD_PAGES 1
84 #endif
85 #endif
86
87 /* When required, allocate more memory from the OS in this size chunks */
88 #define EMEM_PACKET_CHUNK_SIZE (10 * 1024 * 1024)
89
90 /* The canary between allocations is at least 8 bytes and up to 16 bytes to
91  * allow future allocations to be 4- or 8-byte aligned.
92  * All but the last byte of the canary are randomly generated; the last byte is
93  * NULL to separate the canary and the pointer to the next canary.
94  *
95  * For example, if the allocation is a multiple of 8 bytes, the canary and
96  * pointer would look like:
97  *   |0|1|2|3|4|5|6|7||0|1|2|3|4|5|6|7|
98  *   |c|c|c|c|c|c|c|0||p|p|p|p|p|p|p|p| (64-bit), or:
99  *   |c|c|c|c|c|c|c|0||p|p|p|p|         (32-bit)
100  *
101  * If the allocation was, for example, 12 bytes, the canary would look like:
102  *        |0|1|2|3|4|5|6|7||0|1|2|3|4|5|6|7|
103  *   [...]|a|a|a|a|c|c|c|c||c|c|c|c|c|c|c|0| (followed by the pointer)
104  */
105 #define EMEM_CANARY_SIZE 8
106 #define EMEM_CANARY_DATA_SIZE (EMEM_CANARY_SIZE * 2 - 1)
107
108 typedef struct _emem_chunk_t {
109         struct _emem_chunk_t *next;
110         char            *buf;
111         unsigned int    amount_free_init;
112         unsigned int    amount_free;
113         unsigned int    free_offset_init;
114         unsigned int    free_offset;
115         void            *canary_last;
116 } emem_chunk_t;
117
118 typedef struct _emem_header_t {
119         emem_chunk_t *free_list;
120         emem_chunk_t *used_list;
121
122         emem_tree_t *trees;             /* only used by se_mem allocator */
123
124         guint8 canary[EMEM_CANARY_DATA_SIZE];
125         void *(*memory_alloc)(size_t size, struct _emem_header_t *);
126
127         /*
128          * Tools like Valgrind and ElectricFence don't work well with memchunks.
129          * Export the following environment variables to make {ep|se}_alloc() allocate each
130          * object individually.
131          *
132          * WIRESHARK_DEBUG_EP_NO_CHUNKS
133          * WIRESHARK_DEBUG_SE_NO_CHUNKS
134          */
135         gboolean debug_use_chunks;
136
137         /* Do we want to use canaries?
138          * Export the following environment variables to disable/enable canaries
139          *
140          * WIRESHARK_DEBUG_EP_NO_CANARY
141          * For SE memory use of canary is default off as the memory overhead
142          * is considerable.
143          * WIRESHARK_DEBUG_SE_USE_CANARY
144          */
145         gboolean debug_use_canary;
146
147         /*  Do we want to verify no one is using a pointer to an ep_ or se_
148          *  allocated thing where they shouldn't be?
149          *
150          * Export WIRESHARK_EP_VERIFY_POINTERS or WIRESHARK_SE_VERIFY_POINTERS
151          * to turn this on.
152          */
153         gboolean debug_verify_pointers;
154
155 } emem_header_t;
156
157 static emem_header_t ep_packet_mem;
158 static emem_header_t se_packet_mem;
159
160 /*
161  *  Memory scrubbing is expensive but can be useful to ensure we don't:
162  *    - use memory before initializing it
163  *    - use memory after freeing it
164  *  Export WIRESHARK_DEBUG_SCRUB_MEMORY to turn it on.
165  */
166 static gboolean debug_use_memory_scrubber = FALSE;
167
168 #if defined (_WIN32)
169 static SYSTEM_INFO sysinfo;
170 static OSVERSIONINFO versinfo;
171 static int pagesize;
172 #elif defined(USE_GUARD_PAGES)
173 static intptr_t pagesize;
174 #endif /* _WIN32 / USE_GUARD_PAGES */
175
176 static void *emem_alloc_chunk(size_t size, emem_header_t *mem);
177 static void *emem_alloc_glib(size_t size, emem_header_t *mem);
178
179 /*
180  * Set a canary value to be placed between memchunks.
181  */
182 static void
183 emem_canary_init(guint8 *canary)
184 {
185         int i;
186         static GRand *rand_state = NULL;
187
188         if (rand_state == NULL) {
189                 rand_state = g_rand_new();
190         }
191         for (i = 0; i < EMEM_CANARY_DATA_SIZE; i ++) {
192                 canary[i] = (guint8) g_rand_int_range(rand_state, 1, 0x100);
193         }
194         return;
195 }
196
197 static void *
198 emem_canary_next(guint8 *mem_canary, guint8 *canary, int *len)
199 {
200         void *ptr;
201         int i;
202
203         for (i = 0; i < EMEM_CANARY_SIZE-1; i++)
204                 if (mem_canary[i] != canary[i])
205                         return (void *) -1;
206
207         for (; i < EMEM_CANARY_DATA_SIZE; i++) {
208                 if (canary[i] == '\0') {
209                         memcpy(&ptr, &canary[i+1], sizeof(void *));
210
211                         if (len)
212                                 *len = i + 1 + sizeof(void *);
213                         return ptr;
214                 }
215
216                 if (mem_canary[i] != canary[i])
217                         return (void *) -1;
218         }
219
220         return (void *) -1;
221 }
222
223 /*
224  * Given an allocation size, return the amount of room needed for the canary
225  * (with a minimum of 8 bytes) while using the canary to pad to an 8-byte
226  * boundary.
227  */
228 static guint8
229 emem_canary_pad (size_t allocation)
230 {
231         guint8 pad;
232
233         pad = EMEM_CANARY_SIZE - (allocation % EMEM_CANARY_SIZE);
234         if (pad < EMEM_CANARY_SIZE)
235                 pad += EMEM_CANARY_SIZE;
236
237         return pad;
238 }
239
240 /* used for debugging canaries, will block */
241 #ifdef DEBUG_INTENSE_CANARY_CHECKS
242 gboolean intense_canary_checking = FALSE;
243
244 /*  used to intensivelly check ep canaries
245  */
246 void
247 ep_check_canary_integrity(const char* fmt, ...)
248 {
249         va_list ap;
250         static gchar there[128] = {
251                 '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,
252                 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,
253                 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,
254                 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 };
255         gchar here[128];
256         emem_chunk_t* npc = NULL;
257
258         if (! intense_canary_checking ) return;
259
260         va_start(ap,fmt);
261         g_vsnprintf(here, sizeof(here), fmt, ap);
262         va_end(ap);
263
264         for (npc = ep_packet_mem.free_list; npc != NULL; npc = npc->next) {
265                 void *canary_next = npc->canary_last;
266
267                 while (canary_next != NULL) {
268                         canary_next = emem_canary_next(ep_packet_mem.canary, canary_next, NULL);
269                         /* XXX, check if canary_next is inside allocated memory? */
270
271                         if (canary_next == (void *) -1)
272                                 g_error("Per-packet memory corrupted\nbetween: %s\nand: %s", there, here);
273                 }
274         }
275
276         g_strlcpy(there, here, sizeof(there));
277 }
278 #endif
279
280 static void
281 emem_init_chunk(emem_header_t *mem)
282 {
283         if (mem->debug_use_canary)
284                 emem_canary_init(mem->canary);
285
286         if (mem->debug_use_chunks)
287                 mem->memory_alloc = emem_alloc_chunk;
288         else
289                 mem->memory_alloc = emem_alloc_glib;
290 }
291
292
293 /* Initialize the packet-lifetime memory allocation pool.
294  * This function should be called only once when Wireshark or TShark starts
295  * up.
296  */
297 static void
298 ep_init_chunk(void)
299 {
300         ep_packet_mem.free_list=NULL;
301         ep_packet_mem.used_list=NULL;
302         ep_packet_mem.trees=NULL;       /* not used by this allocator */
303
304         ep_packet_mem.debug_use_chunks = (getenv("WIRESHARK_DEBUG_EP_NO_CHUNKS") == NULL);
305         ep_packet_mem.debug_use_canary = ep_packet_mem.debug_use_chunks && (getenv("WIRESHARK_DEBUG_EP_NO_CANARY") == NULL);
306         ep_packet_mem.debug_verify_pointers = (getenv("WIRESHARK_EP_VERIFY_POINTERS") != NULL);
307
308 #ifdef DEBUG_INTENSE_CANARY_CHECKS
309         intense_canary_checking = (getenv("WIRESHARK_DEBUG_EP_INTENSE_CANARY") != NULL);
310 #endif
311
312         emem_init_chunk(&ep_packet_mem);
313 }
314
315 /* Initialize the capture-lifetime memory allocation pool.
316  * This function should be called only once when Wireshark or TShark starts
317  * up.
318  */
319 static void
320 se_init_chunk(void)
321 {
322         se_packet_mem.free_list = NULL;
323         se_packet_mem.used_list = NULL;
324         se_packet_mem.trees = NULL;
325
326         se_packet_mem.debug_use_chunks = (getenv("WIRESHARK_DEBUG_SE_NO_CHUNKS") == NULL);
327         se_packet_mem.debug_use_canary = se_packet_mem.debug_use_chunks && (getenv("WIRESHARK_DEBUG_SE_USE_CANARY") != NULL);
328         se_packet_mem.debug_verify_pointers = (getenv("WIRESHARK_SE_VERIFY_POINTERS") != NULL);
329
330         emem_init_chunk(&se_packet_mem);
331 }
332
333 /*  Initialize all the allocators here.
334  *  This function should be called only once when Wireshark or TShark starts
335  *  up.
336  */
337 void
338 emem_init(void)
339 {
340         ep_init_chunk();
341         se_init_chunk();
342
343         if (getenv("WIRESHARK_DEBUG_SCRUB_MEMORY"))
344                 debug_use_memory_scrubber  = TRUE;
345
346 #if defined (_WIN32)
347         /* Set up our guard page info for Win32 */
348         GetSystemInfo(&sysinfo);
349         pagesize = sysinfo.dwPageSize;
350
351         /* calling GetVersionEx using the OSVERSIONINFO structure.
352          * OSVERSIONINFOEX requires Win NT4 with SP6 or newer NT Versions.
353          * OSVERSIONINFOEX will fail on Win9x and older NT Versions.
354          * See also:
355          * http://msdn.microsoft.com/library/en-us/sysinfo/base/getversionex.asp
356          * http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
357          * http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfoex_str.asp
358          */
359         versinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
360         GetVersionEx(&versinfo);
361
362 #elif defined(USE_GUARD_PAGES)
363         pagesize = sysconf(_SC_PAGESIZE);
364 #ifdef NEED_DEV_ZERO
365         dev_zero_fd = ws_open("/dev/zero", O_RDWR);
366         g_assert(dev_zero_fd != -1);
367 #endif
368 #endif /* _WIN32 / USE_GUARD_PAGES */
369 }
370
371 #ifdef SHOW_EMEM_STATS
372 #define NUM_ALLOC_DIST 10
373 static guint allocations[NUM_ALLOC_DIST] = { 0 };
374 static guint total_no_chunks = 0;
375
376 static void
377 print_alloc_stats()
378 {
379         guint num_chunks = 0;
380         guint num_allocs = 0;
381         guint total_used = 0;
382         guint total_allocation = 0;
383         guint total_free = 0;
384         guint used_for_canaries = 0;
385         guint total_headers;
386         guint i;
387         emem_chunk_t *chunk;
388         guint total_space_allocated_from_os, total_space_wasted;
389         gboolean ep_stat=TRUE;
390
391         fprintf(stderr, "\n-------- EP allocator statistics --------\n");
392         fprintf(stderr, "%s chunks, %s canaries, %s memory scrubber\n",
393                ep_packet_mem.debug_use_chunks ? "Using" : "Not using",
394                ep_packet_mem.debug_use_canary ? "using" : "not using",
395                debug_use_memory_scrubber ? "using" : "not using");
396
397         if (! (ep_packet_mem.free_list || !ep_packet_mem.used_list)) {
398                 fprintf(stderr, "No memory allocated\n");
399                 ep_stat = FALSE;
400         }
401         if (ep_packet_mem.debug_use_chunks && ep_stat) {
402                 /* Nothing interesting without chunks */
403                 /*  Only look at the used_list since those chunks are fully
404                  *  used.  Looking at the free list would skew our view of what
405                  *  we have wasted.
406                  */
407                 for (chunk = ep_packet_mem.used_list; chunk; chunk = chunk->next) {
408                         num_chunks++;
409                         total_used += (chunk->amount_free_init - chunk->amount_free);
410                         total_allocation += chunk->amount_free_init;
411                         total_free += chunk->amount_free;
412                 }
413                 if (num_chunks > 0) {
414                         fprintf (stderr, "\n");
415                         fprintf (stderr, "\n---- Buffer space ----\n");
416                         fprintf (stderr, "\tChunk allocation size: %10u\n", EMEM_PACKET_CHUNK_SIZE);
417                         fprintf (stderr, "\t*    Number of chunks: %10u\n", num_chunks);
418                         fprintf (stderr, "\t-------------------------------------------\n");
419                         fprintf (stderr, "\t= %u (%u including guard pages) total space used for buffers\n",
420                         total_allocation, EMEM_PACKET_CHUNK_SIZE * num_chunks);
421                         fprintf (stderr, "\t-------------------------------------------\n");
422                         total_space_allocated_from_os = total_allocation
423                                 + sizeof(emem_chunk_t) * num_chunks;
424                         fprintf (stderr, "Total allocated from OS: %u\n\n",
425                                 total_space_allocated_from_os);
426                 }else{
427                         fprintf (stderr, "No fully used chunks, nothing to do\n");
428                 }
429                 /* Reset stats */
430                 num_chunks = 0;
431                 num_allocs = 0;
432                 total_used = 0;
433                 total_allocation = 0;
434                 total_free = 0;
435                 used_for_canaries = 0;
436         }
437
438
439         fprintf(stderr, "\n-------- SE allocator statistics --------\n");
440         fprintf(stderr, "Total number of chunk allocations %u\n",
441                 total_no_chunks);
442         fprintf(stderr, "%s chunks, %s canaries\n",
443                se_packet_mem.debug_use_chunks ? "Using" : "Not using",
444                se_packet_mem.debug_use_canary ? "using" : "not using");
445
446         if (! (se_packet_mem.free_list || !se_packet_mem.used_list)) {
447                 fprintf(stderr, "No memory allocated\n");
448                 return;
449         }
450
451         if (!se_packet_mem.debug_use_chunks )
452                 return; /* Nothing interesting without chunks?? */
453
454         /*  Only look at the used_list since those chunks are fully used.
455          *  Looking at the free list would skew our view of what we have wasted.
456          */
457         for (chunk = se_packet_mem.used_list; chunk; chunk = chunk->next) {
458                 num_chunks++;
459                 total_used += (chunk->amount_free_init - chunk->amount_free);
460                 total_allocation += chunk->amount_free_init;
461                 total_free += chunk->amount_free;
462
463                 if (se_packet_mem.debug_use_canary){
464                         void *ptr = chunk->canary_last;
465                         int len;
466
467                         while (ptr != NULL) {
468                                 ptr = emem_canary_next(se_packet_mem.canary, ptr, &len);
469
470                                 if (ptr == (void *) -1)
471                                         g_error("Memory corrupted");
472                                 used_for_canaries += len;
473                         }
474                 }
475         }
476
477         if (num_chunks == 0) {
478
479                 fprintf (stderr, "No fully used chunks, nothing to do\n");
480                 return;
481         }
482
483         fprintf (stderr, "\n");
484         fprintf (stderr, "---------- Allocations from the OS ----------\n");
485         fprintf (stderr, "---- Headers ----\n");
486         fprintf (stderr, "\t(    Chunk header size: %10lu\n",
487                  sizeof(emem_chunk_t));
488         fprintf (stderr, "\t*     Number of chunks: %10u\n", num_chunks);
489         fprintf (stderr, "\t-------------------------------------------\n");
490
491         total_headers = sizeof(emem_chunk_t) * num_chunks;
492         fprintf (stderr, "\t= %u bytes used for headers\n", total_headers);
493         fprintf (stderr, "\n---- Buffer space ----\n");
494         fprintf (stderr, "\tChunk allocation size: %10u\n",
495                  EMEM_PACKET_CHUNK_SIZE);
496         fprintf (stderr, "\t*    Number of chunks: %10u\n", num_chunks);
497         fprintf (stderr, "\t-------------------------------------------\n");
498         fprintf (stderr, "\t= %u (%u including guard pages) bytes used for buffers\n",
499                 total_allocation, EMEM_PACKET_CHUNK_SIZE * num_chunks);
500         fprintf (stderr, "\t-------------------------------------------\n");
501         total_space_allocated_from_os = (EMEM_PACKET_CHUNK_SIZE * num_chunks)
502                                         + total_headers;
503         fprintf (stderr, "Total bytes allocated from the OS: %u\n\n",
504                 total_space_allocated_from_os);
505
506         for (i = 0; i < NUM_ALLOC_DIST; i++)
507                 num_allocs += allocations[i];
508
509         fprintf (stderr, "---------- Allocations from the SE pool ----------\n");
510         fprintf (stderr, "                Number of SE allocations: %10u\n",
511                  num_allocs);
512         fprintf (stderr, "             Bytes used (incl. canaries): %10u\n",
513                  total_used);
514         fprintf (stderr, "                 Bytes used for canaries: %10u\n",
515                  used_for_canaries);
516         fprintf (stderr, "Bytes unused (wasted, excl. guard pages): %10u\n",
517                  total_allocation - total_used);
518         fprintf (stderr, "Bytes unused (wasted, incl. guard pages): %10u\n\n",
519                  total_space_allocated_from_os - total_used);
520
521         fprintf (stderr, "---------- Statistics ----------\n");
522         fprintf (stderr, "Average SE allocation size (incl. canaries): %6.2f\n",
523                 (float)total_used/(float)num_allocs);
524         fprintf (stderr, "Average SE allocation size (excl. canaries): %6.2f\n",
525                 (float)(total_used - used_for_canaries)/(float)num_allocs);
526         fprintf (stderr, "        Average wasted bytes per allocation: %6.2f\n",
527                 (total_allocation - total_used)/(float)num_allocs);
528         total_space_wasted = (total_allocation - total_used)
529                 + (sizeof(emem_chunk_t));
530         fprintf (stderr, " Space used for headers + unused allocation: %8u\n",
531                 total_space_wasted);
532         fprintf (stderr, "--> %% overhead/waste: %4.2f\n",
533                 100 * (float)total_space_wasted/(float)total_space_allocated_from_os);
534
535         fprintf (stderr, "\nAllocation distribution (sizes include canaries):\n");
536         for (i = 0; i < (NUM_ALLOC_DIST-1); i++)
537                 fprintf (stderr, "size < %5d: %8u\n", 32<<i, allocations[i]);
538         fprintf (stderr, "size > %5d: %8u\n", 32<<i, allocations[i]);
539 }
540 #endif
541
542 static gboolean
543 emem_verify_pointer_list(const emem_chunk_t *chunk_list, const void *ptr)
544 {
545         const gchar *cptr = ptr;
546         const emem_chunk_t *chunk;
547
548         for (chunk = chunk_list; chunk; chunk = chunk->next) {
549                 if (cptr >= (chunk->buf + chunk->free_offset_init) && cptr < (chunk->buf + chunk->free_offset))
550                         return TRUE;
551         }
552         return FALSE;
553 }
554
555 static gboolean
556 emem_verify_pointer(const emem_header_t *hdr, const void *ptr)
557 {
558         return emem_verify_pointer_list(hdr->free_list, ptr) || emem_verify_pointer_list(hdr->used_list, ptr);
559 }
560
561 gboolean
562 ep_verify_pointer(const void *ptr)
563 {
564         if (ep_packet_mem.debug_verify_pointers)
565                 return emem_verify_pointer(&ep_packet_mem, ptr);
566         else
567                 return FALSE;
568 }
569
570 gboolean
571 se_verify_pointer(const void *ptr)
572 {
573         if (se_packet_mem.debug_verify_pointers)
574                 return emem_verify_pointer(&se_packet_mem, ptr);
575         else
576                 return FALSE;
577 }
578
579 static void
580 emem_scrub_memory(char *buf, size_t size, gboolean alloc)
581 {
582         guint scrubbed_value;
583         guint offset;
584
585         if (!debug_use_memory_scrubber)
586                 return;
587
588         if (alloc) /* this memory is being allocated */
589                 scrubbed_value = 0xBADDCAFE;
590         else /* this memory is being freed */
591                 scrubbed_value = 0xDEADBEEF;
592
593         /*  We shouldn't need to check the alignment of the starting address
594          *  since this is malloc'd memory (or 'pagesize' bytes into malloc'd
595          *  memory).
596          */
597
598         /* XXX - if the above is *NOT* true, we should use memcpy here,
599          * in order to avoid problems on alignment-sensitive platforms, e.g.
600          * http://stackoverflow.com/questions/108866/is-there-memset-that-accepts-integers-larger-than-char
601          */
602
603         for (offset = 0; offset + sizeof(guint) <= size; offset += sizeof(guint))
604                 *(guint*)(void*)(buf+offset) = scrubbed_value;
605
606         /* Initialize the last bytes, if any */
607         if (offset < size) {
608                 *(guint8*)(buf+offset) = scrubbed_value >> 24;
609                 offset++;
610                 if (offset < size) {
611                         *(guint8*)(buf+offset) = (scrubbed_value >> 16) & 0xFF;
612                         offset++;
613                         if (offset < size) {
614                                 *(guint8*)(buf+offset) = (scrubbed_value >> 8) & 0xFF;
615                         }
616                 }
617         }
618
619
620 }
621
622 static emem_chunk_t *
623 emem_create_chunk(size_t size)
624 {
625         emem_chunk_t *npc;
626
627         npc = g_new(emem_chunk_t, 1);
628         npc->next = NULL;
629         npc->canary_last = NULL;
630
631 #if defined (_WIN32)
632         /*
633          * MSDN documents VirtualAlloc/VirtualProtect at
634          * http://msdn.microsoft.com/library/en-us/memory/base/creating_guard_pages.asp
635          */
636
637         /* XXX - is MEM_COMMIT|MEM_RESERVE correct? */
638         npc->buf = VirtualAlloc(NULL, size,
639                 MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE);
640
641         if (npc->buf == NULL) {
642                 g_free(npc);
643                 THROW(OutOfMemoryError);
644         }
645
646 #elif defined(USE_GUARD_PAGES)
647         npc->buf = mmap(NULL, size,
648                 PROT_READ|PROT_WRITE, ANON_PAGE_MODE, ANON_FD, 0);
649
650         if (npc->buf == MAP_FAILED) {
651                 g_free(npc);
652                 THROW(OutOfMemoryError);
653         }
654
655 #else /* Is there a draft in here? */
656         npc->buf = g_malloc(size);
657         /* g_malloc() can't fail */
658 #endif
659
660 #ifdef SHOW_EMEM_STATS
661         total_no_chunks++;
662 #endif
663
664         npc->amount_free = npc->amount_free_init = (unsigned int) size;
665         npc->free_offset = npc->free_offset_init = 0;
666         return npc;
667 }
668
669 static void
670 emem_destroy_chunk(emem_chunk_t *npc)
671 {
672 #if defined (_WIN32)
673         VirtualFree(npc->buf, 0, MEM_RELEASE);
674 #elif defined(USE_GUARD_PAGES)
675         munmap(npc->buf, npc->amount_free_init);
676 #else
677         g_free(npc->buf);
678 #endif
679 #ifdef SHOW_EMEM_STATS
680         total_no_chunks--;
681 #endif
682         g_free(npc);
683 }
684
685 static emem_chunk_t *
686 emem_create_chunk_gp(size_t size)
687 {
688 #if defined (_WIN32)
689         BOOL ret;
690         char *buf_end, *prot1, *prot2;
691         DWORD oldprot;
692 #elif defined(USE_GUARD_PAGES)
693         int ret;
694         char *buf_end, *prot1, *prot2;
695 #endif /* _WIN32 / USE_GUARD_PAGES */
696         emem_chunk_t *npc;
697
698         npc = emem_create_chunk(size);
699
700 #if defined (_WIN32)
701         buf_end = npc->buf + size;
702
703         /* Align our guard pages on page-sized boundaries */
704         prot1 = (char *) ((((int) npc->buf + pagesize - 1) / pagesize) * pagesize);
705         prot2 = (char *) ((((int) buf_end - (1 * pagesize)) / pagesize) * pagesize);
706
707         ret = VirtualProtect(prot1, pagesize, PAGE_NOACCESS, &oldprot);
708         g_assert(ret != 0 || versinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
709         ret = VirtualProtect(prot2, pagesize, PAGE_NOACCESS, &oldprot);
710         g_assert(ret != 0 || versinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
711
712         npc->amount_free_init = (unsigned int) (prot2 - prot1 - pagesize);
713         npc->free_offset_init = (unsigned int) (prot1 - npc->buf) + pagesize;
714 #elif defined(USE_GUARD_PAGES)
715         buf_end = npc->buf + size;
716
717         /* Align our guard pages on page-sized boundaries */
718         prot1 = (char *) ((((intptr_t) npc->buf + pagesize - 1) / pagesize) * pagesize);
719         prot2 = (char *) ((((intptr_t) buf_end - (1 * pagesize)) / pagesize) * pagesize);
720
721         ret = mprotect(prot1, pagesize, PROT_NONE);
722         g_assert(ret != -1);
723         ret = mprotect(prot2, pagesize, PROT_NONE);
724         g_assert(ret != -1);
725
726         npc->amount_free_init = prot2 - prot1 - pagesize;
727         npc->free_offset_init = (prot1 - npc->buf) + pagesize;
728 #else
729         npc->amount_free_init = size;
730         npc->free_offset_init = 0;
731 #endif /* USE_GUARD_PAGES */
732
733         npc->amount_free = npc->amount_free_init;
734         npc->free_offset = npc->free_offset_init;
735         return npc;
736 }
737
738 static void *
739 emem_alloc_chunk(size_t size, emem_header_t *mem)
740 {
741         void *buf;
742
743         size_t asize = size;
744         gboolean use_canary = mem->debug_use_canary;
745         guint8 pad;
746         emem_chunk_t *free_list;
747
748         /* Allocate room for at least 8 bytes of canary plus some padding
749          * so the canary ends on an 8-byte boundary.
750          * Then add the room needed for the pointer to the next canary.
751          */
752          if (use_canary) {
753                 pad = emem_canary_pad(asize);
754                 asize += sizeof(void *);
755         } else
756                 pad = (G_MEM_ALIGN - (asize & (G_MEM_ALIGN-1))) & (G_MEM_ALIGN-1);
757
758         asize += pad;
759
760 #ifdef SHOW_EMEM_STATS
761         /* Do this check here so we can include the canary size */
762         if (mem == &se_packet_mem) {
763                 if (asize < 32)
764                         allocations[0]++;
765                 else if (asize < 64)
766                         allocations[1]++;
767                 else if (asize < 128)
768                         allocations[2]++;
769                 else if (asize < 256)
770                         allocations[3]++;
771                 else if (asize < 512)
772                         allocations[4]++;
773                 else if (asize < 1024)
774                         allocations[5]++;
775                 else if (asize < 2048)
776                         allocations[6]++;
777                 else if (asize < 4096)
778                         allocations[7]++;
779                 else if (asize < 8192)
780                         allocations[8]++;
781                 else if (asize < 16384)
782                         allocations[8]++;
783                 else
784                         allocations[(NUM_ALLOC_DIST-1)]++;
785         }
786 #endif
787
788         /* make sure we dont try to allocate too much (arbitrary limit) */
789         DISSECTOR_ASSERT(size<(EMEM_PACKET_CHUNK_SIZE>>2));
790
791         if (!mem->free_list)
792                 mem->free_list = emem_create_chunk_gp(EMEM_PACKET_CHUNK_SIZE);
793
794         /* oops, we need to allocate more memory to serve this request
795          * than we have free. move this node to the used list and try again
796          */
797         if(asize > mem->free_list->amount_free) {
798                 emem_chunk_t *npc;
799                 npc=mem->free_list;
800                 mem->free_list=mem->free_list->next;
801                 npc->next=mem->used_list;
802                 mem->used_list=npc;
803
804                 if (!mem->free_list)
805                         mem->free_list = emem_create_chunk_gp(EMEM_PACKET_CHUNK_SIZE);
806         }
807
808         free_list = mem->free_list;
809
810         buf = free_list->buf + free_list->free_offset;
811
812         free_list->amount_free -= (unsigned int) asize;
813         free_list->free_offset += (unsigned int) asize;
814
815         if (use_canary) {
816                 char *cptr = (char *)buf + size;
817
818                 memcpy(cptr, mem->canary, pad-1);
819                 cptr[pad-1] = '\0';
820                 memcpy(cptr + pad, &free_list->canary_last, sizeof(void *));
821
822                 free_list->canary_last = cptr;
823         }
824
825         return buf;
826 }
827
828 static void *
829 emem_alloc_glib(size_t size, emem_header_t *mem)
830 {
831         emem_chunk_t *npc;
832
833         npc=g_new(emem_chunk_t, 1);
834         npc->next=mem->used_list;
835         npc->buf=g_malloc(size);
836         npc->canary_last = NULL;
837         mem->used_list=npc;
838         /* There's no padding/alignment involved (from our point of view) when
839          * we fetch the memory directly from the system pool, so WYSIWYG */
840         npc->free_offset = npc->free_offset_init = 0;
841         npc->amount_free = npc->amount_free_init = (unsigned int) size;
842
843         return npc->buf;
844 }
845
846 /* allocate 'size' amount of memory. */
847 static void *
848 emem_alloc(size_t size, emem_header_t *mem)
849 {
850         void *buf = mem->memory_alloc(size, mem);
851
852         /*  XXX - this is a waste of time if the allocator function is going to
853          *  memset this straight back to 0.
854          */
855         emem_scrub_memory(buf, size, TRUE);
856
857         return buf;
858 }
859
860 /* allocate 'size' amount of memory with an allocation lifetime until the
861  * next packet.
862  */
863 void *
864 ep_alloc(size_t size)
865 {
866         return emem_alloc(size, &ep_packet_mem);
867 }
868
869 /* allocate 'size' amount of memory with an allocation lifetime until the
870  * next capture.
871  */
872 void *
873 se_alloc(size_t size)
874 {
875         return emem_alloc(size, &se_packet_mem);
876 }
877
878 void *
879 sl_alloc(struct ws_memory_slab *mem_chunk)
880 {
881         emem_chunk_t *chunk;
882         void *ptr;
883
884         /* XXX, debug_use_slices -> fallback to g_slice_alloc0 */
885
886         if ((mem_chunk->freed != NULL)) {
887                 ptr = mem_chunk->freed;
888                 memcpy(&mem_chunk->freed, ptr, sizeof(void *));
889                 return ptr;
890         }
891
892         if (!(chunk = mem_chunk->chunk_list) || chunk->amount_free < (guint) mem_chunk->item_size) {
893                 size_t alloc_size = mem_chunk->item_size * mem_chunk->count;
894
895                 /* align to page-size */
896 #if defined (_WIN32) || defined(USE_GUARD_PAGES)
897                 alloc_size = (alloc_size + (pagesize - 1)) & ~(pagesize - 1);
898 #endif
899
900                 chunk = emem_create_chunk(alloc_size);  /* NOTE: using version without guard pages! */
901                 chunk->next = mem_chunk->chunk_list;
902                 mem_chunk->chunk_list = chunk;
903         }
904
905         ptr = chunk->buf + chunk->free_offset;
906         chunk->free_offset += mem_chunk->item_size;
907         chunk->amount_free -= mem_chunk->item_size;
908
909         return ptr;
910 }
911
912 void
913 sl_free(struct ws_memory_slab *mem_chunk, gpointer ptr)
914 {
915         /* XXX, debug_use_slices -> fallback to g_slice_free1 */
916
917         /* XXX, abort if ptr not found in emem_verify_pointer_list()? */
918         if (ptr != NULL /* && emem_verify_pointer_list(mem_chunk->chunk_list, ptr) */) {
919                 memcpy(ptr, &(mem_chunk->freed), sizeof(void *));
920                 mem_chunk->freed = ptr;
921         }
922 }
923
924 void *
925 ep_alloc0(size_t size)
926 {
927         return memset(ep_alloc(size),'\0',size);
928 }
929
930 void *
931 se_alloc0(size_t size)
932 {
933         return memset(se_alloc(size),'\0',size);
934 }
935
936 void *
937 sl_alloc0(struct ws_memory_slab *mem_chunk)
938 {
939         return memset(sl_alloc(mem_chunk), '\0', mem_chunk->item_size);
940 }
941
942 static gchar *
943 emem_strdup(const gchar *src, void *allocator(size_t))
944 {
945         guint len;
946         gchar *dst;
947
948         /* If str is NULL, just return the string "<NULL>" so that the callers don't
949          * have to bother checking it.
950          */
951         if(!src)
952                 return "<NULL>";
953
954         len = (guint) strlen(src);
955         dst = memcpy(allocator(len+1), src, len+1);
956
957         return dst;
958 }
959
960 gchar *
961 ep_strdup(const gchar *src)
962 {
963         return emem_strdup(src, ep_alloc);
964 }
965
966 gchar *
967 se_strdup(const gchar *src)
968 {
969         return emem_strdup(src, se_alloc);
970 }
971
972 static gchar *
973 emem_strndup(const gchar *src, size_t len, void *allocator(size_t))
974 {
975         gchar *dst = allocator(len+1);
976         guint i;
977
978         for (i = 0; (i < len) && src[i]; i++)
979                 dst[i] = src[i];
980
981         dst[i] = '\0';
982
983         return dst;
984 }
985
986 gchar *
987 ep_strndup(const gchar *src, size_t len)
988 {
989         return emem_strndup(src, len, ep_alloc);
990 }
991
992 gchar *
993 se_strndup(const gchar *src, size_t len)
994 {
995         return emem_strndup(src, len, se_alloc);
996 }
997
998
999
1000 void *
1001 ep_memdup(const void* src, size_t len)
1002 {
1003         return memcpy(ep_alloc(len), src, len);
1004 }
1005
1006 void *
1007 se_memdup(const void* src, size_t len)
1008 {
1009         return memcpy(se_alloc(len), src, len);
1010 }
1011
1012 static gchar *
1013 emem_strdup_vprintf(const gchar *fmt, va_list ap, void *allocator(size_t))
1014 {
1015         va_list ap2;
1016         gsize len;
1017         gchar* dst;
1018
1019         G_VA_COPY(ap2, ap);
1020
1021         len = g_printf_string_upper_bound(fmt, ap);
1022
1023         dst = allocator(len+1);
1024         g_vsnprintf (dst, (gulong) len, fmt, ap2);
1025         va_end(ap2);
1026
1027         return dst;
1028 }
1029
1030 gchar *
1031 ep_strdup_vprintf(const gchar *fmt, va_list ap)
1032 {
1033         return emem_strdup_vprintf(fmt, ap, ep_alloc);
1034 }
1035
1036 gchar *
1037 se_strdup_vprintf(const gchar* fmt, va_list ap)
1038 {
1039         return emem_strdup_vprintf(fmt, ap, se_alloc);
1040 }
1041
1042 gchar *
1043 ep_strdup_printf(const gchar *fmt, ...)
1044 {
1045         va_list ap;
1046         gchar *dst;
1047
1048         va_start(ap, fmt);
1049         dst = ep_strdup_vprintf(fmt, ap);
1050         va_end(ap);
1051         return dst;
1052 }
1053
1054 gchar *
1055 se_strdup_printf(const gchar *fmt, ...)
1056 {
1057         va_list ap;
1058         gchar *dst;
1059
1060         va_start(ap, fmt);
1061         dst = se_strdup_vprintf(fmt, ap);
1062         va_end(ap);
1063         return dst;
1064 }
1065
1066 gchar **
1067 ep_strsplit(const gchar* string, const gchar* sep, int max_tokens)
1068 {
1069         gchar* splitted;
1070         gchar* s;
1071         guint tokens;
1072         guint str_len;
1073         guint sep_len;
1074         guint i;
1075         gchar** vec;
1076         enum { AT_START, IN_PAD, IN_TOKEN } state;
1077         guint curr_tok = 0;
1078
1079         if (    ! string
1080              || ! sep
1081              || ! sep[0])
1082                 return NULL;
1083
1084         s = splitted = ep_strdup(string);
1085         str_len = (guint) strlen(splitted);
1086         sep_len = (guint) strlen(sep);
1087
1088         if (max_tokens < 1) max_tokens = INT_MAX;
1089
1090         tokens = 1;
1091
1092
1093         while (tokens <= (guint)max_tokens && ( s = strstr(s,sep) )) {
1094                 tokens++;
1095
1096                 for(i=0; i < sep_len; i++ )
1097                         s[i] = '\0';
1098
1099                 s += sep_len;
1100
1101         }
1102
1103         vec = ep_alloc_array(gchar*,tokens+1);
1104         state = AT_START;
1105
1106         for (i=0; i< str_len; i++) {
1107                 switch(state) {
1108                         case AT_START:
1109                                 switch(splitted[i]) {
1110                                         case '\0':
1111                                                 state  = IN_PAD;
1112                                                 continue;
1113                                         default:
1114                                                 vec[curr_tok] = &(splitted[i]);
1115                                                 curr_tok++;
1116                                                 state = IN_TOKEN;
1117                                                 continue;
1118                                 }
1119                         case IN_TOKEN:
1120                                 switch(splitted[i]) {
1121                                         case '\0':
1122                                                 state = IN_PAD;
1123                                         default:
1124                                                 continue;
1125                                 }
1126                         case IN_PAD:
1127                                 switch(splitted[i]) {
1128                                         default:
1129                                                 vec[curr_tok] = &(splitted[i]);
1130                                                 curr_tok++;
1131                                                 state = IN_TOKEN;
1132                                         case '\0':
1133                                                 continue;
1134                                 }
1135                 }
1136         }
1137
1138         vec[curr_tok] = NULL;
1139
1140         return vec;
1141 }
1142
1143 gchar *
1144 ep_strconcat(const gchar *string1, ...)
1145 {
1146         gsize   l;
1147         va_list args;
1148         gchar   *s;
1149         gchar   *concat;
1150         gchar   *ptr;
1151
1152         if (!string1)
1153                 return NULL;
1154
1155         l = 1 + strlen(string1);
1156         va_start(args, string1);
1157         s = va_arg(args, gchar*);
1158         while (s) {
1159                 l += strlen(s);
1160                 s = va_arg(args, gchar*);
1161         }
1162         va_end(args);
1163
1164         concat = ep_alloc(l);
1165         ptr = concat;
1166
1167         ptr = g_stpcpy(ptr, string1);
1168         va_start(args, string1);
1169         s = va_arg(args, gchar*);
1170         while (s) {
1171                 ptr = g_stpcpy(ptr, s);
1172                 s = va_arg(args, gchar*);
1173         }
1174         va_end(args);
1175
1176         return concat;
1177 }
1178
1179
1180
1181 /* release all allocated memory back to the pool. */
1182 static void
1183 emem_free_all(emem_header_t *mem)
1184 {
1185         gboolean use_chunks = mem->debug_use_chunks;
1186
1187         emem_chunk_t *npc;
1188         emem_tree_t *tree_list;
1189
1190         /* move all used chunks over to the free list */
1191         while(mem->used_list){
1192                 npc=mem->used_list;
1193                 mem->used_list=mem->used_list->next;
1194                 npc->next=mem->free_list;
1195                 mem->free_list=npc;
1196         }
1197
1198         /* clear them all out */
1199         npc = mem->free_list;
1200         while (npc != NULL) {
1201                 if (use_chunks) {
1202                         while (npc->canary_last != NULL) {
1203                                 npc->canary_last = emem_canary_next(mem->canary, npc->canary_last, NULL);
1204                                 /* XXX, check if canary_last is inside allocated memory? */
1205
1206                                 if (npc->canary_last == (void *) -1)
1207                                         g_error("Memory corrupted");
1208                         }
1209
1210                         emem_scrub_memory((npc->buf + npc->free_offset_init),
1211                                           (npc->free_offset - npc->free_offset_init),
1212                                           FALSE);
1213
1214                         npc->amount_free = npc->amount_free_init;
1215                         npc->free_offset = npc->free_offset_init;
1216                         npc = npc->next;
1217                 } else {
1218                         emem_chunk_t *next = npc->next;
1219
1220                         emem_scrub_memory(npc->buf, npc->amount_free_init, FALSE);
1221
1222                         g_free(npc->buf);
1223                         g_free(npc);
1224                         npc = next;
1225                 }
1226         }
1227
1228         if (!use_chunks) {
1229                 /* We've freed all this memory already */
1230                 mem->free_list = NULL;
1231         }
1232
1233         /* release/reset all allocated trees */
1234         for(tree_list=mem->trees;tree_list;tree_list=tree_list->next){
1235                 tree_list->tree=NULL;
1236         }
1237 }
1238
1239 /* release all allocated memory back to the pool. */
1240 void
1241 ep_free_all(void)
1242 {
1243         emem_free_all(&ep_packet_mem);
1244 }
1245
1246 /* release all allocated memory back to the pool. */
1247 void
1248 se_free_all(void)
1249 {
1250 #ifdef SHOW_EMEM_STATS
1251         print_alloc_stats();
1252 #endif
1253
1254         emem_free_all(&se_packet_mem);
1255 }
1256
1257 void
1258 sl_free_all(struct ws_memory_slab *mem_chunk)
1259 {
1260         emem_chunk_t *chunk_list = mem_chunk->chunk_list;
1261
1262         mem_chunk->chunk_list = NULL;
1263         mem_chunk->freed = NULL;
1264         while (chunk_list) {
1265                 emem_chunk_t *chunk = chunk_list;
1266
1267                 chunk_list = chunk_list->next;
1268                 emem_destroy_chunk(chunk);
1269         }
1270 }
1271
1272 ep_stack_t
1273 ep_stack_new(void) {
1274         ep_stack_t s = ep_new(struct _ep_stack_frame_t*);
1275         *s = ep_new0(struct _ep_stack_frame_t);
1276         return s;
1277 }
1278
1279 /*  for ep_stack_t we'll keep the popped frames so we reuse them instead
1280 of allocating new ones.
1281 */
1282
1283 void *
1284 ep_stack_push(ep_stack_t stack, void* data)
1285 {
1286         struct _ep_stack_frame_t* frame;
1287         struct _ep_stack_frame_t* head = (*stack);
1288
1289         if (head->above) {
1290                 frame = head->above;
1291         } else {
1292                 frame = ep_new(struct _ep_stack_frame_t);
1293                 head->above = frame;
1294                 frame->below = head;
1295                 frame->above = NULL;
1296         }
1297
1298         frame->payload = data;
1299         (*stack) = frame;
1300
1301         return data;
1302 }
1303
1304 void *
1305 ep_stack_pop(ep_stack_t stack)
1306 {
1307
1308         if ((*stack)->below) {
1309                 (*stack) = (*stack)->below;
1310                 return (*stack)->above->payload;
1311         } else {
1312                 return NULL;
1313         }
1314 }
1315
1316 emem_tree_t *
1317 se_tree_create(int type, const char *name)
1318 {
1319         emem_tree_t *tree_list;
1320
1321         tree_list=g_malloc(sizeof(emem_tree_t));
1322         tree_list->next=se_packet_mem.trees;
1323         tree_list->type=type;
1324         tree_list->tree=NULL;
1325         tree_list->name=name;
1326         tree_list->malloc=se_alloc;
1327         se_packet_mem.trees=tree_list;
1328
1329         return tree_list;
1330 }
1331
1332 void *
1333 emem_tree_lookup32(emem_tree_t *se_tree, guint32 key)
1334 {
1335         emem_tree_node_t *node;
1336
1337         node=se_tree->tree;
1338
1339         while(node){
1340                 if(key==node->key32){
1341                         return node->data;
1342                 }
1343                 if(key<node->key32){
1344                         node=node->left;
1345                         continue;
1346                 }
1347                 if(key>node->key32){
1348                         node=node->right;
1349                         continue;
1350                 }
1351         }
1352         return NULL;
1353 }
1354
1355 void *
1356 emem_tree_lookup32_le(emem_tree_t *se_tree, guint32 key)
1357 {
1358         emem_tree_node_t *node;
1359
1360         node=se_tree->tree;
1361
1362         if(!node){
1363                 return NULL;
1364         }
1365
1366
1367         while(node){
1368                 if(key==node->key32){
1369                         return node->data;
1370                 }
1371                 if(key<node->key32){
1372                         if(node->left){
1373                                 node=node->left;
1374                                 continue;
1375                         } else {
1376                                 break;
1377                         }
1378                 }
1379                 if(key>node->key32){
1380                         if(node->right){
1381                                 node=node->right;
1382                                 continue;
1383                         } else {
1384                                 break;
1385                         }
1386                 }
1387         }
1388
1389
1390         if(!node){
1391                 return NULL;
1392         }
1393
1394         /* If we are still at the root of the tree this means that this node
1395          * is either smaller than the search key and then we return this
1396          * node or else there is no smaller key available and then
1397          * we return NULL.
1398          */
1399         if(!node->parent){
1400                 if(key>node->key32){
1401                         return node->data;
1402                 } else {
1403                         return NULL;
1404                 }
1405         }
1406
1407         if(node->parent->left==node){
1408                 /* left child */
1409
1410                 if(key>node->key32){
1411                         /* if this is a left child and its key is smaller than
1412                          * the search key, then this is the node we want.
1413                          */
1414                         return node->data;
1415                 } else {
1416                         /* if this is a left child and its key is bigger than
1417                          * the search key, we have to check if any
1418                          * of our ancestors are smaller than the search key.
1419                          */
1420                         while(node){
1421                                 if(key>node->key32){
1422                                         return node->data;
1423                                 }
1424                                 node=node->parent;
1425                         }
1426                         return NULL;
1427                 }
1428         } else {
1429                 /* right child */
1430
1431                 if(node->key32<key){
1432                         /* if this is the right child and its key is smaller
1433                          * than the search key then this is the one we want.
1434                          */
1435                         return node->data;
1436                 } else {
1437                         /* if this is the right child and its key is larger
1438                          * than the search key then our parent is the one we
1439                          * want.
1440                          */
1441                         return node->parent->data;
1442                 }
1443         }
1444
1445 }
1446
1447
1448 static inline emem_tree_node_t *
1449 emem_tree_parent(emem_tree_node_t *node)
1450 {
1451         return node->parent;
1452 }
1453
1454 static inline emem_tree_node_t *
1455 emem_tree_grandparent(emem_tree_node_t *node)
1456 {
1457         emem_tree_node_t *parent;
1458
1459         parent=emem_tree_parent(node);
1460         if(parent){
1461                 return parent->parent;
1462         }
1463         return NULL;
1464 }
1465
1466 static inline emem_tree_node_t *
1467 emem_tree_uncle(emem_tree_node_t *node)
1468 {
1469         emem_tree_node_t *parent, *grandparent;
1470
1471         parent=emem_tree_parent(node);
1472         if(!parent){
1473                 return NULL;
1474         }
1475         grandparent=emem_tree_parent(parent);
1476         if(!grandparent){
1477                 return NULL;
1478         }
1479         if(parent==grandparent->left){
1480                 return grandparent->right;
1481         }
1482         return grandparent->left;
1483 }
1484
1485 static inline void rb_insert_case1(emem_tree_t *se_tree, emem_tree_node_t *node);
1486 static inline void rb_insert_case2(emem_tree_t *se_tree, emem_tree_node_t *node);
1487
1488 static inline void
1489 rotate_left(emem_tree_t *se_tree, emem_tree_node_t *node)
1490 {
1491         if(node->parent){
1492                 if(node->parent->left==node){
1493                         node->parent->left=node->right;
1494                 } else {
1495                         node->parent->right=node->right;
1496                 }
1497         } else {
1498                 se_tree->tree=node->right;
1499         }
1500         node->right->parent=node->parent;
1501         node->parent=node->right;
1502         node->right=node->right->left;
1503         if(node->right){
1504                 node->right->parent=node;
1505         }
1506         node->parent->left=node;
1507 }
1508
1509 static inline void
1510 rotate_right(emem_tree_t *se_tree, emem_tree_node_t *node)
1511 {
1512         if(node->parent){
1513                 if(node->parent->left==node){
1514                         node->parent->left=node->left;
1515                 } else {
1516                         node->parent->right=node->left;
1517                 }
1518         } else {
1519                 se_tree->tree=node->left;
1520         }
1521         node->left->parent=node->parent;
1522         node->parent=node->left;
1523         node->left=node->left->right;
1524         if(node->left){
1525                 node->left->parent=node;
1526         }
1527         node->parent->right=node;
1528 }
1529
1530 static inline void
1531 rb_insert_case5(emem_tree_t *se_tree, emem_tree_node_t *node)
1532 {
1533         emem_tree_node_t *grandparent;
1534         emem_tree_node_t *parent;
1535
1536         parent=emem_tree_parent(node);
1537         grandparent=emem_tree_parent(parent);
1538         parent->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1539         grandparent->u.rb_color=EMEM_TREE_RB_COLOR_RED;
1540         if( (node==parent->left) && (parent==grandparent->left) ){
1541                 rotate_right(se_tree, grandparent);
1542         } else {
1543                 rotate_left(se_tree, grandparent);
1544         }
1545 }
1546
1547 static inline void
1548 rb_insert_case4(emem_tree_t *se_tree, emem_tree_node_t *node)
1549 {
1550         emem_tree_node_t *grandparent;
1551         emem_tree_node_t *parent;
1552
1553         parent=emem_tree_parent(node);
1554         grandparent=emem_tree_parent(parent);
1555         if(!grandparent){
1556                 return;
1557         }
1558         if( (node==parent->right) && (parent==grandparent->left) ){
1559                 rotate_left(se_tree, parent);
1560                 node=node->left;
1561         } else if( (node==parent->left) && (parent==grandparent->right) ){
1562                 rotate_right(se_tree, parent);
1563                 node=node->right;
1564         }
1565         rb_insert_case5(se_tree, node);
1566 }
1567
1568 static inline void
1569 rb_insert_case3(emem_tree_t *se_tree, emem_tree_node_t *node)
1570 {
1571         emem_tree_node_t *grandparent;
1572         emem_tree_node_t *parent;
1573         emem_tree_node_t *uncle;
1574
1575         uncle=emem_tree_uncle(node);
1576         if(uncle && (uncle->u.rb_color==EMEM_TREE_RB_COLOR_RED)){
1577                 parent=emem_tree_parent(node);
1578                 parent->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1579                 uncle->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1580                 grandparent=emem_tree_grandparent(node);
1581                 grandparent->u.rb_color=EMEM_TREE_RB_COLOR_RED;
1582                 rb_insert_case1(se_tree, grandparent);
1583         } else {
1584                 rb_insert_case4(se_tree, node);
1585         }
1586 }
1587
1588 static inline void
1589 rb_insert_case2(emem_tree_t *se_tree, emem_tree_node_t *node)
1590 {
1591         emem_tree_node_t *parent;
1592
1593         parent=emem_tree_parent(node);
1594         /* parent is always non-NULL here */
1595         if(parent->u.rb_color==EMEM_TREE_RB_COLOR_BLACK){
1596                 return;
1597         }
1598         rb_insert_case3(se_tree, node);
1599 }
1600
1601 static inline void
1602 rb_insert_case1(emem_tree_t *se_tree, emem_tree_node_t *node)
1603 {
1604         emem_tree_node_t *parent;
1605
1606         parent=emem_tree_parent(node);
1607         if(!parent){
1608                 node->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1609                 return;
1610         }
1611         rb_insert_case2(se_tree, node);
1612 }
1613
1614 /* insert a new node in the tree. if this node matches an already existing node
1615  * then just replace the data for that node */
1616 void
1617 emem_tree_insert32(emem_tree_t *se_tree, guint32 key, void *data)
1618 {
1619         emem_tree_node_t *node;
1620
1621         node=se_tree->tree;
1622
1623         /* is this the first node ?*/
1624         if(!node){
1625                 node=se_tree->malloc(sizeof(emem_tree_node_t));
1626                 switch(se_tree->type){
1627                 case EMEM_TREE_TYPE_RED_BLACK:
1628                         node->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1629                         break;
1630                 }
1631                 node->parent=NULL;
1632                 node->left=NULL;
1633                 node->right=NULL;
1634                 node->key32=key;
1635                 node->data=data;
1636                 node->u.is_subtree = EMEM_TREE_NODE_IS_DATA;
1637                 se_tree->tree=node;
1638                 return;
1639         }
1640
1641         /* it was not the new root so walk the tree until we find where to
1642          * insert this new leaf.
1643          */
1644         while(1){
1645                 /* this node already exists, so just replace the data pointer*/
1646                 if(key==node->key32){
1647                         node->data=data;
1648                         return;
1649                 }
1650                 if(key<node->key32) {
1651                         if(!node->left){
1652                                 /* new node to the left */
1653                                 emem_tree_node_t *new_node;
1654                                 new_node=se_tree->malloc(sizeof(emem_tree_node_t));
1655                                 node->left=new_node;
1656                                 new_node->parent=node;
1657                                 new_node->left=NULL;
1658                                 new_node->right=NULL;
1659                                 new_node->key32=key;
1660                                 new_node->data=data;
1661                                 new_node->u.is_subtree=EMEM_TREE_NODE_IS_DATA;
1662                                 node=new_node;
1663                                 break;
1664                         }
1665                         node=node->left;
1666                         continue;
1667                 }
1668                 if(key>node->key32) {
1669                         if(!node->right){
1670                                 /* new node to the right */
1671                                 emem_tree_node_t *new_node;
1672                                 new_node=se_tree->malloc(sizeof(emem_tree_node_t));
1673                                 node->right=new_node;
1674                                 new_node->parent=node;
1675                                 new_node->left=NULL;
1676                                 new_node->right=NULL;
1677                                 new_node->key32=key;
1678                                 new_node->data=data;
1679                                 new_node->u.is_subtree=EMEM_TREE_NODE_IS_DATA;
1680                                 node=new_node;
1681                                 break;
1682                         }
1683                         node=node->right;
1684                         continue;
1685                 }
1686         }
1687
1688         /* node will now point to the newly created node */
1689         switch(se_tree->type){
1690         case EMEM_TREE_TYPE_RED_BLACK:
1691                 node->u.rb_color=EMEM_TREE_RB_COLOR_RED;
1692                 rb_insert_case1(se_tree, node);
1693                 break;
1694         }
1695 }
1696
1697 static void *
1698 lookup_or_insert32(emem_tree_t *se_tree, guint32 key, void*(*func)(void*),void* ud, int is_subtree)
1699 {
1700         emem_tree_node_t *node;
1701
1702         node=se_tree->tree;
1703
1704         /* is this the first node ?*/
1705         if(!node){
1706                 node=se_tree->malloc(sizeof(emem_tree_node_t));
1707                 switch(se_tree->type){
1708                         case EMEM_TREE_TYPE_RED_BLACK:
1709                                 node->u.rb_color=EMEM_TREE_RB_COLOR_BLACK;
1710                                 break;
1711                 }
1712                 node->parent=NULL;
1713                 node->left=NULL;
1714                 node->right=NULL;
1715                 node->key32=key;
1716                 node->data= func(ud);
1717                 node->u.is_subtree = is_subtree;
1718                 se_tree->tree=node;
1719                 return node->data;
1720         }
1721
1722         /* it was not the new root so walk the tree until we find where to
1723                 * insert this new leaf.
1724                 */
1725         while(1){
1726                 /* this node already exists, so just return the data pointer*/
1727                 if(key==node->key32){
1728                         return node->data;
1729                 }
1730                 if(key<node->key32) {
1731                         if(!node->left){
1732                                 /* new node to the left */
1733                                 emem_tree_node_t *new_node;
1734                                 new_node=se_tree->malloc(sizeof(emem_tree_node_t));
1735                                 node->left=new_node;
1736                                 new_node->parent=node;
1737                                 new_node->left=NULL;
1738                                 new_node->right=NULL;
1739                                 new_node->key32=key;
1740                                 new_node->data= func(ud);
1741                                 new_node->u.is_subtree = is_subtree;
1742                                 node=new_node;
1743                                 break;
1744                         }
1745                         node=node->left;
1746                         continue;
1747                 }
1748                 if(key>node->key32) {
1749                         if(!node->right){
1750                                 /* new node to the right */
1751                                 emem_tree_node_t *new_node;
1752                                 new_node=se_tree->malloc(sizeof(emem_tree_node_t));
1753                                 node->right=new_node;
1754                                 new_node->parent=node;
1755                                 new_node->left=NULL;
1756                                 new_node->right=NULL;
1757                                 new_node->key32=key;
1758                                 new_node->data= func(ud);
1759                                 new_node->u.is_subtree = is_subtree;
1760                                 node=new_node;
1761                                 break;
1762                         }
1763                         node=node->right;
1764                         continue;
1765                 }
1766         }
1767
1768         /* node will now point to the newly created node */
1769         switch(se_tree->type){
1770                 case EMEM_TREE_TYPE_RED_BLACK:
1771                         node->u.rb_color=EMEM_TREE_RB_COLOR_RED;
1772                         rb_insert_case1(se_tree, node);
1773                         break;
1774         }
1775
1776         return node->data;
1777 }
1778
1779 /* When the se data is released, this entire tree will dissapear as if it
1780  * never existed including all metadata associated with the tree.
1781  */
1782 emem_tree_t *
1783 se_tree_create_non_persistent(int type, const char *name)
1784 {
1785         emem_tree_t *tree_list;
1786
1787         tree_list=se_alloc(sizeof(emem_tree_t));
1788         tree_list->next=NULL;
1789         tree_list->type=type;
1790         tree_list->tree=NULL;
1791         tree_list->name=name;
1792         tree_list->malloc=se_alloc;
1793
1794         return tree_list;
1795 }
1796
1797 /* This tree is PErmanent and will never be released
1798  */
1799 emem_tree_t *
1800 pe_tree_create(int type, const char *name)
1801 {
1802         emem_tree_t *tree_list;
1803
1804         tree_list=g_new(emem_tree_t, 1);
1805         tree_list->next=NULL;
1806         tree_list->type=type;
1807         tree_list->tree=NULL;
1808         tree_list->name=name;
1809         tree_list->malloc=(void *(*)(size_t)) g_malloc;
1810
1811         return tree_list;
1812 }
1813
1814 /* create another (sub)tree using the same memory allocation scope
1815  * as the parent tree.
1816  */
1817 static emem_tree_t *
1818 emem_tree_create_subtree(emem_tree_t *parent_tree, const char *name)
1819 {
1820         emem_tree_t *tree_list;
1821
1822         tree_list=parent_tree->malloc(sizeof(emem_tree_t));
1823         tree_list->next=NULL;
1824         tree_list->type=parent_tree->type;
1825         tree_list->tree=NULL;
1826         tree_list->name=name;
1827         tree_list->malloc=parent_tree->malloc;
1828
1829         return tree_list;
1830 }
1831
1832 static void *
1833 create_sub_tree(void* d)
1834 {
1835         emem_tree_t *se_tree = d;
1836         return emem_tree_create_subtree(se_tree, "subtree");
1837 }
1838
1839 /* insert a new node in the tree. if this node matches an already existing node
1840  * then just replace the data for that node */
1841
1842 void
1843 emem_tree_insert32_array(emem_tree_t *se_tree, emem_tree_key_t *key, void *data)
1844 {
1845         emem_tree_t *next_tree;
1846
1847         if((key[0].length<1)||(key[0].length>100)){
1848                 DISSECTOR_ASSERT_NOT_REACHED();
1849         }
1850         if((key[0].length==1)&&(key[1].length==0)){
1851                 emem_tree_insert32(se_tree, *key[0].key, data);
1852                 return;
1853         }
1854
1855         next_tree=lookup_or_insert32(se_tree, *key[0].key, create_sub_tree, se_tree, EMEM_TREE_NODE_IS_SUBTREE);
1856
1857         if(key[0].length==1){
1858                 key++;
1859         } else {
1860                 key[0].length--;
1861                 key[0].key++;
1862         }
1863         emem_tree_insert32_array(next_tree, key, data);
1864 }
1865
1866 void *
1867 emem_tree_lookup32_array(emem_tree_t *se_tree, emem_tree_key_t *key)
1868 {
1869         emem_tree_t *next_tree;
1870
1871         if(!se_tree || !key) return NULL; /* prevent searching on NULL pointer */
1872
1873         if((key[0].length<1)||(key[0].length>100)){
1874                 DISSECTOR_ASSERT_NOT_REACHED();
1875         }
1876         if((key[0].length==1)&&(key[1].length==0)){
1877                 return emem_tree_lookup32(se_tree, *key[0].key);
1878         }
1879         next_tree=emem_tree_lookup32(se_tree, *key[0].key);
1880         if(!next_tree){
1881                 return NULL;
1882         }
1883         if(key[0].length==1){
1884                 key++;
1885         } else {
1886                 key[0].length--;
1887                 key[0].key++;
1888         }
1889         return emem_tree_lookup32_array(next_tree, key);
1890 }
1891
1892 void *
1893 emem_tree_lookup32_array_le(emem_tree_t *se_tree, emem_tree_key_t *key)
1894 {
1895         emem_tree_t *next_tree;
1896
1897         if(!se_tree || !key) return NULL; /* prevent searching on NULL pointer */
1898
1899         if((key[0].length<1)||(key[0].length>100)){
1900                 DISSECTOR_ASSERT_NOT_REACHED();
1901         }
1902         if((key[0].length==1)&&(key[1].length==0)){ /* last key in key array */
1903                 return emem_tree_lookup32_le(se_tree, *key[0].key);
1904         }
1905         next_tree=emem_tree_lookup32(se_tree, *key[0].key);
1906         /* key[0].key not found so find le and return */
1907         if(!next_tree)
1908                 return emem_tree_lookup32_le(se_tree, *key[0].key);
1909
1910         /* key[0].key found so inc key pointer and try again */
1911         if(key[0].length==1){
1912                 key++;
1913         } else {
1914                 key[0].length--;
1915                 key[0].key++;
1916         }
1917         return emem_tree_lookup32_array_le(next_tree, key);
1918 }
1919
1920 /* Strings are stored as an array of uint32 containing the string characters
1921    with 4 characters in each uint32.
1922    The first byte of the string is stored as the most significant byte.
1923    If the string is not a multiple of 4 characters in length the last
1924    uint32 containing the string bytes are padded with 0 bytes.
1925    After the uint32's containing the string, there is one final terminator
1926    uint32 with the value 0x00000001
1927 */
1928 void
1929 emem_tree_insert_string(emem_tree_t* se_tree, const gchar* k, void* v, guint32 flags)
1930 {
1931         emem_tree_key_t key[2];
1932         guint32 *aligned=NULL;
1933         guint32 len = (guint32) strlen(k);
1934         guint32 divx = (len+3)/4+1;
1935         guint32 i;
1936         guint32 tmp;
1937
1938         aligned = g_malloc(divx * sizeof (guint32));
1939
1940         /* pack the bytes one one by one into guint32s */
1941         tmp = 0;
1942         for (i = 0;i < len;i++) {
1943                 unsigned char ch;
1944
1945                 ch = (unsigned char)k[i];
1946                 if (flags & EMEM_TREE_STRING_NOCASE) {
1947                         if(isupper(ch)) {
1948                                 ch = tolower(ch);
1949                         }
1950                 }
1951                 tmp <<= 8;
1952                 tmp |= ch;
1953                 if (i%4 == 3) {
1954                         aligned[i/4] = tmp;
1955                         tmp = 0;
1956                 }
1957         }
1958         /* add required padding to the last uint32 */
1959         if (i%4 != 0) {
1960                 while (i%4 != 0) {
1961                         i++;
1962                         tmp <<= 8;
1963                 }
1964                 aligned[i/4-1] = tmp;
1965         }
1966
1967         /* add the terminator */
1968         aligned[divx-1] = 0x00000001;
1969
1970         key[0].length = divx;
1971         key[0].key = aligned;
1972         key[1].length = 0;
1973         key[1].key = NULL;
1974
1975
1976         emem_tree_insert32_array(se_tree, key, v);
1977         g_free(aligned);
1978 }
1979
1980 void *
1981 emem_tree_lookup_string(emem_tree_t* se_tree, const gchar* k, guint32 flags)
1982 {
1983         emem_tree_key_t key[2];
1984         guint32 *aligned=NULL;
1985         guint32 len = (guint) strlen(k);
1986         guint32 divx = (len+3)/4+1;
1987         guint32 i;
1988         guint32 tmp;
1989         void *ret;
1990
1991         aligned = g_malloc(divx * sizeof (guint32));
1992
1993         /* pack the bytes one one by one into guint32s */
1994         tmp = 0;
1995         for (i = 0;i < len;i++) {
1996                 unsigned char ch;
1997
1998                 ch = (unsigned char)k[i];
1999                 if (flags & EMEM_TREE_STRING_NOCASE) {
2000                         if(isupper(ch)) {
2001                                 ch = tolower(ch);
2002                         }
2003                 }
2004                 tmp <<= 8;
2005                 tmp |= ch;
2006                 if (i%4 == 3) {
2007                         aligned[i/4] = tmp;
2008                         tmp = 0;
2009                 }
2010         }
2011         /* add required padding to the last uint32 */
2012         if (i%4 != 0) {
2013                 while (i%4 != 0) {
2014                         i++;
2015                         tmp <<= 8;
2016                 }
2017                 aligned[i/4-1] = tmp;
2018         }
2019
2020         /* add the terminator */
2021         aligned[divx-1] = 0x00000001;
2022
2023         key[0].length = divx;
2024         key[0].key = aligned;
2025         key[1].length = 0;
2026         key[1].key = NULL;
2027
2028
2029         ret = emem_tree_lookup32_array(se_tree, key);
2030         g_free(aligned);
2031         return ret;
2032 }
2033
2034 static gboolean
2035 emem_tree_foreach_nodes(emem_tree_node_t* node, tree_foreach_func callback, void *user_data)
2036 {
2037         gboolean stop_traverse = FALSE;
2038
2039         if (!node)
2040                 return FALSE;
2041
2042         if(node->left) {
2043                 stop_traverse = emem_tree_foreach_nodes(node->left, callback, user_data);
2044                 if (stop_traverse) {
2045                         return TRUE;
2046                 }
2047         }
2048
2049         if (node->u.is_subtree == EMEM_TREE_NODE_IS_SUBTREE) {
2050                 stop_traverse = emem_tree_foreach(node->data, callback, user_data);
2051         } else {
2052                 stop_traverse = callback(node->data, user_data);
2053         }
2054
2055         if (stop_traverse) {
2056                 return TRUE;
2057         }
2058
2059         if(node->right) {
2060                 stop_traverse = emem_tree_foreach_nodes(node->right, callback, user_data);
2061                 if (stop_traverse) {
2062                         return TRUE;
2063                 }
2064         }
2065
2066         return FALSE;
2067 }
2068
2069 gboolean
2070 emem_tree_foreach(emem_tree_t* emem_tree, tree_foreach_func callback, void *user_data)
2071 {
2072         if (!emem_tree)
2073                 return FALSE;
2074
2075         if(!emem_tree->tree)
2076                 return FALSE;
2077
2078         return emem_tree_foreach_nodes(emem_tree->tree, callback, user_data);
2079 }
2080
2081
2082 static void
2083 emem_tree_print_nodes(emem_tree_node_t* node, int level)
2084 {
2085         int i;
2086
2087         if (!node)
2088                 return;
2089
2090         for(i=0;i<level;i++){
2091                 printf("    ");
2092         }
2093
2094         printf("NODE:%p parent:%p left:0x%p right:%px key:%d data:%p\n",
2095                 (void *)node,(void *)(node->parent),(void *)(node->left),(void *)(node->right),
2096                 (node->key32),node->data);
2097         if(node->left)
2098                 emem_tree_print_nodes(node->left, level+1);
2099         if(node->right)
2100                 emem_tree_print_nodes(node->right, level+1);
2101 }
2102 void
2103 emem_print_tree(emem_tree_t* emem_tree)
2104 {
2105         if (!emem_tree)
2106                 return;
2107
2108         printf("EMEM tree type:%d name:%s tree:%p\n",emem_tree->type,emem_tree->name,(void *)(emem_tree->tree));
2109         if(emem_tree->tree)
2110                 emem_tree_print_nodes(emem_tree->tree, 0);
2111 }
2112
2113 /*
2114  * String buffers
2115  */
2116
2117 /*
2118  * Presumably we're using these routines for building strings for the tree.
2119  * Use ITEM_LABEL_LENGTH as the basis for our default lengths.
2120  */
2121
2122 #define DEFAULT_STRBUF_LEN (ITEM_LABEL_LENGTH / 10)
2123 #define MAX_STRBUF_LEN 65536
2124
2125 static gsize
2126 next_size(gsize cur_alloc_len, gsize wanted_alloc_len, gsize max_alloc_len)
2127 {
2128         if (max_alloc_len < 1 || max_alloc_len > MAX_STRBUF_LEN) {
2129                 max_alloc_len = MAX_STRBUF_LEN;
2130         }
2131
2132         if (cur_alloc_len < 1) {
2133                 cur_alloc_len = DEFAULT_STRBUF_LEN;
2134         }
2135
2136         while (cur_alloc_len < wanted_alloc_len) {
2137                 cur_alloc_len *= 2;
2138         }
2139
2140         return cur_alloc_len < max_alloc_len ? cur_alloc_len : max_alloc_len;
2141 }
2142
2143 static void
2144 ep_strbuf_grow(emem_strbuf_t *strbuf, gsize wanted_alloc_len)
2145 {
2146         gsize new_alloc_len;
2147         gchar *new_str;
2148
2149         if (!strbuf || (wanted_alloc_len <= strbuf->alloc_len) || (strbuf->alloc_len >= strbuf->max_alloc_len)) {
2150                 return;
2151         }
2152
2153         new_alloc_len = next_size(strbuf->alloc_len, wanted_alloc_len, strbuf->max_alloc_len);
2154         new_str = ep_alloc(new_alloc_len);
2155         g_strlcpy(new_str, strbuf->str, new_alloc_len);
2156
2157         strbuf->alloc_len = new_alloc_len;
2158         strbuf->str = new_str;
2159 }
2160
2161 emem_strbuf_t *
2162 ep_strbuf_sized_new(gsize alloc_len, gsize max_alloc_len)
2163 {
2164         emem_strbuf_t *strbuf;
2165
2166         strbuf = ep_alloc(sizeof(emem_strbuf_t));
2167
2168         if ((max_alloc_len == 0) || (max_alloc_len > MAX_STRBUF_LEN))
2169                 max_alloc_len = MAX_STRBUF_LEN;
2170         if (alloc_len == 0)
2171                 alloc_len = 1;
2172         else if (alloc_len > max_alloc_len)
2173                 alloc_len = max_alloc_len;
2174
2175         strbuf->str = ep_alloc(alloc_len);
2176         strbuf->str[0] = '\0';
2177
2178         strbuf->len = 0;
2179         strbuf->alloc_len = alloc_len;
2180         strbuf->max_alloc_len = max_alloc_len;
2181
2182         return strbuf;
2183 }
2184
2185 emem_strbuf_t *
2186 ep_strbuf_new(const gchar *init)
2187 {
2188         emem_strbuf_t *strbuf;
2189
2190         strbuf = ep_strbuf_sized_new(next_size(0, init?strlen(init)+1:0, 0), 0);  /* +1 for NULL terminator */
2191         if (init) {
2192                 gsize full_len;
2193                 full_len = g_strlcpy(strbuf->str, init, strbuf->alloc_len);
2194                 strbuf->len = MIN(full_len, strbuf->alloc_len-1);
2195         }
2196
2197         return strbuf;
2198 }
2199
2200 emem_strbuf_t *
2201 ep_strbuf_new_label(const gchar *init)
2202 {
2203         emem_strbuf_t *strbuf;
2204         gsize full_len;
2205
2206         /* Be optimistic: Allocate default size strbuf string and only      */
2207         /*  request an increase if needed.                                  */
2208         /* XXX: Is it reasonable to assume that much of the usage of        */
2209         /*  ep_strbuf_new_label will have  init==NULL or                    */
2210         /*   strlen(init) < DEFAULT_STRBUF_LEN) ???                         */
2211         strbuf = ep_strbuf_sized_new(DEFAULT_STRBUF_LEN, ITEM_LABEL_LENGTH);
2212
2213         if (!init)
2214                 return strbuf;
2215
2216         /* full_len does not count the trailing '\0'.                       */
2217         full_len = g_strlcpy(strbuf->str, init, strbuf->alloc_len);
2218         if (full_len < strbuf->alloc_len) {
2219                 strbuf->len += full_len;
2220         } else {
2221                 strbuf = ep_strbuf_sized_new(full_len+1, ITEM_LABEL_LENGTH);
2222                 full_len = g_strlcpy(strbuf->str, init, strbuf->alloc_len);
2223                 strbuf->len = MIN(full_len, strbuf->alloc_len-1);
2224         }
2225
2226         return strbuf;
2227 }
2228
2229 emem_strbuf_t *
2230 ep_strbuf_append(emem_strbuf_t *strbuf, const gchar *str)
2231 {
2232         gsize add_len, full_len;
2233
2234         if (!strbuf || !str || str[0] == '\0') {
2235                 return strbuf;
2236         }
2237
2238         /* Be optimistic; try the g_strlcpy first & see if enough room.                 */
2239         /* Note: full_len doesn't count the trailing '\0'; add_len does allow for same  */
2240         add_len = strbuf->alloc_len - strbuf->len;
2241         full_len = g_strlcpy(&strbuf->str[strbuf->len], str, add_len);
2242         if (full_len < add_len) {
2243                 strbuf->len += full_len;
2244         } else {
2245                 strbuf->str[strbuf->len] = '\0'; /* end string at original length again */
2246                 ep_strbuf_grow(strbuf, strbuf->len + full_len + 1);
2247                 add_len = strbuf->alloc_len - strbuf->len;
2248                 full_len = g_strlcpy(&strbuf->str[strbuf->len], str, add_len);
2249                 strbuf->len += MIN(add_len-1, full_len);
2250         }
2251
2252         return strbuf;
2253 }
2254
2255 void
2256 ep_strbuf_append_vprintf(emem_strbuf_t *strbuf, const gchar *format, va_list ap)
2257 {
2258         va_list ap2;
2259         gsize add_len, full_len;
2260
2261         G_VA_COPY(ap2, ap);
2262
2263         /* Be optimistic; try the g_vsnprintf first & see if enough room.               */
2264         /* Note: full_len doesn't count the trailing '\0'; add_len does allow for same. */
2265         add_len = strbuf->alloc_len - strbuf->len;
2266         full_len = g_vsnprintf(&strbuf->str[strbuf->len], (gulong) add_len, format, ap);
2267         if (full_len < add_len) {
2268                 strbuf->len += full_len;
2269         } else {
2270                 strbuf->str[strbuf->len] = '\0'; /* end string at original length again */
2271                 ep_strbuf_grow(strbuf, strbuf->len + full_len + 1);
2272                 add_len = strbuf->alloc_len - strbuf->len;
2273                 full_len = g_vsnprintf(&strbuf->str[strbuf->len], (gulong) add_len, format, ap2);
2274                 strbuf->len += MIN(add_len-1, full_len);
2275         }
2276
2277         va_end(ap2);
2278 }
2279
2280 void
2281 ep_strbuf_append_printf(emem_strbuf_t *strbuf, const gchar *format, ...)
2282 {
2283         va_list ap;
2284
2285         va_start(ap, format);
2286         ep_strbuf_append_vprintf(strbuf, format, ap);
2287         va_end(ap);
2288 }
2289
2290 void
2291 ep_strbuf_printf(emem_strbuf_t *strbuf, const gchar *format, ...)
2292 {
2293         va_list ap;
2294         if (!strbuf) {
2295                 return;
2296         }
2297
2298         strbuf->len = 0;
2299
2300         va_start(ap, format);
2301         ep_strbuf_append_vprintf(strbuf, format, ap);
2302         va_end(ap);
2303 }
2304
2305 emem_strbuf_t *
2306 ep_strbuf_append_c(emem_strbuf_t *strbuf, const gchar c)
2307 {
2308         if (!strbuf) {
2309                 return strbuf;
2310         }
2311
2312         /* +1 for the new character & +1 for the trailing '\0'. */
2313         if (strbuf->alloc_len < strbuf->len + 1 + 1) {
2314                 ep_strbuf_grow(strbuf, strbuf->len + 1 + 1);
2315         }
2316         if (strbuf->alloc_len >= strbuf->len + 1 + 1) {
2317                 strbuf->str[strbuf->len] = c;
2318                 strbuf->len++;
2319                 strbuf->str[strbuf->len] = '\0';
2320         }
2321
2322         return strbuf;
2323 }
2324
2325 emem_strbuf_t *
2326 ep_strbuf_truncate(emem_strbuf_t *strbuf, gsize len)
2327 {
2328         if (!strbuf || len >= strbuf->len) {
2329                 return strbuf;
2330         }
2331
2332         strbuf->str[len] = '\0';
2333         strbuf->len = len;
2334
2335         return strbuf;
2336 }
2337
2338 /*
2339  * Editor modelines
2340  *
2341  * Local Variables:
2342  * c-basic-offset: 8
2343  * tab-width: 8
2344  * indent-tabs-mode: t
2345  * End:
2346  *
2347  * ex: set shiftwidth=8 tabstop=8 noexpandtab:
2348  * :indentSize=8:tabSize=8:noTabs=false:
2349  */