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)
417 * Generates a new UUID. If you change how this is done,
418 * there's some text about it in the spec that should also change.
420 * @param uuid the uuid to initialize
423 _dbus_generate_uuid (DBusGUID *uuid)
429 _dbus_get_current_time (&now, NULL);
431 uuid->as_uint32s[0] = now;
433 ts_size = sizeof (uuid->as_uint32s[0]);
434 p = ((char*)uuid->as_bytes) + ts_size;
436 _dbus_generate_random_bytes_buffer (p,
437 sizeof (uuid->as_bytes) - ts_size);
443 * @param uuid the uuid
444 * @param encoded string to append hex uuid to
445 * @returns #FALSE if no memory
448 _dbus_uuid_encode (const DBusGUID *uuid,
452 _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
453 return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
457 _dbus_read_uuid_file_without_creating (const DBusString *filename,
465 _dbus_string_init (&contents);
466 _dbus_string_init (&decoded);
468 if (!_dbus_file_get_contents (&contents, filename, error))
471 _dbus_string_chop_white (&contents);
473 if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
475 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
476 "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
477 _dbus_string_get_const_data (filename),
478 DBUS_UUID_LENGTH_HEX,
479 _dbus_string_get_length (&contents));
483 if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
485 _DBUS_SET_OOM (error);
491 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
492 "UUID file '%s' contains invalid hex data",
493 _dbus_string_get_const_data (filename));
497 if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
499 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
500 "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
501 _dbus_string_get_const_data (filename),
502 _dbus_string_get_length (&decoded),
503 DBUS_UUID_LENGTH_BYTES);
507 _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
509 _dbus_string_free (&decoded);
510 _dbus_string_free (&contents);
512 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
517 _DBUS_ASSERT_ERROR_IS_SET (error);
518 _dbus_string_free (&contents);
519 _dbus_string_free (&decoded);
524 _dbus_create_uuid_file_exclusively (const DBusString *filename,
530 _dbus_string_init (&encoded);
532 _dbus_generate_uuid (uuid);
534 if (!_dbus_uuid_encode (uuid, &encoded))
536 _DBUS_SET_OOM (error);
540 /* FIXME this is racy; we need a save_file_exclusively
541 * function. But in practice this should be fine for now.
543 * - first be sure we can create the file and it
544 * doesn't exist by creating it empty with O_EXCL
545 * - then create it by creating a temporary file and
546 * overwriting atomically with rename()
548 if (!_dbus_create_file_exclusively (filename, error))
551 if (!_dbus_string_append_byte (&encoded, '\n'))
553 _DBUS_SET_OOM (error);
557 if (!_dbus_string_save_to_file (&encoded, filename, error))
561 _dbus_string_free (&encoded);
563 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
567 _DBUS_ASSERT_ERROR_IS_SET (error);
568 _dbus_string_free (&encoded);
573 * Reads (and optionally writes) a uuid to a file. Initializes the uuid
574 * unless an error is returned.
576 * @param filename the name of the file
577 * @param uuid uuid to be initialized with the loaded uuid
578 * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
579 * @param error the error return
580 * @returns #FALSE if the error is set
583 _dbus_read_uuid_file (const DBusString *filename,
585 dbus_bool_t create_if_not_found,
588 DBusError read_error;
590 dbus_error_init (&read_error);
592 if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
595 if (!create_if_not_found)
597 dbus_move_error (&read_error, error);
601 /* If the file exists and contains junk, we want to keep that error
602 * message instead of overwriting it with a "file exists" error
603 * message when we try to write
605 if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
607 dbus_move_error (&read_error, error);
612 dbus_error_free (&read_error);
613 return _dbus_create_uuid_file_exclusively (filename, uuid, error);
617 _DBUS_DEFINE_GLOBAL_LOCK (machine_uuid);
618 static int machine_uuid_initialized_generation = 0;
619 static DBusGUID machine_uuid;
622 * Gets the hex-encoded UUID of the machine this function is
623 * executed on. This UUID is guaranteed to be the same for a given
624 * machine at least until it next reboots, though it also
625 * makes some effort to be the same forever, it may change if the
626 * machine is reconfigured or its hardware is modified.
628 * @param uuid_str string to append hex-encoded machine uuid to
629 * @returns #FALSE if no memory
632 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str)
636 _DBUS_LOCK (machine_uuid);
637 if (machine_uuid_initialized_generation != _dbus_current_generation)
640 dbus_error_init (&error);
641 if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE,
644 #ifndef DBUS_BUILD_TESTS
645 /* For the test suite, we may not be installed so just continue silently
646 * here. But in a production build, we want to be nice and loud about
649 _dbus_warn ("D-Bus library appears to be incorrectly set up; failed to read machine uuid: %s\n",
651 _dbus_warn ("See the manual page for dbus-uuidgen to correct this issue.\n");
652 _dbus_warn ("Continuing with a bogus made-up machine UUID, which may cause problems.");
655 dbus_error_free (&error);
657 _dbus_generate_uuid (&machine_uuid);
661 ok = _dbus_uuid_encode (&machine_uuid, uuid_str);
663 _DBUS_UNLOCK (machine_uuid);
668 #ifdef DBUS_BUILD_TESTS
670 * Returns a string describing the given name.
672 * @param header_field the field to describe
673 * @returns a constant string describing the field
676 _dbus_header_field_to_string (int header_field)
678 switch (header_field)
680 case DBUS_HEADER_FIELD_INVALID:
682 case DBUS_HEADER_FIELD_PATH:
684 case DBUS_HEADER_FIELD_INTERFACE:
686 case DBUS_HEADER_FIELD_MEMBER:
688 case DBUS_HEADER_FIELD_ERROR_NAME:
690 case DBUS_HEADER_FIELD_REPLY_SERIAL:
691 return "reply-serial";
692 case DBUS_HEADER_FIELD_DESTINATION:
693 return "destination";
694 case DBUS_HEADER_FIELD_SENDER:
696 case DBUS_HEADER_FIELD_SIGNATURE:
702 #endif /* DBUS_BUILD_TESTS */
704 #ifndef DBUS_DISABLE_CHECKS
705 /** String used in _dbus_return_if_fail macro */
706 const char _dbus_return_if_fail_warning_format[] =
707 "%lu: arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
708 "This is normally a bug in some application using the D-Bus library.\n";
711 #ifndef DBUS_DISABLE_ASSERT
713 * Internals of _dbus_assert(); it's a function
714 * rather than a macro with the inline code so
715 * that the assertion failure blocks don't show up
716 * in test suite coverage, and to shrink code size.
718 * @param condition TRUE if assertion succeeded
719 * @param condition_text condition as a string
720 * @param file file the assertion is in
721 * @param line line the assertion is in
722 * @param func function the assertion is in
725 _dbus_real_assert (dbus_bool_t condition,
726 const char *condition_text,
731 if (_DBUS_UNLIKELY (!condition))
733 _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
734 _dbus_getpid (), condition_text, file, line, func);
740 * Internals of _dbus_assert_not_reached(); it's a function
741 * rather than a macro with the inline code so
742 * that the assertion failure blocks don't show up
743 * in test suite coverage, and to shrink code size.
745 * @param explanation what was reached that shouldn't have been
746 * @param file file the assertion is in
747 * @param line line the assertion is in
750 _dbus_real_assert_not_reached (const char *explanation,
754 _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
755 file, line, _dbus_getpid (), explanation);
758 #endif /* DBUS_DISABLE_ASSERT */
760 #ifdef DBUS_BUILD_TESTS
762 run_failing_each_malloc (int n_mallocs,
763 const char *description,
764 DBusTestMemoryFunction func,
767 n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
769 while (n_mallocs >= 0)
771 _dbus_set_fail_alloc_counter (n_mallocs);
773 _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
774 description, n_mallocs,
775 _dbus_get_fail_alloc_failures ());
777 if (!(* func) (data))
783 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
789 * Tests how well the given function responds to out-of-memory
790 * situations. Calls the function repeatedly, failing a different
791 * call to malloc() each time. If the function ever returns #FALSE,
792 * the test fails. The function should return #TRUE whenever something
793 * valid (such as returning an error, or succeeding) occurs, and #FALSE
794 * if it gets confused in some way.
796 * @param description description of the test used in verbose output
797 * @param func function to call
798 * @param data data to pass to function
799 * @returns #TRUE if the function never returns FALSE
802 _dbus_test_oom_handling (const char *description,
803 DBusTestMemoryFunction func,
808 int max_failures_to_try;
811 /* Run once to see about how many mallocs are involved */
813 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
815 _dbus_verbose ("Running once to count mallocs\n");
817 if (!(* func) (data))
820 approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
822 _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
823 description, approx_mallocs);
825 setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
830 _dbus_string_init_const (&str, setting);
832 if (!_dbus_string_parse_int (&str, 0, &v, NULL))
833 _dbus_warn ("couldn't parse '%s' as integer\n", setting);
834 max_failures_to_try = v;
838 max_failures_to_try = 4;
841 i = setting ? max_failures_to_try - 1 : 1;
842 while (i < max_failures_to_try)
844 _dbus_set_fail_alloc_failures (i);
845 if (!run_failing_each_malloc (approx_mallocs, description, func, data))
850 _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
855 #endif /* DBUS_BUILD_TESTS */