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"
29 #include "dbus-valgrind-internal.h"
34 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
40 * @defgroup DBusInternals D-Bus secret internal implementation details
41 * @brief Documentation useful when developing or debugging D-Bus itself.
46 * @defgroup DBusInternalsUtils Utilities and portability
47 * @ingroup DBusInternals
48 * @brief Utility functions (_dbus_assert(), _dbus_warn(), etc.)
55 * Aborts with an error message if the condition is false.
57 * @param condition condition which must be true.
61 * @def _dbus_assert_not_reached
63 * Aborts with an error message if called.
64 * The given explanation will be printed.
66 * @param explanation explanation of what happened if the code was reached.
70 * @def _DBUS_N_ELEMENTS
72 * Computes the number of elements in a fixed-size array using
75 * @param array the array to count elements in.
79 * @def _DBUS_POINTER_TO_INT
81 * Safely casts a void* to an integer; should only be used on void*
82 * that actually contain integers, for example one created with
83 * _DBUS_INT_TO_POINTER. Only guaranteed to preserve 32 bits.
84 * (i.e. it's used to store 32-bit ints in pointers, but
85 * can't be used to store 64-bit pointers in ints.)
87 * @param pointer pointer to extract an integer from.
90 * @def _DBUS_INT_TO_POINTER
92 * Safely stuffs an integer into a pointer, to be extracted later with
93 * _DBUS_POINTER_TO_INT. Only guaranteed to preserve 32 bits.
95 * @param integer the integer to stuff into a pointer.
100 * Sets all bits in an object to zero.
102 * @param object the object to be zeroed.
105 * @def _DBUS_INT16_MIN
107 * Minimum value of type "int16"
110 * @def _DBUS_INT16_MAX
112 * Maximum value of type "int16"
115 * @def _DBUS_UINT16_MAX
117 * Maximum value of type "uint16"
121 * @def _DBUS_INT32_MIN
123 * Minimum value of type "int32"
126 * @def _DBUS_INT32_MAX
128 * Maximum value of type "int32"
131 * @def _DBUS_UINT32_MAX
133 * Maximum value of type "uint32"
139 * Minimum value of type "int"
144 * Maximum value of type "int"
147 * @def _DBUS_UINT_MAX
149 * Maximum value of type "uint"
153 * @typedef DBusForeachFunction
155 * Used to iterate over each item in a collection, such as
160 * @def _DBUS_LOCK_NAME
162 * Expands to name of a global lock variable.
166 * @def _DBUS_DEFINE_GLOBAL_LOCK
168 * Defines a global lock variable with the given name.
169 * The lock must be added to the list to initialize
170 * in dbus_threads_init().
174 * @def _DBUS_DECLARE_GLOBAL_LOCK
176 * Expands to declaration of a global lock defined
177 * with _DBUS_DEFINE_GLOBAL_LOCK.
178 * The lock must be added to the list to initialize
179 * in dbus_threads_init().
185 * Locks a global lock
191 * Unlocks a global lock
195 * Fixed "out of memory" error message, just to avoid
196 * making up a different string every time and wasting
199 const char *_dbus_no_memory_message = "Not enough memory";
201 static dbus_bool_t warn_initted = FALSE;
202 static dbus_bool_t fatal_warnings = FALSE;
203 static dbus_bool_t fatal_warnings_on_check_failed = TRUE;
211 s = _dbus_getenv ("DBUS_FATAL_WARNINGS");
216 fatal_warnings = FALSE;
217 fatal_warnings_on_check_failed = FALSE;
221 fatal_warnings = TRUE;
222 fatal_warnings_on_check_failed = TRUE;
226 fprintf(stderr, "DBUS_FATAL_WARNINGS should be set to 0 or 1 if set, not '%s'",
236 * Prints a warning message to stderr. Can optionally be made to exit
237 * fatally by setting DBUS_FATAL_WARNINGS, but this is rarely
238 * used. This function should be considered pretty much equivalent to
239 * fprintf(stderr). _dbus_warn_check_failed() on the other hand is
240 * suitable for use when a programming mistake has been made.
242 * @param format printf-style format string.
245 _dbus_warn (const char *format,
253 va_start (args, format);
254 vfprintf (stderr, format, args);
265 * Prints a "critical" warning to stderr when an assertion fails;
266 * differs from _dbus_warn primarily in that it prefixes the pid and
267 * defaults to fatal. This should be used only when a programming
268 * error has been detected. (NOT for unavoidable errors that an app
269 * might handle - those should be returned as DBusError.) Calling this
270 * means "there is a bug"
273 _dbus_warn_check_failed(const char *format,
281 fprintf (stderr, "process %lu: ", _dbus_pid_for_log ());
283 va_start (args, format);
284 vfprintf (stderr, format, args);
287 if (fatal_warnings_on_check_failed)
294 #ifdef DBUS_ENABLE_VERBOSE_MODE
296 static dbus_bool_t verbose_initted = FALSE;
297 static dbus_bool_t verbose = TRUE;
299 /** Whether to show the current thread in verbose messages */
300 #define PTHREAD_IN_VERBOSE 0
301 #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;
354 char *p = (char *)file + strlen(file);
359 if (DBUS_IS_DIR_SEPARATOR(*p))
369 return (char *)file+prefix;
373 * Implementation of dbus_is_verbose() macro if built with verbose logging
375 * @returns whether verbose logging is active.
378 _dbus_is_verbose_real (void)
380 _dbus_verbose_init ();
385 * Prints a warning message to stderr
386 * if the user has enabled verbose mode.
387 * This is the real function implementation,
388 * use _dbus_verbose() macro in code.
390 * @param format printf-style format string.
394 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
397 const char *function,
403 static dbus_bool_t need_pid = TRUE;
406 /* things are written a bit oddly here so that
407 * in the non-verbose case we just have the one
408 * conditional and return immediately.
410 if (!_dbus_is_verbose_real())
413 #ifndef DBUS_USE_OUTPUT_DEBUG_STRING
414 /* Print out pid before the line */
417 #if PTHREAD_IN_VERBOSE
418 fprintf (stderr, "%lu: 0x%lx: ", _dbus_pid_for_log (), pthread_self ());
420 fprintf (stderr, "%lu: ", _dbus_pid_for_log ());
425 /* Only print pid again if the next line is a new line */
426 len = strlen (format);
427 if (format[len-1] == '\n')
432 va_start (args, format);
433 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
436 strcpy(buf,module_name);
437 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
438 sprintf (buf+strlen(buf), "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
440 vsprintf (buf+strlen(buf),format, args);
442 OutputDebugStringA(buf);
445 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
446 fprintf (stderr, "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
449 vfprintf (stderr, format, args);
457 * Reinitializes the verbose logging code, used
458 * as a hack in dbus-spawn.c so that a child
459 * process re-reads its pid
463 _dbus_verbose_reset_real (void)
465 verbose_initted = FALSE;
469 _dbus_trace_ref (const char *obj_name,
477 _dbus_assert (obj_name != NULL);
478 _dbus_assert (obj != NULL);
479 _dbus_assert (old_refcount >= -1);
480 _dbus_assert (new_refcount >= -1);
482 if (old_refcount == -1)
484 _dbus_assert (new_refcount == -1);
488 _dbus_assert (new_refcount >= 0);
489 _dbus_assert (old_refcount >= 0);
490 _dbus_assert (old_refcount > 0 || new_refcount > 0);
493 _dbus_assert (why != NULL);
494 _dbus_assert (env_var != NULL);
495 _dbus_assert (enabled != NULL);
499 const char *s = _dbus_getenv (env_var);
510 _dbus_warn ("%s should be 0 or 1 if set, not '%s'", env_var, s);
516 if (old_refcount == -1)
518 VALGRIND_PRINTF_BACKTRACE ("%s %p ref stolen (%s)",
520 _dbus_verbose ("%s %p ref stolen (%s)",
525 VALGRIND_PRINTF_BACKTRACE ("%s %p %d -> %d refs (%s)",
527 old_refcount, new_refcount, why);
528 _dbus_verbose ("%s %p %d -> %d refs (%s)",
529 obj_name, obj, old_refcount, new_refcount, why);
534 #endif /* DBUS_ENABLE_VERBOSE_MODE */
537 * Duplicates a string. Result must be freed with
538 * dbus_free(). Returns #NULL if memory allocation fails.
539 * If the string to be duplicated is #NULL, returns #NULL.
541 * @param str string to duplicate.
542 * @returns newly-allocated copy.
545 _dbus_strdup (const char *str)
555 copy = dbus_malloc (len + 1);
559 memcpy (copy, str, len + 1);
565 * Duplicates a block of memory. Returns
568 * @param mem memory to copy
569 * @param n_bytes number of bytes to copy
573 _dbus_memdup (const void *mem,
578 copy = dbus_malloc (n_bytes);
582 memcpy (copy, mem, n_bytes);
588 * Duplicates a string array. Result may be freed with
589 * dbus_free_string_array(). Returns #NULL if memory allocation fails.
590 * If the array to be duplicated is #NULL, returns #NULL.
592 * @param array array to duplicate.
593 * @returns newly-allocated copy.
596 _dbus_dup_string_array (const char **array)
605 for (len = 0; array[len] != NULL; ++len)
608 copy = dbus_new0 (char*, len + 1);
615 copy[i] = _dbus_strdup (array[i]);
618 dbus_free_string_array (copy);
629 * Checks whether a string array contains the given string.
631 * @param array array to search.
632 * @param str string to look for
633 * @returns #TRUE if array contains string
636 _dbus_string_array_contains (const char **array,
642 while (array[i] != NULL)
644 if (strcmp (array[i], str) == 0)
653 * Generates a new UUID. If you change how this is done,
654 * there's some text about it in the spec that should also change.
656 * @param uuid the uuid to initialize
659 _dbus_generate_uuid (DBusGUID *uuid)
663 /* don't use monotonic time because the UUID may be saved to disk, e.g.
664 * it may persist across reboots
666 _dbus_get_real_time (&now, NULL);
668 uuid->as_uint32s[DBUS_UUID_LENGTH_WORDS - 1] = DBUS_UINT32_TO_BE (now);
670 _dbus_generate_random_bytes_buffer (uuid->as_bytes, DBUS_UUID_LENGTH_BYTES - 4);
676 * @param uuid the uuid
677 * @param encoded string to append hex uuid to
678 * @returns #FALSE if no memory
681 _dbus_uuid_encode (const DBusGUID *uuid,
685 _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
686 return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
690 _dbus_read_uuid_file_without_creating (const DBusString *filename,
698 if (!_dbus_string_init (&contents))
700 _DBUS_SET_OOM (error);
704 if (!_dbus_string_init (&decoded))
706 _dbus_string_free (&contents);
707 _DBUS_SET_OOM (error);
711 if (!_dbus_file_get_contents (&contents, filename, error))
714 _dbus_string_chop_white (&contents);
716 if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
718 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
719 "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
720 _dbus_string_get_const_data (filename),
721 DBUS_UUID_LENGTH_HEX,
722 _dbus_string_get_length (&contents));
726 if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
728 _DBUS_SET_OOM (error);
734 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
735 "UUID file '%s' contains invalid hex data",
736 _dbus_string_get_const_data (filename));
740 if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
742 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
743 "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
744 _dbus_string_get_const_data (filename),
745 _dbus_string_get_length (&decoded),
746 DBUS_UUID_LENGTH_BYTES);
750 _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
752 _dbus_string_free (&decoded);
753 _dbus_string_free (&contents);
755 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
760 _DBUS_ASSERT_ERROR_IS_SET (error);
761 _dbus_string_free (&contents);
762 _dbus_string_free (&decoded);
767 _dbus_create_uuid_file_exclusively (const DBusString *filename,
773 if (!_dbus_string_init (&encoded))
775 _DBUS_SET_OOM (error);
779 _dbus_generate_uuid (uuid);
781 if (!_dbus_uuid_encode (uuid, &encoded))
783 _DBUS_SET_OOM (error);
787 if (!_dbus_string_append_byte (&encoded, '\n'))
789 _DBUS_SET_OOM (error);
793 if (!_dbus_string_save_to_file (&encoded, filename, TRUE, error))
796 _dbus_string_free (&encoded);
798 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
802 _DBUS_ASSERT_ERROR_IS_SET (error);
803 _dbus_string_free (&encoded);
808 * Reads (and optionally writes) a uuid to a file. Initializes the uuid
809 * unless an error is returned.
811 * @param filename the name of the file
812 * @param uuid uuid to be initialized with the loaded uuid
813 * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
814 * @param error the error return
815 * @returns #FALSE if the error is set
818 _dbus_read_uuid_file (const DBusString *filename,
820 dbus_bool_t create_if_not_found,
823 DBusError read_error = DBUS_ERROR_INIT;
825 if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
828 if (!create_if_not_found)
830 dbus_move_error (&read_error, error);
834 /* If the file exists and contains junk, we want to keep that error
835 * message instead of overwriting it with a "file exists" error
836 * message when we try to write
838 if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
840 dbus_move_error (&read_error, error);
845 dbus_error_free (&read_error);
846 return _dbus_create_uuid_file_exclusively (filename, uuid, error);
850 _DBUS_DEFINE_GLOBAL_LOCK (machine_uuid);
851 static int machine_uuid_initialized_generation = 0;
852 static DBusGUID machine_uuid;
855 * Gets the hex-encoded UUID of the machine this function is
856 * executed on. This UUID is guaranteed to be the same for a given
857 * machine at least until it next reboots, though it also
858 * makes some effort to be the same forever, it may change if the
859 * machine is reconfigured or its hardware is modified.
861 * @param uuid_str string to append hex-encoded machine uuid to
862 * @returns #FALSE if no memory
865 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str)
869 _DBUS_LOCK (machine_uuid);
870 if (machine_uuid_initialized_generation != _dbus_current_generation)
872 DBusError error = DBUS_ERROR_INIT;
874 if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE,
877 #ifndef DBUS_BUILD_TESTS
878 /* For the test suite, we may not be installed so just continue silently
879 * here. But in a production build, we want to be nice and loud about
882 _dbus_warn_check_failed ("D-Bus library appears to be incorrectly set up; failed to read machine uuid: %s\n"
883 "See the manual page for dbus-uuidgen to correct this issue.\n",
887 dbus_error_free (&error);
889 _dbus_generate_uuid (&machine_uuid);
893 ok = _dbus_uuid_encode (&machine_uuid, uuid_str);
895 _DBUS_UNLOCK (machine_uuid);
900 #ifndef DBUS_DISABLE_CHECKS
901 /** String used in _dbus_return_if_fail macro */
902 const char *_dbus_return_if_fail_warning_format =
903 "arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
904 "This is normally a bug in some application using the D-Bus library.\n";
907 #ifndef DBUS_DISABLE_ASSERT
909 * Internals of _dbus_assert(); it's a function
910 * rather than a macro with the inline code so
911 * that the assertion failure blocks don't show up
912 * in test suite coverage, and to shrink code size.
914 * @param condition TRUE if assertion succeeded
915 * @param condition_text condition as a string
916 * @param file file the assertion is in
917 * @param line line the assertion is in
918 * @param func function the assertion is in
921 _dbus_real_assert (dbus_bool_t condition,
922 const char *condition_text,
927 if (_DBUS_UNLIKELY (!condition))
929 _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
930 _dbus_pid_for_log (), condition_text, file, line, func);
936 * Internals of _dbus_assert_not_reached(); it's a function
937 * rather than a macro with the inline code so
938 * that the assertion failure blocks don't show up
939 * in test suite coverage, and to shrink code size.
941 * @param explanation what was reached that shouldn't have been
942 * @param file file the assertion is in
943 * @param line line the assertion is in
946 _dbus_real_assert_not_reached (const char *explanation,
950 _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
951 file, line, _dbus_pid_for_log (), explanation);
954 #endif /* DBUS_DISABLE_ASSERT */
956 #ifdef DBUS_BUILD_TESTS
958 run_failing_each_malloc (int n_mallocs,
959 const char *description,
960 DBusTestMemoryFunction func,
963 n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
965 while (n_mallocs >= 0)
967 _dbus_set_fail_alloc_counter (n_mallocs);
969 _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
970 description, n_mallocs,
971 _dbus_get_fail_alloc_failures ());
973 if (!(* func) (data))
979 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
985 * Tests how well the given function responds to out-of-memory
986 * situations. Calls the function repeatedly, failing a different
987 * call to malloc() each time. If the function ever returns #FALSE,
988 * the test fails. The function should return #TRUE whenever something
989 * valid (such as returning an error, or succeeding) occurs, and #FALSE
990 * if it gets confused in some way.
992 * @param description description of the test used in verbose output
993 * @param func function to call
994 * @param data data to pass to function
995 * @returns #TRUE if the function never returns FALSE
998 _dbus_test_oom_handling (const char *description,
999 DBusTestMemoryFunction func,
1003 const char *setting;
1004 int max_failures_to_try;
1007 /* Run once to see about how many mallocs are involved */
1009 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
1011 _dbus_verbose ("Running once to count mallocs\n");
1013 if (!(* func) (data))
1016 approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
1018 _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
1019 description, approx_mallocs);
1021 setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
1022 if (setting != NULL)
1026 _dbus_string_init_const (&str, setting);
1028 if (!_dbus_string_parse_int (&str, 0, &v, NULL))
1029 _dbus_warn ("couldn't parse '%s' as integer\n", setting);
1030 max_failures_to_try = v;
1034 max_failures_to_try = 4;
1037 i = setting ? max_failures_to_try - 1 : 1;
1038 while (i < max_failures_to_try)
1040 _dbus_set_fail_alloc_failures (i);
1041 if (!run_failing_each_malloc (approx_mallocs, description, func, data))
1046 _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
1051 #endif /* DBUS_BUILD_TESTS */