1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "dbus-internals.h"
24 #include "dbus-protocol.h"
25 #include "dbus-marshal-basic.h"
26 #include "dbus-test.h"
31 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
37 * @defgroup DBusInternals D-Bus secret internal implementation details
38 * @brief Documentation useful when developing or debugging D-Bus itself.
43 * @defgroup DBusInternalsUtils Utilities and portability
44 * @ingroup DBusInternals
45 * @brief Utility functions (_dbus_assert(), _dbus_warn(), etc.)
52 * Aborts with an error message if the condition is false.
54 * @param condition condition which must be true.
58 * @def _dbus_assert_not_reached
60 * Aborts with an error message if called.
61 * The given explanation will be printed.
63 * @param explanation explanation of what happened if the code was reached.
67 * @def _DBUS_N_ELEMENTS
69 * Computes the number of elements in a fixed-size array using
72 * @param array the array to count elements in.
76 * @def _DBUS_POINTER_TO_INT
78 * Safely casts a void* to an integer; should only be used on void*
79 * that actually contain integers, for example one created with
80 * _DBUS_INT_TO_POINTER. Only guaranteed to preserve 32 bits.
81 * (i.e. it's used to store 32-bit ints in pointers, but
82 * can't be used to store 64-bit pointers in ints.)
84 * @param pointer pointer to extract an integer from.
87 * @def _DBUS_INT_TO_POINTER
89 * Safely stuffs an integer into a pointer, to be extracted later with
90 * _DBUS_POINTER_TO_INT. Only guaranteed to preserve 32 bits.
92 * @param integer the integer to stuff into a pointer.
97 * Sets all bits in an object to zero.
99 * @param object the object to be zeroed.
102 * @def _DBUS_INT16_MIN
104 * Minimum value of type "int16"
107 * @def _DBUS_INT16_MAX
109 * Maximum value of type "int16"
112 * @def _DBUS_UINT16_MAX
114 * Maximum value of type "uint16"
118 * @def _DBUS_INT32_MIN
120 * Minimum value of type "int32"
123 * @def _DBUS_INT32_MAX
125 * Maximum value of type "int32"
128 * @def _DBUS_UINT32_MAX
130 * Maximum value of type "uint32"
136 * Minimum value of type "int"
141 * Maximum value of type "int"
144 * @def _DBUS_UINT_MAX
146 * Maximum value of type "uint"
150 * @typedef DBusForeachFunction
152 * Used to iterate over each item in a collection, such as
157 * @def _DBUS_LOCK_NAME
159 * Expands to name of a global lock variable.
163 * @def _DBUS_DEFINE_GLOBAL_LOCK
165 * Defines a global lock variable with the given name.
166 * The lock must be added to the list to initialize
167 * in dbus_threads_init().
171 * @def _DBUS_DECLARE_GLOBAL_LOCK
173 * Expands to declaration of a global lock defined
174 * with _DBUS_DEFINE_GLOBAL_LOCK.
175 * The lock must be added to the list to initialize
176 * in dbus_threads_init().
182 * Locks a global lock
188 * Unlocks a global lock
192 * Fixed "out of memory" error message, just to avoid
193 * making up a different string every time and wasting
196 const char *_dbus_no_memory_message = "Not enough memory";
198 static dbus_bool_t warn_initted = FALSE;
199 static dbus_bool_t fatal_warnings = FALSE;
200 static dbus_bool_t fatal_warnings_on_check_failed = TRUE;
208 s = _dbus_getenv ("DBUS_FATAL_WARNINGS");
213 fatal_warnings = FALSE;
214 fatal_warnings_on_check_failed = FALSE;
218 fatal_warnings = TRUE;
219 fatal_warnings_on_check_failed = TRUE;
223 fprintf(stderr, "DBUS_FATAL_WARNINGS should be set to 0 or 1 if set, not '%s'",
233 * Prints a warning message to stderr. Can optionally be made to exit
234 * fatally by setting DBUS_FATAL_WARNINGS, but this is rarely
235 * used. This function should be considered pretty much equivalent to
236 * fprintf(stderr). _dbus_warn_check_failed() on the other hand is
237 * suitable for use when a programming mistake has been made.
239 * @param format printf-style format string.
242 _dbus_warn (const char *format,
250 va_start (args, format);
251 vfprintf (stderr, format, args);
262 * Prints a "critical" warning to stderr when an assertion fails;
263 * differs from _dbus_warn primarily in that it prefixes the pid and
264 * defaults to fatal. This should be used only when a programming
265 * error has been detected. (NOT for unavoidable errors that an app
266 * might handle - those should be returned as DBusError.) Calling this
267 * means "there is a bug"
270 _dbus_warn_check_failed(const char *format,
278 fprintf (stderr, "process %lu: ", _dbus_pid_for_log ());
280 va_start (args, format);
281 vfprintf (stderr, format, args);
284 if (fatal_warnings_on_check_failed)
291 #ifdef DBUS_ENABLE_VERBOSE_MODE
293 static dbus_bool_t verbose_initted = FALSE;
294 static dbus_bool_t verbose = TRUE;
296 /** Whether to show the current thread in verbose messages */
297 #define PTHREAD_IN_VERBOSE 0
298 #if PTHREAD_IN_VERBOSE
305 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
306 static char module_name[1024];
310 _dbus_verbose_init (void)
312 if (!verbose_initted)
314 const char *p = _dbus_getenv ("DBUS_VERBOSE");
315 verbose = p != NULL && *p == '1';
316 verbose_initted = TRUE;
317 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
319 char *last_period, *last_slash;
320 GetModuleFileName(0,module_name,sizeof(module_name)-1);
321 last_period = _mbsrchr(module_name,'.');
324 last_slash = _mbsrchr(module_name,'\\');
326 strcpy(module_name,last_slash+1);
327 strcat(module_name,": ");
333 /** @def DBUS_IS_DIR_SEPARATOR(c)
334 * macro for checking if character c is a patch separator
336 * @todo move to a header file so that others can use this too
339 #define DBUS_IS_DIR_SEPARATOR(c) (c == '\\' || c == '/')
341 #define DBUS_IS_DIR_SEPARATOR(c) (c == '/')
345 remove source root from file path
346 the source root is determined by
348 static char *_dbus_file_path_extract_elements_from_tail(const char *file,int level)
350 static int prefix = -1;
355 char *p = (char *)file + strlen(file);
360 if (DBUS_IS_DIR_SEPARATOR(*p))
370 return (char *)file+prefix;
374 * Implementation of dbus_is_verbose() macro if built with verbose logging
376 * @returns whether verbose logging is active.
379 _dbus_is_verbose_real (void)
381 _dbus_verbose_init ();
386 * Prints a warning message to stderr
387 * if the user has enabled verbose mode.
388 * This is the real function implementation,
389 * use _dbus_verbose() macro in code.
391 * @param format printf-style format string.
394 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
395 _dbus_verbose_real (const char *file,
397 const char *function,
400 _dbus_verbose_real (const char *format,
405 static dbus_bool_t need_pid = TRUE;
408 /* things are written a bit oddly here so that
409 * in the non-verbose case we just have the one
410 * conditional and return immediately.
412 if (!_dbus_is_verbose_real())
415 #ifndef DBUS_USE_OUTPUT_DEBUG_STRING
416 /* Print out pid before the line */
419 #if PTHREAD_IN_VERBOSE
420 fprintf (stderr, "%lu: 0x%lx: ", _dbus_pid_for_log (), pthread_self ());
422 fprintf (stderr, "%lu: ", _dbus_pid_for_log ());
427 /* Only print pid again if the next line is a new line */
428 len = strlen (format);
429 if (format[len-1] == '\n')
434 va_start (args, format);
435 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
438 strcpy(buf,module_name);
439 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
440 sprintf (buf+strlen(buf), "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
442 vsprintf (buf+strlen(buf),format, args);
444 OutputDebugString(buf);
447 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
448 fprintf (stderr, "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
451 vfprintf (stderr, format, args);
459 * Reinitializes the verbose logging code, used
460 * as a hack in dbus-spawn.c so that a child
461 * process re-reads its pid
465 _dbus_verbose_reset_real (void)
467 verbose_initted = FALSE;
470 #endif /* DBUS_ENABLE_VERBOSE_MODE */
473 * Duplicates a string. Result must be freed with
474 * dbus_free(). Returns #NULL if memory allocation fails.
475 * If the string to be duplicated is #NULL, returns #NULL.
477 * @param str string to duplicate.
478 * @returns newly-allocated copy.
481 _dbus_strdup (const char *str)
491 copy = dbus_malloc (len + 1);
495 memcpy (copy, str, len + 1);
501 * Duplicates a block of memory. Returns
504 * @param mem memory to copy
505 * @param n_bytes number of bytes to copy
509 _dbus_memdup (const void *mem,
514 copy = dbus_malloc (n_bytes);
518 memcpy (copy, mem, n_bytes);
524 * Duplicates a string array. Result may be freed with
525 * dbus_free_string_array(). Returns #NULL if memory allocation fails.
526 * If the array to be duplicated is #NULL, returns #NULL.
528 * @param array array to duplicate.
529 * @returns newly-allocated copy.
532 _dbus_dup_string_array (const char **array)
541 for (len = 0; array[len] != NULL; ++len)
544 copy = dbus_new0 (char*, len + 1);
551 copy[i] = _dbus_strdup (array[i]);
554 dbus_free_string_array (copy);
565 * Checks whether a string array contains the given string.
567 * @param array array to search.
568 * @param str string to look for
569 * @returns #TRUE if array contains string
572 _dbus_string_array_contains (const char **array,
578 while (array[i] != NULL)
580 if (strcmp (array[i], str) == 0)
589 * Generates a new UUID. If you change how this is done,
590 * there's some text about it in the spec that should also change.
592 * @param uuid the uuid to initialize
595 _dbus_generate_uuid (DBusGUID *uuid)
599 _dbus_get_current_time (&now, NULL);
601 uuid->as_uint32s[DBUS_UUID_LENGTH_WORDS - 1] = DBUS_UINT32_TO_BE (now);
603 _dbus_generate_random_bytes_buffer (uuid->as_bytes, DBUS_UUID_LENGTH_BYTES - 4);
609 * @param uuid the uuid
610 * @param encoded string to append hex uuid to
611 * @returns #FALSE if no memory
614 _dbus_uuid_encode (const DBusGUID *uuid,
618 _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
619 return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
623 _dbus_read_uuid_file_without_creating (const DBusString *filename,
631 if (!_dbus_string_init (&contents))
633 _DBUS_SET_OOM (error);
637 if (!_dbus_string_init (&decoded))
639 _dbus_string_free (&contents);
640 _DBUS_SET_OOM (error);
644 if (!_dbus_file_get_contents (&contents, filename, error))
647 _dbus_string_chop_white (&contents);
649 if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
651 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
652 "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
653 _dbus_string_get_const_data (filename),
654 DBUS_UUID_LENGTH_HEX,
655 _dbus_string_get_length (&contents));
659 if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
661 _DBUS_SET_OOM (error);
667 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
668 "UUID file '%s' contains invalid hex data",
669 _dbus_string_get_const_data (filename));
673 if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
675 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
676 "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
677 _dbus_string_get_const_data (filename),
678 _dbus_string_get_length (&decoded),
679 DBUS_UUID_LENGTH_BYTES);
683 _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
685 _dbus_string_free (&decoded);
686 _dbus_string_free (&contents);
688 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
693 _DBUS_ASSERT_ERROR_IS_SET (error);
694 _dbus_string_free (&contents);
695 _dbus_string_free (&decoded);
700 _dbus_create_uuid_file_exclusively (const DBusString *filename,
706 if (!_dbus_string_init (&encoded))
708 _DBUS_SET_OOM (error);
712 _dbus_generate_uuid (uuid);
714 if (!_dbus_uuid_encode (uuid, &encoded))
716 _DBUS_SET_OOM (error);
720 /* FIXME this is racy; we need a save_file_exclusively
721 * function. But in practice this should be fine for now.
723 * - first be sure we can create the file and it
724 * doesn't exist by creating it empty with O_EXCL
725 * - then create it by creating a temporary file and
726 * overwriting atomically with rename()
728 if (!_dbus_create_file_exclusively (filename, error))
731 if (!_dbus_string_append_byte (&encoded, '\n'))
733 _DBUS_SET_OOM (error);
737 if (!_dbus_string_save_to_file (&encoded, filename, error))
740 if (!_dbus_make_file_world_readable (filename, error))
743 _dbus_string_free (&encoded);
745 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
749 _DBUS_ASSERT_ERROR_IS_SET (error);
750 _dbus_string_free (&encoded);
755 * Reads (and optionally writes) a uuid to a file. Initializes the uuid
756 * unless an error is returned.
758 * @param filename the name of the file
759 * @param uuid uuid to be initialized with the loaded uuid
760 * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
761 * @param error the error return
762 * @returns #FALSE if the error is set
765 _dbus_read_uuid_file (const DBusString *filename,
767 dbus_bool_t create_if_not_found,
770 DBusError read_error = DBUS_ERROR_INIT;
772 if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
775 if (!create_if_not_found)
777 dbus_move_error (&read_error, error);
781 /* If the file exists and contains junk, we want to keep that error
782 * message instead of overwriting it with a "file exists" error
783 * message when we try to write
785 if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
787 dbus_move_error (&read_error, error);
792 dbus_error_free (&read_error);
793 return _dbus_create_uuid_file_exclusively (filename, uuid, error);
797 _DBUS_DEFINE_GLOBAL_LOCK (machine_uuid);
798 static int machine_uuid_initialized_generation = 0;
799 static DBusGUID machine_uuid;
802 * Gets the hex-encoded UUID of the machine this function is
803 * executed on. This UUID is guaranteed to be the same for a given
804 * machine at least until it next reboots, though it also
805 * makes some effort to be the same forever, it may change if the
806 * machine is reconfigured or its hardware is modified.
808 * @param uuid_str string to append hex-encoded machine uuid to
809 * @returns #FALSE if no memory
812 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str)
816 _DBUS_LOCK (machine_uuid);
817 if (machine_uuid_initialized_generation != _dbus_current_generation)
819 DBusError error = DBUS_ERROR_INIT;
821 if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE,
824 #ifndef DBUS_BUILD_TESTS
825 /* For the test suite, we may not be installed so just continue silently
826 * here. But in a production build, we want to be nice and loud about
829 _dbus_warn_check_failed ("D-Bus library appears to be incorrectly set up; failed to read machine uuid: %s\n"
830 "See the manual page for dbus-uuidgen to correct this issue.\n",
834 dbus_error_free (&error);
836 _dbus_generate_uuid (&machine_uuid);
840 ok = _dbus_uuid_encode (&machine_uuid, uuid_str);
842 _DBUS_UNLOCK (machine_uuid);
847 #ifdef DBUS_BUILD_TESTS
849 * Returns a string describing the given name.
851 * @param header_field the field to describe
852 * @returns a constant string describing the field
855 _dbus_header_field_to_string (int header_field)
857 switch (header_field)
859 case DBUS_HEADER_FIELD_INVALID:
861 case DBUS_HEADER_FIELD_PATH:
863 case DBUS_HEADER_FIELD_INTERFACE:
865 case DBUS_HEADER_FIELD_MEMBER:
867 case DBUS_HEADER_FIELD_ERROR_NAME:
869 case DBUS_HEADER_FIELD_REPLY_SERIAL:
870 return "reply-serial";
871 case DBUS_HEADER_FIELD_DESTINATION:
872 return "destination";
873 case DBUS_HEADER_FIELD_SENDER:
875 case DBUS_HEADER_FIELD_SIGNATURE:
881 #endif /* DBUS_BUILD_TESTS */
883 #ifndef DBUS_DISABLE_CHECKS
884 /** String used in _dbus_return_if_fail macro */
885 const char *_dbus_return_if_fail_warning_format =
886 "arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
887 "This is normally a bug in some application using the D-Bus library.\n";
890 #ifndef DBUS_DISABLE_ASSERT
892 * Internals of _dbus_assert(); it's a function
893 * rather than a macro with the inline code so
894 * that the assertion failure blocks don't show up
895 * in test suite coverage, and to shrink code size.
897 * @param condition TRUE if assertion succeeded
898 * @param condition_text condition as a string
899 * @param file file the assertion is in
900 * @param line line the assertion is in
901 * @param func function the assertion is in
904 _dbus_real_assert (dbus_bool_t condition,
905 const char *condition_text,
910 if (_DBUS_UNLIKELY (!condition))
912 _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
913 _dbus_pid_for_log (), condition_text, file, line, func);
919 * Internals of _dbus_assert_not_reached(); it's a function
920 * rather than a macro with the inline code so
921 * that the assertion failure blocks don't show up
922 * in test suite coverage, and to shrink code size.
924 * @param explanation what was reached that shouldn't have been
925 * @param file file the assertion is in
926 * @param line line the assertion is in
929 _dbus_real_assert_not_reached (const char *explanation,
933 _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
934 file, line, _dbus_pid_for_log (), explanation);
937 #endif /* DBUS_DISABLE_ASSERT */
939 #ifdef DBUS_BUILD_TESTS
941 run_failing_each_malloc (int n_mallocs,
942 const char *description,
943 DBusTestMemoryFunction func,
946 n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
948 while (n_mallocs >= 0)
950 _dbus_set_fail_alloc_counter (n_mallocs);
952 _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
953 description, n_mallocs,
954 _dbus_get_fail_alloc_failures ());
956 if (!(* func) (data))
962 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
968 * Tests how well the given function responds to out-of-memory
969 * situations. Calls the function repeatedly, failing a different
970 * call to malloc() each time. If the function ever returns #FALSE,
971 * the test fails. The function should return #TRUE whenever something
972 * valid (such as returning an error, or succeeding) occurs, and #FALSE
973 * if it gets confused in some way.
975 * @param description description of the test used in verbose output
976 * @param func function to call
977 * @param data data to pass to function
978 * @returns #TRUE if the function never returns FALSE
981 _dbus_test_oom_handling (const char *description,
982 DBusTestMemoryFunction func,
987 int max_failures_to_try;
990 /* Run once to see about how many mallocs are involved */
992 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
994 _dbus_verbose ("Running once to count mallocs\n");
996 if (!(* func) (data))
999 approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
1001 _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
1002 description, approx_mallocs);
1004 setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
1005 if (setting != NULL)
1009 _dbus_string_init_const (&str, setting);
1011 if (!_dbus_string_parse_int (&str, 0, &v, NULL))
1012 _dbus_warn ("couldn't parse '%s' as integer\n", setting);
1013 max_failures_to_try = v;
1017 max_failures_to_try = 4;
1020 i = setting ? max_failures_to_try - 1 : 1;
1021 while (i < max_failures_to_try)
1023 _dbus_set_fail_alloc_failures (i);
1024 if (!run_failing_each_malloc (approx_mallocs, description, func, data))
1029 _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
1034 #endif /* DBUS_BUILD_TESTS */