Add ep_verify_pointer()/se_verify_pointer() which checks whether the given pointer...
[metze/wireshark/wip.git] / epan / emem.h
1 /* emem.h
2  * Definitions for Wireshark memory management and garbage collection
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
26 #ifndef __EMEM_H__
27 #define __EMEM_H__
28
29 #include "gnuc_format_check.h"
30
31 /* Functions for handling memory allocation and garbage collection with
32  * a packet lifetime scope.
33  * These functions are used to allocate memory that will only remain persistent
34  * until Wireshark starts dissecting the next packet in the list.
35  * Everytime Wireshark starts decoding the next packet all memory allocated
36  * through these functions will be released back to the free pool.
37  *
38  * These functions are very fast and offer automatic garbage collection:
39  * Everytime a new packet is dissected, all memory allocations done in
40  * the previous packet is freed.
41  */
42 /* Initialize packet-lifetime memory allocation pool. This function is called
43  * once when [t]Wireshark is initialized to set up the required structures.
44  */
45 void ep_init_chunk(void);
46
47 /* Allocate memory with a packet lifetime scope */
48 void *ep_alloc(size_t size);
49 #define ep_new(type) ((type*)ep_alloc(sizeof(type)))
50
51 /* Allocate memory with a packet lifetime scope and fill it with zeros*/
52 void* ep_alloc0(size_t size);
53 #define ep_new0(type) ((type*)ep_alloc0(sizeof(type)))
54
55 /* Duplicate a string with a packet lifetime scope */
56 gchar* ep_strdup(const gchar* src);
57
58 /* Duplicate at most n characters of a string with a packet lifetime scope */
59 gchar* ep_strndup(const gchar* src, size_t len);
60
61 /* Duplicate a buffer with a packet lifetime scope */
62 void* ep_memdup(const void* src, size_t len);
63
64 /* Create a formatted string with a packet lifetime scope */
65 gchar* ep_strdup_vprintf(const gchar* fmt, va_list ap);
66 gchar* ep_strdup_printf(const gchar* fmt, ...)
67     GNUC_FORMAT_CHECK(printf, 1, 2);
68
69 /* allocates with a packet lifetime scope an array of type made of num elements */
70 #define ep_alloc_array(type,num) (type*)ep_alloc(sizeof(type)*(num))
71
72 /* allocates with a packet lifetime scope an array of type made of num elements,
73  * initialised to zero.
74  */
75 #define ep_alloc_array0(type,num) (type*)ep_alloc0(sizeof(type)*(num))
76
77 /*
78  * Splits a string into a maximum of max_tokens pieces, using the given
79  * delimiter. If max_tokens is reached, the remainder of string is appended
80  * to the last token. Consecutive delimiters are treated as a single delimiter.
81  *
82  * the vector and all the strings are allocated with packet lifetime scope
83  */
84 gchar** ep_strsplit(const gchar* string, const gchar* delimiter, int max_tokens);
85
86 /* release all memory allocated in the previous packet dissector */
87 void ep_free_all(void);
88
89
90 /* a stack implemented using ephemeral allocators */
91
92 typedef struct _ep_stack_frame_t** ep_stack_t;
93
94 struct _ep_stack_frame_t {
95     void* payload;
96     struct _ep_stack_frame_t* below;
97     struct _ep_stack_frame_t* above;
98 };
99
100 /*
101  * creates an empty stack with a packet lifetime scope
102  */
103 ep_stack_t ep_stack_new(void);
104
105 /*
106  * pushes item into stack, returns item
107  */
108 void* ep_stack_push(ep_stack_t stack, void* item);
109
110 /*
111  * pops an item from the stack
112  */
113 void* ep_stack_pop(ep_stack_t stack);
114
115 /*
116  * returns the item on top of the stack without popping it
117  */
118 #define ep_stack_peek(stack) ((*(stack))->payload)
119
120
121 /* Functions for handling memory allocation and garbage collection with
122  * a capture lifetime scope.
123  * These functions are used to allocate memory that will only remain persistent
124  * until Wireshark opens a new capture or capture file.
125  * Everytime Wireshark starts a new capture or opens a new capture file
126  * all the data allocated through these functions will be released back
127  * to the free pool.
128  *
129  * These functions are very fast and offer automatic garbage collection.
130  */
131 /* Initialize capture-lifetime memory allocation pool. This function is called
132  * once when [t]Wireshark is initialized to set up the required structures.
133  */
134 void se_init_chunk(void);
135
136 /* Allocate memory with a capture lifetime scope */
137 void *se_alloc(size_t size);
138
139 /* Allocate memory with a capture lifetime scope and fill it with zeros*/
140 void* se_alloc0(size_t size);
141
142 /* Duplicate a string with a capture lifetime scope */
143 gchar* se_strdup(const gchar* src);
144
145 /* Duplicate at most n characters of a string with a capture lifetime scope */
146 gchar* se_strndup(const gchar* src, size_t len);
147
148 /* Duplicate a buffer with a capture lifetime scope */
149 void* se_memdup(const void* src, size_t len);
150
151 /* Create a formatted string with a capture lifetime scope */
152 gchar* se_strdup_vprintf(const gchar* fmt, va_list ap);
153 gchar* se_strdup_printf(const gchar* fmt, ...)
154     GNUC_FORMAT_CHECK(printf, 1, 2);
155
156 /* allocates with a capture lifetime scope an array of type made of num elements */
157 #define se_alloc_array(type,num) (type*)se_alloc(sizeof(type)*(num))
158
159 /* release all memory allocated */
160 void se_free_all(void);
161
162
163
164
165 /**************************************************************
166  * binary trees
167  **************************************************************/
168 typedef struct _emem_tree_node_t {
169         struct _emem_tree_node_t *parent;
170         struct _emem_tree_node_t *left;
171         struct _emem_tree_node_t *right;
172         struct {
173 #define EMEM_TREE_RB_COLOR_RED          0
174 #define EMEM_TREE_RB_COLOR_BLACK        1
175                 guint32 rb_color:1;
176 #define EMEM_TREE_NODE_IS_DATA          0
177 #define EMEM_TREE_NODE_IS_SUBTREE       1
178                 guint32 is_subtree:1;
179         } u;
180         guint32 key32;
181         void *data;
182 } emem_tree_node_t;
183
184 /* Right now we only do basic red/black trees   but in the future we might want
185  * to try something different, such as a tree where each node keeps track
186  * of how many times it has been looked up, and letting often looked up
187  * nodes bubble upwards in the tree using rotate_right/left.
188  * That would probably be good for things like nfs filehandles
189  */
190 #define EMEM_TREE_TYPE_RED_BLACK        1
191 typedef struct _emem_tree_t {
192         struct _emem_tree_t *next;
193         int type;
194         const char *name;    /* just a string to make debugging easier */
195         emem_tree_node_t *tree;
196         void *(*malloc)(size_t);
197 } emem_tree_t;
198
199 /* *******************************************************************
200  * Tree functions for SE memory allocation scope
201  * ******************************************************************* */
202 /* This function is used to create a se based tree with monitoring.
203  * When the SE heap is released back to the system the pointer to the
204  * tree is automatically reset to NULL.
205  *
206  * type is : EMEM_TREE_TYPE_RED_BLACK for a standard red/black tree.
207  */
208 emem_tree_t *se_tree_create(int type, const char *name);
209
210 /* This function is similar to the se_tree_create() call but with the
211  * difference that when the se memory is release everything including the
212  * pointer to the tree itself will be released.
213  * This tree will not be just reset to zero  it will be completely forgotten
214  * by the allocator.
215  * Use this function for when you want to store the pointer to a tree inside
216  * another structure that is also se allocated so that when the structure is
217  * released, the tree will be completely released as well.
218  */
219 emem_tree_t *se_tree_create_non_persistent(int type, const char *name);
220
221 /* se_tree_insert32
222  * Insert data into the tree and key it by a 32bit integer value
223  */
224 #define se_tree_insert32 emem_tree_insert32
225
226 /* se_tree_lookup32
227  * Retrieve the data at the search key. the search key is a 32bit integer value
228  */
229 #define se_tree_lookup32 emem_tree_lookup32
230
231 /* se_tree_lookup32_le
232  * Retrieve the data for the largest key that is less than or equal
233  * to the search key.
234  */
235 #define se_tree_lookup32_le emem_tree_lookup32_le
236
237 /* se_tree_insert32_array
238  * Insert data into the tree and key it by a 32bit integer value
239  */
240 #define se_tree_insert32_array emem_tree_insert32_array
241
242 /* se_tree_lookup32_array
243  * Lookup data from the tree that is index by an array
244  */
245 #define se_tree_lookup32_array emem_tree_lookup32_array
246
247
248
249 /* Create a new string based hash table */
250 #define se_tree_create_string() se_tree_create(SE_TREE_TYPE_RED_BLACK)
251
252 /* Insert a new value under a string key */
253 #define se_tree_insert_string emem_tree_insert_string
254
255 /* Lookup the value under a string key */
256 #define se_tree_lookup_string emem_tree_lookup_string
257
258 /* Traverse a tree */
259 #define se_tree_foreach emem_tree_foreach
260
261
262 /* *******************************************************************
263  * Tree functions for PE memory allocation scope
264  * ******************************************************************* */
265 /* These trees have PErmanent allocation scope and will never be released
266  */
267 emem_tree_t *pe_tree_create(int type, const char *name);
268 #define pe_tree_insert32 emem_tree_insert32
269 #define pe_tree_lookup32 emem_tree_lookup32
270 #define pe_tree_lookup32_le emem_tree_lookup32_le
271 #define pe_tree_insert32_array emem_tree_insert32_array
272 #define pe_tree_lookup32_array emem_tree_lookup32_array
273 #define pe_tree_insert_string emem_tree_insert_string
274 #define pe_tree_lookup_string emem_tree_lookup_string
275 #define pe_tree_foreach emem_tree_foreach
276
277
278
279 /* ******************************************************************
280  * Real tree functions
281  * ****************************************************************** */
282
283 /* This function is used to insert a node indexed by a guint32 key value.
284  * The data pointer should be allocated by the appropriate storage scope
285  * so that it will be released at the same time as the tree itself is
286  * destroyed.
287  */
288 void emem_tree_insert32(emem_tree_t *se_tree, guint32 key, void *data);
289
290 /* This function will look up a node in the tree indexed by a guint32 integer
291  * value.
292  */
293 void *emem_tree_lookup32(emem_tree_t *se_tree, guint32 key);
294
295 /* This function will look up a node in the tree indexed by a guint32 integer
296  * value.
297  * The function will return the node that has the largest key that is
298  * equal to or smaller than the search key, or NULL if no such key was
299  * found.
300  */
301 void *emem_tree_lookup32_le(emem_tree_t *se_tree, guint32 key);
302
303 typedef struct _emem_tree_key_t {
304         guint32 length;                 /*length in guint32 words */
305         guint32 *key;
306 } emem_tree_key_t;
307
308 /* This function is used to insert a node indexed by a sequence of guint32
309  * key values.
310  * The data pointer should be allocated by SE allocators so that the
311  * data will be released at the same time as the tree itself is destroyed.
312  *
313  * Note: all the "key" members of the "key" argument MUST be aligned on
314  * 32-bit boundaries; otherwise, this code will crash on platforms such
315  * as SPARC that require aligned pointers.
316  *
317  * If you use ...32_array() calls you MUST make sure that every single node
318  * you add to a specific tree always has a key of exactly the same number of
319  * keylen words or things will most likely crash. Or at least that every single
320  * item that sits behind the same top level node always have exactly the same
321  * number of words.
322  *
323  * One way to guarantee this is the way that NFS does this for the
324  * nfs_name_snoop_known  tree which holds filehandles for both v2 and v3.
325  * v2 filehandles are always 32 bytes (8 words) while v3 filehandles can have
326  * any length (though 32bytes are most common).
327  * The NFS dissector handles this by providing a guint32 containing the length
328  * as the very first item in this vector :
329  *
330  *                      emem_tree_key_t fhkey[3];
331  *
332  *                      fhlen=nns->fh_length;
333  *                      fhkey[0].length=1;
334  *                      fhkey[0].key=&fhlen;
335  *                      fhkey[1].length=fhlen/4;
336  *                      fhkey[1].key=nns->fh;
337  *                      fhkey[2].length=0;
338  */
339 void emem_tree_insert32_array(emem_tree_t *se_tree, emem_tree_key_t *key, void *data);
340
341 /* This function will look up a node in the tree indexed by a sequence of
342  * guint32 integer values.
343  */
344 void *emem_tree_lookup32_array(emem_tree_t *se_tree, emem_tree_key_t *key);
345
346 /* case insensitive strings as keys */
347 #define EMEM_TREE_STRING_NOCASE                 0x00000001
348 /* Insert a new value under a string key */
349 void emem_tree_insert_string(emem_tree_t* h, const gchar* k, void* v, guint32 flags);
350
351 /* Lookup the value under a string key */
352 void* emem_tree_lookup_string(emem_tree_t* h, const gchar* k, guint32 flags);
353
354
355 /* traverse a tree. if the callback returns TRUE the traversal will end */
356 typedef gboolean (*tree_foreach_func)(void *value, void *userdata);
357
358 gboolean emem_tree_foreach(emem_tree_t* emem_tree, tree_foreach_func callback, void *user_data);
359
360
361 /* ******************************************************************
362  * String buffers - Growable strings similar to GStrings
363  * ****************************************************************** */
364
365 typedef struct _emem_strbuf_t {
366     gchar *str;             /* points to the character data. It may move as text is       */
367                             /*  added. The str field is nul-terminated and so can         */
368                             /*  be used as an ordinary C string.                          */
369     gsize len;              /* strlen: ie: length of str not including trailing '\0'      */
370     gsize alloc_len;        /* num bytes curently allocated for str: 1 .. MAX_STRBUF_LEN  */
371     gsize max_alloc_len;    /* max num bytes to allocate for str: 1 .. MAX_STRBUF_LEN     */
372 } emem_strbuf_t;
373
374 /*
375  * The maximum length is limited to 64K. If you need something bigger, you
376  * should probably use an actual GString or GByteArray.
377  */
378
379 /**
380  * Allocate an ephemeral string buffer with "unlimited" size.
381  *
382  * @param init The initial string for the buffer, or NULL to allocate an initial zero-length string.
383  *
384  * @return A newly-allocated string buffer.
385  */
386 emem_strbuf_t *ep_strbuf_new(const gchar *init);
387
388 /**
389  * Allocate an ephemeral string buffer suitable for the protocol tree.
390  * The string will never grow beyond the maximum tree item length.
391  *
392  * @param init The initial string for the buffer, or NULL to allocate an initial zero-length string.
393  *
394  * @return A newly-allocated string buffer.
395  */
396 emem_strbuf_t *ep_strbuf_new_label(const gchar *init);
397
398 /**
399  * Allocate an ephemeral string buffer with enough initial space for @alloc_len bytes
400  * and a maximum of @max_alloc_len bytes.
401  *
402  * @param alloc_len The initial size of the buffer. This value can be 0, but a nonzero
403  * value is recommended.
404  * @param max_alloc_len The maximum size of the buffer. 0 means "unlimited" (within
405  * reason).
406  *
407  * @return A newly-allocated string buffer. @str will be empty.
408  */
409 emem_strbuf_t *ep_strbuf_sized_new(gsize alloc_len, gsize max_alloc_len);
410
411 /**
412  * Append vprintf-style formatted text to a string buffer.
413  *
414  * @param strbuf The ep_strbuf-allocated string buffer to append to.
415  * @param format A printf-style string format.
416  * @param args The list of arguments to append.
417  */
418 void ep_strbuf_append_vprintf(emem_strbuf_t *strbuf, const gchar *format, va_list ap);
419
420 /**
421  * Apply printf-style formatted text to a string buffer.
422  *
423  * @param strbuf The ep_strbuf-allocated string buffer to set to.
424  * @param format A printf-style string format.
425  */
426 void ep_strbuf_printf(emem_strbuf_t *strbuf, const gchar *format, ...)
427     GNUC_FORMAT_CHECK(printf, 2, 3);
428
429 /**
430  * Append printf-style formatted text to a string buffer.
431  *
432  * @param strbuf The ep_strbuf-allocated string buffer to append to.
433  * @param format A printf-style string format.
434  */
435 void ep_strbuf_append_printf(emem_strbuf_t *strbuf, const gchar *format, ...)
436     GNUC_FORMAT_CHECK(printf, 2, 3);
437
438 /**
439  * Append a string to a string buffer.
440  *
441  * @param strbuf The ep_strbuf-allocated string buffer to append to.
442  * @param str A null-terminated string.
443  *
444  * @return strbuf
445  */
446 emem_strbuf_t *ep_strbuf_append(emem_strbuf_t *strbuf, const gchar *str);
447
448 /**
449  * Append a character to a string buffer.
450  *
451  * @param strbuf The ep_strbuf-allocated string buffer to append to.
452  * @param c The character to append.
453  *
454  * @return strbuf
455  */
456 emem_strbuf_t *ep_strbuf_append_c(emem_strbuf_t *strbuf, const gchar c);
457
458 /**
459  * Chop off the end of a string buffer.
460  *
461  * @param strbuf The ep_strbuf-allocated string buffer to append to.
462  * @param len The new string length.
463  *
464  * @return strbuf
465  */
466 emem_strbuf_t *ep_strbuf_truncate(emem_strbuf_t *strbuf, gsize len);
467
468 void emem_print_tree(emem_tree_t* emem_tree);
469
470 /* #define DEBUG_INTENSE_CANARY_CHECKS */
471 /* Helper to troubleshoot ep memory corruption
472  * if compiled and the environment variable WIRESHARK_DEBUG_EP_INTENSE_CANARY exists
473  * it will check the canaries and when found corrupt stop there in the hope
474  * the corruptor is still there in the stack.
475  * Some checkpoints are already set in packet.c in strategic points
476  * before and after dissection of a frame or a dissector call.
477  */
478
479 #ifdef DEBUG_INTENSE_CANARY_CHECKS
480 void ep_check_canary_integrity(const char* fmt, ...);
481 #define EP_CHECK_CANARY(sprintf_args) ep_check_canary_integrity sprintf_args
482 #else
483 #define EP_CHECK_CANARY(dummy)
484 #endif
485
486 /**
487  * Verify that the given pointer is of ephemeral/seasonal type.
488  *
489  * @param ptr The pointer to verify
490  *
491  * @return TRUE if the pointer belongs to the ephemeral/seasonal pool.
492  */
493 gboolean ep_verify_pointer(const void *ptr);
494 gboolean se_verify_pointer(const void *ptr);
495
496 #endif /* emem.h */