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
25 #include "dbus-internals.h"
26 #include "dbus-protocol.h"
27 #include "dbus-marshal-basic.h"
28 #include "dbus-test.h"
33 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
39 * @defgroup DBusInternals D-Bus secret internal implementation details
40 * @brief Documentation useful when developing or debugging D-Bus itself.
45 * @defgroup DBusInternalsUtils Utilities and portability
46 * @ingroup DBusInternals
47 * @brief Utility functions (_dbus_assert(), _dbus_warn(), etc.)
54 * Aborts with an error message if the condition is false.
56 * @param condition condition which must be true.
60 * @def _dbus_assert_not_reached
62 * Aborts with an error message if called.
63 * The given explanation will be printed.
65 * @param explanation explanation of what happened if the code was reached.
69 * @def _DBUS_N_ELEMENTS
71 * Computes the number of elements in a fixed-size array using
74 * @param array the array to count elements in.
78 * @def _DBUS_POINTER_TO_INT
80 * Safely casts a void* to an integer; should only be used on void*
81 * that actually contain integers, for example one created with
82 * _DBUS_INT_TO_POINTER. Only guaranteed to preserve 32 bits.
83 * (i.e. it's used to store 32-bit ints in pointers, but
84 * can't be used to store 64-bit pointers in ints.)
86 * @param pointer pointer to extract an integer from.
89 * @def _DBUS_INT_TO_POINTER
91 * Safely stuffs an integer into a pointer, to be extracted later with
92 * _DBUS_POINTER_TO_INT. Only guaranteed to preserve 32 bits.
94 * @param integer the integer to stuff into a pointer.
99 * Sets all bits in an object to zero.
101 * @param object the object to be zeroed.
104 * @def _DBUS_INT16_MIN
106 * Minimum value of type "int16"
109 * @def _DBUS_INT16_MAX
111 * Maximum value of type "int16"
114 * @def _DBUS_UINT16_MAX
116 * Maximum value of type "uint16"
120 * @def _DBUS_INT32_MIN
122 * Minimum value of type "int32"
125 * @def _DBUS_INT32_MAX
127 * Maximum value of type "int32"
130 * @def _DBUS_UINT32_MAX
132 * Maximum value of type "uint32"
138 * Minimum value of type "int"
143 * Maximum value of type "int"
146 * @def _DBUS_UINT_MAX
148 * Maximum value of type "uint"
152 * @typedef DBusForeachFunction
154 * Used to iterate over each item in a collection, such as
159 * @def _DBUS_LOCK_NAME
161 * Expands to name of a global lock variable.
165 * @def _DBUS_DEFINE_GLOBAL_LOCK
167 * Defines a global lock variable with the given name.
168 * The lock must be added to the list to initialize
169 * in dbus_threads_init().
173 * @def _DBUS_DECLARE_GLOBAL_LOCK
175 * Expands to declaration of a global lock defined
176 * with _DBUS_DEFINE_GLOBAL_LOCK.
177 * The lock must be added to the list to initialize
178 * in dbus_threads_init().
184 * Locks a global lock
190 * Unlocks a global lock
194 * Fixed "out of memory" error message, just to avoid
195 * making up a different string every time and wasting
198 const char *_dbus_no_memory_message = "Not enough memory";
200 static dbus_bool_t warn_initted = FALSE;
201 static dbus_bool_t fatal_warnings = FALSE;
202 static dbus_bool_t fatal_warnings_on_check_failed = TRUE;
210 s = _dbus_getenv ("DBUS_FATAL_WARNINGS");
215 fatal_warnings = FALSE;
216 fatal_warnings_on_check_failed = FALSE;
220 fatal_warnings = TRUE;
221 fatal_warnings_on_check_failed = TRUE;
225 fprintf(stderr, "DBUS_FATAL_WARNINGS should be set to 0 or 1 if set, not '%s'",
235 * Prints a warning message to stderr. Can optionally be made to exit
236 * fatally by setting DBUS_FATAL_WARNINGS, but this is rarely
237 * used. This function should be considered pretty much equivalent to
238 * fprintf(stderr). _dbus_warn_check_failed() on the other hand is
239 * suitable for use when a programming mistake has been made.
241 * @param format printf-style format string.
244 _dbus_warn (const char *format,
252 va_start (args, format);
253 vfprintf (stderr, format, args);
264 * Prints a "critical" warning to stderr when an assertion fails;
265 * differs from _dbus_warn primarily in that it prefixes the pid and
266 * defaults to fatal. This should be used only when a programming
267 * error has been detected. (NOT for unavoidable errors that an app
268 * might handle - those should be returned as DBusError.) Calling this
269 * means "there is a bug"
272 _dbus_warn_check_failed(const char *format,
280 fprintf (stderr, "process %lu: ", _dbus_pid_for_log ());
282 va_start (args, format);
283 vfprintf (stderr, format, args);
286 if (fatal_warnings_on_check_failed)
293 #ifdef DBUS_ENABLE_VERBOSE_MODE
295 static dbus_bool_t verbose_initted = FALSE;
296 static dbus_bool_t verbose = TRUE;
298 /** Whether to show the current thread in verbose messages */
299 #define PTHREAD_IN_VERBOSE 0
300 #if PTHREAD_IN_VERBOSE
307 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
308 static char module_name[1024];
312 _dbus_verbose_init (void)
314 if (!verbose_initted)
316 const char *p = _dbus_getenv ("DBUS_VERBOSE");
317 verbose = p != NULL && *p == '1';
318 verbose_initted = TRUE;
319 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
321 char *last_period, *last_slash;
322 GetModuleFileName(0,module_name,sizeof(module_name)-1);
323 last_period = _mbsrchr(module_name,'.');
326 last_slash = _mbsrchr(module_name,'\\');
328 strcpy(module_name,last_slash+1);
329 strcat(module_name,": ");
335 /** @def DBUS_IS_DIR_SEPARATOR(c)
336 * macro for checking if character c is a patch separator
338 * @todo move to a header file so that others can use this too
341 #define DBUS_IS_DIR_SEPARATOR(c) (c == '\\' || c == '/')
343 #define DBUS_IS_DIR_SEPARATOR(c) (c == '/')
347 remove source root from file path
348 the source root is determined by
350 static char *_dbus_file_path_extract_elements_from_tail(const char *file,int level)
352 static int prefix = -1;
357 char *p = (char *)file + strlen(file);
362 if (DBUS_IS_DIR_SEPARATOR(*p))
372 return (char *)file+prefix;
376 * Implementation of dbus_is_verbose() macro if built with verbose logging
378 * @returns whether verbose logging is active.
381 _dbus_is_verbose_real (void)
383 _dbus_verbose_init ();
388 * Prints a warning message to stderr
389 * if the user has enabled verbose mode.
390 * This is the real function implementation,
391 * use _dbus_verbose() macro in code.
393 * @param format printf-style format string.
396 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
397 _dbus_verbose_real (const char *file,
399 const char *function,
402 _dbus_verbose_real (const char *format,
407 static dbus_bool_t need_pid = TRUE;
410 /* things are written a bit oddly here so that
411 * in the non-verbose case we just have the one
412 * conditional and return immediately.
414 if (!_dbus_is_verbose_real())
417 #ifndef DBUS_USE_OUTPUT_DEBUG_STRING
418 /* Print out pid before the line */
421 #if PTHREAD_IN_VERBOSE
422 fprintf (stderr, "%lu: 0x%lx: ", _dbus_pid_for_log (), pthread_self ());
424 fprintf (stderr, "%lu: ", _dbus_pid_for_log ());
429 /* Only print pid again if the next line is a new line */
430 len = strlen (format);
431 if (format[len-1] == '\n')
436 va_start (args, format);
437 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
440 strcpy(buf,module_name);
441 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
442 sprintf (buf+strlen(buf), "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
444 vsprintf (buf+strlen(buf),format, args);
446 OutputDebugStringA(buf);
449 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
450 fprintf (stderr, "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
453 vfprintf (stderr, format, args);
461 * Reinitializes the verbose logging code, used
462 * as a hack in dbus-spawn.c so that a child
463 * process re-reads its pid
467 _dbus_verbose_reset_real (void)
469 verbose_initted = FALSE;
472 #endif /* DBUS_ENABLE_VERBOSE_MODE */
475 * Duplicates a string. Result must be freed with
476 * dbus_free(). Returns #NULL if memory allocation fails.
477 * If the string to be duplicated is #NULL, returns #NULL.
479 * @param str string to duplicate.
480 * @returns newly-allocated copy.
483 _dbus_strdup (const char *str)
493 copy = dbus_malloc (len + 1);
497 memcpy (copy, str, len + 1);
503 * Duplicates a block of memory. Returns
506 * @param mem memory to copy
507 * @param n_bytes number of bytes to copy
511 _dbus_memdup (const void *mem,
516 copy = dbus_malloc (n_bytes);
520 memcpy (copy, mem, n_bytes);
526 * Duplicates a string array. Result may be freed with
527 * dbus_free_string_array(). Returns #NULL if memory allocation fails.
528 * If the array to be duplicated is #NULL, returns #NULL.
530 * @param array array to duplicate.
531 * @returns newly-allocated copy.
534 _dbus_dup_string_array (const char **array)
543 for (len = 0; array[len] != NULL; ++len)
546 copy = dbus_new0 (char*, len + 1);
553 copy[i] = _dbus_strdup (array[i]);
556 dbus_free_string_array (copy);
567 * Checks whether a string array contains the given string.
569 * @param array array to search.
570 * @param str string to look for
571 * @returns #TRUE if array contains string
574 _dbus_string_array_contains (const char **array,
580 while (array[i] != NULL)
582 if (strcmp (array[i], str) == 0)
591 * Generates a new UUID. If you change how this is done,
592 * there's some text about it in the spec that should also change.
594 * @param uuid the uuid to initialize
597 _dbus_generate_uuid (DBusGUID *uuid)
601 _dbus_get_current_time (&now, NULL);
603 uuid->as_uint32s[DBUS_UUID_LENGTH_WORDS - 1] = DBUS_UINT32_TO_BE (now);
605 _dbus_generate_random_bytes_buffer (uuid->as_bytes, DBUS_UUID_LENGTH_BYTES - 4);
611 * @param uuid the uuid
612 * @param encoded string to append hex uuid to
613 * @returns #FALSE if no memory
616 _dbus_uuid_encode (const DBusGUID *uuid,
620 _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
621 return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
625 _dbus_read_uuid_file_without_creating (const DBusString *filename,
633 if (!_dbus_string_init (&contents))
635 _DBUS_SET_OOM (error);
639 if (!_dbus_string_init (&decoded))
641 _dbus_string_free (&contents);
642 _DBUS_SET_OOM (error);
646 if (!_dbus_file_get_contents (&contents, filename, error))
649 _dbus_string_chop_white (&contents);
651 if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
653 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
654 "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
655 _dbus_string_get_const_data (filename),
656 DBUS_UUID_LENGTH_HEX,
657 _dbus_string_get_length (&contents));
661 if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
663 _DBUS_SET_OOM (error);
669 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
670 "UUID file '%s' contains invalid hex data",
671 _dbus_string_get_const_data (filename));
675 if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
677 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
678 "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
679 _dbus_string_get_const_data (filename),
680 _dbus_string_get_length (&decoded),
681 DBUS_UUID_LENGTH_BYTES);
685 _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
687 _dbus_string_free (&decoded);
688 _dbus_string_free (&contents);
690 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
695 _DBUS_ASSERT_ERROR_IS_SET (error);
696 _dbus_string_free (&contents);
697 _dbus_string_free (&decoded);
702 _dbus_create_uuid_file_exclusively (const DBusString *filename,
708 if (!_dbus_string_init (&encoded))
710 _DBUS_SET_OOM (error);
714 _dbus_generate_uuid (uuid);
716 if (!_dbus_uuid_encode (uuid, &encoded))
718 _DBUS_SET_OOM (error);
722 /* FIXME this is racy; we need a save_file_exclusively
723 * function. But in practice this should be fine for now.
725 * - first be sure we can create the file and it
726 * doesn't exist by creating it empty with O_EXCL
727 * - then create it by creating a temporary file and
728 * overwriting atomically with rename()
730 if (!_dbus_create_file_exclusively (filename, error))
733 if (!_dbus_string_append_byte (&encoded, '\n'))
735 _DBUS_SET_OOM (error);
739 if (!_dbus_string_save_to_file (&encoded, filename, error))
742 if (!_dbus_make_file_world_readable (filename, error))
745 _dbus_string_free (&encoded);
747 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
751 _DBUS_ASSERT_ERROR_IS_SET (error);
752 _dbus_string_free (&encoded);
757 * Reads (and optionally writes) a uuid to a file. Initializes the uuid
758 * unless an error is returned.
760 * @param filename the name of the file
761 * @param uuid uuid to be initialized with the loaded uuid
762 * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
763 * @param error the error return
764 * @returns #FALSE if the error is set
767 _dbus_read_uuid_file (const DBusString *filename,
769 dbus_bool_t create_if_not_found,
772 DBusError read_error = DBUS_ERROR_INIT;
774 if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
777 if (!create_if_not_found)
779 dbus_move_error (&read_error, error);
783 /* If the file exists and contains junk, we want to keep that error
784 * message instead of overwriting it with a "file exists" error
785 * message when we try to write
787 if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
789 dbus_move_error (&read_error, error);
794 dbus_error_free (&read_error);
795 return _dbus_create_uuid_file_exclusively (filename, uuid, error);
799 _DBUS_DEFINE_GLOBAL_LOCK (machine_uuid);
800 static int machine_uuid_initialized_generation = 0;
801 static DBusGUID machine_uuid;
804 * Gets the hex-encoded UUID of the machine this function is
805 * executed on. This UUID is guaranteed to be the same for a given
806 * machine at least until it next reboots, though it also
807 * makes some effort to be the same forever, it may change if the
808 * machine is reconfigured or its hardware is modified.
810 * @param uuid_str string to append hex-encoded machine uuid to
811 * @returns #FALSE if no memory
814 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str)
818 _DBUS_LOCK (machine_uuid);
819 if (machine_uuid_initialized_generation != _dbus_current_generation)
821 DBusError error = DBUS_ERROR_INIT;
823 if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE,
826 #ifndef DBUS_BUILD_TESTS
827 /* For the test suite, we may not be installed so just continue silently
828 * here. But in a production build, we want to be nice and loud about
831 _dbus_warn_check_failed ("D-Bus library appears to be incorrectly set up; failed to read machine uuid: %s\n"
832 "See the manual page for dbus-uuidgen to correct this issue.\n",
836 dbus_error_free (&error);
838 _dbus_generate_uuid (&machine_uuid);
842 ok = _dbus_uuid_encode (&machine_uuid, uuid_str);
844 _DBUS_UNLOCK (machine_uuid);
849 #ifdef DBUS_BUILD_TESTS
851 * Returns a string describing the given name.
853 * @param header_field the field to describe
854 * @returns a constant string describing the field
857 _dbus_header_field_to_string (int header_field)
859 switch (header_field)
861 case DBUS_HEADER_FIELD_INVALID:
863 case DBUS_HEADER_FIELD_PATH:
865 case DBUS_HEADER_FIELD_INTERFACE:
867 case DBUS_HEADER_FIELD_MEMBER:
869 case DBUS_HEADER_FIELD_ERROR_NAME:
871 case DBUS_HEADER_FIELD_REPLY_SERIAL:
872 return "reply-serial";
873 case DBUS_HEADER_FIELD_DESTINATION:
874 return "destination";
875 case DBUS_HEADER_FIELD_SENDER:
877 case DBUS_HEADER_FIELD_SIGNATURE:
883 #endif /* DBUS_BUILD_TESTS */
885 #ifndef DBUS_DISABLE_CHECKS
886 /** String used in _dbus_return_if_fail macro */
887 const char *_dbus_return_if_fail_warning_format =
888 "arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
889 "This is normally a bug in some application using the D-Bus library.\n";
892 #ifndef DBUS_DISABLE_ASSERT
894 * Internals of _dbus_assert(); it's a function
895 * rather than a macro with the inline code so
896 * that the assertion failure blocks don't show up
897 * in test suite coverage, and to shrink code size.
899 * @param condition TRUE if assertion succeeded
900 * @param condition_text condition as a string
901 * @param file file the assertion is in
902 * @param line line the assertion is in
903 * @param func function the assertion is in
906 _dbus_real_assert (dbus_bool_t condition,
907 const char *condition_text,
912 if (_DBUS_UNLIKELY (!condition))
914 _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
915 _dbus_pid_for_log (), condition_text, file, line, func);
921 * Internals of _dbus_assert_not_reached(); it's a function
922 * rather than a macro with the inline code so
923 * that the assertion failure blocks don't show up
924 * in test suite coverage, and to shrink code size.
926 * @param explanation what was reached that shouldn't have been
927 * @param file file the assertion is in
928 * @param line line the assertion is in
931 _dbus_real_assert_not_reached (const char *explanation,
935 _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
936 file, line, _dbus_pid_for_log (), explanation);
939 #endif /* DBUS_DISABLE_ASSERT */
941 #ifdef DBUS_BUILD_TESTS
943 run_failing_each_malloc (int n_mallocs,
944 const char *description,
945 DBusTestMemoryFunction func,
948 n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
950 while (n_mallocs >= 0)
952 _dbus_set_fail_alloc_counter (n_mallocs);
954 _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
955 description, n_mallocs,
956 _dbus_get_fail_alloc_failures ());
958 if (!(* func) (data))
964 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
970 * Tests how well the given function responds to out-of-memory
971 * situations. Calls the function repeatedly, failing a different
972 * call to malloc() each time. If the function ever returns #FALSE,
973 * the test fails. The function should return #TRUE whenever something
974 * valid (such as returning an error, or succeeding) occurs, and #FALSE
975 * if it gets confused in some way.
977 * @param description description of the test used in verbose output
978 * @param func function to call
979 * @param data data to pass to function
980 * @returns #TRUE if the function never returns FALSE
983 _dbus_test_oom_handling (const char *description,
984 DBusTestMemoryFunction func,
989 int max_failures_to_try;
992 /* Run once to see about how many mallocs are involved */
994 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
996 _dbus_verbose ("Running once to count mallocs\n");
998 if (!(* func) (data))
1001 approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
1003 _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
1004 description, approx_mallocs);
1006 setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
1007 if (setting != NULL)
1011 _dbus_string_init_const (&str, setting);
1013 if (!_dbus_string_parse_int (&str, 0, &v, NULL))
1014 _dbus_warn ("couldn't parse '%s' as integer\n", setting);
1015 max_failures_to_try = v;
1019 max_failures_to_try = 4;
1022 i = setting ? max_failures_to_try - 1 : 1;
1023 while (i < max_failures_to_try)
1025 _dbus_set_fail_alloc_failures (i);
1026 if (!run_failing_each_malloc (approx_mallocs, description, func, data))
1031 _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
1036 #endif /* DBUS_BUILD_TESTS */