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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-memory.h"
26 #include "dbus-internals.h"
27 #include "dbus-sysdeps.h"
28 #include "dbus-list.h"
32 * @defgroup DBusMemory Memory Allocation
34 * @brief dbus_malloc(), dbus_free(), etc.
36 * Functions and macros related to allocating and releasing
42 * @defgroup DBusMemoryInternals Memory allocation implementation details
43 * @ingroup DBusInternals
44 * @brief internals of dbus_malloc() etc.
46 * Implementation details related to allocating and releasing blocks
51 * @addtogroup DBusMemory
59 * Safe macro for using dbus_malloc(). Accepts the type
60 * to allocate and the number of type instances to
61 * allocate as arguments, and returns a memory block
62 * cast to the desired type, instead of as a void*.
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
72 * Safe macro for using dbus_malloc0(). Accepts the type
73 * to allocate and the number of type instances to
74 * allocate as arguments, and returns a memory block
75 * cast to the desired type, instead of as a void*.
76 * The allocated array is initialized to all-bits-zero.
78 * @param type type name to allocate
79 * @param count number of instances in the allocated array
80 * @returns the new memory block or #NULL on failure
84 * @typedef DBusFreeFunction
86 * The type of a function which frees a block of memory.
88 * @param memory the memory to free
91 /** @} */ /* end of public API docs */
94 * @addtogroup DBusMemoryInternals
99 #ifdef DBUS_BUILD_TESTS
100 static dbus_bool_t debug_initialized = FALSE;
101 static int fail_nth = -1;
102 static size_t fail_size = 0;
103 static int fail_alloc_counter = _DBUS_INT_MAX;
104 static int n_failures_per_failure = 1;
105 static int n_failures_this_failure = 0;
106 static dbus_bool_t guards = FALSE;
107 static dbus_bool_t disable_mem_pools = FALSE;
108 static dbus_bool_t backtrace_on_fail_alloc = FALSE;
109 static DBusAtomic n_blocks_outstanding = {0};
111 /** value stored in guard padding for debugging buffer overrun */
112 #define GUARD_VALUE 0xdeadbeef
113 /** size of the information about the block stored in guard mode */
114 #define GUARD_INFO_SIZE 8
115 /** size of the GUARD_VALUE-filled padding after the header info */
116 #define GUARD_START_PAD 16
117 /** size of the GUARD_VALUE-filled padding at the end of the block */
118 #define GUARD_END_PAD 16
119 /** size of stuff at start of block */
120 #define GUARD_START_OFFSET (GUARD_START_PAD + GUARD_INFO_SIZE)
121 /** total extra size over the requested allocation for guard stuff */
122 #define GUARD_EXTRA_SIZE (GUARD_START_OFFSET + GUARD_END_PAD)
125 _dbus_initialize_malloc_debug (void)
127 if (!debug_initialized)
129 debug_initialized = TRUE;
131 if (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH") != NULL)
133 fail_nth = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH"));
134 fail_alloc_counter = fail_nth;
135 _dbus_verbose ("Will fail malloc every %d times\n", fail_nth);
138 if (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN") != NULL)
140 fail_size = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN"));
141 _dbus_verbose ("Will fail mallocs over %ld bytes\n",
145 if (_dbus_getenv ("DBUS_MALLOC_GUARDS") != NULL)
148 _dbus_verbose ("Will use malloc guards\n");
151 if (_dbus_getenv ("DBUS_DISABLE_MEM_POOLS") != NULL)
153 disable_mem_pools = TRUE;
154 _dbus_verbose ("Will disable memory pools\n");
157 if (_dbus_getenv ("DBUS_MALLOC_BACKTRACES") != NULL)
159 backtrace_on_fail_alloc = TRUE;
160 _dbus_verbose ("Will backtrace on failing a malloc\n");
166 * Whether to turn off mem pools, useful for leak checking.
168 * @returns #TRUE if mempools should not be used.
171 _dbus_disable_mem_pools (void)
173 _dbus_initialize_malloc_debug ();
174 return disable_mem_pools;
178 * Sets the number of allocations until we simulate a failed
179 * allocation. If set to 0, the next allocation to run
180 * fails; if set to 1, one succeeds then the next fails; etc.
181 * Set to _DBUS_INT_MAX to not fail anything.
183 * @param until_next_fail number of successful allocs before one fails
186 _dbus_set_fail_alloc_counter (int until_next_fail)
188 _dbus_initialize_malloc_debug ();
190 fail_alloc_counter = until_next_fail;
193 _dbus_verbose ("Set fail alloc counter = %d\n", fail_alloc_counter);
198 * Gets the number of successful allocs until we'll simulate
201 * @returns current counter value
204 _dbus_get_fail_alloc_counter (void)
206 _dbus_initialize_malloc_debug ();
208 return fail_alloc_counter;
212 * Sets how many mallocs to fail when the fail alloc counter reaches
215 * @param failures_per_failure number to fail
218 _dbus_set_fail_alloc_failures (int failures_per_failure)
220 n_failures_per_failure = failures_per_failure;
224 * Gets the number of failures we'll have when the fail malloc
227 * @returns number of failures planned
230 _dbus_get_fail_alloc_failures (void)
232 return n_failures_per_failure;
235 #ifdef DBUS_BUILD_TESTS
237 * Called when about to alloc some memory; if
238 * it returns #TRUE, then the allocation should
239 * fail. If it returns #FALSE, then the allocation
242 * @returns #TRUE if this alloc should fail
245 _dbus_decrement_fail_alloc_counter (void)
247 _dbus_initialize_malloc_debug ();
248 #ifdef DBUS_WIN_FIXME
250 static dbus_bool_t called = 0;
253 _dbus_warn("TODO: memory allocation testing errors disabled for now\n");
260 if (fail_alloc_counter <= 0)
262 if (backtrace_on_fail_alloc)
263 _dbus_print_backtrace ();
265 _dbus_verbose ("failure %d\n", n_failures_this_failure);
267 n_failures_this_failure += 1;
268 if (n_failures_this_failure >= n_failures_per_failure)
271 fail_alloc_counter = fail_nth;
273 fail_alloc_counter = _DBUS_INT_MAX;
275 n_failures_this_failure = 0;
277 _dbus_verbose ("reset fail alloc counter to %d\n", fail_alloc_counter);
284 fail_alloc_counter -= 1;
288 #endif /* DBUS_BUILD_TESTS */
291 * Get the number of outstanding malloc()'d blocks.
293 * @returns number of blocks
296 _dbus_get_malloc_blocks_outstanding (void)
298 return n_blocks_outstanding.value;
302 * Where the block came from.
314 source_string (BlockSource source)
324 case SOURCE_MALLOC_ZERO:
326 case SOURCE_REALLOC_NULL:
327 return "realloc(NULL)";
329 _dbus_assert_not_reached ("Invalid malloc block source ID");
334 check_guards (void *free_block,
335 dbus_bool_t overwrite)
337 if (free_block != NULL)
339 unsigned char *block = ((unsigned char*)free_block) - GUARD_START_OFFSET;
340 size_t requested_bytes = *(dbus_uint32_t*)block;
341 BlockSource source = *(dbus_uint32_t*)(block + 4);
348 _dbus_verbose ("Checking %d bytes request from source %s\n",
349 requested_bytes, source_string (source));
353 while (i < GUARD_START_OFFSET)
355 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
356 if (value != GUARD_VALUE)
358 _dbus_warn ("Block of %lu bytes from %s had start guard value 0x%ux at %d expected 0x%x\n",
359 (long) requested_bytes, source_string (source),
360 value, i, GUARD_VALUE);
367 i = GUARD_START_OFFSET + requested_bytes;
368 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
370 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
371 if (value != GUARD_VALUE)
373 _dbus_warn ("Block of %lu bytes from %s had end guard value 0x%ux at %d expected 0x%x\n",
374 (long) requested_bytes, source_string (source),
375 value, i, GUARD_VALUE);
382 /* set memory to anything but nul bytes */
384 memset (free_block, 'g', requested_bytes);
387 _dbus_assert_not_reached ("guard value corruption");
392 set_guards (void *real_block,
393 size_t requested_bytes,
396 unsigned char *block = real_block;
402 _dbus_assert (GUARD_START_OFFSET + GUARD_END_PAD == GUARD_EXTRA_SIZE);
404 *((dbus_uint32_t*)block) = requested_bytes;
405 *((dbus_uint32_t*)(block + 4)) = source;
408 while (i < GUARD_START_OFFSET)
410 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
415 i = GUARD_START_OFFSET + requested_bytes;
416 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
418 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
423 check_guards (block + GUARD_START_OFFSET, FALSE);
425 return block + GUARD_START_OFFSET;
430 /** @} */ /* End of internals docs */
434 * @addtogroup DBusMemory
440 * Allocates the given number of bytes, as with standard
441 * malloc(). Guaranteed to return #NULL if bytes is zero
442 * on all platforms. Returns #NULL if the allocation fails.
443 * The memory must be released with dbus_free().
445 * dbus_malloc() memory is NOT safe to free with regular free() from
446 * the C library. Free it with dbus_free() only.
448 * @param bytes number of bytes to allocate
449 * @return allocated memory, or #NULL if the allocation fails.
452 dbus_malloc (size_t bytes)
454 #ifdef DBUS_BUILD_TESTS
455 _dbus_initialize_malloc_debug ();
457 if (_dbus_decrement_fail_alloc_counter ())
459 _dbus_verbose (" FAILING malloc of %ld bytes\n", (long) bytes);
464 if (bytes == 0) /* some system mallocs handle this, some don't */
466 #ifdef DBUS_BUILD_TESTS
467 else if (fail_size != 0 && bytes > fail_size)
473 block = malloc (bytes + GUARD_EXTRA_SIZE);
475 _dbus_atomic_inc (&n_blocks_outstanding);
477 return set_guards (block, bytes, SOURCE_MALLOC);
483 mem = malloc (bytes);
484 #ifdef DBUS_BUILD_TESTS
486 _dbus_atomic_inc (&n_blocks_outstanding);
493 * Allocates the given number of bytes, as with standard malloc(), but
494 * all bytes are initialized to zero as with calloc(). Guaranteed to
495 * return #NULL if bytes is zero on all platforms. Returns #NULL if the
496 * allocation fails. The memory must be released with dbus_free().
498 * dbus_malloc0() memory is NOT safe to free with regular free() from
499 * the C library. Free it with dbus_free() only.
501 * @param bytes number of bytes to allocate
502 * @return allocated memory, or #NULL if the allocation fails.
505 dbus_malloc0 (size_t bytes)
507 #ifdef DBUS_BUILD_TESTS
508 _dbus_initialize_malloc_debug ();
510 if (_dbus_decrement_fail_alloc_counter ())
512 _dbus_verbose (" FAILING malloc0 of %ld bytes\n", (long) bytes);
520 #ifdef DBUS_BUILD_TESTS
521 else if (fail_size != 0 && bytes > fail_size)
527 block = calloc (bytes + GUARD_EXTRA_SIZE, 1);
529 _dbus_atomic_inc (&n_blocks_outstanding);
530 return set_guards (block, bytes, SOURCE_MALLOC_ZERO);
536 mem = calloc (bytes, 1);
537 #ifdef DBUS_BUILD_TESTS
539 _dbus_atomic_inc (&n_blocks_outstanding);
546 * Resizes a block of memory previously allocated by dbus_malloc() or
547 * dbus_malloc0(). Guaranteed to free the memory and return #NULL if bytes
548 * is zero on all platforms. Returns #NULL if the resize fails.
549 * If the resize fails, the memory is not freed.
551 * @param memory block to be resized
552 * @param bytes new size of the memory block
553 * @return allocated memory, or #NULL if the resize fails.
556 dbus_realloc (void *memory,
559 #ifdef DBUS_BUILD_TESTS
560 _dbus_initialize_malloc_debug ();
562 if (_dbus_decrement_fail_alloc_counter ())
564 _dbus_verbose (" FAILING realloc of %ld bytes\n", (long) bytes);
570 if (bytes == 0) /* guarantee this is safe */
575 #ifdef DBUS_BUILD_TESTS
576 else if (fail_size != 0 && bytes > fail_size)
585 check_guards (memory, FALSE);
587 block = realloc (((unsigned char*)memory) - GUARD_START_OFFSET,
588 bytes + GUARD_EXTRA_SIZE);
590 old_bytes = *(dbus_uint32_t*)block;
591 if (block && bytes >= old_bytes)
592 /* old guards shouldn't have moved */
593 check_guards (((unsigned char*)block) + GUARD_START_OFFSET, FALSE);
595 return set_guards (block, bytes, SOURCE_REALLOC);
601 block = malloc (bytes + GUARD_EXTRA_SIZE);
604 _dbus_atomic_inc (&n_blocks_outstanding);
606 return set_guards (block, bytes, SOURCE_REALLOC_NULL);
613 mem = realloc (memory, bytes);
614 #ifdef DBUS_BUILD_TESTS
615 if (memory == NULL && mem != NULL)
616 _dbus_atomic_inc (&n_blocks_outstanding);
623 * Frees a block of memory previously allocated by dbus_malloc() or
624 * dbus_malloc0(). If passed #NULL, does nothing.
626 * @param memory block to be freed
629 dbus_free (void *memory)
631 #ifdef DBUS_BUILD_TESTS
634 check_guards (memory, TRUE);
637 _dbus_atomic_dec (&n_blocks_outstanding);
639 _dbus_assert (n_blocks_outstanding.value >= 0);
641 free (((unsigned char*)memory) - GUARD_START_OFFSET);
648 if (memory) /* we guarantee it's safe to free (NULL) */
650 #ifdef DBUS_BUILD_TESTS
651 _dbus_atomic_dec (&n_blocks_outstanding);
653 _dbus_assert (n_blocks_outstanding.value >= 0);
661 * Frees a #NULL-terminated array of strings.
662 * If passed #NULL, does nothing.
664 * @param str_array the array to be freed
667 dbus_free_string_array (char **str_array)
676 dbus_free (str_array[i]);
680 dbus_free (str_array);
684 /** @} */ /* End of public API docs block */
688 * @addtogroup DBusMemoryInternals
694 * _dbus_current_generation is used to track each
695 * time that dbus_shutdown() is called, so we can
696 * reinit things after it's been called. It is simply
697 * incremented each time we shut down.
699 int _dbus_current_generation = 1;
702 * Represents a function to be called on shutdown.
704 typedef struct ShutdownClosure ShutdownClosure;
707 * This struct represents a function to be called on shutdown.
709 struct ShutdownClosure
711 ShutdownClosure *next; /**< Next ShutdownClosure */
712 DBusShutdownFunction func; /**< Function to call */
713 void *data; /**< Data for function */
716 _DBUS_DEFINE_GLOBAL_LOCK (shutdown_funcs);
717 static ShutdownClosure *registered_globals = NULL;
720 * Register a cleanup function to be called exactly once
721 * the next time dbus_shutdown() is called.
723 * @param func the function
724 * @param data data to pass to the function
725 * @returns #FALSE on not enough memory
728 _dbus_register_shutdown_func (DBusShutdownFunction func,
733 c = dbus_new (ShutdownClosure, 1);
741 _DBUS_LOCK (shutdown_funcs);
743 c->next = registered_globals;
744 registered_globals = c;
746 _DBUS_UNLOCK (shutdown_funcs);
751 /** @} */ /* End of private API docs block */
755 * @addtogroup DBusMemory
761 * Frees all memory allocated internally by libdbus and
762 * reverses the effects of dbus_threads_init(). libdbus keeps internal
763 * global variables, for example caches and thread locks, and it
764 * can be useful to free these internal data structures.
766 * dbus_shutdown() does NOT free memory that was returned
767 * to the application. It only returns libdbus-internal
770 * You MUST free all memory and release all reference counts
771 * returned to you by libdbus prior to calling dbus_shutdown().
773 * You can't continue to use any D-Bus objects, such as connections,
774 * that were allocated prior to dbus_shutdown(). You can, however,
775 * start over; call dbus_threads_init() again, create new connections,
778 * WARNING: dbus_shutdown() is NOT thread safe, it must be called
779 * while NO other threads are using D-Bus. (Remember, you have to free
780 * all D-Bus objects and memory before you call dbus_shutdown(), so no
781 * thread can be using libdbus.)
783 * The purpose of dbus_shutdown() is to allow applications to get
784 * clean output from memory leak checkers. dbus_shutdown() may also be
785 * useful if you want to dlopen() libdbus instead of linking to it,
786 * and want to be able to unload the library again.
788 * There is absolutely no requirement to call dbus_shutdown() - in fact,
789 * most applications won't bother and should not feel guilty.
791 * You have to know that nobody is using libdbus in your application's
792 * process before you can call dbus_shutdown(). One implication of this
793 * is that calling dbus_shutdown() from a library is almost certainly
794 * wrong, since you don't know what the rest of the app is up to.
800 while (registered_globals != NULL)
804 c = registered_globals;
805 registered_globals = c->next;
807 (* c->func) (c->data);
812 _dbus_current_generation += 1;
815 /** @} */ /** End of public API docs block */
817 #ifdef DBUS_BUILD_TESTS
818 #include "dbus-test.h"
821 * @ingroup DBusMemoryInternals
822 * Unit test for DBusMemory
823 * @returns #TRUE on success.
826 _dbus_memory_test (void)
828 dbus_bool_t old_guards;
836 _dbus_assert_not_reached ("no memory");
837 for (size = 4; size < 256; size += 4)
839 p = dbus_realloc (p, size);
841 _dbus_assert_not_reached ("no memory");
843 for (size = 256; size != 0; size -= 4)
845 p = dbus_realloc (p, size);
847 _dbus_assert_not_reached ("no memory");