2006-10-19 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-internals.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23 #include "dbus-internals.h"
24 #include "dbus-protocol.h"
25 #include "dbus-test.h"
26 #include <stdio.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <stdlib.h>
30
31 /* the blurb for this is "D-Bus secret" so it comes after "D-Bus low-level"
32  * which is the blurb for the DBus group, which makes Doxygen show
33  * the public API first on the index page. Yay for lame hacks.
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_getpid ());
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 static inline void
302 _dbus_verbose_init (void)
303 {
304   if (!verbose_initted)
305     {
306       const char *p = _dbus_getenv ("DBUS_VERBOSE"); 
307       verbose = p != NULL && *p == '1';
308       verbose_initted = TRUE;
309     }
310 }
311
312 /**
313  * Implementation of dbus_is_verbose() macro if built with verbose logging
314  * enabled.
315  * @returns whether verbose logging is active.
316  */
317 dbus_bool_t
318 _dbus_is_verbose_real (void)
319 {
320   _dbus_verbose_init ();
321   return verbose;
322 }
323
324 /**
325  * Prints a warning message to stderr
326  * if the user has enabled verbose mode.
327  * This is the real function implementation,
328  * use _dbus_verbose() macro in code.
329  *
330  * @param format printf-style format string.
331  */
332 void
333 _dbus_verbose_real (const char *format,
334                     ...)
335 {
336   va_list args;
337   static dbus_bool_t need_pid = TRUE;
338   int len;
339   
340   /* things are written a bit oddly here so that
341    * in the non-verbose case we just have the one
342    * conditional and return immediately.
343    */
344   if (!_dbus_is_verbose_real())
345     return;
346
347   /* Print out pid before the line */
348   if (need_pid)
349     {
350 #if PTHREAD_IN_VERBOSE
351       fprintf (stderr, "%lu: 0x%lx: ", _dbus_getpid (), pthread_self ());
352 #else
353       fprintf (stderr, "%lu: ", _dbus_getpid ());
354 #endif
355     }
356       
357
358   /* Only print pid again if the next line is a new line */
359   len = strlen (format);
360   if (format[len-1] == '\n')
361     need_pid = TRUE;
362   else
363     need_pid = FALSE;
364   
365   va_start (args, format);
366   vfprintf (stderr, format, args);
367   va_end (args);
368
369   fflush (stderr);
370 }
371
372 /**
373  * Reinitializes the verbose logging code, used
374  * as a hack in dbus-spawn.c so that a child
375  * process re-reads its pid
376  *
377  */
378 void
379 _dbus_verbose_reset_real (void)
380 {
381   verbose_initted = FALSE;
382 }
383
384 #endif /* DBUS_ENABLE_VERBOSE_MODE */
385
386 /**
387  * Duplicates a string. Result must be freed with
388  * dbus_free(). Returns #NULL if memory allocation fails.
389  * If the string to be duplicated is #NULL, returns #NULL.
390  * 
391  * @param str string to duplicate.
392  * @returns newly-allocated copy.
393  */
394 char*
395 _dbus_strdup (const char *str)
396 {
397   size_t len;
398   char *copy;
399   
400   if (str == NULL)
401     return NULL;
402   
403   len = strlen (str);
404
405   copy = dbus_malloc (len + 1);
406   if (copy == NULL)
407     return NULL;
408
409   memcpy (copy, str, len + 1);
410   
411   return copy;
412 }
413
414 /**
415  * Duplicates a block of memory. Returns
416  * #NULL on failure.
417  *
418  * @param mem memory to copy
419  * @param n_bytes number of bytes to copy
420  * @returns the copy
421  */
422 void*
423 _dbus_memdup (const void  *mem,
424               size_t       n_bytes)
425 {
426   void *copy;
427
428   copy = dbus_malloc (n_bytes);
429   if (copy == NULL)
430     return NULL;
431
432   memcpy (copy, mem, n_bytes);
433   
434   return copy;
435 }
436
437 /**
438  * Duplicates a string array. Result may be freed with
439  * dbus_free_string_array(). Returns #NULL if memory allocation fails.
440  * If the array to be duplicated is #NULL, returns #NULL.
441  * 
442  * @param array array to duplicate.
443  * @returns newly-allocated copy.
444  */
445 char**
446 _dbus_dup_string_array (const char **array)
447 {
448   int len;
449   int i;
450   char **copy;
451   
452   if (array == NULL)
453     return NULL;
454
455   for (len = 0; array[len] != NULL; ++len)
456     ;
457
458   copy = dbus_new0 (char*, len + 1);
459   if (copy == NULL)
460     return NULL;
461
462   i = 0;
463   while (i < len)
464     {
465       copy[i] = _dbus_strdup (array[i]);
466       if (copy[i] == NULL)
467         {
468           dbus_free_string_array (copy);
469           return NULL;
470         }
471
472       ++i;
473     }
474
475   return copy;
476 }
477
478 /**
479  * Checks whether a string array contains the given string.
480  * 
481  * @param array array to search.
482  * @param str string to look for
483  * @returns #TRUE if array contains string
484  */
485 dbus_bool_t
486 _dbus_string_array_contains (const char **array,
487                              const char  *str)
488 {
489   int i;
490
491   i = 0;
492   while (array[i] != NULL)
493     {
494       if (strcmp (array[i], str) == 0)
495         return TRUE;
496       ++i;
497     }
498
499   return FALSE;
500 }
501
502 /**
503  * Generates a new UUID. If you change how this is done,
504  * there's some text about it in the spec that should also change.
505  *
506  * @param uuid the uuid to initialize
507  */
508 void
509 _dbus_generate_uuid (DBusGUID *uuid)
510 {
511   long now;
512   char *p;
513   int ts_size;
514
515   _dbus_get_current_time (&now, NULL);
516
517   uuid->as_uint32s[0] = now;
518
519   ts_size = sizeof (uuid->as_uint32s[0]);
520   p = ((char*)uuid->as_bytes) + ts_size;
521   
522   _dbus_generate_random_bytes_buffer (p,
523                                       sizeof (uuid->as_bytes) - ts_size);
524 }
525
526 /**
527  * Hex-encode a UUID.
528  *
529  * @param uuid the uuid
530  * @param encoded string to append hex uuid to
531  * @returns #FALSE if no memory
532  */
533 dbus_bool_t
534 _dbus_uuid_encode (const DBusGUID *uuid,
535                    DBusString     *encoded)
536 {
537   DBusString binary;
538   _dbus_string_init_const_len (&binary, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
539   return _dbus_string_hex_encode (&binary, 0, encoded, _dbus_string_get_length (encoded));
540 }
541
542 static dbus_bool_t
543 _dbus_read_uuid_file_without_creating (const DBusString *filename,
544                                        DBusGUID         *uuid,
545                                        DBusError        *error)
546 {
547   DBusString contents;
548   DBusString decoded;
549   int end;
550   
551   _dbus_string_init (&contents);
552   _dbus_string_init (&decoded);
553   
554   if (!_dbus_file_get_contents (&contents, filename, error))
555     goto error;
556
557   _dbus_string_chop_white (&contents);
558
559   if (_dbus_string_get_length (&contents) != DBUS_UUID_LENGTH_HEX)
560     {
561       dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
562                       "UUID file '%s' should contain a hex string of length %d, not length %d, with no other text",
563                       _dbus_string_get_const_data (filename),
564                       DBUS_UUID_LENGTH_HEX,
565                       _dbus_string_get_length (&contents));
566       goto error;
567     }
568
569   if (!_dbus_string_hex_decode (&contents, 0, &end, &decoded, 0))
570     {
571       _DBUS_SET_OOM (error);
572       goto error;
573     }
574
575   if (end == 0)
576     {
577       dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
578                       "UUID file '%s' contains invalid hex data",
579                       _dbus_string_get_const_data (filename));
580       goto error;
581     }
582
583   if (_dbus_string_get_length (&decoded) != DBUS_UUID_LENGTH_BYTES)
584     {
585       dbus_set_error (error, DBUS_ERROR_INVALID_FILE_CONTENT,
586                       "UUID file '%s' contains %d bytes of hex-encoded data instead of %d",
587                       _dbus_string_get_const_data (filename),
588                       _dbus_string_get_length (&decoded),
589                       DBUS_UUID_LENGTH_BYTES);
590       goto error;
591     }
592
593   _dbus_string_copy_to_buffer (&decoded, uuid->as_bytes, DBUS_UUID_LENGTH_BYTES);
594
595   _dbus_string_free (&decoded);
596   _dbus_string_free (&contents);
597
598   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
599
600   return TRUE;
601   
602  error:
603   _DBUS_ASSERT_ERROR_IS_SET (error);
604   _dbus_string_free (&contents);
605   _dbus_string_free (&decoded);
606   return FALSE;
607 }
608
609 static dbus_bool_t
610 _dbus_create_uuid_file_exclusively (const DBusString *filename,
611                                     DBusGUID         *uuid,
612                                     DBusError        *error)
613 {
614   DBusString encoded;
615
616   _dbus_string_init (&encoded);
617
618   _dbus_generate_uuid (uuid);
619   
620   if (!_dbus_uuid_encode (uuid, &encoded))
621     {
622       _DBUS_SET_OOM (error);
623       goto error;
624     }
625   
626   /* FIXME this is racy; we need a save_file_exclusively
627    * function. But in practice this should be fine for now.
628    *
629    * - first be sure we can create the file and it
630    *   doesn't exist by creating it empty with O_EXCL
631    * - then create it by creating a temporary file and
632    *   overwriting atomically with rename()
633    */
634   if (!_dbus_create_file_exclusively (filename, error))
635     goto error;
636
637   if (!_dbus_string_append_byte (&encoded, '\n'))
638     {
639       _DBUS_SET_OOM (error);
640       goto error;
641     }
642   
643   if (!_dbus_string_save_to_file (&encoded, filename, error))
644     goto error;
645
646
647   _dbus_string_free (&encoded);
648
649   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
650   return TRUE;
651   
652  error:
653   _DBUS_ASSERT_ERROR_IS_SET (error);
654   _dbus_string_free (&encoded);
655   return FALSE;        
656 }
657
658 /**
659  * Reads (and optionally writes) a uuid to a file. Initializes the uuid
660  * unless an error is returned.
661  *
662  * @param filename the name of the file
663  * @param uuid uuid to be initialized with the loaded uuid
664  * @param create_if_not_found #TRUE to create a new uuid and save it if the file doesn't exist
665  * @param error the error return
666  * @returns #FALSE if the error is set
667  */
668 dbus_bool_t
669 _dbus_read_uuid_file (const DBusString *filename,
670                       DBusGUID         *uuid,
671                       dbus_bool_t       create_if_not_found,
672                       DBusError        *error)
673 {
674   DBusError read_error;
675
676   dbus_error_init (&read_error);
677
678   if (_dbus_read_uuid_file_without_creating (filename, uuid, &read_error))
679     return TRUE;
680
681   if (!create_if_not_found)
682     {
683       dbus_move_error (&read_error, error);
684       return FALSE;
685     }
686
687   /* If the file exists and contains junk, we want to keep that error
688    * message instead of overwriting it with a "file exists" error
689    * message when we try to write
690    */
691   if (dbus_error_has_name (&read_error, DBUS_ERROR_INVALID_FILE_CONTENT))
692     {
693       dbus_move_error (&read_error, error);
694       return FALSE;
695     }
696   else
697     {
698       dbus_error_free (&read_error);
699       return _dbus_create_uuid_file_exclusively (filename, uuid, error);
700     }
701 }
702
703 _DBUS_DEFINE_GLOBAL_LOCK (machine_uuid);
704 static int machine_uuid_initialized_generation = 0;
705 static DBusGUID machine_uuid;
706
707 /**
708  * Gets the hex-encoded UUID of the machine this function is
709  * executed on. This UUID is guaranteed to be the same for a given
710  * machine at least until it next reboots, though it also
711  * makes some effort to be the same forever, it may change if the
712  * machine is reconfigured or its hardware is modified.
713  * 
714  * @param uuid_str string to append hex-encoded machine uuid to
715  * @returns #FALSE if no memory
716  */
717 dbus_bool_t
718 _dbus_get_local_machine_uuid_encoded (DBusString *uuid_str)
719 {
720   dbus_bool_t ok;
721   
722   _DBUS_LOCK (machine_uuid);
723   if (machine_uuid_initialized_generation != _dbus_current_generation)
724     {
725       DBusError error;
726       dbus_error_init (&error);
727       if (!_dbus_read_local_machine_uuid (&machine_uuid, FALSE,
728                                           &error))
729         {          
730 #ifndef DBUS_BUILD_TESTS
731           /* For the test suite, we may not be installed so just continue silently
732            * here. But in a production build, we want to be nice and loud about
733            * this.
734            */
735           _dbus_warn_check_failed ("D-Bus library appears to be incorrectly set up; failed to read machine uuid: %s\n"
736                                    "See the manual page for dbus-uuidgen to correct this issue.\n",
737                                    error.message);
738 #endif
739           
740           dbus_error_free (&error);
741           
742           _dbus_generate_uuid (&machine_uuid);
743         }
744     }
745
746   ok = _dbus_uuid_encode (&machine_uuid, uuid_str);
747
748   _DBUS_UNLOCK (machine_uuid);
749
750   return ok;
751 }
752
753 #ifdef DBUS_BUILD_TESTS
754 /**
755  * Returns a string describing the given name.
756  *
757  * @param header_field the field to describe
758  * @returns a constant string describing the field
759  */
760 const char *
761 _dbus_header_field_to_string (int header_field)
762 {
763   switch (header_field)
764     {
765     case DBUS_HEADER_FIELD_INVALID:
766       return "invalid";
767     case DBUS_HEADER_FIELD_PATH:
768       return "path";
769     case DBUS_HEADER_FIELD_INTERFACE:
770       return "interface";
771     case DBUS_HEADER_FIELD_MEMBER:
772       return "member";
773     case DBUS_HEADER_FIELD_ERROR_NAME:
774       return "error-name";
775     case DBUS_HEADER_FIELD_REPLY_SERIAL:
776       return "reply-serial";
777     case DBUS_HEADER_FIELD_DESTINATION:
778       return "destination";
779     case DBUS_HEADER_FIELD_SENDER:
780       return "sender";
781     case DBUS_HEADER_FIELD_SIGNATURE:
782       return "signature";
783     default:
784       return "unknown";
785     }
786 }
787 #endif /* DBUS_BUILD_TESTS */
788
789 #ifndef DBUS_DISABLE_CHECKS
790 /** String used in _dbus_return_if_fail macro */
791 const char _dbus_return_if_fail_warning_format[] =
792 "arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
793 "This is normally a bug in some application using the D-Bus library.\n";
794 #endif
795
796 #ifndef DBUS_DISABLE_ASSERT
797 /**
798  * Internals of _dbus_assert(); it's a function
799  * rather than a macro with the inline code so
800  * that the assertion failure blocks don't show up
801  * in test suite coverage, and to shrink code size.
802  *
803  * @param condition TRUE if assertion succeeded
804  * @param condition_text condition as a string
805  * @param file file the assertion is in
806  * @param line line the assertion is in
807  * @param func function the assertion is in
808  */
809 void
810 _dbus_real_assert (dbus_bool_t  condition,
811                    const char  *condition_text,
812                    const char  *file,
813                    int          line,
814                    const char  *func)
815 {
816   if (_DBUS_UNLIKELY (!condition))
817     {
818       _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
819                   _dbus_getpid (), condition_text, file, line, func);
820       _dbus_abort ();
821     }
822 }
823
824 /**
825  * Internals of _dbus_assert_not_reached(); it's a function
826  * rather than a macro with the inline code so
827  * that the assertion failure blocks don't show up
828  * in test suite coverage, and to shrink code size.
829  *
830  * @param explanation what was reached that shouldn't have been
831  * @param file file the assertion is in
832  * @param line line the assertion is in
833  */
834 void
835 _dbus_real_assert_not_reached (const char *explanation,
836                                const char *file,
837                                int         line)
838 {
839   _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
840               file, line, _dbus_getpid (), explanation);
841   _dbus_abort ();
842 }
843 #endif /* DBUS_DISABLE_ASSERT */
844   
845 #ifdef DBUS_BUILD_TESTS
846 static dbus_bool_t
847 run_failing_each_malloc (int                    n_mallocs,
848                          const char            *description,
849                          DBusTestMemoryFunction func,
850                          void                  *data)
851 {
852   n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
853   
854   while (n_mallocs >= 0)
855     {      
856       _dbus_set_fail_alloc_counter (n_mallocs);
857
858       _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
859                      description, n_mallocs,
860                      _dbus_get_fail_alloc_failures ());
861
862       if (!(* func) (data))
863         return FALSE;
864       
865       n_mallocs -= 1;
866     }
867
868   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
869
870   return TRUE;
871 }                        
872
873 /**
874  * Tests how well the given function responds to out-of-memory
875  * situations. Calls the function repeatedly, failing a different
876  * call to malloc() each time. If the function ever returns #FALSE,
877  * the test fails. The function should return #TRUE whenever something
878  * valid (such as returning an error, or succeeding) occurs, and #FALSE
879  * if it gets confused in some way.
880  *
881  * @param description description of the test used in verbose output
882  * @param func function to call
883  * @param data data to pass to function
884  * @returns #TRUE if the function never returns FALSE
885  */
886 dbus_bool_t
887 _dbus_test_oom_handling (const char             *description,
888                          DBusTestMemoryFunction  func,
889                          void                   *data)
890 {
891   int approx_mallocs;
892   const char *setting;
893   int max_failures_to_try;
894   int i;
895
896   /* Run once to see about how many mallocs are involved */
897   
898   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
899
900   _dbus_verbose ("Running once to count mallocs\n");
901   
902   if (!(* func) (data))
903     return FALSE;
904   
905   approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
906
907   _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
908                  description, approx_mallocs);
909
910   setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
911   if (setting != NULL)
912     {
913       DBusString str;
914       long v;
915       _dbus_string_init_const (&str, setting);
916       v = 4;
917       if (!_dbus_string_parse_int (&str, 0, &v, NULL))
918         _dbus_warn ("couldn't parse '%s' as integer\n", setting);
919       max_failures_to_try = v;
920     }
921   else
922     {
923       max_failures_to_try = 4;
924     }
925
926   i = setting ? max_failures_to_try - 1 : 1;
927   while (i < max_failures_to_try)
928     {
929       _dbus_set_fail_alloc_failures (i);
930       if (!run_failing_each_malloc (approx_mallocs, description, func, data))
931         return FALSE;
932       ++i;
933     }
934   
935   _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
936                  description);
937
938   return TRUE;
939 }
940 #endif /* DBUS_BUILD_TESTS */
941
942 /** @} */