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