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