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-marshal-basic.h"
26 #include "dbus-test.h"
33 * @defgroup DBusInternals D-Bus secret internal implementation details
34 * @brief Documentation useful when developing or debugging D-Bus itself.
39 * @defgroup DBusInternalsUtils Utilities and portability
40 * @ingroup DBusInternals
41 * @brief Utility functions (_dbus_assert(), _dbus_warn(), etc.)
48 * Aborts with an error message if the condition is false.
50 * @param condition condition which must be true.
54 * @def _dbus_assert_not_reached
56 * Aborts with an error message if called.
57 * The given explanation will be printed.
59 * @param explanation explanation of what happened if the code was reached.
63 * @def _DBUS_N_ELEMENTS
65 * Computes the number of elements in a fixed-size array using
68 * @param array the array to count elements in.
72 * @def _DBUS_POINTER_TO_INT
74 * Safely casts a void* to an integer; should only be used on void*
75 * that actually contain integers, for example one created with
76 * _DBUS_INT_TO_POINTER. Only guaranteed to preserve 32 bits.
77 * (i.e. it's used to store 32-bit ints in pointers, but
78 * can't be used to store 64-bit pointers in ints.)
80 * @param pointer pointer to extract an integer from.
83 * @def _DBUS_INT_TO_POINTER
85 * Safely stuffs an integer into a pointer, to be extracted later with
86 * _DBUS_POINTER_TO_INT. Only guaranteed to preserve 32 bits.
88 * @param integer the integer to stuff into a pointer.
93 * Sets all bits in an object to zero.
95 * @param object the object to be zeroed.
98 * @def _DBUS_INT16_MIN
100 * Minimum value of type "int16"
103 * @def _DBUS_INT16_MAX
105 * Maximum value of type "int16"
108 * @def _DBUS_UINT16_MAX
110 * Maximum value of type "uint16"
114 * @def _DBUS_INT32_MIN
116 * Minimum value of type "int32"
119 * @def _DBUS_INT32_MAX
121 * Maximum value of type "int32"
124 * @def _DBUS_UINT32_MAX
126 * Maximum value of type "uint32"
132 * Minimum value of type "int"
137 * Maximum value of type "int"
140 * @def _DBUS_UINT_MAX
142 * Maximum value of type "uint"
146 * @typedef DBusForeachFunction
148 * Used to iterate over each item in a collection, such as
153 * @def _DBUS_LOCK_NAME
155 * Expands to name of a global lock variable.
159 * @def _DBUS_DEFINE_GLOBAL_LOCK
161 * Defines a global lock variable with the given name.
162 * The lock must be added to the list to initialize
163 * in dbus_threads_init().
167 * @def _DBUS_DECLARE_GLOBAL_LOCK
169 * Expands to declaration of a global lock defined
170 * with _DBUS_DEFINE_GLOBAL_LOCK.
171 * The lock must be added to the list to initialize
172 * in dbus_threads_init().
178 * Locks a global lock
184 * Unlocks a global lock
188 * Fixed "out of memory" error message, just to avoid
189 * making up a different string every time and wasting
192 const char _dbus_no_memory_message[] = "Not enough memory";
194 static dbus_bool_t warn_initted = FALSE;
195 static dbus_bool_t fatal_warnings = FALSE;
196 static dbus_bool_t fatal_warnings_on_check_failed = TRUE;
204 s = _dbus_getenv ("DBUS_FATAL_WARNINGS");
209 fatal_warnings = FALSE;
210 fatal_warnings_on_check_failed = FALSE;
214 fatal_warnings = TRUE;
215 fatal_warnings_on_check_failed = TRUE;
219 fprintf(stderr, "DBUS_FATAL_WARNINGS should be set to 0 or 1 if set, not '%s'",
229 * Prints a warning message to stderr. Can optionally be made to exit
230 * fatally by setting DBUS_FATAL_WARNINGS, but this is rarely
231 * used. This function should be considered pretty much equivalent to
232 * fprintf(stderr). _dbus_warn_check_failed() on the other hand is
233 * suitable for use when a programming mistake has been made.
235 * @param format printf-style format string.
238 _dbus_warn (const char *format,
246 va_start (args, format);
247 vfprintf (stderr, format, args);
258 * Prints a "critical" warning to stderr when an assertion fails;
259 * differs from _dbus_warn primarily in that it prefixes the pid and
260 * defaults to fatal. This should be used only when a programming
261 * error has been detected. (NOT for unavoidable errors that an app
262 * might handle - those should be returned as DBusError.) Calling this
263 * means "there is a bug"
266 _dbus_warn_check_failed(const char *format,
274 fprintf (stderr, "process %lu: ", _dbus_getpid ());
276 va_start (args, format);
277 vfprintf (stderr, format, args);
280 if (fatal_warnings_on_check_failed)
287 #ifdef DBUS_ENABLE_VERBOSE_MODE
289 static dbus_bool_t verbose_initted = FALSE;
290 static dbus_bool_t verbose = TRUE;
292 /** Whether to show the current thread in verbose messages */
293 #define PTHREAD_IN_VERBOSE 0
294 #if PTHREAD_IN_VERBOSE
299 _dbus_verbose_init (void)
301 if (!verbose_initted)
303 const char *p = _dbus_getenv ("DBUS_VERBOSE");
304 verbose = p != NULL && *p == '1';
305 verbose_initted = TRUE;
310 * Implementation of dbus_is_verbose() macro if built with verbose logging
312 * @returns whether verbose logging is active.
315 _dbus_is_verbose_real (void)
317 _dbus_verbose_init ();
322 * Prints a warning message to stderr
323 * if the user has enabled verbose mode.
324 * This is the real function implementation,
325 * use _dbus_verbose() macro in code.
327 * @param format printf-style format string.
330 _dbus_verbose_real (const char *format,
334 static dbus_bool_t need_pid = TRUE;
337 /* things are written a bit oddly here so that
338 * in the non-verbose case we just have the one
339 * conditional and return immediately.
341 if (!_dbus_is_verbose_real())
344 /* Print out pid before the line */
347 #if PTHREAD_IN_VERBOSE
348 fprintf (stderr, "%lu: 0x%lx: ", _dbus_getpid (), pthread_self ());
350 fprintf (stderr, "%lu: ", _dbus_getpid ());
355 /* Only print pid again if the next line is a new line */
356 len = strlen (format);
357 if (format[len-1] == '\n')
362 va_start (args, format);
363 vfprintf (stderr, format, args);
370 * Reinitializes the verbose logging code, used
371 * as a hack in dbus-spawn.c so that a child
372 * process re-reads its pid
376 _dbus_verbose_reset_real (void)
378 verbose_initted = FALSE;
381 #endif /* DBUS_ENABLE_VERBOSE_MODE */
384 * Duplicates a string. Result must be freed with
385 * dbus_free(). Returns #NULL if memory allocation fails.
386 * If the string to be duplicated is #NULL, returns #NULL.
388 * @param str string to duplicate.
389 * @returns newly-allocated copy.
392 _dbus_strdup (const char *str)
402 copy = dbus_malloc (len + 1);
406 memcpy (copy, str, len + 1);
412 * Duplicates a block of memory. Returns
415 * @param mem memory to copy
416 * @param n_bytes number of bytes to copy
420 _dbus_memdup (const void *mem,
425 copy = dbus_malloc (n_bytes);
429 memcpy (copy, mem, n_bytes);
435 * Duplicates a string array. Result may be freed with
436 * dbus_free_string_array(). Returns #NULL if memory allocation fails.
437 * If the array to be duplicated is #NULL, returns #NULL.
439 * @param array array to duplicate.
440 * @returns newly-allocated copy.
443 _dbus_dup_string_array (const char **array)
452 for (len = 0; array[len] != NULL; ++len)
455 copy = dbus_new0 (char*, len + 1);
462 copy[i] = _dbus_strdup (array[i]);
465 dbus_free_string_array (copy);
476 * Checks whether a string array contains the given string.
478 * @param array array to search.
479 * @param str string to look for
480 * @returns #TRUE if array contains string
483 _dbus_string_array_contains (const char **array,
489 while (array[i] != NULL)
491 if (strcmp (array[i], str) == 0)
500 * Generates a new UUID. If you change how this is done,
501 * there's some text about it in the spec that should also change.
503 * @param uuid the uuid to initialize
506 _dbus_generate_uuid (DBusGUID *uuid)
510 _dbus_get_current_time (&now, NULL);
512 uuid->as_uint32s[DBUS_UUID_LENGTH_WORDS - 1] = DBUS_UINT32_TO_BE (now);
514 _dbus_generate_random_bytes_buffer (uuid->as_bytes, DBUS_UUID_LENGTH_BYTES - 4);
520 * @param uuid the uuid
521 * @param encoded string to append hex uuid to
522 * @returns #FALSE if no memory
525 _dbus_uuid_encode (const DBusGUID *uuid,
529 _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
530 return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
534 _dbus_read_uuid_file_without_creating (const DBusString *filename,
542 _dbus_string_init (&contents);
543 _dbus_string_init (&decoded);
545 if (!_dbus_file_get_contents (&contents, filename, error))
548 _dbus_string_chop_white (&contents);
550 if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
552 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
553 "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
554 _dbus_string_get_const_data (filename),
555 DBUS_UUID_LENGTH_HEX,
556 _dbus_string_get_length (&contents));
560 if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
562 _DBUS_SET_OOM (error);
568 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
569 "UUID file '%s' contains invalid hex data",
570 _dbus_string_get_const_data (filename));
574 if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
576 dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
577 "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
578 _dbus_string_get_const_data (filename),
579 _dbus_string_get_length (&decoded),
580 DBUS_UUID_LENGTH_BYTES);
584 _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
586 _dbus_string_free (&decoded);
587 _dbus_string_free (&contents);
589 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
594 _DBUS_ASSERT_ERROR_IS_SET (error);
595 _dbus_string_free (&contents);
596 _dbus_string_free (&decoded);
601 _dbus_create_uuid_file_exclusively (const DBusString *filename,
607 _dbus_string_init (&encoded);
609 _dbus_generate_uuid (uuid);
611 if (!_dbus_uuid_encode (uuid, &encoded))
613 _DBUS_SET_OOM (error);
617 /* FIXME this is racy; we need a save_file_exclusively
618 * function. But in practice this should be fine for now.
620 * - first be sure we can create the file and it
621 * doesn't exist by creating it empty with O_EXCL
622 * - then create it by creating a temporary file and
623 * overwriting atomically with rename()
625 if (!_dbus_create_file_exclusively (filename, error))
628 if (!_dbus_string_append_byte (&encoded, '\n'))
630 _DBUS_SET_OOM (error);
634 if (!_dbus_string_save_to_file (&encoded, filename, error))
637 if (!_dbus_make_file_world_readable (filename, error))
640 _dbus_string_free (&encoded);
642 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
646 _DBUS_ASSERT_ERROR_IS_SET (error);
647 _dbus_string_free (&encoded);
652 * Reads (and optionally writes) a uuid to a file. Initializes the uuid
653 * unless an error is returned.
655 * @param filename the name of the file
656 * @param uuid uuid to be initialized with the loaded uuid
657 * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
658 * @param error the error return
659 * @returns #FALSE if the error is set
662 _dbus_read_uuid_file (const DBusString *filename,
664 dbus_bool_t create_if_not_found,
667 DBusError read_error;
669 dbus_error_init (&read_error);
671 if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
674 if (!create_if_not_found)
676 dbus_move_error (&read_error, error);
680 /* If the file exists and contains junk, we want to keep that error
681 * message instead of overwriting it with a "file exists" error
682 * message when we try to write
684 if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
686 dbus_move_error (&read_error, error);
691 dbus_error_free (&read_error);
692 return _dbus_create_uuid_file_exclusively (filename, uuid, error);
696 _DBUS_DEFINE_GLOBAL_LOCK (machine_uuid);
697 static int machine_uuid_initialized_generation = 0;
698 static DBusGUID machine_uuid;
701 * Gets the hex-encoded UUID of the machine this function is
702 * executed on. This UUID is guaranteed to be the same for a given
703 * machine at least until it next reboots, though it also
704 * makes some effort to be the same forever, it may change if the
705 * machine is reconfigured or its hardware is modified.
707 * @param uuid_str string to append hex-encoded machine uuid to
708 * @returns #FALSE if no memory
711 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str)
715 _DBUS_LOCK (machine_uuid);
716 if (machine_uuid_initialized_generation != _dbus_current_generation)
719 dbus_error_init (&error);
720 if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE,
723 #ifndef DBUS_BUILD_TESTS
724 /* For the test suite, we may not be installed so just continue silently
725 * here. But in a production build, we want to be nice and loud about
728 _dbus_warn_check_failed ("D-Bus library appears to be incorrectly set up; failed to read machine uuid: %s\n"
729 "See the manual page for dbus-uuidgen to correct this issue.\n",
733 dbus_error_free (&error);
735 _dbus_generate_uuid (&machine_uuid);
739 ok = _dbus_uuid_encode (&machine_uuid, uuid_str);
741 _DBUS_UNLOCK (machine_uuid);
746 #ifdef DBUS_BUILD_TESTS
748 * Returns a string describing the given name.
750 * @param header_field the field to describe
751 * @returns a constant string describing the field
754 _dbus_header_field_to_string (int header_field)
756 switch (header_field)
758 case DBUS_HEADER_FIELD_INVALID:
760 case DBUS_HEADER_FIELD_PATH:
762 case DBUS_HEADER_FIELD_INTERFACE:
764 case DBUS_HEADER_FIELD_MEMBER:
766 case DBUS_HEADER_FIELD_ERROR_NAME:
768 case DBUS_HEADER_FIELD_REPLY_SERIAL:
769 return "reply-serial";
770 case DBUS_HEADER_FIELD_DESTINATION:
771 return "destination";
772 case DBUS_HEADER_FIELD_SENDER:
774 case DBUS_HEADER_FIELD_SIGNATURE:
780 #endif /* DBUS_BUILD_TESTS */
782 #ifndef DBUS_DISABLE_CHECKS
783 /** String used in _dbus_return_if_fail macro */
784 const char _dbus_return_if_fail_warning_format[] =
785 "arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
786 "This is normally a bug in some application using the D-Bus library.\n";
789 #ifndef DBUS_DISABLE_ASSERT
791 * Internals of _dbus_assert(); it's a function
792 * rather than a macro with the inline code so
793 * that the assertion failure blocks don't show up
794 * in test suite coverage, and to shrink code size.
796 * @param condition TRUE if assertion succeeded
797 * @param condition_text condition as a string
798 * @param file file the assertion is in
799 * @param line line the assertion is in
800 * @param func function the assertion is in
803 _dbus_real_assert (dbus_bool_t condition,
804 const char *condition_text,
809 if (_DBUS_UNLIKELY (!condition))
811 _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
812 _dbus_getpid (), condition_text, file, line, func);
818 * Internals of _dbus_assert_not_reached(); it's a function
819 * rather than a macro with the inline code so
820 * that the assertion failure blocks don't show up
821 * in test suite coverage, and to shrink code size.
823 * @param explanation what was reached that shouldn't have been
824 * @param file file the assertion is in
825 * @param line line the assertion is in
828 _dbus_real_assert_not_reached (const char *explanation,
832 _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
833 file, line, _dbus_getpid (), explanation);
836 #endif /* DBUS_DISABLE_ASSERT */
838 #ifdef DBUS_BUILD_TESTS
840 run_failing_each_malloc (int n_mallocs,
841 const char *description,
842 DBusTestMemoryFunction func,
845 n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
847 while (n_mallocs >= 0)
849 _dbus_set_fail_alloc_counter (n_mallocs);
851 _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
852 description, n_mallocs,
853 _dbus_get_fail_alloc_failures ());
855 if (!(* func) (data))
861 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
867 * Tests how well the given function responds to out-of-memory
868 * situations. Calls the function repeatedly, failing a different
869 * call to malloc() each time. If the function ever returns #FALSE,
870 * the test fails. The function should return #TRUE whenever something
871 * valid (such as returning an error, or succeeding) occurs, and #FALSE
872 * if it gets confused in some way.
874 * @param description description of the test used in verbose output
875 * @param func function to call
876 * @param data data to pass to function
877 * @returns #TRUE if the function never returns FALSE
880 _dbus_test_oom_handling (const char *description,
881 DBusTestMemoryFunction func,
886 int max_failures_to_try;
889 /* Run once to see about how many mallocs are involved */
891 _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
893 _dbus_verbose ("Running once to count mallocs\n");
895 if (!(* func) (data))
898 approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
900 _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
901 description, approx_mallocs);
903 setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
908 _dbus_string_init_const (&str, setting);
910 if (!_dbus_string_parse_int (&str, 0, &v, NULL))
911 _dbus_warn ("couldn't parse '%s' as integer\n", setting);
912 max_failures_to_try = v;
916 max_failures_to_try = 4;
919 i = setting ? max_failures_to_try - 1 : 1;
920 while (i < max_failures_to_try)
922 _dbus_set_fail_alloc_failures (i);
923 if (!run_failing_each_malloc (approx_mallocs, description, func, data))
928 _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
933 #endif /* DBUS_BUILD_TESTS */