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