1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-internals.c random utility stuff (internal to D-Bus implementation)
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include "dbus-internals.h"
24 #include "dbus-protocol.h"
25 #include "dbus-test.h"
32 * @defgroup DBusInternals D-Bus internal implementation details
33 * @brief Documentation useful when developing or debugging D-Bus itself.
38 * @defgroup DBusInternalsUtils Utilities and portability
39 * @ingroup DBusInternals
40 * @brief Utility functions (_dbus_assert(), _dbus_warn(), etc.)
47 * Aborts with an error message if the condition is false.
49 * @param condition condition which must be true.
53 * @def _dbus_assert_not_reached
55 * Aborts with an error message if called.
56 * The given explanation will be printed.
58 * @param explanation explanation of what happened if the code was reached.
62 * @def _DBUS_N_ELEMENTS
64 * Computes the number of elements in a fixed-size array using
67 * @param array the array to count elements in.
71 * @def _DBUS_POINTER_TO_INT
73 * Safely casts a void* to an integer; should only be used on void*
74 * that actually contain integers, for example one created with
75 * _DBUS_INT_TO_POINTER. Only guaranteed to preserve 32 bits.
76 * (i.e. it's used to store 32-bit ints in pointers, but
77 * can't be used to store 64-bit pointers in ints.)
79 * @param pointer pointer to extract an integer from.
82 * @def _DBUS_INT_TO_POINTER
84 * Safely stuffs an integer into a pointer, to be extracted later with
85 * _DBUS_POINTER_TO_INT. Only guaranteed to preserve 32 bits.
87 * @param integer the integer to stuff into a pointer.
92 * Sets all bits in an object to zero.
94 * @param object the object to be zeroed.
97 * @def _DBUS_INT16_MIN
99 * Minimum value of type "int16"
102 * @def _DBUS_INT16_MAX
104 * Maximum value of type "int16"
107 * @def _DBUS_UINT16_MAX
109 * Maximum value of type "uint16"
113 * @def _DBUS_INT32_MIN
115 * Minimum value of type "int32"
118 * @def _DBUS_INT32_MAX
120 * Maximum value of type "int32"
123 * @def _DBUS_UINT32_MAX
125 * Maximum value of type "uint32"
131 * Minimum value of type "int"
136 * Maximum value of type "int"
139 * @def _DBUS_UINT_MAX
141 * Maximum value of type "uint"
145 * @typedef DBusForeachFunction
147 * Used to iterate over each item in a collection, such as
152 * @def _DBUS_LOCK_NAME
154 * Expands to name of a global lock variable.
158 * @def _DBUS_DEFINE_GLOBAL_LOCK
160 * Defines a global lock variable with the given name.
161 * The lock must be added to the list to initialize
162 * in dbus_threads_init().
166 * @def _DBUS_DECLARE_GLOBAL_LOCK
168 * Expands to declaration of a global lock defined
169 * with _DBUS_DEFINE_GLOBAL_LOCK.
170 * The lock must be added to the list to initialize
171 * in dbus_threads_init().
177 * Locks a global lock
183 * Unlocks a global lock
187 * Fixed "out of memory" error message, just to avoid
188 * making up a different string every time and wasting
191 const char _dbus_no_memory_message[] = "Not enough memory";
194 * Prints a warning message to stderr.
196 * @param format printf-style format string.
199 _dbus_warn (const char *format,
202 /* FIXME not portable enough? */
205 va_start (args, format);
206 vfprintf (stderr, format, args);
210 #ifdef DBUS_ENABLE_VERBOSE_MODE
212 static dbus_bool_t verbose_initted = FALSE;
213 static dbus_bool_t verbose = TRUE;
215 #define PTHREAD_IN_VERBOSE 0
216 #if PTHREAD_IN_VERBOSE
221 _dbus_verbose_init (void)
223 if (!verbose_initted)
225 const char *p = _dbus_getenv ("DBUS_VERBOSE");
226 verbose = p != NULL && *p == '1';
227 verbose_initted = TRUE;
232 _dbus_is_verbose_real (void)
234 _dbus_verbose_init ();
239 * Prints a warning message to stderr
240 * if the user has enabled verbose mode.
241 * This is the real function implementation,
242 * use _dbus_verbose() macro in code.
244 * @param format printf-style format string.
247 _dbus_verbose_real (const char *format,
251 static dbus_bool_t need_pid = TRUE;
254 /* things are written a bit oddly here so that
255 * in the non-verbose case we just have the one
256 * conditional and return immediately.
258 if (!_dbus_is_verbose_real())
261 /* Print out pid before the line */
264 #if PTHREAD_IN_VERBOSE
265 fprintf (stderr, "%lu: 0x%lx: ", _dbus_getpid (), pthread_self ());
267 fprintf (stderr, "%lu: ", _dbus_getpid ());
272 /* Only print pid again if the next line is a new line */
273 len = strlen (format);
274 if (format[len-1] == '\n')
279 va_start (args, format);
280 vfprintf (stderr, format, args);
287 * Reinitializes the verbose logging code, used
288 * as a hack in dbus-spawn.c so that a child
289 * process re-reads its pid
293 _dbus_verbose_reset_real (void)
295 verbose_initted = FALSE;
298 #endif /* DBUS_ENABLE_VERBOSE_MODE */
301 * Duplicates a string. Result must be freed with
302 * dbus_free(). Returns #NULL if memory allocation fails.
303 * If the string to be duplicated is #NULL, returns #NULL.
305 * @param str string to duplicate.
306 * @returns newly-allocated copy.
309 _dbus_strdup (const char *str)
319 copy = dbus_malloc (len + 1);
323 memcpy (copy, str, len + 1);
329 * Duplicates a block of memory. Returns
332 * @param mem memory to copy
333 * @param n_bytes number of bytes to copy
337 _dbus_memdup (const void *mem,
342 copy = dbus_malloc (n_bytes);
346 memcpy (copy, mem, n_bytes);
352 * Duplicates a string array. Result may be freed with
353 * dbus_free_string_array(). Returns #NULL if memory allocation fails.
354 * If the array to be duplicated is #NULL, returns #NULL.
356 * @param array array to duplicate.
357 * @returns newly-allocated copy.
360 _dbus_dup_string_array (const char **array)
369 for (len = 0; array[len] != NULL; ++len)
372 copy = dbus_new0 (char*, len + 1);
379 copy[i] = _dbus_strdup (array[i]);
382 dbus_free_string_array (copy);
393 * Checks whether a string array contains the given string.
395 * @param array array to search.
396 * @param str string to look for
397 * @returns #TRUE if array contains string
400 _dbus_string_array_contains (const char **array,
406 while (array[i] != NULL)
408 if (strcmp (array[i], str) == 0)
416 #ifdef DBUS_BUILD_TESTS
418 * Returns a string describing the given name.
420 * @param header_field the field to describe
421 * @returns a constant string describing the field
424 _dbus_header_field_to_string (int header_field)
426 switch (header_field)
428 case DBUS_HEADER_FIELD_INVALID:
430 case DBUS_HEADER_FIELD_PATH:
432 case DBUS_HEADER_FIELD_INTERFACE:
434 case DBUS_HEADER_FIELD_MEMBER:
436 case DBUS_HEADER_FIELD_ERROR_NAME:
438 case DBUS_HEADER_FIELD_REPLY_SERIAL:
439 return "reply-serial";
440 case DBUS_HEADER_FIELD_DESTINATION:
441 return "destination";
442 case DBUS_HEADER_FIELD_SENDER:
444 case DBUS_HEADER_FIELD_SIGNATURE:
450 #endif /* DBUS_BUILD_TESTS */
452 #ifndef DBUS_DISABLE_CHECKS
453 /** String used in _dbus_return_if_fail macro */
454 const char _dbus_return_if_fail_warning_format[] =
455 "%lu: arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
456 "This is normally a bug in some application using the D-Bus library.\n";
459 #ifndef DBUS_DISABLE_ASSERT
461 * Internals of _dbus_assert(); it's a function
462 * rather than a macro with the inline code so
463 * that the assertion failure blocks don't show up
464 * in test suite coverage, and to shrink code size.
466 * @param condition TRUE if assertion succeeded
467 * @param condition_text condition as a string
468 * @param file file the assertion is in
469 * @param line line the assertion is in
470 * @param func function the assertion is in
473 _dbus_real_assert (dbus_bool_t condition,
474 const char *condition_text,
479 if (_DBUS_UNLIKELY (!condition))
481 _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
482 _dbus_getpid (), condition_text, file, line, func);
488 * Internals of _dbus_assert_not_reached(); it's a function
489 * rather than a macro with the inline code so
490 * that the assertion failure blocks don't show up
491 * in test suite coverage, and to shrink code size.
493 * @param explanation what was reached that shouldn't have been
494 * @param file file the assertion is in
495 * @param line line the assertion is in
498 _dbus_real_assert_not_reached (const char *explanation,
502 _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
503 file, line, _dbus_getpid (), explanation);
506 #endif /* DBUS_DISABLE_ASSERT */
508 #ifdef DBUS_BUILD_TESTS
510 run_failing_each_malloc (int n_mallocs,
511 const char *description,
512 DBusTestMemoryFunction func,
515 n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
517 while (n_mallocs >= 0)
519 _dbus_set_fail_alloc_counter (n_mallocs);
521 _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
522 description, n_mallocs,
523 _dbus_get_fail_alloc_failures ());
525 if (!(* func) (data))
531 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
537 * Tests how well the given function responds to out-of-memory
538 * situations. Calls the function repeatedly, failing a different
539 * call to malloc() each time. If the function ever returns #FALSE,
540 * the test fails. The function should return #TRUE whenever something
541 * valid (such as returning an error, or succeeding) occurs, and #FALSE
542 * if it gets confused in some way.
544 * @param description description of the test used in verbose output
545 * @param func function to call
546 * @param data data to pass to function
547 * @returns #TRUE if the function never returns FALSE
550 _dbus_test_oom_handling (const char *description,
551 DBusTestMemoryFunction func,
556 int max_failures_to_try;
559 /* Run once to see about how many mallocs are involved */
561 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
563 _dbus_verbose ("Running once to count mallocs\n");
565 if (!(* func) (data))
568 approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
570 _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
571 description, approx_mallocs);
573 setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
578 _dbus_string_init_const (&str, setting);
580 if (!_dbus_string_parse_int (&str, 0, &v, NULL))
581 _dbus_warn ("couldn't parse '%s' as integer\n", setting);
582 max_failures_to_try = v;
586 max_failures_to_try = 4;
589 i = setting ? max_failures_to_try - 1 : 1;
590 while (i < max_failures_to_try)
592 _dbus_set_fail_alloc_failures (i);
593 if (!run_failing_each_malloc (approx_mallocs, description, func, data))
598 _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
603 #endif /* DBUS_BUILD_TESTS */