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