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"
31 /* the blurb for this is "D-Bus secret" so it comes after "D-Bus low-level"
32 * which is the blurb for the DBus group, which makes Doxygen show
33 * the public API first on the index page. Yay for lame hacks.
36 * @defgroup DBusInternals D-Bus secret internal implementation details
37 * @brief Documentation useful when developing or debugging D-Bus itself.
42 * @defgroup DBusInternalsUtils Utilities and portability
43 * @ingroup DBusInternals
44 * @brief Utility functions (_dbus_assert(), _dbus_warn(), etc.)
51 * Aborts with an error message if the condition is false.
53 * @param condition condition which must be true.
57 * @def _dbus_assert_not_reached
59 * Aborts with an error message if called.
60 * The given explanation will be printed.
62 * @param explanation explanation of what happened if the code was reached.
66 * @def _DBUS_N_ELEMENTS
68 * Computes the number of elements in a fixed-size array using
71 * @param array the array to count elements in.
75 * @def _DBUS_POINTER_TO_INT
77 * Safely casts a void* to an integer; should only be used on void*
78 * that actually contain integers, for example one created with
79 * _DBUS_INT_TO_POINTER. Only guaranteed to preserve 32 bits.
80 * (i.e. it's used to store 32-bit ints in pointers, but
81 * can't be used to store 64-bit pointers in ints.)
83 * @param pointer pointer to extract an integer from.
86 * @def _DBUS_INT_TO_POINTER
88 * Safely stuffs an integer into a pointer, to be extracted later with
89 * _DBUS_POINTER_TO_INT. Only guaranteed to preserve 32 bits.
91 * @param integer the integer to stuff into a pointer.
96 * Sets all bits in an object to zero.
98 * @param object the object to be zeroed.
101 * @def _DBUS_INT16_MIN
103 * Minimum value of type "int16"
106 * @def _DBUS_INT16_MAX
108 * Maximum value of type "int16"
111 * @def _DBUS_UINT16_MAX
113 * Maximum value of type "uint16"
117 * @def _DBUS_INT32_MIN
119 * Minimum value of type "int32"
122 * @def _DBUS_INT32_MAX
124 * Maximum value of type "int32"
127 * @def _DBUS_UINT32_MAX
129 * Maximum value of type "uint32"
135 * Minimum value of type "int"
140 * Maximum value of type "int"
143 * @def _DBUS_UINT_MAX
145 * Maximum value of type "uint"
149 * @typedef DBusForeachFunction
151 * Used to iterate over each item in a collection, such as
156 * @def _DBUS_LOCK_NAME
158 * Expands to name of a global lock variable.
162 * @def _DBUS_DEFINE_GLOBAL_LOCK
164 * Defines a global lock variable with the given name.
165 * The lock must be added to the list to initialize
166 * in dbus_threads_init().
170 * @def _DBUS_DECLARE_GLOBAL_LOCK
172 * Expands to declaration of a global lock defined
173 * with _DBUS_DEFINE_GLOBAL_LOCK.
174 * The lock must be added to the list to initialize
175 * in dbus_threads_init().
181 * Locks a global lock
187 * Unlocks a global lock
191 * Fixed "out of memory" error message, just to avoid
192 * making up a different string every time and wasting
195 const char _dbus_no_memory_message[] = "Not enough memory";
197 static dbus_bool_t warn_initted = FALSE;
198 static dbus_bool_t fatal_warnings = FALSE;
199 static dbus_bool_t fatal_warnings_on_check_failed = TRUE;
207 s = _dbus_getenv ("DBUS_FATAL_WARNINGS");
212 fatal_warnings = FALSE;
213 fatal_warnings_on_check_failed = FALSE;
217 fatal_warnings = TRUE;
218 fatal_warnings_on_check_failed = TRUE;
222 fprintf(stderr, "DBUS_FATAL_WARNINGS should be set to 0 or 1 if set, not '%s'",
232 * Prints a warning message to stderr. Can optionally be made to exit
233 * fatally by setting DBUS_FATAL_WARNINGS, but this is rarely
234 * used. This function should be considered pretty much equivalent to
235 * fprintf(stderr). _dbus_warn_check_failed() on the other hand is
236 * suitable for use when a programming mistake has been made.
238 * @param format printf-style format string.
241 _dbus_warn (const char *format,
249 va_start (args, format);
250 vfprintf (stderr, format, args);
261 * Prints a "critical" warning to stderr when an assertion fails;
262 * differs from _dbus_warn primarily in that it prefixes the pid and
263 * defaults to fatal. This should be used only when a programming
264 * error has been detected. (NOT for unavoidable errors that an app
265 * might handle - those should be returned as DBusError.) Calling this
266 * means "there is a bug"
269 _dbus_warn_check_failed(const char *format,
277 fprintf (stderr, "process %lu: ", _dbus_getpid ());
279 va_start (args, format);
280 vfprintf (stderr, format, args);
283 if (fatal_warnings_on_check_failed)
290 #ifdef DBUS_ENABLE_VERBOSE_MODE
292 static dbus_bool_t verbose_initted = FALSE;
293 static dbus_bool_t verbose = TRUE;
295 /** Whether to show the current thread in verbose messages */
296 #define PTHREAD_IN_VERBOSE 0
297 #if PTHREAD_IN_VERBOSE
302 _dbus_verbose_init (void)
304 if (!verbose_initted)
306 const char *p = _dbus_getenv ("DBUS_VERBOSE");
307 verbose = p != NULL && *p == '1';
308 verbose_initted = TRUE;
313 * Implementation of dbus_is_verbose() macro if built with verbose logging
315 * @returns whether verbose logging is active.
318 _dbus_is_verbose_real (void)
320 _dbus_verbose_init ();
325 * Prints a warning message to stderr
326 * if the user has enabled verbose mode.
327 * This is the real function implementation,
328 * use _dbus_verbose() macro in code.
330 * @param format printf-style format string.
333 _dbus_verbose_real (const char *format,
337 static dbus_bool_t need_pid = TRUE;
340 /* things are written a bit oddly here so that
341 * in the non-verbose case we just have the one
342 * conditional and return immediately.
344 if (!_dbus_is_verbose_real())
347 /* Print out pid before the line */
350 #if PTHREAD_IN_VERBOSE
351 fprintf (stderr, "%lu: 0x%lx: ", _dbus_getpid (), pthread_self ());
353 fprintf (stderr, "%lu: ", _dbus_getpid ());
358 /* Only print pid again if the next line is a new line */
359 len = strlen (format);
360 if (format[len-1] == '\n')
365 va_start (args, format);
366 vfprintf (stderr, format, args);
373 * Reinitializes the verbose logging code, used
374 * as a hack in dbus-spawn.c so that a child
375 * process re-reads its pid
379 _dbus_verbose_reset_real (void)
381 verbose_initted = FALSE;
384 #endif /* DBUS_ENABLE_VERBOSE_MODE */
387 * Duplicates a string. Result must be freed with
388 * dbus_free(). Returns #NULL if memory allocation fails.
389 * If the string to be duplicated is #NULL, returns #NULL.
391 * @param str string to duplicate.
392 * @returns newly-allocated copy.
395 _dbus_strdup (const char *str)
405 copy = dbus_malloc (len + 1);
409 memcpy (copy, str, len + 1);
415 * Duplicates a block of memory. Returns
418 * @param mem memory to copy
419 * @param n_bytes number of bytes to copy
423 _dbus_memdup (const void *mem,
428 copy = dbus_malloc (n_bytes);
432 memcpy (copy, mem, n_bytes);
438 * Duplicates a string array. Result may be freed with
439 * dbus_free_string_array(). Returns #NULL if memory allocation fails.
440 * If the array to be duplicated is #NULL, returns #NULL.
442 * @param array array to duplicate.
443 * @returns newly-allocated copy.
446 _dbus_dup_string_array (const char **array)
455 for (len = 0; array[len] != NULL; ++len)
458 copy = dbus_new0 (char*, len + 1);
465 copy[i] = _dbus_strdup (array[i]);
468 dbus_free_string_array (copy);
479 * Checks whether a string array contains the given string.
481 * @param array array to search.
482 * @param str string to look for
483 * @returns #TRUE if array contains string
486 _dbus_string_array_contains (const char **array,
492 while (array[i] != NULL)
494 if (strcmp (array[i], str) == 0)
503 * Generates a new UUID. If you change how this is done,
504 * there's some text about it in the spec that should also change.
506 * @param uuid the uuid to initialize
509 _dbus_generate_uuid (DBusGUID *uuid)
515 _dbus_get_current_time (&now, NULL);
517 uuid->as_uint32s[0] = now;
519 ts_size = sizeof (uuid->as_uint32s[0]);
520 p = ((char*)uuid->as_bytes) + ts_size;
522 _dbus_generate_random_bytes_buffer (p,
523 sizeof (uuid->as_bytes) - ts_size);
529 * @param uuid the uuid
530 * @param encoded string to append hex uuid to
531 * @returns #FALSE if no memory
534 _dbus_uuid_encode (const DBusGUID *uuid,
538 _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
539 return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
543 _dbus_read_uuid_file_without_creating (const DBusString *filename,
551 _dbus_string_init (&contents);
552 _dbus_string_init (&decoded);
554 if (!_dbus_file_get_contents (&contents, filename, error))
557 _dbus_string_chop_white (&contents);
559 if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
561 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
562 "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
563 _dbus_string_get_const_data (filename),
564 DBUS_UUID_LENGTH_HEX,
565 _dbus_string_get_length (&contents));
569 if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
571 _DBUS_SET_OOM (error);
577 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
578 "UUID file '%s' contains invalid hex data",
579 _dbus_string_get_const_data (filename));
583 if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
585 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
586 "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
587 _dbus_string_get_const_data (filename),
588 _dbus_string_get_length (&decoded),
589 DBUS_UUID_LENGTH_BYTES);
593 _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
595 _dbus_string_free (&decoded);
596 _dbus_string_free (&contents);
598 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
603 _DBUS_ASSERT_ERROR_IS_SET (error);
604 _dbus_string_free (&contents);
605 _dbus_string_free (&decoded);
610 _dbus_create_uuid_file_exclusively (const DBusString *filename,
616 _dbus_string_init (&encoded);
618 _dbus_generate_uuid (uuid);
620 if (!_dbus_uuid_encode (uuid, &encoded))
622 _DBUS_SET_OOM (error);
626 /* FIXME this is racy; we need a save_file_exclusively
627 * function. But in practice this should be fine for now.
629 * - first be sure we can create the file and it
630 * doesn't exist by creating it empty with O_EXCL
631 * - then create it by creating a temporary file and
632 * overwriting atomically with rename()
634 if (!_dbus_create_file_exclusively (filename, error))
637 if (!_dbus_string_append_byte (&encoded, '\n'))
639 _DBUS_SET_OOM (error);
643 if (!_dbus_string_save_to_file (&encoded, filename, error))
647 _dbus_string_free (&encoded);
649 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
653 _DBUS_ASSERT_ERROR_IS_SET (error);
654 _dbus_string_free (&encoded);
659 * Reads (and optionally writes) a uuid to a file. Initializes the uuid
660 * unless an error is returned.
662 * @param filename the name of the file
663 * @param uuid uuid to be initialized with the loaded uuid
664 * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
665 * @param error the error return
666 * @returns #FALSE if the error is set
669 _dbus_read_uuid_file (const DBusString *filename,
671 dbus_bool_t create_if_not_found,
674 DBusError read_error;
676 dbus_error_init (&read_error);
678 if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
681 if (!create_if_not_found)
683 dbus_move_error (&read_error, error);
687 /* If the file exists and contains junk, we want to keep that error
688 * message instead of overwriting it with a "file exists" error
689 * message when we try to write
691 if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
693 dbus_move_error (&read_error, error);
698 dbus_error_free (&read_error);
699 return _dbus_create_uuid_file_exclusively (filename, uuid, error);
703 _DBUS_DEFINE_GLOBAL_LOCK (machine_uuid);
704 static int machine_uuid_initialized_generation = 0;
705 static DBusGUID machine_uuid;
708 * Gets the hex-encoded UUID of the machine this function is
709 * executed on. This UUID is guaranteed to be the same for a given
710 * machine at least until it next reboots, though it also
711 * makes some effort to be the same forever, it may change if the
712 * machine is reconfigured or its hardware is modified.
714 * @param uuid_str string to append hex-encoded machine uuid to
715 * @returns #FALSE if no memory
718 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str)
722 _DBUS_LOCK (machine_uuid);
723 if (machine_uuid_initialized_generation != _dbus_current_generation)
726 dbus_error_init (&error);
727 if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE,
730 #ifndef DBUS_BUILD_TESTS
731 /* For the test suite, we may not be installed so just continue silently
732 * here. But in a production build, we want to be nice and loud about
735 _dbus_warn_check_failed ("D-Bus library appears to be incorrectly set up; failed to read machine uuid: %s\n"
736 "See the manual page for dbus-uuidgen to correct this issue.\n",
740 dbus_error_free (&error);
742 _dbus_generate_uuid (&machine_uuid);
746 ok = _dbus_uuid_encode (&machine_uuid, uuid_str);
748 _DBUS_UNLOCK (machine_uuid);
753 #ifdef DBUS_BUILD_TESTS
755 * Returns a string describing the given name.
757 * @param header_field the field to describe
758 * @returns a constant string describing the field
761 _dbus_header_field_to_string (int header_field)
763 switch (header_field)
765 case DBUS_HEADER_FIELD_INVALID:
767 case DBUS_HEADER_FIELD_PATH:
769 case DBUS_HEADER_FIELD_INTERFACE:
771 case DBUS_HEADER_FIELD_MEMBER:
773 case DBUS_HEADER_FIELD_ERROR_NAME:
775 case DBUS_HEADER_FIELD_REPLY_SERIAL:
776 return "reply-serial";
777 case DBUS_HEADER_FIELD_DESTINATION:
778 return "destination";
779 case DBUS_HEADER_FIELD_SENDER:
781 case DBUS_HEADER_FIELD_SIGNATURE:
787 #endif /* DBUS_BUILD_TESTS */
789 #ifndef DBUS_DISABLE_CHECKS
790 /** String used in _dbus_return_if_fail macro */
791 const char _dbus_return_if_fail_warning_format[] =
792 "arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
793 "This is normally a bug in some application using the D-Bus library.\n";
796 #ifndef DBUS_DISABLE_ASSERT
798 * Internals of _dbus_assert(); it's a function
799 * rather than a macro with the inline code so
800 * that the assertion failure blocks don't show up
801 * in test suite coverage, and to shrink code size.
803 * @param condition TRUE if assertion succeeded
804 * @param condition_text condition as a string
805 * @param file file the assertion is in
806 * @param line line the assertion is in
807 * @param func function the assertion is in
810 _dbus_real_assert (dbus_bool_t condition,
811 const char *condition_text,
816 if (_DBUS_UNLIKELY (!condition))
818 _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
819 _dbus_getpid (), condition_text, file, line, func);
825 * Internals of _dbus_assert_not_reached(); it's a function
826 * rather than a macro with the inline code so
827 * that the assertion failure blocks don't show up
828 * in test suite coverage, and to shrink code size.
830 * @param explanation what was reached that shouldn't have been
831 * @param file file the assertion is in
832 * @param line line the assertion is in
835 _dbus_real_assert_not_reached (const char *explanation,
839 _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
840 file, line, _dbus_getpid (), explanation);
843 #endif /* DBUS_DISABLE_ASSERT */
845 #ifdef DBUS_BUILD_TESTS
847 run_failing_each_malloc (int n_mallocs,
848 const char *description,
849 DBusTestMemoryFunction func,
852 n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
854 while (n_mallocs >= 0)
856 _dbus_set_fail_alloc_counter (n_mallocs);
858 _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
859 description, n_mallocs,
860 _dbus_get_fail_alloc_failures ());
862 if (!(* func) (data))
868 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
874 * Tests how well the given function responds to out-of-memory
875 * situations. Calls the function repeatedly, failing a different
876 * call to malloc() each time. If the function ever returns #FALSE,
877 * the test fails. The function should return #TRUE whenever something
878 * valid (such as returning an error, or succeeding) occurs, and #FALSE
879 * if it gets confused in some way.
881 * @param description description of the test used in verbose output
882 * @param func function to call
883 * @param data data to pass to function
884 * @returns #TRUE if the function never returns FALSE
887 _dbus_test_oom_handling (const char *description,
888 DBusTestMemoryFunction func,
893 int max_failures_to_try;
896 /* Run once to see about how many mallocs are involved */
898 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
900 _dbus_verbose ("Running once to count mallocs\n");
902 if (!(* func) (data))
905 approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
907 _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
908 description, approx_mallocs);
910 setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
915 _dbus_string_init_const (&str, setting);
917 if (!_dbus_string_parse_int (&str, 0, &v, NULL))
918 _dbus_warn ("couldn't parse '%s' as integer\n", setting);
919 max_failures_to_try = v;
923 max_failures_to_try = 4;
926 i = setting ? max_failures_to_try - 1 : 1;
927 while (i < max_failures_to_try)
929 _dbus_set_fail_alloc_failures (i);
930 if (!run_failing_each_malloc (approx_mallocs, description, func, data))
935 _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
940 #endif /* DBUS_BUILD_TESTS */