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