Merge branch 'my-dbus-1.2'
[platform/upstream/dbus.git] / dbus / dbus-internals.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-internals.c  random utility stuff (internal to D-Bus implementation)
3  *
4  * Copyright (C) 2002, 2003  Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
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.
12  *
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.
17  * 
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
21  *
22  */
23 #include "dbus-internals.h"
24 #include "dbus-protocol.h"
25 #include "dbus-marshal-basic.h"
26 #include "dbus-test.h"
27 #include <stdio.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
32 #include <windows.h>
33 #endif
34
35 /**
36  * @defgroup DBusInternals D-Bus secret internal implementation details
37  * @brief Documentation useful when developing or debugging D-Bus itself.
38  * 
39  */
40
41 /**
42  * @defgroup DBusInternalsUtils Utilities and portability
43  * @ingroup DBusInternals
44  * @brief Utility functions (_dbus_assert(), _dbus_warn(), etc.)
45  * @{
46  */
47
48 /**
49  * @def _dbus_assert
50  *
51  * Aborts with an error message if the condition is false.
52  * 
53  * @param condition condition which must be true.
54  */
55
56 /**
57  * @def _dbus_assert_not_reached
58  *
59  * Aborts with an error message if called.
60  * The given explanation will be printed.
61  * 
62  * @param explanation explanation of what happened if the code was reached.
63  */
64
65 /**
66  * @def _DBUS_N_ELEMENTS
67  *
68  * Computes the number of elements in a fixed-size array using
69  * sizeof().
70  *
71  * @param array the array to count elements in.
72  */
73
74 /**
75  * @def _DBUS_POINTER_TO_INT
76  *
77  * Safely casts a void* to an integer; should only be used on void*
78  * that actually contain integers, for example one created with
79  * _DBUS_INT_TO_POINTER.  Only guaranteed to preserve 32 bits.
80  * (i.e. it's used to store 32-bit ints in pointers, but
81  * can't be used to store 64-bit pointers in ints.)
82  *
83  * @param pointer pointer to extract an integer from.
84  */
85 /**
86  * @def _DBUS_INT_TO_POINTER
87  *
88  * Safely stuffs an integer into a pointer, to be extracted later with
89  * _DBUS_POINTER_TO_INT. Only guaranteed to preserve 32 bits.
90  *
91  * @param integer the integer to stuff into a pointer.
92  */
93 /**
94  * @def _DBUS_ZERO
95  *
96  * Sets all bits in an object to zero.
97  *
98  * @param object the object to be zeroed.
99  */
100 /**
101  * @def _DBUS_INT16_MIN
102  *
103  * Minimum value of type "int16"
104  */
105 /**
106  * @def _DBUS_INT16_MAX
107  *
108  * Maximum value of type "int16"
109  */
110 /**
111  * @def _DBUS_UINT16_MAX
112  *
113  * Maximum value of type "uint16"
114  */
115
116 /**
117  * @def _DBUS_INT32_MIN
118  *
119  * Minimum value of type "int32"
120  */
121 /**
122  * @def _DBUS_INT32_MAX
123  *
124  * Maximum value of type "int32"
125  */
126 /**
127  * @def _DBUS_UINT32_MAX
128  *
129  * Maximum value of type "uint32"
130  */
131
132 /**
133  * @def _DBUS_INT_MIN
134  *
135  * Minimum value of type "int"
136  */
137 /**
138  * @def _DBUS_INT_MAX
139  *
140  * Maximum value of type "int"
141  */
142 /**
143  * @def _DBUS_UINT_MAX
144  *
145  * Maximum value of type "uint"
146  */
147
148 /**
149  * @typedef DBusForeachFunction
150  * 
151  * Used to iterate over each item in a collection, such as
152  * a DBusList.
153  */
154
155 /**
156  * @def _DBUS_LOCK_NAME
157  *
158  * Expands to name of a global lock variable.
159  */
160
161 /**
162  * @def _DBUS_DEFINE_GLOBAL_LOCK
163  *
164  * Defines a global lock variable with the given name.
165  * The lock must be added to the list to initialize
166  * in dbus_threads_init().
167  */
168
169 /**
170  * @def _DBUS_DECLARE_GLOBAL_LOCK
171  *
172  * Expands to declaration of a global lock defined
173  * with _DBUS_DEFINE_GLOBAL_LOCK.
174  * The lock must be added to the list to initialize
175  * in dbus_threads_init().
176  */
177
178 /**
179  * @def _DBUS_LOCK
180  *
181  * Locks a global lock
182  */
183
184 /**
185  * @def _DBUS_UNLOCK
186  *
187  * Unlocks a global lock
188  */
189
190 /**
191  * Fixed "out of memory" error message, just to avoid
192  * making up a different string every time and wasting
193  * space.
194  */
195 const char *_dbus_no_memory_message = "Not enough memory";
196
197 static dbus_bool_t warn_initted = FALSE;
198 static dbus_bool_t fatal_warnings = FALSE;
199 static dbus_bool_t fatal_warnings_on_check_failed = TRUE;
200
201 static void
202 init_warnings(void)
203 {
204   if (!warn_initted)
205     {
206       const char *s;
207       s = _dbus_getenv ("DBUS_FATAL_WARNINGS");
208       if (s && *s)
209         {
210           if (*s == '0')
211             {
212               fatal_warnings = FALSE;
213               fatal_warnings_on_check_failed = FALSE;
214             }
215           else if (*s == '1')
216             {
217               fatal_warnings = TRUE;
218               fatal_warnings_on_check_failed = TRUE;
219             }
220           else
221             {
222               fprintf(stderr, "DBUS_FATAL_WARNINGS should be set to 0 or 1 if set, not '%s'",
223                       s);
224             }
225         }
226
227       warn_initted = TRUE;
228     }
229 }
230
231 /**
232  * Prints a warning message to stderr. Can optionally be made to exit
233  * fatally by setting DBUS_FATAL_WARNINGS, but this is rarely
234  * used. This function should be considered pretty much equivalent to
235  * fprintf(stderr). _dbus_warn_check_failed() on the other hand is
236  * suitable for use when a programming mistake has been made.
237  *
238  * @param format printf-style format string.
239  */
240 void
241 _dbus_warn (const char *format,
242             ...)
243 {
244   va_list args;
245
246   if (!warn_initted)
247     init_warnings ();
248   
249   va_start (args, format);
250   vfprintf (stderr, format, args);
251   va_end (args);
252
253   if (fatal_warnings)
254     {
255       fflush (stderr);
256       _dbus_abort ();
257     }
258 }
259
260 /**
261  * Prints a "critical" warning to stderr when an assertion fails;
262  * differs from _dbus_warn primarily in that it prefixes the pid and
263  * defaults to fatal. This should be used only when a programming
264  * error has been detected. (NOT for unavoidable errors that an app
265  * might handle - those should be returned as DBusError.) Calling this
266  * means "there is a bug"
267  */
268 void
269 _dbus_warn_check_failed(const char *format,
270                         ...)
271 {
272   va_list args;
273   
274   if (!warn_initted)
275     init_warnings ();
276
277   fprintf (stderr, "process %lu: ", _dbus_pid_for_log ());
278   
279   va_start (args, format);
280   vfprintf (stderr, format, args);
281   va_end (args);
282
283   if (fatal_warnings_on_check_failed)
284     {
285       fflush (stderr);
286       _dbus_abort ();
287     }
288 }
289
290 #ifdef DBUS_ENABLE_VERBOSE_MODE
291
292 static dbus_bool_t verbose_initted = FALSE;
293 static dbus_bool_t verbose = TRUE;
294
295 /** Whether to show the current thread in verbose messages */
296 #define PTHREAD_IN_VERBOSE 0
297 #if PTHREAD_IN_VERBOSE
298 #include <pthread.h>
299 #endif
300
301 #ifdef _MSC_VER
302 #define inline
303 #endif
304 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
305 static char module_name[1024];
306 #endif
307
308 static inline void
309 _dbus_verbose_init (void)
310 {
311   if (!verbose_initted)
312     {
313       const char *p = _dbus_getenv ("DBUS_VERBOSE");
314       verbose = p != NULL && *p == '1';
315       verbose_initted = TRUE;
316 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
317       {
318         char *last_period, *last_slash;
319         GetModuleFileName(0,module_name,sizeof(module_name)-1);
320         last_period = _mbsrchr(module_name,'.');
321         if (last_period)
322           *last_period ='\0';
323         last_slash = _mbsrchr(module_name,'\\');
324         if (last_slash)
325           strcpy(module_name,last_slash+1);
326         strcat(module_name,": ");
327       }
328 #endif
329     }
330 }
331
332 /** @def DBUS_IS_DIR_SEPARATOR(c)
333  * macro for checking if character c is a patch separator
334  * 
335  * @todo move to a header file so that others can use this too
336  */
337 #ifdef DBUS_WIN 
338 #define DBUS_IS_DIR_SEPARATOR(c) (c == '\\' || c == '/')
339 #else
340 #define DBUS_IS_DIR_SEPARATOR(c) (c == '/')
341 #endif
342
343 /** 
344  remove source root from file path 
345  the source root is determined by 
346 */ 
347 static char *_dbus_file_path_extract_elements_from_tail(const char *file,int level)
348 {
349   static int prefix = -1;
350   char *p;
351
352   if (prefix == -1) 
353     {
354       char *p = (char *)file + strlen(file);
355       int i = 0;
356       prefix = 0;
357       for (;p >= file;p--)
358         {
359           if (DBUS_IS_DIR_SEPARATOR(*p))
360             {
361               if (++i >= level) 
362                 {
363                   prefix = p-file+1;
364                   break;
365                 }
366            }
367         }
368     }
369   return (char *)file+prefix;
370 }
371
372 /**
373  * Implementation of dbus_is_verbose() macro if built with verbose logging
374  * enabled.
375  * @returns whether verbose logging is active.
376  */
377 dbus_bool_t
378 _dbus_is_verbose_real (void)
379 {
380   _dbus_verbose_init ();
381   return verbose;
382 }
383
384 /**
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.
389  *
390  * @param format printf-style format string.
391  */
392 void
393 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
394 _dbus_verbose_real (const char *file, 
395                     const int line, 
396                     const char *function, 
397                     const char *format,
398 #else
399 _dbus_verbose_real (const char *format,
400 #endif
401                     ...)
402 {
403   va_list args;
404   static dbus_bool_t need_pid = TRUE;
405   int len;
406   
407   /* things are written a bit oddly here so that
408    * in the non-verbose case we just have the one
409    * conditional and return immediately.
410    */
411   if (!_dbus_is_verbose_real())
412     return;
413
414 #ifndef DBUS_USE_OUTPUT_DEBUG_STRING
415   /* Print out pid before the line */
416   if (need_pid)
417     {
418 #if PTHREAD_IN_VERBOSE
419       fprintf (stderr, "%lu: 0x%lx: ", _dbus_pid_for_log (), pthread_self ());
420 #else
421       fprintf (stderr, "%lu: ", _dbus_pid_for_log ());
422 #endif
423     }
424 #endif
425
426   /* Only print pid again if the next line is a new line */
427   len = strlen (format);
428   if (format[len-1] == '\n')
429     need_pid = TRUE;
430   else
431     need_pid = FALSE;
432
433   va_start (args, format);
434 #ifdef DBUS_USE_OUTPUT_DEBUG_STRING
435   {
436   char buf[1024];
437   strcpy(buf,module_name);
438 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
439   vsprintf (buf+strlen(buf), "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
440 #endif
441   vsprintf (buf+strlen(buf),format, args);
442   va_end (args);
443   OutputDebugString(buf);
444   }
445 #else
446 #ifdef DBUS_CPP_SUPPORTS_VARIABLE_MACRO_ARGUMENTS
447   fprintf (stderr, "[%s(%d):%s] ",_dbus_file_path_extract_elements_from_tail(file,2),line,function);
448 #endif
449
450   vfprintf (stderr, format, args);
451   va_end (args);
452
453   fflush (stderr);
454 #endif
455 }
456
457 /**
458  * Reinitializes the verbose logging code, used
459  * as a hack in dbus-spawn.c so that a child
460  * process re-reads its pid
461  *
462  */
463 void
464 _dbus_verbose_reset_real (void)
465 {
466   verbose_initted = FALSE;
467 }
468
469 #endif /* DBUS_ENABLE_VERBOSE_MODE */
470
471 /**
472  * Duplicates a string. Result must be freed with
473  * dbus_free(). Returns #NULL if memory allocation fails.
474  * If the string to be duplicated is #NULL, returns #NULL.
475  * 
476  * @param str string to duplicate.
477  * @returns newly-allocated copy.
478  */
479 char*
480 _dbus_strdup (const char *str)
481 {
482   size_t len;
483   char *copy;
484   
485   if (str == NULL)
486     return NULL;
487   
488   len = strlen (str);
489
490   copy = dbus_malloc (len + 1);
491   if (copy == NULL)
492     return NULL;
493
494   memcpy (copy, str, len + 1);
495   
496   return copy;
497 }
498
499 /**
500  * Duplicates a block of memory. Returns
501  * #NULL on failure.
502  *
503  * @param mem memory to copy
504  * @param n_bytes number of bytes to copy
505  * @returns the copy
506  */
507 void*
508 _dbus_memdup (const void  *mem,
509               size_t       n_bytes)
510 {
511   void *copy;
512
513   copy = dbus_malloc (n_bytes);
514   if (copy == NULL)
515     return NULL;
516
517   memcpy (copy, mem, n_bytes);
518   
519   return copy;
520 }
521
522 /**
523  * Duplicates a string array. Result may be freed with
524  * dbus_free_string_array(). Returns #NULL if memory allocation fails.
525  * If the array to be duplicated is #NULL, returns #NULL.
526  * 
527  * @param array array to duplicate.
528  * @returns newly-allocated copy.
529  */
530 char**
531 _dbus_dup_string_array (const char **array)
532 {
533   int len;
534   int i;
535   char **copy;
536   
537   if (array == NULL)
538     return NULL;
539
540   for (len = 0; array[len] != NULL; ++len)
541     ;
542
543   copy = dbus_new0 (char*, len + 1);
544   if (copy == NULL)
545     return NULL;
546
547   i = 0;
548   while (i < len)
549     {
550       copy[i] = _dbus_strdup (array[i]);
551       if (copy[i] == NULL)
552         {
553           dbus_free_string_array (copy);
554           return NULL;
555         }
556
557       ++i;
558     }
559
560   return copy;
561 }
562
563 /**
564  * Checks whether a string array contains the given string.
565  * 
566  * @param array array to search.
567  * @param str string to look for
568  * @returns #TRUE if array contains string
569  */
570 dbus_bool_t
571 _dbus_string_array_contains (const char **array,
572                              const char  *str)
573 {
574   int i;
575
576   i = 0;
577   while (array[i] != NULL)
578     {
579       if (strcmp (array[i], str) == 0)
580         return TRUE;
581       ++i;
582     }
583
584   return FALSE;
585 }
586
587 /**
588  * Generates a new UUID. If you change how this is done,
589  * there's some text about it in the spec that should also change.
590  *
591  * @param uuid the uuid to initialize
592  */
593 void
594 _dbus_generate_uuid (DBusGUID *uuid)
595 {
596   long now;
597
598   _dbus_get_current_time (&now, NULL);
599
600   uuid->as_uint32s[DBUS_UUID_LENGTH_WORDS - 1] = DBUS_UINT32_TO_BE (now);
601   
602   _dbus_generate_random_bytes_buffer (uuid->as_bytes, DBUS_UUID_LENGTH_BYTES - 4);
603 }
604
605 /**
606  * Hex-encode a UUID.
607  *
608  * @param uuid the uuid
609  * @param encoded string to append hex uuid to
610  * @returns #FALSE if no memory
611  */
612 dbus_bool_t
613 _dbus_uuid_encode (const DBusGUID *uuid,
614                    DBusString     *encoded)
615 {
616   DBusString binary;
617   _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
618   return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
619 }
620
621 static dbus_bool_t
622 _dbus_read_uuid_file_without_creating (const DBusString *filename,
623                                        DBusGUID         *uuid,
624                                        DBusError        *error)
625 {
626   DBusString contents;
627   DBusString decoded;
628   int end;
629   
630   if (!_dbus_string_init (&contents))
631     {
632       _DBUS_SET_OOM (error);
633       return FALSE;
634     }
635
636   if (!_dbus_string_init (&decoded))
637     {
638       _dbus_string_free (&contents);
639       _DBUS_SET_OOM (error);
640       return FALSE;
641     }
642   
643   if (!_dbus_file_get_contents (&contents, filename, error))
644     goto error;
645
646   _dbus_string_chop_white (&contents);
647
648   if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
649     {
650       dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
651                       "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
652                       _dbus_string_get_const_data (filename),
653                       DBUS_UUID_LENGTH_HEX,
654                       _dbus_string_get_length (&contents));
655       goto error;
656     }
657
658   if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
659     {
660       _DBUS_SET_OOM (error);
661       goto error;
662     }
663
664   if (end == 0)
665     {
666       dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
667                       "UUID file '%s' contains invalid hex data",
668                       _dbus_string_get_const_data (filename));
669       goto error;
670     }
671
672   if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
673     {
674       dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
675                       "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
676                       _dbus_string_get_const_data (filename),
677                       _dbus_string_get_length (&decoded),
678                       DBUS_UUID_LENGTH_BYTES);
679       goto error;
680     }
681
682   _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
683
684   _dbus_string_free (&decoded);
685   _dbus_string_free (&contents);
686
687   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
688
689   return TRUE;
690   
691  error:
692   _DBUS_ASSERT_ERROR_IS_SET (error);
693   _dbus_string_free (&contents);
694   _dbus_string_free (&decoded);
695   return FALSE;
696 }
697
698 static dbus_bool_t
699 _dbus_create_uuid_file_exclusively (const DBusString *filename,
700                                     DBusGUID         *uuid,
701                                     DBusError        *error)
702 {
703   DBusString encoded;
704
705   if (!_dbus_string_init (&encoded))
706     {
707       _DBUS_SET_OOM (error);
708       return FALSE;
709     }
710
711   _dbus_generate_uuid (uuid);
712   
713   if (!_dbus_uuid_encode (uuid, &encoded))
714     {
715       _DBUS_SET_OOM (error);
716       goto error;
717     }
718   
719   /* FIXME this is racy; we need a save_file_exclusively
720    * function. But in practice this should be fine for now.
721    *
722    * - first be sure we can create the file and it
723    *   doesn't exist by creating it empty with O_EXCL
724    * - then create it by creating a temporary file and
725    *   overwriting atomically with rename()
726    */
727   if (!_dbus_create_file_exclusively (filename, error))
728     goto error;
729
730   if (!_dbus_string_append_byte (&encoded, '\n'))
731     {
732       _DBUS_SET_OOM (error);
733       goto error;
734     }
735   
736   if (!_dbus_string_save_to_file (&encoded, filename, error))
737     goto error;
738
739   if (!_dbus_make_file_world_readable (filename, error))
740     goto error;
741
742   _dbus_string_free (&encoded);
743
744   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
745   return TRUE;
746   
747  error:
748   _DBUS_ASSERT_ERROR_IS_SET (error);
749   _dbus_string_free (&encoded);
750   return FALSE;        
751 }
752
753 /**
754  * Reads (and optionally writes) a uuid to a file. Initializes the uuid
755  * unless an error is returned.
756  *
757  * @param filename the name of the file
758  * @param uuid uuid to be initialized with the loaded uuid
759  * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
760  * @param error the error return
761  * @returns #FALSE if the error is set
762  */
763 dbus_bool_t
764 _dbus_read_uuid_file (const DBusString *filename,
765                       DBusGUID         *uuid,
766                       dbus_bool_t       create_if_not_found,
767                       DBusError        *error)
768 {
769   DBusError read_error = DBUS_ERROR_INIT;
770
771   if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
772     return TRUE;
773
774   if (!create_if_not_found)
775     {
776       dbus_move_error (&read_error, error);
777       return FALSE;
778     }
779
780   /* If the file exists and contains junk, we want to keep that error
781    * message instead of overwriting it with a "file exists" error
782    * message when we try to write
783    */
784   if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
785     {
786       dbus_move_error (&read_error, error);
787       return FALSE;
788     }
789   else
790     {
791       dbus_error_free (&read_error);
792       return _dbus_create_uuid_file_exclusively (filename, uuid, error);
793     }
794 }
795
796 _DBUS_DEFINE_GLOBAL_LOCK (machine_uuid);
797 static int machine_uuid_initialized_generation = 0;
798 static DBusGUID machine_uuid;
799
800 /**
801  * Gets the hex-encoded UUID of the machine this function is
802  * executed on. This UUID is guaranteed to be the same for a given
803  * machine at least until it next reboots, though it also
804  * makes some effort to be the same forever, it may change if the
805  * machine is reconfigured or its hardware is modified.
806  * 
807  * @param uuid_str string to append hex-encoded machine uuid to
808  * @returns #FALSE if no memory
809  */
810 dbus_bool_t
811 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str)
812 {
813   dbus_bool_t ok;
814   
815   _DBUS_LOCK (machine_uuid);
816   if (machine_uuid_initialized_generation != _dbus_current_generation)
817     {
818       DBusError error = DBUS_ERROR_INIT;
819
820       if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE,
821                                           &error))
822         {          
823 #ifndef DBUS_BUILD_TESTS
824           /* For the test suite, we may not be installed so just continue silently
825            * here. But in a production build, we want to be nice and loud about
826            * this.
827            */
828           _dbus_warn_check_failed ("D-Bus library appears to be incorrectly set up; failed to read machine uuid: %s\n"
829                                    "See the manual page for dbus-uuidgen to correct this issue.\n",
830                                    error.message);
831 #endif
832           
833           dbus_error_free (&error);
834           
835           _dbus_generate_uuid (&machine_uuid);
836         }
837     }
838
839   ok = _dbus_uuid_encode (&machine_uuid, uuid_str);
840
841   _DBUS_UNLOCK (machine_uuid);
842
843   return ok;
844 }
845
846 #ifdef DBUS_BUILD_TESTS
847 /**
848  * Returns a string describing the given name.
849  *
850  * @param header_field the field to describe
851  * @returns a constant string describing the field
852  */
853 const char *
854 _dbus_header_field_to_string (int header_field)
855 {
856   switch (header_field)
857     {
858     case DBUS_HEADER_FIELD_INVALID:
859       return "invalid";
860     case DBUS_HEADER_FIELD_PATH:
861       return "path";
862     case DBUS_HEADER_FIELD_INTERFACE:
863       return "interface";
864     case DBUS_HEADER_FIELD_MEMBER:
865       return "member";
866     case DBUS_HEADER_FIELD_ERROR_NAME:
867       return "error-name";
868     case DBUS_HEADER_FIELD_REPLY_SERIAL:
869       return "reply-serial";
870     case DBUS_HEADER_FIELD_DESTINATION:
871       return "destination";
872     case DBUS_HEADER_FIELD_SENDER:
873       return "sender";
874     case DBUS_HEADER_FIELD_SIGNATURE:
875       return "signature";
876     default:
877       return "unknown";
878     }
879 }
880 #endif /* DBUS_BUILD_TESTS */
881
882 #ifndef DBUS_DISABLE_CHECKS
883 /** String used in _dbus_return_if_fail macro */
884 const char *_dbus_return_if_fail_warning_format =
885 "arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
886 "This is normally a bug in some application using the D-Bus library.\n";
887 #endif
888
889 #ifndef DBUS_DISABLE_ASSERT
890 /**
891  * Internals of _dbus_assert(); it's a function
892  * rather than a macro with the inline code so
893  * that the assertion failure blocks don't show up
894  * in test suite coverage, and to shrink code size.
895  *
896  * @param condition TRUE if assertion succeeded
897  * @param condition_text condition as a string
898  * @param file file the assertion is in
899  * @param line line the assertion is in
900  * @param func function the assertion is in
901  */
902 void
903 _dbus_real_assert (dbus_bool_t  condition,
904                    const char  *condition_text,
905                    const char  *file,
906                    int          line,
907                    const char  *func)
908 {
909   if (_DBUS_UNLIKELY (!condition))
910     {
911       _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
912                   _dbus_pid_for_log (), condition_text, file, line, func);
913       _dbus_abort ();
914     }
915 }
916
917 /**
918  * Internals of _dbus_assert_not_reached(); it's a function
919  * rather than a macro with the inline code so
920  * that the assertion failure blocks don't show up
921  * in test suite coverage, and to shrink code size.
922  *
923  * @param explanation what was reached that shouldn't have been
924  * @param file file the assertion is in
925  * @param line line the assertion is in
926  */
927 void
928 _dbus_real_assert_not_reached (const char *explanation,
929                                const char *file,
930                                int         line)
931 {
932   _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
933               file, line, _dbus_pid_for_log (), explanation);
934   _dbus_abort ();
935 }
936 #endif /* DBUS_DISABLE_ASSERT */
937   
938 #ifdef DBUS_BUILD_TESTS
939 static dbus_bool_t
940 run_failing_each_malloc (int                    n_mallocs,
941                          const char            *description,
942                          DBusTestMemoryFunction func,
943                          void                  *data)
944 {
945   n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
946   
947   while (n_mallocs >= 0)
948     {      
949       _dbus_set_fail_alloc_counter (n_mallocs);
950
951       _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
952                      description, n_mallocs,
953                      _dbus_get_fail_alloc_failures ());
954
955       if (!(* func) (data))
956         return FALSE;
957       
958       n_mallocs -= 1;
959     }
960
961   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
962
963   return TRUE;
964 }                        
965
966 /**
967  * Tests how well the given function responds to out-of-memory
968  * situations. Calls the function repeatedly, failing a different
969  * call to malloc() each time. If the function ever returns #FALSE,
970  * the test fails. The function should return #TRUE whenever something
971  * valid (such as returning an error, or succeeding) occurs, and #FALSE
972  * if it gets confused in some way.
973  *
974  * @param description description of the test used in verbose output
975  * @param func function to call
976  * @param data data to pass to function
977  * @returns #TRUE if the function never returns FALSE
978  */
979 dbus_bool_t
980 _dbus_test_oom_handling (const char             *description,
981                          DBusTestMemoryFunction  func,
982                          void                   *data)
983 {
984   int approx_mallocs;
985   const char *setting;
986   int max_failures_to_try;
987   int i;
988
989   /* Run once to see about how many mallocs are involved */
990   
991   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
992
993   _dbus_verbose ("Running once to count mallocs\n");
994   
995   if (!(* func) (data))
996     return FALSE;
997   
998   approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
999
1000   _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
1001                  description, approx_mallocs);
1002
1003   setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
1004   if (setting != NULL)
1005     {
1006       DBusString str;
1007       long v;
1008       _dbus_string_init_const (&str, setting);
1009       v = 4;
1010       if (!_dbus_string_parse_int (&str, 0, &v, NULL))
1011         _dbus_warn ("couldn't parse '%s' as integer\n", setting);
1012       max_failures_to_try = v;
1013     }
1014   else
1015     {
1016       max_failures_to_try = 4;
1017     }
1018
1019   i = setting ? max_failures_to_try - 1 : 1;
1020   while (i < max_failures_to_try)
1021     {
1022       _dbus_set_fail_alloc_failures (i);
1023       if (!run_failing_each_malloc (approx_mallocs, description, func, data))
1024         return FALSE;
1025       ++i;
1026     }
1027   
1028   _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
1029                  description);
1030
1031   return TRUE;
1032 }
1033 #endif /* DBUS_BUILD_TESTS */
1034
1035 /** @} */