983c6e31d61ed71ead004e86c2ea9ae665a2cb88
[platform/upstream/dbus.git] / dbus / dbus-memory.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-memory.c  D-BUS memory handling
3  *
4  * Copyright (C) 2002, 2003  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-memory.h"
25 #include "dbus-internals.h"
26 #include "dbus-sysdeps.h"
27 #include "dbus-list.h"
28 #include <stdlib.h>
29
30
31 /**
32  * @defgroup DBusMemory Memory Allocation
33  * @ingroup  DBus
34  * @brief dbus_malloc(), dbus_free(), etc.
35  *
36  * Functions and macros related to allocating and releasing
37  * blocks of memory.
38  *
39  * @{
40  */
41
42 /**
43  * @def dbus_new
44  *
45  * Safe macro for using dbus_malloc(). Accepts the type
46  * to allocate and the number of type instances to
47  * allocate as arguments, and returns a memory block
48  * cast to the desired type, instead of as a void*.
49  *
50  * @param type type name to allocate
51  * @param count number of instances in the allocated array
52  * @returns the new memory block or #NULL on failure
53  */
54
55 /**
56  * @def dbus_new0
57  *
58  * Safe macro for using dbus_malloc0(). Accepts the type
59  * to allocate and the number of type instances to
60  * allocate as arguments, and returns a memory block
61  * cast to the desired type, instead of as a void*.
62  * The allocated array is initialized to all-bits-zero.
63  *
64  * @param type type name to allocate
65  * @param count number of instances in the allocated array
66  * @returns the new memory block or #NULL on failure
67  */
68
69 /**
70  * @typedef DBusFreeFunction
71  *
72  * The type of a function which frees a block of memory.
73  *
74  * @param memory the memory to free
75  */
76
77 #ifdef DBUS_BUILD_TESTS
78 static dbus_bool_t debug_initialized = FALSE;
79 static int fail_counts = -1;
80 static size_t fail_size = 0;
81 static int fail_alloc_counter = _DBUS_INT_MAX;
82 static dbus_bool_t guards = FALSE;
83 static dbus_bool_t disable_mem_pools = FALSE;
84 static dbus_bool_t backtrace_on_fail_alloc = FALSE;
85 static int n_blocks_outstanding = 0;
86
87 /** value stored in guard padding for debugging buffer overrun */
88 #define GUARD_VALUE 0xdeadbeef
89 /** size of the information about the block stored in guard mode */
90 #define GUARD_INFO_SIZE 8
91 /** size of the GUARD_VALUE-filled padding after the header info  */
92 #define GUARD_START_PAD 16
93 /** size of the GUARD_VALUE-filled padding at the end of the block */
94 #define GUARD_END_PAD 16
95 /** size of stuff at start of block */
96 #define GUARD_START_OFFSET (GUARD_START_PAD + GUARD_INFO_SIZE)
97 /** total extra size over the requested allocation for guard stuff */
98 #define GUARD_EXTRA_SIZE (GUARD_START_OFFSET + GUARD_END_PAD)
99
100 static void
101 _dbus_initialize_malloc_debug (void)
102 {
103   if (!debug_initialized)
104     {
105       debug_initialized = TRUE;
106       
107       if (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH") != NULL)
108         {
109           fail_counts = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH"));
110           fail_alloc_counter = fail_counts;
111           _dbus_verbose ("Will fail malloc every %d times\n", fail_counts);
112         }
113       
114       if (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN") != NULL)
115         {
116           fail_size = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN"));
117           _dbus_verbose ("Will fail mallocs over %d bytes\n",
118                          fail_size);
119         }
120
121       if (_dbus_getenv ("DBUS_MALLOC_GUARDS") != NULL)
122         {
123           guards = TRUE;
124           _dbus_verbose ("Will use malloc guards\n");
125         }
126
127       if (_dbus_getenv ("DBUS_DISABLE_MEM_POOLS") != NULL)
128         {
129           disable_mem_pools = TRUE;
130           _dbus_verbose ("Will disable memory pools\n");
131         }
132
133       if (_dbus_getenv ("DBUS_MALLOC_BACKTRACES") != NULL)
134         {
135           backtrace_on_fail_alloc = TRUE;
136           _dbus_verbose ("Will backtrace on failing a malloc\n");
137         }
138     }
139 }
140
141 /**
142  * Whether to turn off mem pools, useful for leak checking.
143  *
144  * @returns #TRUE if mempools should not be used.
145  */
146 dbus_bool_t
147 _dbus_disable_mem_pools (void)
148 {
149   _dbus_initialize_malloc_debug ();
150   return disable_mem_pools;
151 }
152
153 /**
154  * Sets the number of allocations until we simulate a failed
155  * allocation. If set to 0, the next allocation to run
156  * fails; if set to 1, one succeeds then the next fails; etc.
157  * Set to _DBUS_INT_MAX to not fail anything. 
158  *
159  * @param until_next_fail number of successful allocs before one fails
160  */
161 void
162 _dbus_set_fail_alloc_counter (int until_next_fail)
163 {
164   _dbus_initialize_malloc_debug ();
165
166   fail_alloc_counter = until_next_fail;
167
168 #if 0
169   _dbus_verbose ("Set fail alloc counter = %d\n", fail_alloc_counter);
170 #endif
171 }
172
173 /**
174  * Gets the number of successful allocs until we'll simulate
175  * a failed alloc.
176  *
177  * @returns current counter value
178  */
179 int
180 _dbus_get_fail_alloc_counter (void)
181 {
182   _dbus_initialize_malloc_debug ();
183
184   return fail_alloc_counter;
185 }
186
187 /**
188  * Called when about to alloc some memory; if
189  * it returns #TRUE, then the allocation should
190  * fail. If it returns #FALSE, then the allocation
191  * should not fail.
192  *
193  * @returns #TRUE if this alloc should fail
194  */
195 dbus_bool_t
196 _dbus_decrement_fail_alloc_counter (void)
197 {
198   _dbus_initialize_malloc_debug ();
199   
200   if (fail_alloc_counter <= 0)
201     {
202       if (fail_counts >= 0)
203         fail_alloc_counter = fail_counts;
204       else
205         fail_alloc_counter = _DBUS_INT_MAX;
206
207       _dbus_verbose ("reset fail alloc counter to %d\n", fail_alloc_counter);
208       if (backtrace_on_fail_alloc)
209         _dbus_print_backtrace ();
210       
211       return TRUE;
212     }
213   else
214     {
215       fail_alloc_counter -= 1;
216       return FALSE;
217     }
218 }
219
220 /**
221  * Get the number of outstanding malloc()'d blocks.
222  *
223  * @returns number of blocks
224  */
225 int
226 _dbus_get_malloc_blocks_outstanding (void)
227 {
228   return n_blocks_outstanding;
229 }
230
231 /**
232  * Where the block came from.
233  */
234 typedef enum
235 {
236   SOURCE_UNKNOWN,
237   SOURCE_MALLOC,
238   SOURCE_REALLOC,
239   SOURCE_MALLOC_ZERO,
240   SOURCE_REALLOC_NULL
241 } BlockSource;
242
243 static const char*
244 source_string (BlockSource source)
245 {
246   switch (source)
247     {
248     case SOURCE_UNKNOWN:
249       return "unknown";
250     case SOURCE_MALLOC:
251       return "malloc";
252     case SOURCE_REALLOC:
253       return "realloc";
254     case SOURCE_MALLOC_ZERO:
255       return "malloc0";
256     case SOURCE_REALLOC_NULL:
257       return "realloc(NULL)";
258     }
259   _dbus_assert_not_reached ("Invalid malloc block source ID");
260   return "invalid!";
261 }
262
263 static void
264 check_guards (void *free_block)
265 {
266   if (free_block != NULL)
267     {
268       unsigned char *block = ((unsigned char*)free_block) - GUARD_START_OFFSET;
269       size_t requested_bytes = *(dbus_uint32_t*)block;
270       BlockSource source = *(dbus_uint32_t*)(block + 4);
271       unsigned int i;
272       dbus_bool_t failed;
273
274       failed = FALSE;
275
276 #if 0
277       _dbus_verbose ("Checking %d bytes request from source %s\n",
278                      requested_bytes, source_string (source));
279 #endif
280       
281       i = GUARD_INFO_SIZE;
282       while (i < GUARD_START_OFFSET)
283         {
284           dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
285           if (value != GUARD_VALUE)
286             {
287               _dbus_warn ("Block of %u bytes from %s had start guard value 0x%x at %d expected 0x%x\n",
288                           requested_bytes, source_string (source),
289                           value, i, GUARD_VALUE);
290               failed = TRUE;
291             }
292           
293           i += 4;
294         }
295
296       i = GUARD_START_OFFSET + requested_bytes;
297       while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
298         {
299           dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
300           if (value != GUARD_VALUE)
301             {
302               _dbus_warn ("Block of %u bytes from %s had end guard value 0x%x at %d expected 0x%x\n",
303                           requested_bytes, source_string (source),
304                           value, i, GUARD_VALUE);
305               failed = TRUE;
306             }
307           
308           i += 4;
309         }
310
311       if (failed)
312         _dbus_assert_not_reached ("guard value corruption");
313     }
314 }
315
316 static void*
317 set_guards (void       *real_block,
318             size_t      requested_bytes,
319             BlockSource source)
320 {
321   unsigned char *block = real_block;
322   unsigned int i;
323   
324   if (block == NULL)
325     return NULL;
326
327   _dbus_assert (GUARD_START_OFFSET + GUARD_END_PAD == GUARD_EXTRA_SIZE);
328   
329   *((dbus_uint32_t*)block) = requested_bytes;
330   *((dbus_uint32_t*)(block + 4)) = source;
331
332   i = GUARD_INFO_SIZE;
333   while (i < GUARD_START_OFFSET)
334     {
335       (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
336       
337       i += 4;
338     }
339
340   i = GUARD_START_OFFSET + requested_bytes;
341   while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
342     {
343       (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
344       
345       i += 4;
346     }
347   
348   check_guards (block + GUARD_START_OFFSET);
349   
350   return block + GUARD_START_OFFSET;
351 }
352
353 #endif
354
355 /**
356  * Allocates the given number of bytes, as with standard
357  * malloc(). Guaranteed to return #NULL if bytes is zero
358  * on all platforms. Returns #NULL if the allocation fails.
359  * The memory must be released with dbus_free().
360  *
361  * @param bytes number of bytes to allocate
362  * @return allocated memory, or #NULL if the allocation fails.
363  */
364 void*
365 dbus_malloc (size_t bytes)
366 {
367 #ifdef DBUS_BUILD_TESTS
368   _dbus_initialize_malloc_debug ();
369   
370   if (_dbus_decrement_fail_alloc_counter ())
371     {
372       _dbus_verbose (" FAILING malloc of %d bytes\n", bytes);
373       
374       return NULL;
375     }
376 #endif
377   
378   if (bytes == 0) /* some system mallocs handle this, some don't */
379     return NULL;
380 #if DBUS_BUILD_TESTS
381   else if (fail_size != 0 && bytes > fail_size)
382     return NULL;
383   else if (guards)
384     {
385       void *block;
386
387       block = malloc (bytes + GUARD_EXTRA_SIZE);
388       if (block)
389         n_blocks_outstanding += 1;
390       
391       return set_guards (block, bytes, SOURCE_MALLOC);
392     }
393 #endif
394   else
395     {
396       void *mem;
397       mem = malloc (bytes);
398 #ifdef DBUS_BUILD_TESTS
399       if (mem)
400         n_blocks_outstanding += 1;
401 #endif
402       return mem;
403     }
404 }
405
406 /**
407  * Allocates the given number of bytes, as with standard malloc(), but
408  * all bytes are initialized to zero as with calloc(). Guaranteed to
409  * return #NULL if bytes is zero on all platforms. Returns #NULL if the
410  * allocation fails.  The memory must be released with dbus_free().
411  *
412  * @param bytes number of bytes to allocate
413  * @return allocated memory, or #NULL if the allocation fails.
414  */
415 void*
416 dbus_malloc0 (size_t bytes)
417 {
418 #ifdef DBUS_BUILD_TESTS
419   _dbus_initialize_malloc_debug ();
420   
421   if (_dbus_decrement_fail_alloc_counter ())
422     {
423       _dbus_verbose (" FAILING malloc0 of %d bytes\n", bytes);
424       
425       return NULL;
426     }
427 #endif
428
429   if (bytes == 0)
430     return NULL;
431 #if DBUS_BUILD_TESTS
432   else if (fail_size != 0 && bytes > fail_size)
433     return NULL;
434   else if (guards)
435     {
436       void *block;
437
438       block = calloc (bytes + GUARD_EXTRA_SIZE, 1);
439       if (block)
440         n_blocks_outstanding += 1;
441       return set_guards (block, bytes, SOURCE_MALLOC_ZERO);
442     }
443 #endif
444   else
445     {
446       void *mem;
447       mem = calloc (bytes, 1);
448 #ifdef DBUS_BUILD_TESTS
449       if (mem)
450         n_blocks_outstanding += 1;
451 #endif
452       return mem;
453     }
454 }
455
456 /**
457  * Resizes a block of memory previously allocated by dbus_malloc() or
458  * dbus_malloc0(). Guaranteed to free the memory and return #NULL if bytes
459  * is zero on all platforms. Returns #NULL if the resize fails.
460  * If the resize fails, the memory is not freed.
461  *
462  * @param memory block to be resized
463  * @param bytes new size of the memory block
464  * @return allocated memory, or #NULL if the resize fails.
465  */
466 void*
467 dbus_realloc (void  *memory,
468               size_t bytes)
469 {
470 #ifdef DBUS_BUILD_TESTS
471   _dbus_initialize_malloc_debug ();
472   
473   if (_dbus_decrement_fail_alloc_counter ())
474     {
475       _dbus_verbose (" FAILING realloc of %d bytes\n", bytes);
476       
477       return NULL;
478     }
479 #endif
480   
481   if (bytes == 0) /* guarantee this is safe */
482     {
483       dbus_free (memory);
484       return NULL;
485     }
486 #if DBUS_BUILD_TESTS
487   else if (fail_size != 0 && bytes > fail_size)
488     return NULL;
489   else if (guards)
490     {
491       if (memory)
492         {
493           void *block;
494           
495           check_guards (memory);
496           
497           block = realloc (((unsigned char*)memory) - GUARD_START_OFFSET,
498                            bytes + GUARD_EXTRA_SIZE);
499
500           if (block)
501             /* old guards shouldn't have moved */
502             check_guards (((unsigned char*)block) + GUARD_START_OFFSET);
503           
504           return set_guards (block, bytes, SOURCE_REALLOC);
505         }
506       else
507         {
508           void *block;
509           
510           block = malloc (bytes + GUARD_EXTRA_SIZE);
511
512           if (block)
513             n_blocks_outstanding += 1;
514           
515           return set_guards (block, bytes, SOURCE_REALLOC_NULL);   
516         }
517     }
518 #endif
519   else
520     {
521       void *mem;
522       mem = realloc (memory, bytes);
523 #ifdef DBUS_BUILD_TESTS
524       if (memory == NULL && mem != NULL)
525         n_blocks_outstanding += 1;
526 #endif
527       return mem;
528     }
529 }
530
531 /**
532  * Frees a block of memory previously allocated by dbus_malloc() or
533  * dbus_malloc0(). If passed #NULL, does nothing.
534  * 
535  * @param memory block to be freed
536  */
537 void
538 dbus_free (void  *memory)
539 {
540 #ifdef DBUS_BUILD_TESTS
541   if (guards)
542     {
543       check_guards (memory);
544       if (memory)
545         {
546           n_blocks_outstanding -= 1;
547           
548           _dbus_assert (n_blocks_outstanding >= 0);
549           
550           free (((unsigned char*)memory) - GUARD_START_OFFSET);
551         }
552       
553       return;
554     }
555 #endif
556     
557   if (memory) /* we guarantee it's safe to free (NULL) */
558     {
559 #ifdef DBUS_BUILD_TESTS
560       n_blocks_outstanding -= 1;
561       
562       _dbus_assert (n_blocks_outstanding >= 0);
563 #endif
564
565       free (memory);
566     }
567 }
568
569 /**
570  * Frees a #NULL-terminated array of strings.
571  * If passed #NULL, does nothing.
572  *
573  * @param str_array the array to be freed
574  */
575 void
576 dbus_free_string_array (char **str_array)
577 {
578   if (str_array)
579     {
580       int i;
581
582       i = 0;
583       while (str_array[i])
584         {
585           dbus_free (str_array[i]);
586           i++;
587         }
588
589       dbus_free (str_array);
590     }
591 }
592
593 /**
594  * _dbus_current_generation is used to track each
595  * time that dbus_shutdown() is called, so we can
596  * reinit things after it's been called. It is simply
597  * incremented each time we shut down.
598  */
599 int _dbus_current_generation = 1;
600
601 static DBusList *registered_globals = NULL;
602
603 typedef struct
604 {
605   DBusShutdownFunction func;
606   void *data;
607 } ShutdownClosure;
608
609 /**
610  * The D-BUS library keeps some internal global variables, for example
611  * to cache the username of the current process.  This function is
612  * used to free these global variables.  It is really useful only for
613  * leak-checking cleanliness and the like. WARNING: this function is
614  * NOT thread safe, it must be called while NO other threads are using
615  * D-BUS. You cannot continue using D-BUS after calling this function,
616  * as it does things like free global mutexes created by
617  * dbus_threads_init(). To use a D-BUS function after calling
618  * dbus_shutdown(), you have to start over from scratch, e.g. calling
619  * dbus_threads_init() again.
620  */
621 void
622 dbus_shutdown (void)
623 {
624   DBusList *link;
625
626   link = _dbus_list_get_first_link (&registered_globals);
627   while (link != NULL)
628     {
629       ShutdownClosure *c = link->data;
630
631       (* c->func) (c->data);
632
633       dbus_free (c);
634       
635       link = _dbus_list_get_next_link (&registered_globals, link);
636     }
637
638   _dbus_list_clear (&registered_globals);
639
640   _dbus_current_generation += 1;
641 }
642
643 /**
644  * Register a cleanup function to be called exactly once
645  * the next time dbus_shutdown() is called.
646  *
647  * @param func the function
648  * @param data data to pass to the function
649  * @returns #FALSE on not enough memory
650  */
651 dbus_bool_t
652 _dbus_register_shutdown_func (DBusShutdownFunction  func,
653                               void                 *data)
654 {
655   ShutdownClosure *c;
656
657   c = dbus_new (ShutdownClosure, 1);
658
659   if (c == NULL)
660     return FALSE;
661   
662   c->func = func;
663   c->data = data;
664
665   /* We prepend, then shutdown the list in order, so
666    * we shutdown last-registered stuff first which
667    * is right.
668    */
669   if (!_dbus_list_prepend (&registered_globals, c))
670     {
671       dbus_free (c);
672       return FALSE;
673     }
674
675   return TRUE;
676 }
677
678 /** @} */