1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-memory.c D-Bus memory handling
4 * Copyright (C) 2002, 2003 Red Hat Inc.
6 * Licensed under the Academic Free License version 2.1
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.
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.
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
24 #include "dbus-memory.h"
25 #include "dbus-internals.h"
26 #include "dbus-sysdeps.h"
27 #include "dbus-list.h"
31 * @defgroup DBusMemory Memory Allocation
33 * @brief dbus_malloc(), dbus_free(), etc.
35 * Functions and macros related to allocating and releasing
41 * @defgroup DBusMemoryInternals Memory allocation implementation details
42 * @ingroup DBusInternals
43 * @brief internals of dbus_malloc() etc.
45 * Implementation details related to allocating and releasing blocks
50 * @addtogroup DBusMemory
58 * Safe macro for using dbus_malloc(). 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*.
63 * @param type type name to allocate
64 * @param count number of instances in the allocated array
65 * @returns the new memory block or #NULL on failure
71 * Safe macro for using dbus_malloc0(). Accepts the type
72 * to allocate and the number of type instances to
73 * allocate as arguments, and returns a memory block
74 * cast to the desired type, instead of as a void*.
75 * The allocated array is initialized to all-bits-zero.
77 * @param type type name to allocate
78 * @param count number of instances in the allocated array
79 * @returns the new memory block or #NULL on failure
83 * @typedef DBusFreeFunction
85 * The type of a function which frees a block of memory.
87 * @param memory the memory to free
90 /** @} */ /* end of public API docs */
93 * @addtogroup DBusMemoryInternals
98 #ifdef DBUS_BUILD_TESTS
99 static dbus_bool_t debug_initialized = FALSE;
100 static int fail_nth = -1;
101 static size_t fail_size = 0;
102 static int fail_alloc_counter = _DBUS_INT_MAX;
103 static int n_failures_per_failure = 1;
104 static int n_failures_this_failure = 0;
105 static dbus_bool_t guards = FALSE;
106 static dbus_bool_t disable_mem_pools = FALSE;
107 static dbus_bool_t backtrace_on_fail_alloc = FALSE;
108 static DBusAtomic n_blocks_outstanding = {0};
110 /** value stored in guard padding for debugging buffer overrun */
111 #define GUARD_VALUE 0xdeadbeef
112 /** size of the information about the block stored in guard mode */
113 #define GUARD_INFO_SIZE 8
114 /** size of the GUARD_VALUE-filled padding after the header info */
115 #define GUARD_START_PAD 16
116 /** size of the GUARD_VALUE-filled padding at the end of the block */
117 #define GUARD_END_PAD 16
118 /** size of stuff at start of block */
119 #define GUARD_START_OFFSET (GUARD_START_PAD + GUARD_INFO_SIZE)
120 /** total extra size over the requested allocation for guard stuff */
121 #define GUARD_EXTRA_SIZE (GUARD_START_OFFSET + GUARD_END_PAD)
124 _dbus_initialize_malloc_debug (void)
126 if (!debug_initialized)
128 debug_initialized = TRUE;
130 if (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH") != NULL)
132 fail_nth = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH"));
133 fail_alloc_counter = fail_nth;
134 _dbus_verbose ("Will fail malloc every %d times\n", fail_nth);
137 if (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN") != NULL)
139 fail_size = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN"));
140 _dbus_verbose ("Will fail mallocs over %ld bytes\n",
144 if (_dbus_getenv ("DBUS_MALLOC_GUARDS") != NULL)
147 _dbus_verbose ("Will use malloc guards\n");
150 if (_dbus_getenv ("DBUS_DISABLE_MEM_POOLS") != NULL)
152 disable_mem_pools = TRUE;
153 _dbus_verbose ("Will disable memory pools\n");
156 if (_dbus_getenv ("DBUS_MALLOC_BACKTRACES") != NULL)
158 backtrace_on_fail_alloc = TRUE;
159 _dbus_verbose ("Will backtrace on failing a malloc\n");
165 * Whether to turn off mem pools, useful for leak checking.
167 * @returns #TRUE if mempools should not be used.
170 _dbus_disable_mem_pools (void)
172 _dbus_initialize_malloc_debug ();
173 return disable_mem_pools;
177 * Sets the number of allocations until we simulate a failed
178 * allocation. If set to 0, the next allocation to run
179 * fails; if set to 1, one succeeds then the next fails; etc.
180 * Set to _DBUS_INT_MAX to not fail anything.
182 * @param until_next_fail number of successful allocs before one fails
185 _dbus_set_fail_alloc_counter (int until_next_fail)
187 _dbus_initialize_malloc_debug ();
189 fail_alloc_counter = until_next_fail;
192 _dbus_verbose ("Set fail alloc counter = %d\n", fail_alloc_counter);
197 * Gets the number of successful allocs until we'll simulate
200 * @returns current counter value
203 _dbus_get_fail_alloc_counter (void)
205 _dbus_initialize_malloc_debug ();
207 return fail_alloc_counter;
211 * Sets how many mallocs to fail when the fail alloc counter reaches
214 * @param failures_per_failure number to fail
217 _dbus_set_fail_alloc_failures (int failures_per_failure)
219 n_failures_per_failure = failures_per_failure;
223 * Gets the number of failures we'll have when the fail malloc
226 * @returns number of failures planned
229 _dbus_get_fail_alloc_failures (void)
231 return n_failures_per_failure;
234 #ifdef DBUS_BUILD_TESTS
236 * Called when about to alloc some memory; if
237 * it returns #TRUE, then the allocation should
238 * fail. If it returns #FALSE, then the allocation
241 * @returns #TRUE if this alloc should fail
244 _dbus_decrement_fail_alloc_counter (void)
246 _dbus_initialize_malloc_debug ();
248 if (fail_alloc_counter <= 0)
250 if (backtrace_on_fail_alloc)
251 _dbus_print_backtrace ();
253 _dbus_verbose ("failure %d\n", n_failures_this_failure);
255 n_failures_this_failure += 1;
256 if (n_failures_this_failure >= n_failures_per_failure)
259 fail_alloc_counter = fail_nth;
261 fail_alloc_counter = _DBUS_INT_MAX;
263 n_failures_this_failure = 0;
265 _dbus_verbose ("reset fail alloc counter to %d\n", fail_alloc_counter);
272 fail_alloc_counter -= 1;
276 #endif /* DBUS_BUILD_TESTS */
279 * Get the number of outstanding malloc()'d blocks.
281 * @returns number of blocks
284 _dbus_get_malloc_blocks_outstanding (void)
286 return n_blocks_outstanding.value;
290 * Where the block came from.
302 source_string (BlockSource source)
312 case SOURCE_MALLOC_ZERO:
314 case SOURCE_REALLOC_NULL:
315 return "realloc(NULL)";
317 _dbus_assert_not_reached ("Invalid malloc block source ID");
322 check_guards (void *free_block,
323 dbus_bool_t overwrite)
325 if (free_block != NULL)
327 unsigned char *block = ((unsigned char*)free_block) - GUARD_START_OFFSET;
328 size_t requested_bytes = *(dbus_uint32_t*)block;
329 BlockSource source = *(dbus_uint32_t*)(block + 4);
336 _dbus_verbose ("Checking %d bytes request from source %s\n",
337 requested_bytes, source_string (source));
341 while (i < GUARD_START_OFFSET)
343 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
344 if (value != GUARD_VALUE)
346 _dbus_warn ("Block of %lu bytes from %s had start guard value 0x%ux at %d expected 0x%x\n",
347 (long) requested_bytes, source_string (source),
348 value, i, GUARD_VALUE);
355 i = GUARD_START_OFFSET + requested_bytes;
356 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
358 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
359 if (value != GUARD_VALUE)
361 _dbus_warn ("Block of %lu bytes from %s had end guard value 0x%ux at %d expected 0x%x\n",
362 (long) requested_bytes, source_string (source),
363 value, i, GUARD_VALUE);
370 /* set memory to anything but nul bytes */
372 memset (free_block, 'g', requested_bytes);
375 _dbus_assert_not_reached ("guard value corruption");
380 set_guards (void *real_block,
381 size_t requested_bytes,
384 unsigned char *block = real_block;
390 _dbus_assert (GUARD_START_OFFSET + GUARD_END_PAD == GUARD_EXTRA_SIZE);
392 *((dbus_uint32_t*)block) = requested_bytes;
393 *((dbus_uint32_t*)(block + 4)) = source;
396 while (i < GUARD_START_OFFSET)
398 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
403 i = GUARD_START_OFFSET + requested_bytes;
404 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
406 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
411 check_guards (block + GUARD_START_OFFSET, FALSE);
413 return block + GUARD_START_OFFSET;
418 /** @} */ /* End of internals docs */
422 * @addtogroup DBusMemory
428 * Allocates the given number of bytes, as with standard
429 * malloc(). Guaranteed to return #NULL if bytes is zero
430 * on all platforms. Returns #NULL if the allocation fails.
431 * The memory must be released with dbus_free().
433 * dbus_malloc() memory is NOT safe to free with regular free() from
434 * the C library. Free it with dbus_free() only.
436 * @param bytes number of bytes to allocate
437 * @return allocated memory, or #NULL if the allocation fails.
440 dbus_malloc (size_t bytes)
442 #ifdef DBUS_BUILD_TESTS
443 _dbus_initialize_malloc_debug ();
445 if (_dbus_decrement_fail_alloc_counter ())
447 _dbus_verbose (" FAILING malloc of %ld bytes\n", (long) bytes);
452 if (bytes == 0) /* some system mallocs handle this, some don't */
454 #ifdef DBUS_BUILD_TESTS
455 else if (fail_size != 0 && bytes > fail_size)
461 block = malloc (bytes + GUARD_EXTRA_SIZE);
463 _dbus_atomic_inc (&n_blocks_outstanding);
465 return set_guards (block, bytes, SOURCE_MALLOC);
471 mem = malloc (bytes);
472 #ifdef DBUS_BUILD_TESTS
474 _dbus_atomic_inc (&n_blocks_outstanding);
481 * Allocates the given number of bytes, as with standard malloc(), but
482 * all bytes are initialized to zero as with calloc(). Guaranteed to
483 * return #NULL if bytes is zero on all platforms. Returns #NULL if the
484 * allocation fails. The memory must be released with dbus_free().
486 * dbus_malloc0() memory is NOT safe to free with regular free() from
487 * the C library. Free it with dbus_free() only.
489 * @param bytes number of bytes to allocate
490 * @return allocated memory, or #NULL if the allocation fails.
493 dbus_malloc0 (size_t bytes)
495 #ifdef DBUS_BUILD_TESTS
496 _dbus_initialize_malloc_debug ();
498 if (_dbus_decrement_fail_alloc_counter ())
500 _dbus_verbose (" FAILING malloc0 of %ld bytes\n", (long) bytes);
508 #ifdef DBUS_BUILD_TESTS
509 else if (fail_size != 0 && bytes > fail_size)
515 block = calloc (bytes + GUARD_EXTRA_SIZE, 1);
517 _dbus_atomic_inc (&n_blocks_outstanding);
518 return set_guards (block, bytes, SOURCE_MALLOC_ZERO);
524 mem = calloc (bytes, 1);
525 #ifdef DBUS_BUILD_TESTS
527 _dbus_atomic_inc (&n_blocks_outstanding);
534 * Resizes a block of memory previously allocated by dbus_malloc() or
535 * dbus_malloc0(). Guaranteed to free the memory and return #NULL if bytes
536 * is zero on all platforms. Returns #NULL if the resize fails.
537 * If the resize fails, the memory is not freed.
539 * @param memory block to be resized
540 * @param bytes new size of the memory block
541 * @return allocated memory, or #NULL if the resize fails.
544 dbus_realloc (void *memory,
547 #ifdef DBUS_BUILD_TESTS
548 _dbus_initialize_malloc_debug ();
550 if (_dbus_decrement_fail_alloc_counter ())
552 _dbus_verbose (" FAILING realloc of %ld bytes\n", (long) bytes);
558 if (bytes == 0) /* guarantee this is safe */
563 #ifdef DBUS_BUILD_TESTS
564 else if (fail_size != 0 && bytes > fail_size)
573 check_guards (memory, FALSE);
575 block = realloc (((unsigned char*)memory) - GUARD_START_OFFSET,
576 bytes + GUARD_EXTRA_SIZE);
578 old_bytes = *(dbus_uint32_t*)block;
579 if (block && bytes >= old_bytes)
580 /* old guards shouldn't have moved */
581 check_guards (((unsigned char*)block) + GUARD_START_OFFSET, FALSE);
583 return set_guards (block, bytes, SOURCE_REALLOC);
589 block = malloc (bytes + GUARD_EXTRA_SIZE);
592 _dbus_atomic_inc (&n_blocks_outstanding);
594 return set_guards (block, bytes, SOURCE_REALLOC_NULL);
601 mem = realloc (memory, bytes);
602 #ifdef DBUS_BUILD_TESTS
603 if (memory == NULL && mem != NULL)
604 _dbus_atomic_inc (&n_blocks_outstanding);
611 * Frees a block of memory previously allocated by dbus_malloc() or
612 * dbus_malloc0(). If passed #NULL, does nothing.
614 * @param memory block to be freed
617 dbus_free (void *memory)
619 #ifdef DBUS_BUILD_TESTS
622 check_guards (memory, TRUE);
625 _dbus_atomic_dec (&n_blocks_outstanding);
627 _dbus_assert (n_blocks_outstanding.value >= 0);
629 free (((unsigned char*)memory) - GUARD_START_OFFSET);
636 if (memory) /* we guarantee it's safe to free (NULL) */
638 #ifdef DBUS_BUILD_TESTS
639 _dbus_atomic_dec (&n_blocks_outstanding);
641 _dbus_assert (n_blocks_outstanding.value >= 0);
649 * Frees a #NULL-terminated array of strings.
650 * If passed #NULL, does nothing.
652 * @param str_array the array to be freed
655 dbus_free_string_array (char **str_array)
664 dbus_free (str_array[i]);
668 dbus_free (str_array);
672 /** @} */ /* End of public API docs block */
676 * @addtogroup DBusMemoryInternals
682 * _dbus_current_generation is used to track each
683 * time that dbus_shutdown() is called, so we can
684 * reinit things after it's been called. It is simply
685 * incremented each time we shut down.
687 int _dbus_current_generation = 1;
690 * Represents a function to be called on shutdown.
692 typedef struct ShutdownClosure ShutdownClosure;
695 * This struct represents a function to be called on shutdown.
697 struct ShutdownClosure
699 ShutdownClosure *next; /**< Next ShutdownClosure */
700 DBusShutdownFunction func; /**< Function to call */
701 void *data; /**< Data for function */
704 _DBUS_DEFINE_GLOBAL_LOCK (shutdown_funcs);
705 static ShutdownClosure *registered_globals = NULL;
708 * Register a cleanup function to be called exactly once
709 * the next time dbus_shutdown() is called.
711 * @param func the function
712 * @param data data to pass to the function
713 * @returns #FALSE on not enough memory
716 _dbus_register_shutdown_func (DBusShutdownFunction func,
721 c = dbus_new (ShutdownClosure, 1);
729 _DBUS_LOCK (shutdown_funcs);
731 c->next = registered_globals;
732 registered_globals = c;
734 _DBUS_UNLOCK (shutdown_funcs);
739 /** @} */ /* End of private API docs block */
743 * @addtogroup DBusMemory
749 * Frees all memory allocated internally by libdbus and
750 * reverses the effects of dbus_threads_init(). libdbus keeps internal
751 * global variables, for example caches and thread locks, and it
752 * can be useful to free these internal data structures.
754 * dbus_shutdown() does NOT free memory that was returned
755 * to the application. It only returns libdbus-internal
758 * You MUST free all memory and release all reference counts
759 * returned to you by libdbus prior to calling dbus_shutdown().
761 * You can't continue to use any D-Bus objects, such as connections,
762 * that were allocated prior to dbus_shutdown(). You can, however,
763 * start over; call dbus_threads_init() again, create new connections,
766 * WARNING: dbus_shutdown() is NOT thread safe, it must be called
767 * while NO other threads are using D-Bus. (Remember, you have to free
768 * all D-Bus objects and memory before you call dbus_shutdown(), so no
769 * thread can be using libdbus.)
771 * The purpose of dbus_shutdown() is to allow applications to get
772 * clean output from memory leak checkers. dbus_shutdown() may also be
773 * useful if you want to dlopen() libdbus instead of linking to it,
774 * and want to be able to unload the library again.
776 * There is absolutely no requirement to call dbus_shutdown() - in fact,
777 * most applications won't bother and should not feel guilty.
779 * You have to know that nobody is using libdbus in your application's
780 * process before you can call dbus_shutdown(). One implication of this
781 * is that calling dbus_shutdown() from a library is almost certainly
782 * wrong, since you don't know what the rest of the app is up to.
788 while (registered_globals != NULL)
792 c = registered_globals;
793 registered_globals = c->next;
795 (* c->func) (c->data);
800 _dbus_current_generation += 1;
803 /** @} */ /** End of public API docs block */
805 #ifdef DBUS_BUILD_TESTS
806 #include "dbus-test.h"
809 * @ingroup DBusMemoryInternals
810 * Unit test for DBusMemory
811 * @returns #TRUE on success.
814 _dbus_memory_test (void)
816 dbus_bool_t old_guards;
824 _dbus_assert_not_reached ("no memory");
825 for (size = 4; size < 256; size += 4)
827 p = dbus_realloc (p, size);
829 _dbus_assert_not_reached ("no memory");
831 for (size = 256; size != 0; size -= 4)
833 p = dbus_realloc (p, size);
835 _dbus_assert_not_reached ("no memory");