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 dbus_bool_t malloc_cannot_fail = FALSE;
110 static DBusAtomic n_blocks_outstanding = {0};
112 /** value stored in guard padding for debugging buffer overrun */
113 #define GUARD_VALUE 0xdeadbeef
114 /** size of the information about the block stored in guard mode */
115 #define GUARD_INFO_SIZE 8
116 /** size of the GUARD_VALUE-filled padding after the header info */
117 #define GUARD_START_PAD 16
118 /** size of the GUARD_VALUE-filled padding at the end of the block */
119 #define GUARD_END_PAD 16
120 /** size of stuff at start of block */
121 #define GUARD_START_OFFSET (GUARD_START_PAD + GUARD_INFO_SIZE)
122 /** total extra size over the requested allocation for guard stuff */
123 #define GUARD_EXTRA_SIZE (GUARD_START_OFFSET + GUARD_END_PAD)
126 _dbus_initialize_malloc_debug (void)
128 if (!debug_initialized)
130 debug_initialized = TRUE;
132 if (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH") != NULL)
134 fail_nth = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH"));
135 fail_alloc_counter = fail_nth;
136 _dbus_verbose ("Will fail dbus_malloc every %d times\n", fail_nth);
139 if (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN") != NULL)
141 fail_size = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN"));
142 _dbus_verbose ("Will fail mallocs over %ld bytes\n",
146 if (_dbus_getenv ("DBUS_MALLOC_GUARDS") != NULL)
149 _dbus_verbose ("Will use dbus_malloc guards\n");
152 if (_dbus_getenv ("DBUS_DISABLE_MEM_POOLS") != NULL)
154 disable_mem_pools = TRUE;
155 _dbus_verbose ("Will disable memory pools\n");
158 if (_dbus_getenv ("DBUS_MALLOC_BACKTRACES") != NULL)
160 backtrace_on_fail_alloc = TRUE;
161 _dbus_verbose ("Will backtrace on failing a dbus_malloc\n");
164 if (_dbus_getenv ("DBUS_MALLOC_CANNOT_FAIL") != NULL)
166 malloc_cannot_fail = TRUE;
167 _dbus_verbose ("Will abort if system malloc() and friends fail\n");
173 * Whether to turn off mem pools, useful for leak checking.
175 * @returns #TRUE if mempools should not be used.
178 _dbus_disable_mem_pools (void)
180 _dbus_initialize_malloc_debug ();
181 return disable_mem_pools;
185 * Sets the number of allocations until we simulate a failed
186 * allocation. If set to 0, the next allocation to run
187 * fails; if set to 1, one succeeds then the next fails; etc.
188 * Set to _DBUS_INT_MAX to not fail anything.
190 * @param until_next_fail number of successful allocs before one fails
193 _dbus_set_fail_alloc_counter (int until_next_fail)
195 _dbus_initialize_malloc_debug ();
197 fail_alloc_counter = until_next_fail;
200 _dbus_verbose ("Set fail alloc counter = %d\n", fail_alloc_counter);
205 * Gets the number of successful allocs until we'll simulate
208 * @returns current counter value
211 _dbus_get_fail_alloc_counter (void)
213 _dbus_initialize_malloc_debug ();
215 return fail_alloc_counter;
219 * Sets how many mallocs to fail when the fail alloc counter reaches
222 * @param failures_per_failure number to fail
225 _dbus_set_fail_alloc_failures (int failures_per_failure)
227 n_failures_per_failure = failures_per_failure;
231 * Gets the number of failures we'll have when the fail malloc
234 * @returns number of failures planned
237 _dbus_get_fail_alloc_failures (void)
239 return n_failures_per_failure;
242 #ifdef DBUS_BUILD_TESTS
244 * Called when about to alloc some memory; if
245 * it returns #TRUE, then the allocation should
246 * fail. If it returns #FALSE, then the allocation
249 * @returns #TRUE if this alloc should fail
252 _dbus_decrement_fail_alloc_counter (void)
254 _dbus_initialize_malloc_debug ();
255 #ifdef DBUS_WIN_FIXME
257 static dbus_bool_t called = 0;
261 _dbus_verbose("TODO: memory allocation testing errors disabled for now\n");
268 if (fail_alloc_counter <= 0)
270 if (backtrace_on_fail_alloc)
271 _dbus_print_backtrace ();
273 _dbus_verbose ("failure %d\n", n_failures_this_failure);
275 n_failures_this_failure += 1;
276 if (n_failures_this_failure >= n_failures_per_failure)
279 fail_alloc_counter = fail_nth;
281 fail_alloc_counter = _DBUS_INT_MAX;
283 n_failures_this_failure = 0;
285 _dbus_verbose ("reset fail alloc counter to %d\n", fail_alloc_counter);
292 fail_alloc_counter -= 1;
296 #endif /* DBUS_BUILD_TESTS */
299 * Get the number of outstanding malloc()'d blocks.
301 * @returns number of blocks
304 _dbus_get_malloc_blocks_outstanding (void)
306 return _dbus_atomic_get (&n_blocks_outstanding);
310 * Where the block came from.
322 source_string (BlockSource source)
332 case SOURCE_MALLOC_ZERO:
334 case SOURCE_REALLOC_NULL:
335 return "realloc(NULL)";
337 _dbus_assert_not_reached ("Invalid malloc block source ID");
342 check_guards (void *free_block,
343 dbus_bool_t overwrite)
345 if (free_block != NULL)
347 unsigned char *block = ((unsigned char*)free_block) - GUARD_START_OFFSET;
348 size_t requested_bytes = *(dbus_uint32_t*)block;
349 BlockSource source = *(dbus_uint32_t*)(block + 4);
356 _dbus_verbose ("Checking %d bytes request from source %s\n",
357 requested_bytes, source_string (source));
361 while (i < GUARD_START_OFFSET)
363 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
364 if (value != GUARD_VALUE)
366 _dbus_warn ("Block of %lu bytes from %s had start guard value 0x%ux at %d expected 0x%x\n",
367 (long) requested_bytes, source_string (source),
368 value, i, GUARD_VALUE);
375 i = GUARD_START_OFFSET + requested_bytes;
376 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
378 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
379 if (value != GUARD_VALUE)
381 _dbus_warn ("Block of %lu bytes from %s had end guard value 0x%ux at %d expected 0x%x\n",
382 (long) requested_bytes, source_string (source),
383 value, i, GUARD_VALUE);
390 /* set memory to anything but nul bytes */
392 memset (free_block, 'g', requested_bytes);
395 _dbus_assert_not_reached ("guard value corruption");
400 set_guards (void *real_block,
401 size_t requested_bytes,
404 unsigned char *block = real_block;
410 _dbus_assert (GUARD_START_OFFSET + GUARD_END_PAD == GUARD_EXTRA_SIZE);
412 *((dbus_uint32_t*)block) = requested_bytes;
413 *((dbus_uint32_t*)(block + 4)) = source;
416 while (i < GUARD_START_OFFSET)
418 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
423 i = GUARD_START_OFFSET + requested_bytes;
424 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
426 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
431 check_guards (block + GUARD_START_OFFSET, FALSE);
433 return block + GUARD_START_OFFSET;
438 /** @} */ /* End of internals docs */
442 * @addtogroup DBusMemory
448 * Allocates the given number of bytes, as with standard
449 * malloc(). Guaranteed to return #NULL if bytes is zero
450 * on all platforms. Returns #NULL if the allocation fails.
451 * The memory must be released with dbus_free().
453 * dbus_malloc() memory is NOT safe to free with regular free() from
454 * the C library. Free it with dbus_free() only.
456 * @param bytes number of bytes to allocate
457 * @return allocated memory, or #NULL if the allocation fails.
460 dbus_malloc (size_t bytes)
462 #ifdef DBUS_BUILD_TESTS
463 _dbus_initialize_malloc_debug ();
465 if (_dbus_decrement_fail_alloc_counter ())
467 _dbus_verbose (" FAILING malloc of %ld bytes\n", (long) bytes);
472 if (bytes == 0) /* some system mallocs handle this, some don't */
474 #ifdef DBUS_BUILD_TESTS
475 else if (fail_size != 0 && bytes > fail_size)
481 block = malloc (bytes + GUARD_EXTRA_SIZE);
484 _dbus_atomic_inc (&n_blocks_outstanding);
486 else if (malloc_cannot_fail)
488 _dbus_warn ("out of memory: malloc (%ld + %ld)\n",
489 (long) bytes, (long) GUARD_EXTRA_SIZE);
493 return set_guards (block, bytes, SOURCE_MALLOC);
499 mem = malloc (bytes);
501 #ifdef DBUS_BUILD_TESTS
504 _dbus_atomic_inc (&n_blocks_outstanding);
506 else if (malloc_cannot_fail)
508 _dbus_warn ("out of memory: malloc (%ld)\n", (long) bytes);
518 * Allocates the given number of bytes, as with standard malloc(), but
519 * all bytes are initialized to zero as with calloc(). Guaranteed to
520 * return #NULL if bytes is zero on all platforms. Returns #NULL if the
521 * allocation fails. The memory must be released with dbus_free().
523 * dbus_malloc0() memory is NOT safe to free with regular free() from
524 * the C library. Free it with dbus_free() only.
526 * @param bytes number of bytes to allocate
527 * @return allocated memory, or #NULL if the allocation fails.
530 dbus_malloc0 (size_t bytes)
532 #ifdef DBUS_BUILD_TESTS
533 _dbus_initialize_malloc_debug ();
535 if (_dbus_decrement_fail_alloc_counter ())
537 _dbus_verbose (" FAILING malloc0 of %ld bytes\n", (long) bytes);
545 #ifdef DBUS_BUILD_TESTS
546 else if (fail_size != 0 && bytes > fail_size)
552 block = calloc (bytes + GUARD_EXTRA_SIZE, 1);
556 _dbus_atomic_inc (&n_blocks_outstanding);
558 else if (malloc_cannot_fail)
560 _dbus_warn ("out of memory: calloc (%ld + %ld, 1)\n",
561 (long) bytes, (long) GUARD_EXTRA_SIZE);
565 return set_guards (block, bytes, SOURCE_MALLOC_ZERO);
571 mem = calloc (bytes, 1);
573 #ifdef DBUS_BUILD_TESTS
576 _dbus_atomic_inc (&n_blocks_outstanding);
578 else if (malloc_cannot_fail)
580 _dbus_warn ("out of memory: calloc (%ld)\n", (long) bytes);
590 * Resizes a block of memory previously allocated by dbus_malloc() or
591 * dbus_malloc0(). Guaranteed to free the memory and return #NULL if bytes
592 * is zero on all platforms. Returns #NULL if the resize fails.
593 * If the resize fails, the memory is not freed.
595 * @param memory block to be resized
596 * @param bytes new size of the memory block
597 * @return allocated memory, or #NULL if the resize fails.
600 dbus_realloc (void *memory,
603 #ifdef DBUS_BUILD_TESTS
604 _dbus_initialize_malloc_debug ();
606 if (_dbus_decrement_fail_alloc_counter ())
608 _dbus_verbose (" FAILING realloc of %ld bytes\n", (long) bytes);
614 if (bytes == 0) /* guarantee this is safe */
619 #ifdef DBUS_BUILD_TESTS
620 else if (fail_size != 0 && bytes > fail_size)
629 check_guards (memory, FALSE);
631 block = realloc (((unsigned char*)memory) - GUARD_START_OFFSET,
632 bytes + GUARD_EXTRA_SIZE);
636 if (malloc_cannot_fail)
638 _dbus_warn ("out of memory: realloc (%p, %ld + %ld)\n",
639 memory, (long) bytes, (long) GUARD_EXTRA_SIZE);
646 old_bytes = *(dbus_uint32_t*)block;
647 if (bytes >= old_bytes)
648 /* old guards shouldn't have moved */
649 check_guards (((unsigned char*)block) + GUARD_START_OFFSET, FALSE);
651 return set_guards (block, bytes, SOURCE_REALLOC);
657 block = malloc (bytes + GUARD_EXTRA_SIZE);
661 _dbus_atomic_inc (&n_blocks_outstanding);
663 else if (malloc_cannot_fail)
665 _dbus_warn ("out of memory: malloc (%ld + %ld)\n",
666 (long) bytes, (long) GUARD_EXTRA_SIZE);
670 return set_guards (block, bytes, SOURCE_REALLOC_NULL);
677 mem = realloc (memory, bytes);
679 #ifdef DBUS_BUILD_TESTS
680 if (mem == NULL && malloc_cannot_fail)
682 _dbus_warn ("out of memory: malloc (%ld)\n", (long) bytes);
686 if (memory == NULL && mem != NULL)
687 _dbus_atomic_inc (&n_blocks_outstanding);
694 * Frees a block of memory previously allocated by dbus_malloc() or
695 * dbus_malloc0(). If passed #NULL, does nothing.
697 * @param memory block to be freed
700 dbus_free (void *memory)
702 #ifdef DBUS_BUILD_TESTS
705 check_guards (memory, TRUE);
708 #ifdef DBUS_DISABLE_ASSERT
709 _dbus_atomic_dec (&n_blocks_outstanding);
711 dbus_int32_t old_value;
713 old_value = _dbus_atomic_dec (&n_blocks_outstanding);
714 _dbus_assert (old_value >= 1);
717 free (((unsigned char*)memory) - GUARD_START_OFFSET);
724 if (memory) /* we guarantee it's safe to free (NULL) */
726 #ifdef DBUS_BUILD_TESTS
727 #ifdef DBUS_DISABLE_ASSERT
728 _dbus_atomic_dec (&n_blocks_outstanding);
730 dbus_int32_t old_value;
732 old_value = _dbus_atomic_dec (&n_blocks_outstanding);
733 _dbus_assert (old_value >= 1);
742 * Frees a #NULL-terminated array of strings.
743 * If passed #NULL, does nothing.
745 * @param str_array the array to be freed
748 dbus_free_string_array (char **str_array)
757 dbus_free (str_array[i]);
761 dbus_free (str_array);
765 /** @} */ /* End of public API docs block */
769 * @addtogroup DBusMemoryInternals
775 * _dbus_current_generation is used to track each
776 * time that dbus_shutdown() is called, so we can
777 * reinit things after it's been called. It is simply
778 * incremented each time we shut down.
780 int _dbus_current_generation = 1;
783 * Represents a function to be called on shutdown.
785 typedef struct ShutdownClosure ShutdownClosure;
788 * This struct represents a function to be called on shutdown.
790 struct ShutdownClosure
792 ShutdownClosure *next; /**< Next ShutdownClosure */
793 DBusShutdownFunction func; /**< Function to call */
794 void *data; /**< Data for function */
797 _DBUS_DEFINE_GLOBAL_LOCK (shutdown_funcs);
798 static ShutdownClosure *registered_globals = NULL;
801 * Register a cleanup function to be called exactly once
802 * the next time dbus_shutdown() is called.
804 * @param func the function
805 * @param data data to pass to the function
806 * @returns #FALSE on not enough memory
809 _dbus_register_shutdown_func (DBusShutdownFunction func,
814 c = dbus_new (ShutdownClosure, 1);
822 _DBUS_LOCK (shutdown_funcs);
824 c->next = registered_globals;
825 registered_globals = c;
827 _DBUS_UNLOCK (shutdown_funcs);
832 /** @} */ /* End of private API docs block */
836 * @addtogroup DBusMemory
842 * Frees all memory allocated internally by libdbus and
843 * reverses the effects of dbus_threads_init(). libdbus keeps internal
844 * global variables, for example caches and thread locks, and it
845 * can be useful to free these internal data structures.
847 * dbus_shutdown() does NOT free memory that was returned
848 * to the application. It only returns libdbus-internal
851 * You MUST free all memory and release all reference counts
852 * returned to you by libdbus prior to calling dbus_shutdown().
854 * You can't continue to use any D-Bus objects, such as connections,
855 * that were allocated prior to dbus_shutdown(). You can, however,
856 * start over; call dbus_threads_init() again, create new connections,
859 * WARNING: dbus_shutdown() is NOT thread safe, it must be called
860 * while NO other threads are using D-Bus. (Remember, you have to free
861 * all D-Bus objects and memory before you call dbus_shutdown(), so no
862 * thread can be using libdbus.)
864 * The purpose of dbus_shutdown() is to allow applications to get
865 * clean output from memory leak checkers. dbus_shutdown() may also be
866 * useful if you want to dlopen() libdbus instead of linking to it,
867 * and want to be able to unload the library again.
869 * There is absolutely no requirement to call dbus_shutdown() - in fact,
870 * most applications won't bother and should not feel guilty.
872 * You have to know that nobody is using libdbus in your application's
873 * process before you can call dbus_shutdown(). One implication of this
874 * is that calling dbus_shutdown() from a library is almost certainly
875 * wrong, since you don't know what the rest of the app is up to.
881 while (registered_globals != NULL)
885 c = registered_globals;
886 registered_globals = c->next;
888 (* c->func) (c->data);
893 _dbus_current_generation += 1;
896 /** @} */ /** End of public API docs block */
898 #ifdef DBUS_BUILD_TESTS
899 #include "dbus-test.h"
902 * @ingroup DBusMemoryInternals
903 * Unit test for DBusMemory
904 * @returns #TRUE on success.
907 _dbus_memory_test (void)
909 dbus_bool_t old_guards;
917 _dbus_assert_not_reached ("no memory");
918 for (size = 4; size < 256; size += 4)
920 p = dbus_realloc (p, size);
922 _dbus_assert_not_reached ("no memory");
924 for (size = 256; size != 0; size -= 4)
926 p = dbus_realloc (p, size);
928 _dbus_assert_not_reached ("no memory");