1e1753da20062a74604c2987b3b1ea8fe2904432
[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_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 /**
198  * Prints a warning message to stderr.
199  *
200  * @param format printf-style format string.
201  */
202 void
203 _dbus_warn (const char *format,
204             ...)
205 {
206   /* FIXME not portable enough? */
207   va_list args;
208
209   va_start (args, format);
210   vfprintf (stderr, format, args);
211   va_end (args);
212 }
213
214 #ifdef DBUS_ENABLE_VERBOSE_MODE
215
216 static dbus_bool_t verbose_initted = FALSE;
217
218 /**
219  * Prints a warning message to stderr
220  * if the user has enabled verbose mode.
221  * This is the real function implementation,
222  * use _dbus_verbose() macro in code.
223  *
224  * @param format printf-style format string.
225  */
226 void
227 _dbus_verbose_real (const char *format,
228                     ...)
229 {
230   va_list args;
231   static dbus_bool_t verbose = TRUE;
232   static dbus_bool_t need_pid = TRUE;
233   int len;
234   
235   /* things are written a bit oddly here so that
236    * in the non-verbose case we just have the one
237    * conditional and return immediately.
238    */
239   if (!verbose)
240     return;
241   
242   if (!verbose_initted)
243     {
244       verbose = _dbus_getenv ("DBUS_VERBOSE") != NULL;
245       verbose_initted = TRUE;
246       if (!verbose)
247         return;
248     }
249
250   /* Print out pid before the line */
251   if (need_pid)
252     fprintf (stderr, "%lu: ", _dbus_getpid ());
253
254   /* Only print pid again if the next line is a new line */
255   len = strlen (format);
256   if (format[len-1] == '\n')
257     need_pid = TRUE;
258   else
259     need_pid = FALSE;
260   
261   va_start (args, format);
262   vfprintf (stderr, format, args);
263   va_end (args);
264
265   fflush (stderr);
266 }
267
268 /**
269  * Reinitializes the verbose logging code, used
270  * as a hack in dbus-spawn.c so that a child
271  * process re-reads its pid
272  *
273  */
274 void
275 _dbus_verbose_reset_real (void)
276 {
277   verbose_initted = FALSE;
278 }
279
280 #endif /* DBUS_ENABLE_VERBOSE_MODE */
281
282 /**
283  * Duplicates a string. Result must be freed with
284  * dbus_free(). Returns #NULL if memory allocation fails.
285  * If the string to be duplicated is #NULL, returns #NULL.
286  * 
287  * @param str string to duplicate.
288  * @returns newly-allocated copy.
289  */
290 char*
291 _dbus_strdup (const char *str)
292 {
293   size_t len;
294   char *copy;
295   
296   if (str == NULL)
297     return NULL;
298   
299   len = strlen (str);
300
301   copy = dbus_malloc (len + 1);
302   if (copy == NULL)
303     return NULL;
304
305   memcpy (copy, str, len + 1);
306   
307   return copy;
308 }
309
310 /**
311  * Duplicates a block of memory. Returns
312  * #NULL on failure.
313  *
314  * @param mem memory to copy
315  * @param n_bytes number of bytes to copy
316  * @returns the copy
317  */
318 void*
319 _dbus_memdup (const void  *mem,
320               size_t       n_bytes)
321 {
322   void *copy;
323
324   copy = dbus_malloc (n_bytes);
325   if (copy == NULL)
326     return NULL;
327
328   memcpy (copy, mem, n_bytes);
329   
330   return copy;
331 }
332
333 /**
334  * Duplicates a string array. Result may be freed with
335  * dbus_free_string_array(). Returns #NULL if memory allocation fails.
336  * If the array to be duplicated is #NULL, returns #NULL.
337  * 
338  * @param array array to duplicate.
339  * @returns newly-allocated copy.
340  */
341 char**
342 _dbus_dup_string_array (const char **array)
343 {
344   int len;
345   int i;
346   char **copy;
347   
348   if (array == NULL)
349     return NULL;
350
351   for (len = 0; array[len] != NULL; ++len)
352     ;
353
354   copy = dbus_new0 (char*, len + 1);
355   if (copy == NULL)
356     return NULL;
357
358   i = 0;
359   while (i < len)
360     {
361       copy[i] = _dbus_strdup (array[i]);
362       if (copy[i] == NULL)
363         {
364           dbus_free_string_array (copy);
365           return NULL;
366         }
367
368       ++i;
369     }
370
371   return copy;
372 }
373
374 /**
375  * Checks whether a string array contains the given string.
376  * 
377  * @param array array to search.
378  * @param str string to look for
379  * @returns #TRUE if array contains string
380  */
381 dbus_bool_t
382 _dbus_string_array_contains (const char **array,
383                              const char  *str)
384 {
385   int i;
386
387   i = 0;
388   while (array[i] != NULL)
389     {
390       if (strcmp (array[i], str) == 0)
391         return TRUE;
392       ++i;
393     }
394
395   return FALSE;
396 }
397
398 #ifdef DBUS_BUILD_TESTS
399 /**
400  * Returns a string describing the given name.
401  *
402  * @param header_field the field to describe
403  * @returns a constant string describing the field
404  */
405 const char *
406 _dbus_header_field_to_string (int header_field)
407 {
408   switch (header_field)
409     {
410     case DBUS_HEADER_FIELD_INVALID:
411       return "invalid";
412     case DBUS_HEADER_FIELD_PATH:
413       return "path";
414     case DBUS_HEADER_FIELD_INTERFACE:
415       return "interface";
416     case DBUS_HEADER_FIELD_MEMBER:
417       return "member";
418     case DBUS_HEADER_FIELD_ERROR_NAME:
419       return "error-name";
420     case DBUS_HEADER_FIELD_REPLY_SERIAL:
421       return "reply-serial";
422     case DBUS_HEADER_FIELD_DESTINATION:
423       return "destination";
424     case DBUS_HEADER_FIELD_SENDER:
425       return "sender";
426     case DBUS_HEADER_FIELD_SIGNATURE:
427       return "signature";
428     default:
429       return "unknown";
430     }
431 }
432 #endif /* DBUS_BUILD_TESTS */
433
434 #ifndef DBUS_DISABLE_CHECKS
435 /** String used in _dbus_return_if_fail macro */
436 const char _dbus_return_if_fail_warning_format[] =
437 "%lu: arguments to %s() were incorrect, assertion \"%s\" failed in file %s line %d.\n"
438 "This is normally a bug in some application using the D-BUS library.\n";
439 #endif
440
441 #ifndef DBUS_DISABLE_ASSERT
442 /**
443  * Internals of _dbus_assert(); it's a function
444  * rather than a macro with the inline code so
445  * that the assertion failure blocks don't show up
446  * in test suite coverage, and to shrink code size.
447  *
448  * @param condition TRUE if assertion succeeded
449  * @param condition_text condition as a string
450  * @param file file the assertion is in
451  * @param line line the assertion is in
452  * @param func function the assertion is in
453  */
454 void
455 _dbus_real_assert (dbus_bool_t  condition,
456                    const char  *condition_text,
457                    const char  *file,
458                    int          line,
459                    const char  *func)
460 {
461   if (_DBUS_UNLIKELY (!condition))
462     {
463       _dbus_warn ("%lu: assertion failed \"%s\" file \"%s\" line %d function %s\n",
464                   _dbus_getpid (), condition_text, file, line, func);
465       _dbus_abort ();
466     }
467 }
468
469 /**
470  * Internals of _dbus_assert_not_reached(); it's a function
471  * rather than a macro with the inline code so
472  * that the assertion failure blocks don't show up
473  * in test suite coverage, and to shrink code size.
474  *
475  * @param explanation what was reached that shouldn't have been
476  * @param file file the assertion is in
477  * @param line line the assertion is in
478  */
479 void
480 _dbus_real_assert_not_reached (const char *explanation,
481                                const char *file,
482                                int         line)
483 {
484   _dbus_warn ("File \"%s\" line %d process %lu should not have been reached: %s\n",
485               file, line, _dbus_getpid (), explanation);
486   _dbus_abort ();
487 }
488 #endif /* DBUS_DISABLE_ASSERT */
489   
490 #ifdef DBUS_BUILD_TESTS
491 static dbus_bool_t
492 run_failing_each_malloc (int                    n_mallocs,
493                          const char            *description,
494                          DBusTestMemoryFunction func,
495                          void                  *data)
496 {
497   n_mallocs += 10; /* fudge factor to ensure reallocs etc. are covered */
498   
499   while (n_mallocs >= 0)
500     {      
501       _dbus_set_fail_alloc_counter (n_mallocs);
502
503       _dbus_verbose ("\n===\n%s: (will fail malloc %d with %d failures)\n===\n",
504                      description, n_mallocs,
505                      _dbus_get_fail_alloc_failures ());
506
507       if (!(* func) (data))
508         return FALSE;
509       
510       n_mallocs -= 1;
511     }
512
513   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
514
515   return TRUE;
516 }                        
517
518 /**
519  * Tests how well the given function responds to out-of-memory
520  * situations. Calls the function repeatedly, failing a different
521  * call to malloc() each time. If the function ever returns #FALSE,
522  * the test fails. The function should return #TRUE whenever something
523  * valid (such as returning an error, or succeeding) occurs, and #FALSE
524  * if it gets confused in some way.
525  *
526  * @param description description of the test used in verbose output
527  * @param func function to call
528  * @param data data to pass to function
529  * @returns #TRUE if the function never returns FALSE
530  */
531 dbus_bool_t
532 _dbus_test_oom_handling (const char             *description,
533                          DBusTestMemoryFunction  func,
534                          void                   *data)
535 {
536   int approx_mallocs;
537   const char *setting;
538   int max_failures_to_try;
539   int i;
540
541   /* Run once to see about how many mallocs are involved */
542   
543   _dbus_set_fail_alloc_counter (_DBUS_INT_MAX);
544
545   _dbus_verbose ("Running once to count mallocs\n");
546   
547   if (!(* func) (data))
548     return FALSE;
549   
550   approx_mallocs = _DBUS_INT_MAX - _dbus_get_fail_alloc_counter ();
551
552   _dbus_verbose ("\n=================\n%s: about %d mallocs total\n=================\n",
553                  description, approx_mallocs);
554
555   setting = _dbus_getenv ("DBUS_TEST_MALLOC_FAILURES");
556   if (setting != NULL)
557     {
558       DBusString str;
559       long v;
560       _dbus_string_init_const (&str, setting);
561       v = 4;
562       if (!_dbus_string_parse_int (&str, 0, &v, NULL))
563         _dbus_warn ("couldn't parse '%s' as integer\n", setting);
564       max_failures_to_try = v;
565     }
566   else
567     {
568       max_failures_to_try = 4;
569     }
570
571   i = setting ? max_failures_to_try - 1 : 1;
572   while (i < max_failures_to_try)
573     {
574       _dbus_set_fail_alloc_failures (i);
575       if (!run_failing_each_malloc (approx_mallocs, description, func, data))
576         return FALSE;
577       ++i;
578     }
579   
580   _dbus_verbose ("\n=================\n%s: all iterations passed\n=================\n",
581                  description);
582
583   return TRUE;
584 }
585 #endif /* DBUS_BUILD_TESTS */
586
587 /** @} */