8567ebb5f486f2e11e5193eb9613faa2a07ef819
[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 /**
32  * @defgroup DBusInternals D-Bus internal implementation details
33  * @brief Documentation useful when developing or debugging D-Bus itself.
34  * 
35  */
36
37 /**
38  * @defgroup DBusInternalsUtils Utilities and portability
39  * @ingroup DBusInternals
40  * @brief Utility functions (_dbus_assert(), _dbus_warn(), etc.)
41  * @{
42  */
43
44 /**
45  * @def _dbus_assert
46  *
47  * Aborts with an error message if the condition is false.
48  * 
49  * @param condition condition which must be true.
50  */
51
52 /**
53  * @def _dbus_assert_not_reached
54  *
55  * Aborts with an error message if called.
56  * The given explanation will be printed.
57  * 
58  * @param explanation explanation of what happened if the code was reached.
59  */
60
61 /**
62  * @def _DBUS_N_ELEMENTS
63  *
64  * Computes the number of elements in a fixed-size array using
65  * sizeof().
66  *
67  * @param array the array to count elements in.
68  */
69
70 /**
71  * @def _DBUS_POINTER_TO_INT
72  *
73  * Safely casts a void* to an integer; should only be used on void*
74  * that actually contain integers, for example one created with
75  * _DBUS_INT_TO_POINTER.  Only guaranteed to preserve 32 bits.
76  * (i.e. it's used to store 32-bit ints in pointers, but
77  * can't be used to store 64-bit pointers in ints.)
78  *
79  * @param pointer pointer to extract an integer from.
80  */
81 /**
82  * @def _DBUS_INT_TO_POINTER
83  *
84  * Safely stuffs an integer into a pointer, to be extracted later with
85  * _DBUS_POINTER_TO_INT. Only guaranteed to preserve 32 bits.
86  *
87  * @param integer the integer to stuff into a pointer.
88  */
89 /**
90  * @def _DBUS_ZERO
91  *
92  * Sets all bits in an object to zero.
93  *
94  * @param object the object to be zeroed.
95  */
96 /**
97  * @def _DBUS_INT16_MIN
98  *
99  * Minimum value of type "int16"
100  */
101 /**
102  * @def _DBUS_INT16_MAX
103  *
104  * Maximum value of type "int16"
105  */
106 /**
107  * @def _DBUS_UINT16_MAX
108  *
109  * Maximum value of type "uint16"
110  */
111
112 /**
113  * @def _DBUS_INT32_MIN
114  *
115  * Minimum value of type "int32"
116  */
117 /**
118  * @def _DBUS_INT32_MAX
119  *
120  * Maximum value of type "int32"
121  */
122 /**
123  * @def _DBUS_UINT32_MAX
124  *
125  * Maximum value of type "uint32"
126  */
127
128 /**
129  * @def _DBUS_INT_MIN
130  *
131  * Minimum value of type "int"
132  */
133 /**
134  * @def _DBUS_INT_MAX
135  *
136  * Maximum value of type "int"
137  */
138 /**
139  * @def _DBUS_UINT_MAX
140  *
141  * Maximum value of type "uint"
142  */
143
144 /**
145  * @typedef DBusForeachFunction
146  * 
147  * Used to iterate over each item in a collection, such as
148  * a DBusList.
149  */
150
151 /**
152  * @def _DBUS_LOCK_NAME
153  *
154  * Expands to name of a global lock variable.
155  */
156
157 /**
158  * @def _DBUS_DEFINE_GLOBAL_LOCK
159  *
160  * Defines a global lock variable with the given name.
161  * The lock must be added to the list to initialize
162  * in dbus_threads_init().
163  */
164
165 /**
166  * @def _DBUS_DECLARE_GLOBAL_LOCK
167  *
168  * Expands to declaration of a global lock defined
169  * with _DBUS_DEFINE_GLOBAL_LOCK.
170  * The lock must be added to the list to initialize
171  * in dbus_threads_init().
172  */
173
174 /**
175  * @def _DBUS_LOCK
176  *
177  * Locks a global lock
178  */
179
180 /**
181  * @def _DBUS_UNLOCK
182  *
183  * Unlocks a global lock
184  */
185
186 /**
187  * Fixed "out of memory" error message, just to avoid
188  * making up a different string every time and wasting
189  * space.
190  */
191 const char _dbus_no_memory_message[] = "Not enough memory";
192
193 /**
194  * Prints a warning message to stderr.
195  *
196  * @param format printf-style format string.
197  */
198 void
199 _dbus_warn (const char *format,
200             ...)
201 {
202   /* FIXME not portable enough? */
203   va_list args;
204
205   va_start (args, format);
206   vfprintf (stderr, format, args);
207   va_end (args);
208 }
209
210 #ifdef DBUS_ENABLE_VERBOSE_MODE
211
212 static dbus_bool_t verbose_initted = FALSE;
213 static dbus_bool_t verbose = TRUE;
214
215 #define PTHREAD_IN_VERBOSE 0
216 #if PTHREAD_IN_VERBOSE
217 #include <pthread.h>
218 #endif
219
220 static inline void
221 _dbus_verbose_init (void)
222 {
223   if (!verbose_initted)
224     {
225       const char *p = _dbus_getenv ("DBUS_VERBOSE"); 
226       verbose = p != NULL && *p == '1';
227       verbose_initted = TRUE;
228     }
229 }
230
231 dbus_bool_t
232 _dbus_is_verbose_real (void)
233 {
234   _dbus_verbose_init ();
235   return verbose;
236 }
237
238 /**
239  * Prints a warning message to stderr
240  * if the user has enabled verbose mode.
241  * This is the real function implementation,
242  * use _dbus_verbose() macro in code.
243  *
244  * @param format printf-style format string.
245  */
246 void
247 _dbus_verbose_real (const char *format,
248                     ...)
249 {
250   va_list args;
251   static dbus_bool_t need_pid = TRUE;
252   int len;
253   
254   /* things are written a bit oddly here so that
255    * in the non-verbose case we just have the one
256    * conditional and return immediately.
257    */
258   if (!_dbus_is_verbose_real())
259     return;
260
261   /* Print out pid before the line */
262   if (need_pid)
263     {
264 #if PTHREAD_IN_VERBOSE
265       fprintf (stderr, "%lu: 0x%lx: ", _dbus_getpid (), pthread_self ());
266 #else
267       fprintf (stderr, "%lu: ", _dbus_getpid ());
268 #endif
269     }
270       
271
272   /* Only print pid again if the next line is a new line */
273   len = strlen (format);
274   if (format[len-1] == '\n')
275     need_pid = TRUE;
276   else
277     need_pid = FALSE;
278   
279   va_start (args, format);
280   vfprintf (stderr, format, args);
281   va_end (args);
282
283   fflush (stderr);
284 }
285
286 /**
287  * Reinitializes the verbose logging code, used
288  * as a hack in dbus-spawn.c so that a child
289  * process re-reads its pid
290  *
291  */
292 void
293 _dbus_verbose_reset_real (void)
294 {
295   verbose_initted = FALSE;
296 }
297
298 #endif /* DBUS_ENABLE_VERBOSE_MODE */
299
300 /**
301  * Duplicates a string. Result must be freed with
302  * dbus_free(). Returns #NULL if memory allocation fails.
303  * If the string to be duplicated is #NULL, returns #NULL.
304  * 
305  * @param str string to duplicate.
306  * @returns newly-allocated copy.
307  */
308 char*
309 _dbus_strdup (const char *str)
310 {
311   size_t len;
312   char *copy;
313   
314   if (str == NULL)
315     return NULL;
316   
317   len = strlen (str);
318
319   copy = dbus_malloc (len + 1);
320   if (copy == NULL)
321     return NULL;
322
323   memcpy (copy, str, len + 1);
324   
325   return copy;
326 }
327
328 /**
329  * Duplicates a block of memory. Returns
330  * #NULL on failure.
331  *
332  * @param mem memory to copy
333  * @param n_bytes number of bytes to copy
334  * @returns the copy
335  */
336 void*
337 _dbus_memdup (const void  *mem,
338               size_t       n_bytes)
339 {
340   void *copy;
341
342   copy = dbus_malloc (n_bytes);
343   if (copy == NULL)
344     return NULL;
345
346   memcpy (copy, mem, n_bytes);
347   
348   return copy;
349 }
350
351 /**
352  * Duplicates a string array. Result may be freed with
353  * dbus_free_string_array(). Returns #NULL if memory allocation fails.
354  * If the array to be duplicated is #NULL, returns #NULL.
355  * 
356  * @param array array to duplicate.
357  * @returns newly-allocated copy.
358  */
359 char**
360 _dbus_dup_string_array (const char **array)
361 {
362   int len;
363   int i;
364   char **copy;
365   
366   if (array == NULL)
367     return NULL;
368
369   for (len = 0; array[len] != NULL; ++len)
370     ;
371
372   copy = dbus_new0 (char*, len + 1);
373   if (copy == NULL)
374     return NULL;
375
376   i = 0;
377   while (i < len)
378     {
379       copy[i] = _dbus_strdup (array[i]);
380       if (copy[i] == NULL)
381         {
382           dbus_free_string_array (copy);
383           return NULL;
384         }
385
386       ++i;
387     }
388
389   return copy;
390 }
391
392 /**
393  * Checks whether a string array contains the given string.
394  * 
395  * @param array array to search.
396  * @param str string to look for
397  * @returns #TRUE if array contains string
398  */
399 dbus_bool_t
400 _dbus_string_array_contains (const char **array,
401                              const char  *str)
402 {
403   int i;
404
405   i = 0;
406   while (array[i] != NULL)
407     {
408       if (strcmp (array[i], str) == 0)
409         return TRUE;
410       ++i;
411     }
412
413   return FALSE;
414 }
415
416 #ifdef DBUS_BUILD_TESTS
417 /**
418  * Returns a string describing the given name.
419  *
420  * @param header_field the field to describe
421  * @returns a constant string describing the field
422  */
423 const char *
424 _dbus_header_field_to_string (int header_field)
425 {
426   switch (header_field)
427     {
428     case DBUS_HEADER_FIELD_INVALID:
429       return "invalid";
430     case DBUS_HEADER_FIELD_PATH:
431       return "path";
432     case DBUS_HEADER_FIELD_INTERFACE:
433       return "interface";
434     case DBUS_HEADER_FIELD_MEMBER:
435       return "member";
436     case DBUS_HEADER_FIELD_ERROR_NAME:
437       return "error-name";
438     case DBUS_HEADER_FIELD_REPLY_SERIAL:
439       return "reply-serial";
440     case DBUS_HEADER_FIELD_DESTINATION:
441       return "destination";
442     case DBUS_HEADER_FIELD_SENDER:
443       return "sender";
444     case DBUS_HEADER_FIELD_SIGNATURE:
445       return "signature";
446     default:
447       return "unknown";
448     }
449 }
450 #endif /* DBUS_BUILD_TESTS */
451
452 #ifndef DBUS_DISABLE_CHECKS
453 /** String used in _dbus_return_if_fail macro */
454 const char _dbus_return_if_fail_warning_format[] =
455 "%lu: arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
456 "This is normally a bug in some application using the D-Bus library.\n";
457 #endif
458
459 #ifndef DBUS_DISABLE_ASSERT
460 /**
461  * Internals of _dbus_assert(); it's a function
462  * rather than a macro with the inline code so
463  * that the assertion failure blocks don't show up
464  * in test suite coverage, and to shrink code size.
465  *
466  * @param condition TRUE if assertion succeeded
467  * @param condition_text condition as a string
468  * @param file file the assertion is in
469  * @param line line the assertion is in
470  * @param func function the assertion is in
471  */
472 void
473 _dbus_real_assert (dbus_bool_t  condition,
474                    const char  *condition_text,
475                    const char  *file,
476                    int          line,
477                    const char  *func)
478 {
479   if (_DBUS_UNLIKELY (!condition))
480     {
481       _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
482                   _dbus_getpid (), condition_text, file, line, func);
483       _dbus_abort ();
484     }
485 }
486
487 /**
488  * Internals of _dbus_assert_not_reached(); it's a function
489  * rather than a macro with the inline code so
490  * that the assertion failure blocks don't show up
491  * in test suite coverage, and to shrink code size.
492  *
493  * @param explanation what was reached that shouldn't have been
494  * @param file file the assertion is in
495  * @param line line the assertion is in
496  */
497 void
498 _dbus_real_assert_not_reached (const char *explanation,
499                                const char *file,
500                                int         line)
501 {
502   _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
503               file, line, _dbus_getpid (), explanation);
504   _dbus_abort ();
505 }
506 #endif /* DBUS_DISABLE_ASSERT */
507   
508 #ifdef DBUS_BUILD_TESTS
509 static dbus_bool_t
510 run_failing_each_malloc (int                    n_mallocs,
511                          const char            *description,
512                          DBusTestMemoryFunction func,
513                          void                  *data)
514 {
515   n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
516   
517   while (n_mallocs >= 0)
518     {      
519       _dbus_set_fail_alloc_counter (n_mallocs);
520
521       _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
522                      description, n_mallocs,
523                      _dbus_get_fail_alloc_failures ());
524
525       if (!(* func) (data))
526         return FALSE;
527       
528       n_mallocs -= 1;
529     }
530
531   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
532
533   return TRUE;
534 }                        
535
536 /**
537  * Tests how well the given function responds to out-of-memory
538  * situations. Calls the function repeatedly, failing a different
539  * call to malloc() each time. If the function ever returns #FALSE,
540  * the test fails. The function should return #TRUE whenever something
541  * valid (such as returning an error, or succeeding) occurs, and #FALSE
542  * if it gets confused in some way.
543  *
544  * @param description description of the test used in verbose output
545  * @param func function to call
546  * @param data data to pass to function
547  * @returns #TRUE if the function never returns FALSE
548  */
549 dbus_bool_t
550 _dbus_test_oom_handling (const char             *description,
551                          DBusTestMemoryFunction  func,
552                          void                   *data)
553 {
554   int approx_mallocs;
555   const char *setting;
556   int max_failures_to_try;
557   int i;
558
559   /* Run once to see about how many mallocs are involved */
560   
561   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
562
563   _dbus_verbose ("Running once to count mallocs\n");
564   
565   if (!(* func) (data))
566     return FALSE;
567   
568   approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
569
570   _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
571                  description, approx_mallocs);
572
573   setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
574   if (setting != NULL)
575     {
576       DBusString str;
577       long v;
578       _dbus_string_init_const (&str, setting);
579       v = 4;
580       if (!_dbus_string_parse_int (&str, 0, &v, NULL))
581         _dbus_warn ("couldn't parse '%s' as integer\n", setting);
582       max_failures_to_try = v;
583     }
584   else
585     {
586       max_failures_to_try = 4;
587     }
588
589   i = setting ? max_failures_to_try - 1 : 1;
590   while (i < max_failures_to_try)
591     {
592       _dbus_set_fail_alloc_failures (i);
593       if (!run_failing_each_malloc (approx_mallocs, description, func, data))
594         return FALSE;
595       ++i;
596     }
597   
598   _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
599                  description);
600
601   return TRUE;
602 }
603 #endif /* DBUS_BUILD_TESTS */
604
605 /** @} */