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.
168 * Locks a global lock, initializing it first if necessary.
170 * @returns #FALSE if not enough memory
176 * Unlocks a global lock
180 * Fixed "out of memory" error message, just to avoid
181 * making up a different string every time and wasting
184 const char *_dbus_no_memory_message = "Not enough memory";
186 static dbus_bool_t warn_initted = FALSE;
187 static dbus_bool_t fatal_warnings = FALSE;
188 static dbus_bool_t fatal_warnings_on_check_failed = TRUE;
196 s = _dbus_getenv ("DBUS_FATAL_WARNINGS");
201 fatal_warnings = FALSE;
202 fatal_warnings_on_check_failed = FALSE;
206 fatal_warnings = TRUE;
207 fatal_warnings_on_check_failed = TRUE;
211 fprintf(stderr, "DBUS_FATAL_WARNINGS should be set to 0 or 1 if set, not '%s'",
221 * Prints a warning message to stderr. Can optionally be made to exit
222 * fatally by setting DBUS_FATAL_WARNINGS, but this is rarely
223 * used. This function should be considered pretty much equivalent to
224 * fprintf(stderr). _dbus_warn_check_failed() on the other hand is
225 * suitable for use when a programming mistake has been made.
227 * @param format printf-style format string.
230 _dbus_warn (const char *format,
233 DBusSystemLogSeverity severity = DBUS_SYSTEM_LOG_WARNING;
240 severity = DBUS_SYSTEM_LOG_ERROR;
242 va_start (args, format);
243 _dbus_logv (severity, format, args);
254 * Prints a "critical" warning to stderr when an assertion fails;
255 * differs from _dbus_warn primarily in that it
256 * defaults to fatal. This should be used only when a programming
257 * error has been detected. (NOT for unavoidable errors that an app
258 * might handle - those should be returned as DBusError.) Calling this
259 * means "there is a bug"
262 _dbus_warn_check_failed(const char *format,
265 DBusSystemLogSeverity severity = DBUS_SYSTEM_LOG_WARNING;
271 if (fatal_warnings_on_check_failed)
272 severity = DBUS_SYSTEM_LOG_ERROR;
274 va_start (args, format);
275 _dbus_logv (severity, format, args);
278 if (fatal_warnings_on_check_failed)
285 #ifdef DBUS_ENABLE_VERBOSE_MODE
287 static dbus_bool_t verbose_initted = FALSE;
288 static dbus_bool_t verbose = TRUE;
290 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
291 static char module_name[1024];
295 _dbus_verbose_init (void)
297 if (!verbose_initted)
299 const char *p = _dbus_getenv ("DBUS_VERBOSE");
300 verbose = p != NULL && *p == '1';
301 verbose_initted = TRUE;
302 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
304 char *last_period, *last_slash;
305 GetModuleFileName(0,module_name,sizeof(module_name)-1);
306 last_period = _mbsrchr(module_name,'.');
309 last_slash = _mbsrchr(module_name,'\\');
311 strcpy(module_name,last_slash+1);
312 strcat(module_name,": ");
318 /** @def DBUS_IS_DIR_SEPARATOR(c)
319 * macro for checking if character c is a patch separator
321 * @todo move to a header file so that others can use this too
324 #define DBUS_IS_DIR_SEPARATOR(c) (c == '\\' || c == '/')
326 #define DBUS_IS_DIR_SEPARATOR(c) (c == '/')
330 remove source root from file path
331 the source root is determined by
333 static char *_dbus_file_path_extract_elements_from_tail(const char *file,int level)
336 char *p = (char *)file + strlen(file);
341 if (DBUS_IS_DIR_SEPARATOR(*p))
351 return (char *)file+prefix;
355 * Implementation of dbus_is_verbose() macro if built with verbose logging
357 * @returns whether verbose logging is active.
360 _dbus_is_verbose_real (void)
362 _dbus_verbose_init ();
366 void _dbus_set_verbose (dbus_bool_t state)
371 dbus_bool_t _dbus_get_verbose (void)
377 * Prints a warning message to stderr
378 * if the user has enabled verbose mode.
379 * This is the real function implementation,
380 * use _dbus_verbose() macro in code.
382 * @param format printf-style format string.
386 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
389 const char *function,
395 static dbus_bool_t need_pid = TRUE;
399 /* things are written a bit oddly here so that
400 * in the non-verbose case we just have the one
401 * conditional and return immediately.
403 if (!_dbus_is_verbose_real())
406 #ifndef DBUS_USE_OUTPUT_DEBUG_STRING
407 /* Print out pid before the line */
410 _dbus_print_thread ();
412 _dbus_get_real_time (&sec, &usec);
413 fprintf (stderr, "%ld.%06ld ", sec, usec);
416 /* Only print pid again if the next line is a new line */
417 len = strlen (format);
418 if (format[len-1] == '\n')
423 va_start (args, format);
424 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
427 strcpy(buf,module_name);
428 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
429 sprintf (buf+strlen(buf), "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
431 vsprintf (buf+strlen(buf),format, args);
433 OutputDebugStringA(buf);
436 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
437 fprintf (stderr, "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
440 vfprintf (stderr, format, args);
448 * Reinitializes the verbose logging code, used
449 * as a hack in dbus-spawn.c so that a child
450 * process re-reads its pid
454 _dbus_verbose_reset_real (void)
456 verbose_initted = FALSE;
460 _dbus_trace_ref (const char *obj_name,
468 _dbus_assert (obj_name != NULL);
469 _dbus_assert (obj != NULL);
470 _dbus_assert (old_refcount >= -1);
471 _dbus_assert (new_refcount >= -1);
473 if (old_refcount == -1)
475 _dbus_assert (new_refcount == -1);
479 _dbus_assert (new_refcount >= 0);
480 _dbus_assert (old_refcount >= 0);
481 _dbus_assert (old_refcount > 0 || new_refcount > 0);
484 _dbus_assert (why != NULL);
485 _dbus_assert (env_var != NULL);
486 _dbus_assert (enabled != NULL);
490 const char *s = _dbus_getenv (env_var);
501 _dbus_warn ("%s should be 0 or 1 if set, not '%s'", env_var, s);
507 if (old_refcount == -1)
509 VALGRIND_PRINTF_BACKTRACE ("%s %p ref stolen (%s)",
511 _dbus_verbose ("%s %p ref stolen (%s)\n",
516 VALGRIND_PRINTF_BACKTRACE ("%s %p %d -> %d refs (%s)",
518 old_refcount, new_refcount, why);
519 _dbus_verbose ("%s %p %d -> %d refs (%s)\n",
520 obj_name, obj, old_refcount, new_refcount, why);
525 #endif /* DBUS_ENABLE_VERBOSE_MODE */
528 * Duplicates a string. Result must be freed with
529 * dbus_free(). Returns #NULL if memory allocation fails.
530 * If the string to be duplicated is #NULL, returns #NULL.
532 * @param str string to duplicate.
533 * @returns newly-allocated copy.
536 _dbus_strdup (const char *str)
546 copy = dbus_malloc (len + 1);
550 memcpy (copy, str, len + 1);
556 * Duplicates a block of memory. Returns
559 * @param mem memory to copy
560 * @param n_bytes number of bytes to copy
564 _dbus_memdup (const void *mem,
569 copy = dbus_malloc (n_bytes);
573 memcpy (copy, mem, n_bytes);
579 * Duplicates a string array. Result may be freed with
580 * dbus_free_string_array(). Returns #NULL if memory allocation fails.
581 * If the array to be duplicated is #NULL, returns #NULL.
583 * @param array array to duplicate.
584 * @returns newly-allocated copy.
587 _dbus_dup_string_array (const char **array)
596 for (len = 0; array[len] != NULL; ++len)
599 copy = dbus_new0 (char*, len + 1);
606 copy[i] = _dbus_strdup (array[i]);
609 dbus_free_string_array (copy);
620 * Checks whether a string array contains the given string.
622 * @param array array to search.
623 * @param str string to look for
624 * @returns #TRUE if array contains string
627 _dbus_string_array_contains (const char **array,
633 while (array[i] != NULL)
635 if (strcmp (array[i], str) == 0)
644 * Returns the size of a string array
646 * @param array array to search.
647 * @returns size of array
650 _dbus_string_array_length (const char **array)
653 for (i = 0; array[i]; i++) {}
659 * Generates a new UUID. If you change how this is done,
660 * there's some text about it in the spec that should also change.
662 * @param uuid the uuid to initialize
663 * @param error location to store reason for failure
664 * @returns #TRUE on success
667 _dbus_generate_uuid (DBusGUID *uuid,
670 DBusError rand_error;
673 dbus_error_init (&rand_error);
675 /* don't use monotonic time because the UUID may be saved to disk, e.g.
676 * it may persist across reboots
678 _dbus_get_real_time (&now, NULL);
680 uuid->as_uint32s[DBUS_UUID_LENGTH_WORDS - 1] = DBUS_UINT32_TO_BE (now);
682 if (!_dbus_generate_random_bytes_buffer (uuid->as_bytes,
683 DBUS_UUID_LENGTH_BYTES - 4,
686 dbus_set_error (error, rand_error.name,
687 "Failed to generate UUID: %s", rand_error.message);
688 dbus_error_free (&rand_error);
698 * @param uuid the uuid
699 * @param encoded string to append hex uuid to
700 * @returns #FALSE if no memory
703 _dbus_uuid_encode (const DBusGUID *uuid,
707 _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
708 return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
712 _dbus_read_uuid_file_without_creating (const DBusString *filename,
720 if (!_dbus_string_init (&contents))
722 _DBUS_SET_OOM (error);
726 if (!_dbus_string_init (&decoded))
728 _dbus_string_free (&contents);
729 _DBUS_SET_OOM (error);
733 if (!_dbus_file_get_contents (&contents, filename, error))
736 _dbus_string_chop_white (&contents);
738 if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
740 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
741 "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
742 _dbus_string_get_const_data (filename),
743 DBUS_UUID_LENGTH_HEX,
744 _dbus_string_get_length (&contents));
748 if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
750 _DBUS_SET_OOM (error);
756 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
757 "UUID file '%s' contains invalid hex data",
758 _dbus_string_get_const_data (filename));
762 if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
764 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
765 "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
766 _dbus_string_get_const_data (filename),
767 _dbus_string_get_length (&decoded),
768 DBUS_UUID_LENGTH_BYTES);
772 _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
774 _dbus_string_free (&decoded);
775 _dbus_string_free (&contents);
777 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
782 _DBUS_ASSERT_ERROR_IS_SET (error);
783 _dbus_string_free (&contents);
784 _dbus_string_free (&decoded);
789 * Write the give UUID to a file.
791 * @param filename the file to write
792 * @param uuid the UUID to save
793 * @param error used to raise an error
794 * @returns #FALSE on error
797 _dbus_write_uuid_file (const DBusString *filename,
798 const DBusGUID *uuid,
803 if (!_dbus_string_init (&encoded))
805 _DBUS_SET_OOM (error);
809 if (!_dbus_uuid_encode (uuid, &encoded))
811 _DBUS_SET_OOM (error);
815 if (!_dbus_string_append_byte (&encoded, '\n'))
817 _DBUS_SET_OOM (error);
821 if (!_dbus_string_save_to_file (&encoded, filename, TRUE, error))
824 _dbus_string_free (&encoded);
826 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
830 _DBUS_ASSERT_ERROR_IS_SET (error);
831 _dbus_string_free (&encoded);
836 * Reads (and optionally writes) a uuid to a file. Initializes the uuid
837 * unless an error is returned.
839 * @param filename the name of the file
840 * @param uuid uuid to be initialized with the loaded uuid
841 * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
842 * @param error the error return
843 * @returns #FALSE if the error is set
846 _dbus_read_uuid_file (const DBusString *filename,
848 dbus_bool_t create_if_not_found,
851 DBusError read_error = DBUS_ERROR_INIT;
853 if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
856 if (!create_if_not_found)
858 dbus_move_error (&read_error, error);
862 /* If the file exists and contains junk, we want to keep that error
863 * message instead of overwriting it with a "file exists" error
864 * message when we try to write
866 if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
868 dbus_move_error (&read_error, error);
873 dbus_error_free (&read_error);
875 if (!_dbus_generate_uuid (uuid, error))
878 return _dbus_write_uuid_file (filename, uuid, error);
882 /* Protected by _DBUS_LOCK (machine_uuid) */
883 static int machine_uuid_initialized_generation = 0;
884 static DBusGUID machine_uuid;
887 * Gets the hex-encoded UUID of the machine this function is
888 * executed on. This UUID is guaranteed to be the same for a given
889 * machine at least until it next reboots, though it also
890 * makes some effort to be the same forever, it may change if the
891 * machine is reconfigured or its hardware is modified.
893 * @param uuid_str string to append hex-encoded machine uuid to
894 * @param error location to store reason for failure
895 * @returns #TRUE if successful
898 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str,
901 dbus_bool_t ok = TRUE;
903 if (!_DBUS_LOCK (machine_uuid))
905 _DBUS_SET_OOM (error);
909 if (machine_uuid_initialized_generation != _dbus_current_generation)
911 if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE, error))
917 if (!_dbus_uuid_encode (&machine_uuid, uuid_str))
920 _DBUS_SET_OOM (error);
924 _DBUS_UNLOCK (machine_uuid);
929 #ifndef DBUS_DISABLE_CHECKS
931 _dbus_warn_return_if_fail (const char *function,
932 const char *assertion,
936 _dbus_warn_check_failed (
937 "arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
938 "This is normally a bug in some application using the D-Bus library.\n",
939 function, assertion, file, line);
943 #ifndef DBUS_DISABLE_ASSERT
945 * Internals of _dbus_assert(); it's a function
946 * rather than a macro with the inline code so
947 * that the assertion failure blocks don't show up
948 * in test suite coverage, and to shrink code size.
950 * @param condition TRUE if assertion succeeded
951 * @param condition_text condition as a string
952 * @param file file the assertion is in
953 * @param line line the assertion is in
954 * @param func function the assertion is in
957 _dbus_real_assert (dbus_bool_t condition,
958 const char *condition_text,
963 if (_DBUS_UNLIKELY (!condition))
965 _dbus_warn ("assertion failed \"%s\" file \"%s\" line %d function %s",
966 condition_text, file, line, func);
972 * Internals of _dbus_assert_not_reached(); it's a function
973 * rather than a macro with the inline code so
974 * that the assertion failure blocks don't show up
975 * in test suite coverage, and to shrink code size.
977 * @param explanation what was reached that shouldn't have been
978 * @param file file the assertion is in
979 * @param line line the assertion is in
982 _dbus_real_assert_not_reached (const char *explanation,
986 _dbus_warn ("File \"%s\" line %d should not have been reached: %s",
987 file, line, explanation);
990 #endif /* DBUS_DISABLE_ASSERT */
992 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
994 run_failing_each_malloc (int n_mallocs,
995 const char *description,
996 DBusTestMemoryFunction func,
999 n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
1001 while (n_mallocs >= 0)
1003 _dbus_set_fail_alloc_counter (n_mallocs);
1005 _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
1006 description, n_mallocs,
1007 _dbus_get_fail_alloc_failures ());
1009 if (!(* func) (data))
1015 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
1021 * Tests how well the given function responds to out-of-memory
1022 * situations. Calls the function repeatedly, failing a different
1023 * call to malloc() each time. If the function ever returns #FALSE,
1024 * the test fails. The function should return #TRUE whenever something
1025 * valid (such as returning an error, or succeeding) occurs, and #FALSE
1026 * if it gets confused in some way.
1028 * @param description description of the test used in verbose output
1029 * @param func function to call
1030 * @param data data to pass to function
1031 * @returns #TRUE if the function never returns FALSE
1034 _dbus_test_oom_handling (const char *description,
1035 DBusTestMemoryFunction func,
1039 const char *setting;
1040 int max_failures_to_try;
1043 /* Run once to see about how many mallocs are involved */
1045 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
1047 _dbus_verbose ("Running once to count mallocs\n");
1049 if (!(* func) (data))
1052 approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
1054 _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
1055 description, approx_mallocs);
1057 setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
1058 if (setting != NULL)
1062 _dbus_string_init_const (&str, setting);
1064 if (!_dbus_string_parse_int (&str, 0, &v, NULL))
1065 _dbus_warn ("couldn't parse '%s' as integer\n", setting);
1066 max_failures_to_try = v;
1070 max_failures_to_try = 4;
1073 if (max_failures_to_try < 1)
1075 _dbus_verbose ("not testing OOM handling\n");
1079 i = setting ? max_failures_to_try - 1 : 1;
1080 while (i < max_failures_to_try)
1082 _dbus_set_fail_alloc_failures (i);
1083 if (!run_failing_each_malloc (approx_mallocs, description, func, data))
1088 _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
1093 #endif /* DBUS_ENABLE_EMBEDDED_TESTS */