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