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"
29 #include "dbus-threads.h"
33 * @defgroup DBusMemory Memory Allocation
35 * @brief dbus_malloc(), dbus_free(), etc.
37 * Functions and macros related to allocating and releasing
43 * @defgroup DBusMemoryInternals Memory allocation implementation details
44 * @ingroup DBusInternals
45 * @brief internals of dbus_malloc() etc.
47 * Implementation details related to allocating and releasing blocks
52 * @addtogroup DBusMemory
60 * Safe macro for using dbus_malloc(). Accepts the type
61 * to allocate and the number of type instances to
62 * allocate as arguments, and returns a memory block
63 * cast to the desired type, instead of as a void*.
65 * @param type type name to allocate
66 * @param count number of instances in the allocated array
67 * @returns the new memory block or #NULL on failure
73 * Safe macro for using dbus_malloc0(). Accepts the type
74 * to allocate and the number of type instances to
75 * allocate as arguments, and returns a memory block
76 * cast to the desired type, instead of as a void*.
77 * The allocated array is initialized to all-bits-zero.
79 * @param type type name to allocate
80 * @param count number of instances in the allocated array
81 * @returns the new memory block or #NULL on failure
85 * @typedef DBusFreeFunction
87 * The type of a function which frees a block of memory.
89 * @param memory the memory to free
92 /** @} */ /* end of public API docs */
95 * @addtogroup DBusMemoryInternals
100 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
101 static dbus_bool_t debug_initialized = FALSE;
102 static int fail_nth = -1;
103 static size_t fail_size = 0;
104 static int fail_alloc_counter = _DBUS_INT_MAX;
105 static int n_failures_per_failure = 1;
106 static int n_failures_this_failure = 0;
107 static dbus_bool_t guards = FALSE;
108 static dbus_bool_t disable_mem_pools = FALSE;
109 static dbus_bool_t backtrace_on_fail_alloc = FALSE;
110 static dbus_bool_t malloc_cannot_fail = FALSE;
111 static DBusAtomic n_blocks_outstanding = {0};
113 /** value stored in guard padding for debugging buffer overrun */
114 #define GUARD_VALUE 0xdeadbeef
115 /** size of the information about the block stored in guard mode */
116 #define GUARD_INFO_SIZE 8
117 /** size of the GUARD_VALUE-filled padding after the header info */
118 #define GUARD_START_PAD 16
119 /** size of the GUARD_VALUE-filled padding at the end of the block */
120 #define GUARD_END_PAD 16
121 /** size of stuff at start of block */
122 #define GUARD_START_OFFSET (GUARD_START_PAD + GUARD_INFO_SIZE)
123 /** total extra size over the requested allocation for guard stuff */
124 #define GUARD_EXTRA_SIZE (GUARD_START_OFFSET + GUARD_END_PAD)
127 _dbus_initialize_malloc_debug (void)
129 if (!debug_initialized)
131 debug_initialized = TRUE;
133 if (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH") != NULL)
135 fail_nth = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH"));
136 fail_alloc_counter = fail_nth;
137 _dbus_verbose ("Will fail dbus_malloc every %d times\n", fail_nth);
140 if (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN") != NULL)
142 fail_size = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN"));
143 _dbus_verbose ("Will fail mallocs over %ld bytes\n",
147 if (_dbus_getenv ("DBUS_MALLOC_GUARDS") != NULL)
150 _dbus_verbose ("Will use dbus_malloc guards\n");
153 if (_dbus_getenv ("DBUS_DISABLE_MEM_POOLS") != NULL)
155 disable_mem_pools = TRUE;
156 _dbus_verbose ("Will disable memory pools\n");
159 if (_dbus_getenv ("DBUS_MALLOC_BACKTRACES") != NULL)
161 backtrace_on_fail_alloc = TRUE;
162 _dbus_verbose ("Will backtrace on failing a dbus_malloc\n");
165 if (_dbus_getenv ("DBUS_MALLOC_CANNOT_FAIL") != NULL)
167 malloc_cannot_fail = TRUE;
168 _dbus_verbose ("Will abort if system malloc() and friends fail\n");
174 * Whether to turn off mem pools, useful for leak checking.
176 * @returns #TRUE if mempools should not be used.
179 _dbus_disable_mem_pools (void)
181 _dbus_initialize_malloc_debug ();
182 return disable_mem_pools;
186 * Sets the number of allocations until we simulate a failed
187 * allocation. If set to 0, the next allocation to run
188 * fails; if set to 1, one succeeds then the next fails; etc.
189 * Set to _DBUS_INT_MAX to not fail anything.
191 * @param until_next_fail number of successful allocs before one fails
194 _dbus_set_fail_alloc_counter (int until_next_fail)
196 _dbus_initialize_malloc_debug ();
198 fail_alloc_counter = until_next_fail;
201 _dbus_verbose ("Set fail alloc counter = %d\n", fail_alloc_counter);
206 * Gets the number of successful allocs until we'll simulate
209 * @returns current counter value
212 _dbus_get_fail_alloc_counter (void)
214 _dbus_initialize_malloc_debug ();
216 return fail_alloc_counter;
220 * Sets how many mallocs to fail when the fail alloc counter reaches
223 * @param failures_per_failure number to fail
226 _dbus_set_fail_alloc_failures (int failures_per_failure)
228 n_failures_per_failure = failures_per_failure;
232 * Gets the number of failures we'll have when the fail malloc
235 * @returns number of failures planned
238 _dbus_get_fail_alloc_failures (void)
240 return n_failures_per_failure;
243 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
245 * Called when about to alloc some memory; if
246 * it returns #TRUE, then the allocation should
247 * fail. If it returns #FALSE, then the allocation
250 * @returns #TRUE if this alloc should fail
253 _dbus_decrement_fail_alloc_counter (void)
255 _dbus_initialize_malloc_debug ();
256 #ifdef DBUS_WIN_FIXME
258 static dbus_bool_t called = 0;
262 _dbus_verbose("TODO: memory allocation testing errors disabled for now\n");
269 if (fail_alloc_counter <= 0)
271 if (backtrace_on_fail_alloc)
272 _dbus_print_backtrace ();
274 _dbus_verbose ("failure %d\n", n_failures_this_failure);
276 n_failures_this_failure += 1;
277 if (n_failures_this_failure >= n_failures_per_failure)
280 fail_alloc_counter = fail_nth;
282 fail_alloc_counter = _DBUS_INT_MAX;
284 n_failures_this_failure = 0;
286 _dbus_verbose ("reset fail alloc counter to %d\n", fail_alloc_counter);
293 fail_alloc_counter -= 1;
297 #endif /* DBUS_ENABLE_EMBEDDED_TESTS */
300 * Get the number of outstanding malloc()'d blocks.
302 * @returns number of blocks
305 _dbus_get_malloc_blocks_outstanding (void)
307 return _dbus_atomic_get (&n_blocks_outstanding);
311 * Where the block came from.
323 source_string (BlockSource source)
333 case SOURCE_MALLOC_ZERO:
335 case SOURCE_REALLOC_NULL:
336 return "realloc(NULL)";
338 _dbus_assert_not_reached ("Invalid malloc block source ID");
344 check_guards (void *free_block,
345 dbus_bool_t overwrite)
347 if (free_block != NULL)
349 unsigned char *block = ((unsigned char*)free_block) - GUARD_START_OFFSET;
350 size_t requested_bytes = *(dbus_uint32_t*)block;
351 BlockSource source = *(dbus_uint32_t*)(block + 4);
358 _dbus_verbose ("Checking %d bytes request from source %s\n",
359 requested_bytes, source_string (source));
363 while (i < GUARD_START_OFFSET)
365 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
366 if (value != GUARD_VALUE)
368 _dbus_warn ("Block of %lu bytes from %s had start guard value 0x%ux at %d expected 0x%x",
369 (long) requested_bytes, source_string (source),
370 value, i, GUARD_VALUE);
377 i = GUARD_START_OFFSET + requested_bytes;
378 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
380 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
381 if (value != GUARD_VALUE)
383 _dbus_warn ("Block of %lu bytes from %s had end guard value 0x%ux at %d expected 0x%x",
384 (long) requested_bytes, source_string (source),
385 value, i, GUARD_VALUE);
392 /* set memory to anything but nul bytes */
394 memset (free_block, 'g', requested_bytes);
397 _dbus_assert_not_reached ("guard value corruption");
402 set_guards (void *real_block,
403 size_t requested_bytes,
406 unsigned char *block = real_block;
412 _dbus_assert (GUARD_START_OFFSET + GUARD_END_PAD == GUARD_EXTRA_SIZE);
414 *((dbus_uint32_t*)block) = requested_bytes;
415 *((dbus_uint32_t*)(block + 4)) = source;
418 while (i < GUARD_START_OFFSET)
420 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
425 i = GUARD_START_OFFSET + requested_bytes;
426 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
428 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
433 check_guards (block + GUARD_START_OFFSET, FALSE);
435 return block + GUARD_START_OFFSET;
440 /** @} */ /* End of internals docs */
444 * @addtogroup DBusMemory
450 * Allocates the given number of bytes, as with standard
451 * malloc(). Guaranteed to return #NULL if bytes is zero
452 * on all platforms. Returns #NULL if the allocation fails.
453 * The memory must be released with dbus_free().
455 * dbus_malloc() memory is NOT safe to free with regular free() from
456 * the C library. Free it with dbus_free() only.
458 * @param bytes number of bytes to allocate
459 * @return allocated memory, or #NULL if the allocation fails.
462 dbus_malloc (size_t bytes)
464 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
465 _dbus_initialize_malloc_debug ();
467 if (_dbus_decrement_fail_alloc_counter ())
469 _dbus_verbose (" FAILING malloc of %ld bytes\n", (long) bytes);
474 if (bytes == 0) /* some system mallocs handle this, some don't */
476 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
477 else if (fail_size != 0 && bytes > fail_size)
483 block = malloc (bytes + GUARD_EXTRA_SIZE);
486 _dbus_atomic_inc (&n_blocks_outstanding);
488 else if (malloc_cannot_fail)
490 _dbus_warn ("out of memory: malloc (%ld + %ld)",
491 (long) bytes, (long) GUARD_EXTRA_SIZE);
495 return set_guards (block, bytes, SOURCE_MALLOC);
501 mem = malloc (bytes);
503 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
506 _dbus_atomic_inc (&n_blocks_outstanding);
508 else if (malloc_cannot_fail)
510 _dbus_warn ("out of memory: malloc (%ld)", (long) bytes);
520 * Allocates the given number of bytes, as with standard malloc(), but
521 * all bytes are initialized to zero as with calloc(). Guaranteed to
522 * return #NULL if bytes is zero on all platforms. Returns #NULL if the
523 * allocation fails. The memory must be released with dbus_free().
525 * dbus_malloc0() memory is NOT safe to free with regular free() from
526 * the C library. Free it with dbus_free() only.
528 * @param bytes number of bytes to allocate
529 * @return allocated memory, or #NULL if the allocation fails.
532 dbus_malloc0 (size_t bytes)
534 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
535 _dbus_initialize_malloc_debug ();
537 if (_dbus_decrement_fail_alloc_counter ())
539 _dbus_verbose (" FAILING malloc0 of %ld bytes\n", (long) bytes);
547 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
548 else if (fail_size != 0 && bytes > fail_size)
554 block = calloc (bytes + GUARD_EXTRA_SIZE, 1);
558 _dbus_atomic_inc (&n_blocks_outstanding);
560 else if (malloc_cannot_fail)
562 _dbus_warn ("out of memory: calloc (%ld + %ld, 1)",
563 (long) bytes, (long) GUARD_EXTRA_SIZE);
567 return set_guards (block, bytes, SOURCE_MALLOC_ZERO);
573 mem = calloc (bytes, 1);
575 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
578 _dbus_atomic_inc (&n_blocks_outstanding);
580 else if (malloc_cannot_fail)
582 _dbus_warn ("out of memory: calloc (%ld)", (long) bytes);
592 * Resizes a block of memory previously allocated by dbus_malloc() or
593 * dbus_malloc0(). Guaranteed to free the memory and return #NULL if bytes
594 * is zero on all platforms. Returns #NULL if the resize fails.
595 * If the resize fails, the memory is not freed.
597 * @param memory block to be resized
598 * @param bytes new size of the memory block
599 * @return allocated memory, or #NULL if the resize fails.
602 dbus_realloc (void *memory,
605 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
606 _dbus_initialize_malloc_debug ();
608 if (_dbus_decrement_fail_alloc_counter ())
610 _dbus_verbose (" FAILING realloc of %ld bytes\n", (long) bytes);
616 if (bytes == 0) /* guarantee this is safe */
621 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
622 else if (fail_size != 0 && bytes > fail_size)
631 check_guards (memory, FALSE);
633 block = realloc (((unsigned char*)memory) - GUARD_START_OFFSET,
634 bytes + GUARD_EXTRA_SIZE);
638 if (malloc_cannot_fail)
640 _dbus_warn ("out of memory: realloc (%p, %ld + %ld)",
641 memory, (long) bytes, (long) GUARD_EXTRA_SIZE);
648 old_bytes = *(dbus_uint32_t*)block;
649 if (bytes >= old_bytes)
650 /* old guards shouldn't have moved */
651 check_guards (((unsigned char*)block) + GUARD_START_OFFSET, FALSE);
653 return set_guards (block, bytes, SOURCE_REALLOC);
659 block = malloc (bytes + GUARD_EXTRA_SIZE);
663 _dbus_atomic_inc (&n_blocks_outstanding);
665 else if (malloc_cannot_fail)
667 _dbus_warn ("out of memory: malloc (%ld + %ld)",
668 (long) bytes, (long) GUARD_EXTRA_SIZE);
672 return set_guards (block, bytes, SOURCE_REALLOC_NULL);
679 mem = realloc (memory, bytes);
681 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
682 if (mem == NULL && malloc_cannot_fail)
684 _dbus_warn ("out of memory: malloc (%ld)", (long) bytes);
688 if (memory == NULL && mem != NULL)
689 _dbus_atomic_inc (&n_blocks_outstanding);
696 * Frees a block of memory previously allocated by dbus_malloc() or
697 * dbus_malloc0(). If passed #NULL, does nothing.
699 * @param memory block to be freed
702 dbus_free (void *memory)
704 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
707 check_guards (memory, TRUE);
710 #ifdef DBUS_DISABLE_ASSERT
711 _dbus_atomic_dec (&n_blocks_outstanding);
713 dbus_int32_t old_value;
715 old_value = _dbus_atomic_dec (&n_blocks_outstanding);
716 _dbus_assert (old_value >= 1);
719 free (((unsigned char*)memory) - GUARD_START_OFFSET);
726 if (memory) /* we guarantee it's safe to free (NULL) */
728 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
729 #ifdef DBUS_DISABLE_ASSERT
730 _dbus_atomic_dec (&n_blocks_outstanding);
732 dbus_int32_t old_value;
734 old_value = _dbus_atomic_dec (&n_blocks_outstanding);
735 _dbus_assert (old_value >= 1);
744 * Frees a #NULL-terminated array of strings.
745 * If passed #NULL, does nothing.
747 * @param str_array the array to be freed
750 dbus_free_string_array (char **str_array)
759 dbus_free (str_array[i]);
763 dbus_free (str_array);
767 /** @} */ /* End of public API docs block */
771 * @addtogroup DBusMemoryInternals
777 * _dbus_current_generation is used to track each
778 * time that dbus_shutdown() is called, so we can
779 * reinit things after it's been called. It is simply
780 * incremented each time we shut down.
782 int _dbus_current_generation = 1;
785 * Represents a function to be called on shutdown.
787 typedef struct ShutdownClosure ShutdownClosure;
790 * This struct represents a function to be called on shutdown.
792 struct ShutdownClosure
794 ShutdownClosure *next; /**< Next ShutdownClosure */
795 DBusShutdownFunction func; /**< Function to call */
796 void *data; /**< Data for function */
799 /* Protected by _DBUS_LOCK (shutdown_funcs) */
800 static ShutdownClosure *registered_globals = NULL;
803 * Register a cleanup function to be called exactly once
804 * the next time dbus_shutdown() is called.
806 * @param func the function
807 * @param data data to pass to the function
808 * @returns #FALSE on not enough memory
811 _dbus_register_shutdown_func (DBusShutdownFunction func,
816 if (!_DBUS_LOCK (shutdown_funcs))
819 ok = _dbus_register_shutdown_func_unlocked (func, data);
820 _DBUS_UNLOCK (shutdown_funcs);
825 _dbus_register_shutdown_func_unlocked (DBusShutdownFunction func,
830 c = dbus_new (ShutdownClosure, 1);
838 c->next = registered_globals;
839 registered_globals = c;
844 /** @} */ /* End of private API docs block */
848 * @addtogroup DBusMemory
854 * Frees all memory allocated internally by libdbus and
855 * reverses the effects of dbus_threads_init(). libdbus keeps internal
856 * global variables, for example caches and thread locks, and it
857 * can be useful to free these internal data structures.
859 * dbus_shutdown() does NOT free memory that was returned
860 * to the application. It only frees libdbus-internal
863 * You MUST free all memory and release all reference counts
864 * returned to you by libdbus prior to calling dbus_shutdown().
866 * If a shared connection is open, calling dbus_shutdown() will
867 * drain its queue of messages and disconnect it. In particular,
868 * this will result in processing of the special Disconnected
869 * signal, which may result in a call to _exit(), unless you
870 * have used dbus_connection_set_exit_on_disconnect() to disable
873 * You can't continue to use any D-Bus objects, such as connections,
874 * that were allocated prior to dbus_shutdown(). You can, however,
875 * start over; call dbus_threads_init() again, create new connections,
878 * WARNING: dbus_shutdown() is NOT thread safe, it must be called
879 * while NO other threads are using D-Bus. (Remember, you have to free
880 * all D-Bus objects and memory before you call dbus_shutdown(), so no
881 * thread can be using libdbus.)
883 * The purpose of dbus_shutdown() is to allow applications to get
884 * clean output from memory leak checkers. dbus_shutdown() may also be
885 * useful if you want to dlopen() libdbus instead of linking to it,
886 * and want to be able to unload the library again.
888 * There is absolutely no requirement to call dbus_shutdown() - in fact,
889 * most applications won't bother and should not feel guilty.
891 * You have to know that nobody is using libdbus in your application's
892 * process before you can call dbus_shutdown(). One implication of this
893 * is that calling dbus_shutdown() from a library is almost certainly
894 * wrong, since you don't know what the rest of the app is up to.
900 while (registered_globals != NULL)
904 c = registered_globals;
905 registered_globals = c->next;
907 (* c->func) (c->data);
912 /* We wrap this in the thread-initialization lock because
913 * dbus_threads_init() uses the current generation to tell whether
914 * we're initialized, so we need to make sure that un-initializing
915 * propagates into all threads. */
916 _dbus_threads_lock_platform_specific ();
917 _dbus_current_generation += 1;
918 _dbus_threads_unlock_platform_specific ();
921 /** @} */ /** End of public API docs block */
923 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
924 #include "dbus-test.h"
927 * @ingroup DBusMemoryInternals
928 * Unit test for DBusMemory
929 * @returns #TRUE on success.
932 _dbus_memory_test (void)
934 dbus_bool_t old_guards;
942 _dbus_assert_not_reached ("no memory");
943 for (size = 4; size < 256; size += 4)
945 p = dbus_realloc (p, size);
947 _dbus_assert_not_reached ("no memory");
949 for (size = 256; size != 0; size -= 4)
951 p = dbus_realloc (p, size);
953 _dbus_assert_not_reached ("no memory");