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