2005-01-16 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 <sys/types.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <stdlib.h>
34
35 /**
36  * @defgroup DBusInternals D-BUS 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_INT_MIN
102  *
103  * Minimum value of type "int"
104  */
105 /**
106  * @def _DBUS_INT_MAX
107  *
108  * Maximum value of type "int"
109  */
110
111 /**
112  * @typedef DBusForeachFunction
113  * 
114  * Used to iterate over each item in a collection, such as
115  * a DBusList.
116  */
117
118 /**
119  * @def _DBUS_LOCK_NAME
120  *
121  * Expands to name of a global lock variable.
122  */
123
124 /**
125  * @def _DBUS_DEFINE_GLOBAL_LOCK
126  *
127  * Defines a global lock variable with the given name.
128  * The lock must be added to the list to initialize
129  * in dbus_threads_init().
130  */
131
132 /**
133  * @def _DBUS_DECLARE_GLOBAL_LOCK
134  *
135  * Expands to declaration of a global lock defined
136  * with _DBUS_DEFINE_GLOBAL_LOCK.
137  * The lock must be added to the list to initialize
138  * in dbus_threads_init().
139  */
140
141 /**
142  * @def _DBUS_LOCK
143  *
144  * Locks a global lock
145  */
146
147 /**
148  * @def _DBUS_UNLOCK
149  *
150  * Unlocks a global lock
151  */
152
153 /**
154  * Fixed "out of memory" error message, just to avoid
155  * making up a different string every time and wasting
156  * space.
157  */
158 const char _dbus_no_memory_message[] = "Not enough memory";
159
160 /**
161  * Prints a warning message to stderr.
162  *
163  * @param format printf-style format string.
164  */
165 void
166 _dbus_warn (const char *format,
167             ...)
168 {
169   /* FIXME not portable enough? */
170   va_list args;
171
172   va_start (args, format);
173   vfprintf (stderr, format, args);
174   va_end (args);
175 }
176
177 #ifdef DBUS_ENABLE_VERBOSE_MODE
178
179 static dbus_bool_t verbose_initted = FALSE;
180
181 /**
182  * Prints a warning message to stderr
183  * if the user has enabled verbose mode.
184  * This is the real function implementation,
185  * use _dbus_verbose() macro in code.
186  *
187  * @param format printf-style format string.
188  */
189 void
190 _dbus_verbose_real (const char *format,
191                     ...)
192 {
193   va_list args;
194   static dbus_bool_t verbose = TRUE;
195   static dbus_bool_t need_pid = TRUE;
196   int len;
197   
198   /* things are written a bit oddly here so that
199    * in the non-verbose case we just have the one
200    * conditional and return immediately.
201    */
202   if (!verbose)
203     return;
204   
205   if (!verbose_initted)
206     {
207       verbose = _dbus_getenv ("DBUS_VERBOSE") != NULL;
208       verbose_initted = TRUE;
209       if (!verbose)
210         return;
211     }
212
213   /* Print out pid before the line */
214   if (need_pid)
215     fprintf (stderr, "%lu: ", _dbus_getpid ());
216
217   /* Only print pid again if the next line is a new line */
218   len = strlen (format);
219   if (format[len-1] == '\n')
220     need_pid = TRUE;
221   else
222     need_pid = FALSE;
223   
224   va_start (args, format);
225   vfprintf (stderr, format, args);
226   va_end (args);
227
228   fflush (stderr);
229 }
230
231 /**
232  * Reinitializes the verbose logging code, used
233  * as a hack in dbus-spawn.c so that a child
234  * process re-reads its pid
235  *
236  */
237 void
238 _dbus_verbose_reset_real (void)
239 {
240   verbose_initted = FALSE;
241 }
242
243 #endif /* DBUS_ENABLE_VERBOSE_MODE */
244
245 /**
246  * Duplicates a string. Result must be freed with
247  * dbus_free(). Returns #NULL if memory allocation fails.
248  * If the string to be duplicated is #NULL, returns #NULL.
249  * 
250  * @param str string to duplicate.
251  * @returns newly-allocated copy.
252  */
253 char*
254 _dbus_strdup (const char *str)
255 {
256   size_t len;
257   char *copy;
258   
259   if (str == NULL)
260     return NULL;
261   
262   len = strlen (str);
263
264   copy = dbus_malloc (len + 1);
265   if (copy == NULL)
266     return NULL;
267
268   memcpy (copy, str, len + 1);
269   
270   return copy;
271 }
272
273 /**
274  * Duplicates a block of memory. Returns
275  * #NULL on failure.
276  *
277  * @param mem memory to copy
278  * @param n_bytes number of bytes to copy
279  * @returns the copy
280  */
281 void*
282 _dbus_memdup (const void  *mem,
283               size_t       n_bytes)
284 {
285   void *copy;
286
287   copy = dbus_malloc (n_bytes);
288   if (copy == NULL)
289     return NULL;
290
291   memcpy (copy, mem, n_bytes);
292   
293   return copy;
294 }
295
296 /**
297  * Duplicates a string array. Result may be freed with
298  * dbus_free_string_array(). Returns #NULL if memory allocation fails.
299  * If the array to be duplicated is #NULL, returns #NULL.
300  * 
301  * @param array array to duplicate.
302  * @returns newly-allocated copy.
303  */
304 char**
305 _dbus_dup_string_array (const char **array)
306 {
307   int len;
308   int i;
309   char **copy;
310   
311   if (array == NULL)
312     return NULL;
313
314   for (len = 0; array[len] != NULL; ++len)
315     ;
316
317   copy = dbus_new0 (char*, len + 1);
318   if (copy == NULL)
319     return NULL;
320
321   i = 0;
322   while (i < len)
323     {
324       copy[i] = _dbus_strdup (array[i]);
325       if (copy[i] == NULL)
326         {
327           dbus_free_string_array (copy);
328           return NULL;
329         }
330
331       ++i;
332     }
333
334   return copy;
335 }
336
337 /**
338  * Checks whether a string array contains the given string.
339  * 
340  * @param array array to search.
341  * @param str string to look for
342  * @returns #TRUE if array contains string
343  */
344 dbus_bool_t
345 _dbus_string_array_contains (const char **array,
346                              const char  *str)
347 {
348   int i;
349
350   i = 0;
351   while (array[i] != NULL)
352     {
353       if (strcmp (array[i], str) == 0)
354         return TRUE;
355       ++i;
356     }
357
358   return FALSE;
359 }
360
361 #ifdef DBUS_BUILD_TESTS
362 /**
363  * Returns a string describing the given name.
364  *
365  * @param header_field the field to describe
366  * @returns a constant string describing the field
367  */
368 const char *
369 _dbus_header_field_to_string (int header_field)
370 {
371   switch (header_field)
372     {
373     case DBUS_HEADER_FIELD_INVALID:
374       return "invalid";
375     case DBUS_HEADER_FIELD_PATH:
376       return "path";
377     case DBUS_HEADER_FIELD_INTERFACE:
378       return "interface";
379     case DBUS_HEADER_FIELD_MEMBER:
380       return "member";
381     case DBUS_HEADER_FIELD_ERROR_NAME:
382       return "error-name";
383     case DBUS_HEADER_FIELD_REPLY_SERIAL:
384       return "reply-serial";
385     case DBUS_HEADER_FIELD_DESTINATION:
386       return "destination";
387     case DBUS_HEADER_FIELD_SENDER:
388       return "sender";
389     case DBUS_HEADER_FIELD_SIGNATURE:
390       return "signature";
391     default:
392       return "unknown";
393     }
394 }
395 #endif /* DBUS_BUILD_TESTS */
396
397 #ifndef DBUS_DISABLE_CHECKS
398 /** String used in _dbus_return_if_fail macro */
399 const char _dbus_return_if_fail_warning_format[] =
400 "%lu: arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
401 "This is normally a bug in some application using the D-BUS library.\n";
402 #endif
403
404 #ifndef DBUS_DISABLE_ASSERT
405 /**
406  * Internals of _dbus_assert(); it's a function
407  * rather than a macro with the inline code so
408  * that the assertion failure blocks don't show up
409  * in test suite coverage, and to shrink code size.
410  *
411  * @param condition TRUE if assertion succeeded
412  * @param condition_text condition as a string
413  * @param file file the assertion is in
414  * @param line line the assertion is in
415  * @param func function the assertion is in
416  */
417 void
418 _dbus_real_assert (dbus_bool_t  condition,
419                    const char  *condition_text,
420                    const char  *file,
421                    int          line,
422                    const char  *func)
423 {
424   if (_DBUS_UNLIKELY (!condition))
425     {
426       _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
427                   _dbus_getpid (), condition_text, file, line, func);
428       _dbus_abort ();
429     }
430 }
431
432 /**
433  * Internals of _dbus_assert_not_reached(); it's a function
434  * rather than a macro with the inline code so
435  * that the assertion failure blocks don't show up
436  * in test suite coverage, and to shrink code size.
437  *
438  * @param explanation what was reached that shouldn't have been
439  * @param file file the assertion is in
440  * @param line line the assertion is in
441  */
442 void
443 _dbus_real_assert_not_reached (const char *explanation,
444                                const char *file,
445                                int         line)
446 {
447   _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
448               file, line, _dbus_getpid (), explanation);
449   _dbus_abort ();
450 }
451 #endif /* DBUS_DISABLE_ASSERT */
452   
453 #ifdef DBUS_BUILD_TESTS
454 static dbus_bool_t
455 run_failing_each_malloc (int                    n_mallocs,
456                          const char            *description,
457                          DBusTestMemoryFunction func,
458                          void                  *data)
459 {
460   n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
461   
462   while (n_mallocs >= 0)
463     {      
464       _dbus_set_fail_alloc_counter (n_mallocs);
465
466       _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
467                      description, n_mallocs,
468                      _dbus_get_fail_alloc_failures ());
469
470       if (!(* func) (data))
471         return FALSE;
472       
473       n_mallocs -= 1;
474     }
475
476   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
477
478   return TRUE;
479 }                        
480
481 /**
482  * Tests how well the given function responds to out-of-memory
483  * situations. Calls the function repeatedly, failing a different
484  * call to malloc() each time. If the function ever returns #FALSE,
485  * the test fails. The function should return #TRUE whenever something
486  * valid (such as returning an error, or succeeding) occurs, and #FALSE
487  * if it gets confused in some way.
488  *
489  * @param description description of the test used in verbose output
490  * @param func function to call
491  * @param data data to pass to function
492  * @returns #TRUE if the function never returns FALSE
493  */
494 dbus_bool_t
495 _dbus_test_oom_handling (const char             *description,
496                          DBusTestMemoryFunction  func,
497                          void                   *data)
498 {
499   int approx_mallocs;
500   const char *setting;
501   int max_failures_to_try;
502   int i;
503
504   /* Run once to see about how many mallocs are involved */
505   
506   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
507
508   _dbus_verbose ("Running once to count mallocs\n");
509   
510   if (!(* func) (data))
511     return FALSE;
512   
513   approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
514
515   _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
516                  description, approx_mallocs);
517
518   setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
519   if (setting != NULL)
520     {
521       DBusString str;
522       long v;
523       _dbus_string_init_const (&str, setting);
524       v = 4;
525       if (!_dbus_string_parse_int (&str, 0, &v, NULL))
526         _dbus_warn ("couldn't parse '%s' as integer\n", setting);
527       max_failures_to_try = v;
528     }
529   else
530     {
531       max_failures_to_try = 4;
532     }
533
534   i = setting ? max_failures_to_try - 1 : 1;
535   while (i < max_failures_to_try)
536     {
537       _dbus_set_fail_alloc_failures (i);
538       if (!run_failing_each_malloc (approx_mallocs, description, func, data))
539         return FALSE;
540       ++i;
541     }
542   
543   _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
544                  description);
545
546   return TRUE;
547 }
548 #endif /* DBUS_BUILD_TESTS */
549
550 /** @} */