1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-memory.c D-BUS memory handling
4 * Copyright (C) 2002, 2003 Red Hat Inc.
6 * Licensed under the Academic Free License version 1.2
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"
32 * @defgroup DBusMemory Memory Allocation
34 * @brief dbus_malloc(), dbus_free(), etc.
36 * Functions and macros related to allocating and releasing
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*.
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
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.
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
70 * @typedef DBusFreeFunction
72 * The type of a function which frees a block of memory.
74 * @param memory the memory to free
77 #ifdef DBUS_BUILD_TESTS
78 static dbus_bool_t debug_initialized = FALSE;
79 static int fail_nth = -1;
80 static size_t fail_size = 0;
81 static int fail_alloc_counter = _DBUS_INT_MAX;
82 static int n_failures_per_failure = 1;
83 static int n_failures_this_failure = 0;
84 static dbus_bool_t guards = FALSE;
85 static dbus_bool_t disable_mem_pools = FALSE;
86 static dbus_bool_t backtrace_on_fail_alloc = FALSE;
87 static int n_blocks_outstanding = 0;
89 /** value stored in guard padding for debugging buffer overrun */
90 #define GUARD_VALUE 0xdeadbeef
91 /** size of the information about the block stored in guard mode */
92 #define GUARD_INFO_SIZE 8
93 /** size of the GUARD_VALUE-filled padding after the header info */
94 #define GUARD_START_PAD 16
95 /** size of the GUARD_VALUE-filled padding at the end of the block */
96 #define GUARD_END_PAD 16
97 /** size of stuff at start of block */
98 #define GUARD_START_OFFSET (GUARD_START_PAD + GUARD_INFO_SIZE)
99 /** total extra size over the requested allocation for guard stuff */
100 #define GUARD_EXTRA_SIZE (GUARD_START_OFFSET + GUARD_END_PAD)
103 _dbus_initialize_malloc_debug (void)
105 if (!debug_initialized)
107 debug_initialized = TRUE;
109 if (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH") != NULL)
111 fail_nth = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH"));
112 fail_alloc_counter = fail_nth;
113 _dbus_verbose ("Will fail malloc every %d times\n", fail_nth);
116 if (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN") != NULL)
118 fail_size = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN"));
119 _dbus_verbose ("Will fail mallocs over %d bytes\n",
123 if (_dbus_getenv ("DBUS_MALLOC_GUARDS") != NULL)
126 _dbus_verbose ("Will use malloc guards\n");
129 if (_dbus_getenv ("DBUS_DISABLE_MEM_POOLS") != NULL)
131 disable_mem_pools = TRUE;
132 _dbus_verbose ("Will disable memory pools\n");
135 if (_dbus_getenv ("DBUS_MALLOC_BACKTRACES") != NULL)
137 backtrace_on_fail_alloc = TRUE;
138 _dbus_verbose ("Will backtrace on failing a malloc\n");
144 * Whether to turn off mem pools, useful for leak checking.
146 * @returns #TRUE if mempools should not be used.
149 _dbus_disable_mem_pools (void)
151 _dbus_initialize_malloc_debug ();
152 return disable_mem_pools;
156 * Sets the number of allocations until we simulate a failed
157 * allocation. If set to 0, the next allocation to run
158 * fails; if set to 1, one succeeds then the next fails; etc.
159 * Set to _DBUS_INT_MAX to not fail anything.
161 * @param until_next_fail number of successful allocs before one fails
164 _dbus_set_fail_alloc_counter (int until_next_fail)
166 _dbus_initialize_malloc_debug ();
168 fail_alloc_counter = until_next_fail;
171 _dbus_verbose ("Set fail alloc counter = %d\n", fail_alloc_counter);
176 * Gets the number of successful allocs until we'll simulate
179 * @returns current counter value
182 _dbus_get_fail_alloc_counter (void)
184 _dbus_initialize_malloc_debug ();
186 return fail_alloc_counter;
190 * Sets how many mallocs to fail when the fail alloc counter reaches
193 * @param failures_per_failure number to fail
196 _dbus_set_fail_alloc_failures (int failures_per_failure)
198 n_failures_per_failure = failures_per_failure;
202 * Gets the number of failures we'll have when the fail malloc
205 * @returns number of failures planned
208 _dbus_get_fail_alloc_failures (void)
210 return n_failures_per_failure;
214 * Called when about to alloc some memory; if
215 * it returns #TRUE, then the allocation should
216 * fail. If it returns #FALSE, then the allocation
219 * @returns #TRUE if this alloc should fail
222 _dbus_decrement_fail_alloc_counter (void)
224 _dbus_initialize_malloc_debug ();
226 if (fail_alloc_counter <= 0)
228 if (backtrace_on_fail_alloc)
229 _dbus_print_backtrace ();
231 _dbus_verbose ("failure %d\n", n_failures_this_failure);
233 n_failures_this_failure += 1;
234 if (n_failures_this_failure >= n_failures_per_failure)
237 fail_alloc_counter = fail_nth;
239 fail_alloc_counter = _DBUS_INT_MAX;
241 n_failures_this_failure = 0;
243 _dbus_verbose ("reset fail alloc counter to %d\n", fail_alloc_counter);
250 fail_alloc_counter -= 1;
256 * Get the number of outstanding malloc()'d blocks.
258 * @returns number of blocks
261 _dbus_get_malloc_blocks_outstanding (void)
263 return n_blocks_outstanding;
267 * Where the block came from.
279 source_string (BlockSource source)
289 case SOURCE_MALLOC_ZERO:
291 case SOURCE_REALLOC_NULL:
292 return "realloc(NULL)";
294 _dbus_assert_not_reached ("Invalid malloc block source ID");
299 check_guards (void *free_block)
301 if (free_block != NULL)
303 unsigned char *block = ((unsigned char*)free_block) - GUARD_START_OFFSET;
304 size_t requested_bytes = *(dbus_uint32_t*)block;
305 BlockSource source = *(dbus_uint32_t*)(block + 4);
312 _dbus_verbose ("Checking %d bytes request from source %s\n",
313 requested_bytes, source_string (source));
317 while (i < GUARD_START_OFFSET)
319 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
320 if (value != GUARD_VALUE)
322 _dbus_warn ("Block of %u bytes from %s had start guard value 0x%x at %d expected 0x%x\n",
323 requested_bytes, source_string (source),
324 value, i, GUARD_VALUE);
331 i = GUARD_START_OFFSET + requested_bytes;
332 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
334 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
335 if (value != GUARD_VALUE)
337 _dbus_warn ("Block of %u bytes from %s had end guard value 0x%x at %d expected 0x%x\n",
338 requested_bytes, source_string (source),
339 value, i, GUARD_VALUE);
347 _dbus_assert_not_reached ("guard value corruption");
352 set_guards (void *real_block,
353 size_t requested_bytes,
356 unsigned char *block = real_block;
362 _dbus_assert (GUARD_START_OFFSET + GUARD_END_PAD == GUARD_EXTRA_SIZE);
364 *((dbus_uint32_t*)block) = requested_bytes;
365 *((dbus_uint32_t*)(block + 4)) = source;
368 while (i < GUARD_START_OFFSET)
370 (*(dbus_uint32_t*) &block[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*) &block[i]) = GUARD_VALUE;
383 check_guards (block + GUARD_START_OFFSET);
385 return block + GUARD_START_OFFSET;
391 * Allocates the given number of bytes, as with standard
392 * malloc(). Guaranteed to return #NULL if bytes is zero
393 * on all platforms. Returns #NULL if the allocation fails.
394 * The memory must be released with dbus_free().
396 * @param bytes number of bytes to allocate
397 * @return allocated memory, or #NULL if the allocation fails.
400 dbus_malloc (size_t bytes)
402 #ifdef DBUS_BUILD_TESTS
403 _dbus_initialize_malloc_debug ();
405 if (_dbus_decrement_fail_alloc_counter ())
407 _dbus_verbose (" FAILING malloc of %d bytes\n", bytes);
413 if (bytes == 0) /* some system mallocs handle this, some don't */
416 else if (fail_size != 0 && bytes > fail_size)
422 block = malloc (bytes + GUARD_EXTRA_SIZE);
424 n_blocks_outstanding += 1;
426 return set_guards (block, bytes, SOURCE_MALLOC);
432 mem = malloc (bytes);
433 #ifdef DBUS_BUILD_TESTS
435 n_blocks_outstanding += 1;
442 * Allocates the given number of bytes, as with standard malloc(), but
443 * all bytes are initialized to zero as with calloc(). Guaranteed to
444 * return #NULL if bytes is zero on all platforms. Returns #NULL if the
445 * allocation fails. The memory must be released with dbus_free().
447 * @param bytes number of bytes to allocate
448 * @return allocated memory, or #NULL if the allocation fails.
451 dbus_malloc0 (size_t bytes)
453 #ifdef DBUS_BUILD_TESTS
454 _dbus_initialize_malloc_debug ();
456 if (_dbus_decrement_fail_alloc_counter ())
458 _dbus_verbose (" FAILING malloc0 of %d bytes\n", bytes);
467 else if (fail_size != 0 && bytes > fail_size)
473 block = calloc (bytes + GUARD_EXTRA_SIZE, 1);
475 n_blocks_outstanding += 1;
476 return set_guards (block, bytes, SOURCE_MALLOC_ZERO);
482 mem = calloc (bytes, 1);
483 #ifdef DBUS_BUILD_TESTS
485 n_blocks_outstanding += 1;
492 * Resizes a block of memory previously allocated by dbus_malloc() or
493 * dbus_malloc0(). Guaranteed to free the memory and return #NULL if bytes
494 * is zero on all platforms. Returns #NULL if the resize fails.
495 * If the resize fails, the memory is not freed.
497 * @param memory block to be resized
498 * @param bytes new size of the memory block
499 * @return allocated memory, or #NULL if the resize fails.
502 dbus_realloc (void *memory,
505 #ifdef DBUS_BUILD_TESTS
506 _dbus_initialize_malloc_debug ();
508 if (_dbus_decrement_fail_alloc_counter ())
510 _dbus_verbose (" FAILING realloc of %d bytes\n", bytes);
516 if (bytes == 0) /* guarantee this is safe */
522 else if (fail_size != 0 && bytes > fail_size)
530 check_guards (memory);
532 block = realloc (((unsigned char*)memory) - GUARD_START_OFFSET,
533 bytes + GUARD_EXTRA_SIZE);
536 /* old guards shouldn't have moved */
537 check_guards (((unsigned char*)block) + GUARD_START_OFFSET);
539 return set_guards (block, bytes, SOURCE_REALLOC);
545 block = malloc (bytes + GUARD_EXTRA_SIZE);
548 n_blocks_outstanding += 1;
550 return set_guards (block, bytes, SOURCE_REALLOC_NULL);
557 mem = realloc (memory, bytes);
558 #ifdef DBUS_BUILD_TESTS
559 if (memory == NULL && mem != NULL)
560 n_blocks_outstanding += 1;
567 * Frees a block of memory previously allocated by dbus_malloc() or
568 * dbus_malloc0(). If passed #NULL, does nothing.
570 * @param memory block to be freed
573 dbus_free (void *memory)
575 #ifdef DBUS_BUILD_TESTS
578 check_guards (memory);
581 n_blocks_outstanding -= 1;
583 _dbus_assert (n_blocks_outstanding >= 0);
585 free (((unsigned char*)memory) - GUARD_START_OFFSET);
592 if (memory) /* we guarantee it's safe to free (NULL) */
594 #ifdef DBUS_BUILD_TESTS
595 n_blocks_outstanding -= 1;
597 _dbus_assert (n_blocks_outstanding >= 0);
605 * Frees a #NULL-terminated array of strings.
606 * If passed #NULL, does nothing.
608 * @param str_array the array to be freed
611 dbus_free_string_array (char **str_array)
620 dbus_free (str_array[i]);
624 dbus_free (str_array);
629 * _dbus_current_generation is used to track each
630 * time that dbus_shutdown() is called, so we can
631 * reinit things after it's been called. It is simply
632 * incremented each time we shut down.
634 int _dbus_current_generation = 1;
637 * Represents a function to be called on shutdown.
639 typedef struct ShutdownClosure ShutdownClosure;
642 * This struct represents a function to be called on shutdown.
644 struct ShutdownClosure
646 ShutdownClosure *next; /**< Next ShutdownClosure */
647 DBusShutdownFunction func; /**< Function to call */
648 void *data; /**< Data for function */
651 _DBUS_DEFINE_GLOBAL_LOCK (shutdown_funcs);
652 static ShutdownClosure *registered_globals = NULL;
655 * The D-BUS library keeps some internal global variables, for example
656 * to cache the username of the current process. This function is
657 * used to free these global variables. It is really useful only for
658 * leak-checking cleanliness and the like. WARNING: this function is
659 * NOT thread safe, it must be called while NO other threads are using
660 * D-BUS. You cannot continue using D-BUS after calling this function,
661 * as it does things like free global mutexes created by
662 * dbus_threads_init(). To use a D-BUS function after calling
663 * dbus_shutdown(), you have to start over from scratch, e.g. calling
664 * dbus_threads_init() again.
669 while (registered_globals != NULL)
673 c = registered_globals;
674 registered_globals = c->next;
676 (* c->func) (c->data);
681 _dbus_current_generation += 1;
685 * Register a cleanup function to be called exactly once
686 * the next time dbus_shutdown() is called.
688 * @param func the function
689 * @param data data to pass to the function
690 * @returns #FALSE on not enough memory
693 _dbus_register_shutdown_func (DBusShutdownFunction func,
698 c = dbus_new (ShutdownClosure, 1);
706 _DBUS_LOCK (shutdown_funcs);
708 c->next = registered_globals;
709 registered_globals = c;
711 _DBUS_UNLOCK (shutdown_funcs);