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_counts = -1;
80 static size_t fail_size = 0;
81 static int fail_alloc_counter = _DBUS_INT_MAX;
82 static dbus_bool_t guards = FALSE;
83 static dbus_bool_t disable_mem_pools = FALSE;
84 static dbus_bool_t backtrace_on_fail_alloc = FALSE;
85 static int n_blocks_outstanding = 0;
87 /** value stored in guard padding for debugging buffer overrun */
88 #define GUARD_VALUE 0xdeadbeef
89 /** size of the information about the block stored in guard mode */
90 #define GUARD_INFO_SIZE 8
91 /** size of the GUARD_VALUE-filled padding after the header info */
92 #define GUARD_START_PAD 16
93 /** size of the GUARD_VALUE-filled padding at the end of the block */
94 #define GUARD_END_PAD 16
95 /** size of stuff at start of block */
96 #define GUARD_START_OFFSET (GUARD_START_PAD + GUARD_INFO_SIZE)
97 /** total extra size over the requested allocation for guard stuff */
98 #define GUARD_EXTRA_SIZE (GUARD_START_OFFSET + GUARD_END_PAD)
101 _dbus_initialize_malloc_debug (void)
103 if (!debug_initialized)
105 debug_initialized = TRUE;
107 if (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH") != NULL)
109 fail_counts = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_NTH"));
110 fail_alloc_counter = fail_counts;
111 _dbus_verbose ("Will fail malloc every %d times\n", fail_counts);
114 if (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN") != NULL)
116 fail_size = atoi (_dbus_getenv ("DBUS_MALLOC_FAIL_GREATER_THAN"));
117 _dbus_verbose ("Will fail mallocs over %d bytes\n",
121 if (_dbus_getenv ("DBUS_MALLOC_GUARDS") != NULL)
124 _dbus_verbose ("Will use malloc guards\n");
127 if (_dbus_getenv ("DBUS_DISABLE_MEM_POOLS") != NULL)
129 disable_mem_pools = TRUE;
130 _dbus_verbose ("Will disable memory pools\n");
133 if (_dbus_getenv ("DBUS_MALLOC_BACKTRACES") != NULL)
135 backtrace_on_fail_alloc = TRUE;
136 _dbus_verbose ("Will backtrace on failing a malloc\n");
142 * Whether to turn off mem pools, useful for leak checking.
144 * @returns #TRUE if mempools should not be used.
147 _dbus_disable_mem_pools (void)
149 _dbus_initialize_malloc_debug ();
150 return disable_mem_pools;
154 * Sets the number of allocations until we simulate a failed
155 * allocation. If set to 0, the next allocation to run
156 * fails; if set to 1, one succeeds then the next fails; etc.
157 * Set to _DBUS_INT_MAX to not fail anything.
159 * @param until_next_fail number of successful allocs before one fails
162 _dbus_set_fail_alloc_counter (int until_next_fail)
164 _dbus_initialize_malloc_debug ();
166 fail_alloc_counter = until_next_fail;
169 _dbus_verbose ("Set fail alloc counter = %d\n", fail_alloc_counter);
174 * Gets the number of successful allocs until we'll simulate
177 * @returns current counter value
180 _dbus_get_fail_alloc_counter (void)
182 _dbus_initialize_malloc_debug ();
184 return fail_alloc_counter;
188 * Called when about to alloc some memory; if
189 * it returns #TRUE, then the allocation should
190 * fail. If it returns #FALSE, then the allocation
193 * @returns #TRUE if this alloc should fail
196 _dbus_decrement_fail_alloc_counter (void)
198 _dbus_initialize_malloc_debug ();
200 if (fail_alloc_counter <= 0)
202 if (fail_counts >= 0)
203 fail_alloc_counter = fail_counts;
205 fail_alloc_counter = _DBUS_INT_MAX;
207 _dbus_verbose ("reset fail alloc counter to %d\n", fail_alloc_counter);
208 if (backtrace_on_fail_alloc)
209 _dbus_print_backtrace ();
215 fail_alloc_counter -= 1;
221 * Get the number of outstanding malloc()'d blocks.
223 * @returns number of blocks
226 _dbus_get_malloc_blocks_outstanding (void)
228 return n_blocks_outstanding;
232 * Where the block came from.
244 source_string (BlockSource source)
254 case SOURCE_MALLOC_ZERO:
256 case SOURCE_REALLOC_NULL:
257 return "realloc(NULL)";
259 _dbus_assert_not_reached ("Invalid malloc block source ID");
264 check_guards (void *free_block)
266 if (free_block != NULL)
268 unsigned char *block = ((unsigned char*)free_block) - GUARD_START_OFFSET;
269 size_t requested_bytes = *(dbus_uint32_t*)block;
270 BlockSource source = *(dbus_uint32_t*)(block + 4);
277 _dbus_verbose ("Checking %d bytes request from source %s\n",
278 requested_bytes, source_string (source));
282 while (i < GUARD_START_OFFSET)
284 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
285 if (value != GUARD_VALUE)
287 _dbus_warn ("Block of %u bytes from %s had start guard value 0x%x at %d expected 0x%x\n",
288 requested_bytes, source_string (source),
289 value, i, GUARD_VALUE);
296 i = GUARD_START_OFFSET + requested_bytes;
297 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
299 dbus_uint32_t value = *(dbus_uint32_t*) &block[i];
300 if (value != GUARD_VALUE)
302 _dbus_warn ("Block of %u bytes from %s had end guard value 0x%x at %d expected 0x%x\n",
303 requested_bytes, source_string (source),
304 value, i, GUARD_VALUE);
312 _dbus_assert_not_reached ("guard value corruption");
317 set_guards (void *real_block,
318 size_t requested_bytes,
321 unsigned char *block = real_block;
327 _dbus_assert (GUARD_START_OFFSET + GUARD_END_PAD == GUARD_EXTRA_SIZE);
329 *((dbus_uint32_t*)block) = requested_bytes;
330 *((dbus_uint32_t*)(block + 4)) = source;
333 while (i < GUARD_START_OFFSET)
335 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
340 i = GUARD_START_OFFSET + requested_bytes;
341 while (i < (GUARD_START_OFFSET + requested_bytes + GUARD_END_PAD))
343 (*(dbus_uint32_t*) &block[i]) = GUARD_VALUE;
348 check_guards (block + GUARD_START_OFFSET);
350 return block + GUARD_START_OFFSET;
356 * Allocates the given number of bytes, as with standard
357 * malloc(). Guaranteed to return #NULL if bytes is zero
358 * on all platforms. Returns #NULL if the allocation fails.
359 * The memory must be released with dbus_free().
361 * @param bytes number of bytes to allocate
362 * @return allocated memory, or #NULL if the allocation fails.
365 dbus_malloc (size_t bytes)
367 #ifdef DBUS_BUILD_TESTS
368 _dbus_initialize_malloc_debug ();
370 if (_dbus_decrement_fail_alloc_counter ())
372 _dbus_verbose (" FAILING malloc of %d bytes\n", bytes);
378 if (bytes == 0) /* some system mallocs handle this, some don't */
381 else if (fail_size != 0 && bytes > fail_size)
387 block = malloc (bytes + GUARD_EXTRA_SIZE);
389 n_blocks_outstanding += 1;
391 return set_guards (block, bytes, SOURCE_MALLOC);
397 mem = malloc (bytes);
398 #ifdef DBUS_BUILD_TESTS
400 n_blocks_outstanding += 1;
407 * Allocates the given number of bytes, as with standard malloc(), but
408 * all bytes are initialized to zero as with calloc(). Guaranteed to
409 * return #NULL if bytes is zero on all platforms. Returns #NULL if the
410 * allocation fails. The memory must be released with dbus_free().
412 * @param bytes number of bytes to allocate
413 * @return allocated memory, or #NULL if the allocation fails.
416 dbus_malloc0 (size_t bytes)
418 #ifdef DBUS_BUILD_TESTS
419 _dbus_initialize_malloc_debug ();
421 if (_dbus_decrement_fail_alloc_counter ())
423 _dbus_verbose (" FAILING malloc0 of %d bytes\n", bytes);
432 else if (fail_size != 0 && bytes > fail_size)
438 block = calloc (bytes + GUARD_EXTRA_SIZE, 1);
440 n_blocks_outstanding += 1;
441 return set_guards (block, bytes, SOURCE_MALLOC_ZERO);
447 mem = calloc (bytes, 1);
448 #ifdef DBUS_BUILD_TESTS
450 n_blocks_outstanding += 1;
457 * Resizes a block of memory previously allocated by dbus_malloc() or
458 * dbus_malloc0(). Guaranteed to free the memory and return #NULL if bytes
459 * is zero on all platforms. Returns #NULL if the resize fails.
460 * If the resize fails, the memory is not freed.
462 * @param memory block to be resized
463 * @param bytes new size of the memory block
464 * @return allocated memory, or #NULL if the resize fails.
467 dbus_realloc (void *memory,
470 #ifdef DBUS_BUILD_TESTS
471 _dbus_initialize_malloc_debug ();
473 if (_dbus_decrement_fail_alloc_counter ())
475 _dbus_verbose (" FAILING realloc of %d bytes\n", bytes);
481 if (bytes == 0) /* guarantee this is safe */
487 else if (fail_size != 0 && bytes > fail_size)
495 check_guards (memory);
497 block = realloc (((unsigned char*)memory) - GUARD_START_OFFSET,
498 bytes + GUARD_EXTRA_SIZE);
501 /* old guards shouldn't have moved */
502 check_guards (((unsigned char*)block) + GUARD_START_OFFSET);
504 return set_guards (block, bytes, SOURCE_REALLOC);
510 block = malloc (bytes + GUARD_EXTRA_SIZE);
513 n_blocks_outstanding += 1;
515 return set_guards (block, bytes, SOURCE_REALLOC_NULL);
522 mem = realloc (memory, bytes);
523 #ifdef DBUS_BUILD_TESTS
524 if (memory == NULL && mem != NULL)
525 n_blocks_outstanding += 1;
532 * Frees a block of memory previously allocated by dbus_malloc() or
533 * dbus_malloc0(). If passed #NULL, does nothing.
535 * @param memory block to be freed
538 dbus_free (void *memory)
540 #ifdef DBUS_BUILD_TESTS
543 check_guards (memory);
546 n_blocks_outstanding -= 1;
548 _dbus_assert (n_blocks_outstanding >= 0);
550 free (((unsigned char*)memory) - GUARD_START_OFFSET);
557 if (memory) /* we guarantee it's safe to free (NULL) */
559 #ifdef DBUS_BUILD_TESTS
560 n_blocks_outstanding -= 1;
562 _dbus_assert (n_blocks_outstanding >= 0);
570 * Frees a #NULL-terminated array of strings.
571 * If passed #NULL, does nothing.
573 * @param str_array the array to be freed
576 dbus_free_string_array (char **str_array)
585 dbus_free (str_array[i]);
589 dbus_free (str_array);
594 * _dbus_current_generation is used to track each
595 * time that dbus_shutdown() is called, so we can
596 * reinit things after it's been called. It is simply
597 * incremented each time we shut down.
599 int _dbus_current_generation = 1;
601 static DBusList *registered_globals = NULL;
605 DBusShutdownFunction func;
610 * The D-BUS library keeps some internal global variables, for example
611 * to cache the username of the current process. This function is
612 * used to free these global variables. It is really useful only for
613 * leak-checking cleanliness and the like. WARNING: this function is
614 * NOT thread safe, it must be called while NO other threads are using
615 * D-BUS. You cannot continue using D-BUS after calling this function,
616 * as it does things like free global mutexes created by
617 * dbus_threads_init(). To use a D-BUS function after calling
618 * dbus_shutdown(), you have to start over from scratch, e.g. calling
619 * dbus_threads_init() again.
626 link = _dbus_list_get_first_link (®istered_globals);
629 ShutdownClosure *c = link->data;
631 (* c->func) (c->data);
635 link = _dbus_list_get_next_link (®istered_globals, link);
638 _dbus_list_clear (®istered_globals);
640 _dbus_current_generation += 1;
644 * Register a cleanup function to be called exactly once
645 * the next time dbus_shutdown() is called.
647 * @param func the function
648 * @param data data to pass to the function
649 * @returns #FALSE on not enough memory
652 _dbus_register_shutdown_func (DBusShutdownFunction func,
657 c = dbus_new (ShutdownClosure, 1);
665 /* We prepend, then shutdown the list in order, so
666 * we shutdown last-registered stuff first which
669 if (!_dbus_list_prepend (®istered_globals, c))