2003-03-12 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 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  * @def _DBUS_MAX_SUN_PATH_LENGTH
112  *
113  * Maximum length of the path to a UNIX domain socket,
114  * sockaddr_un::sun_path member. POSIX requires that all systems
115  * support at least 100 bytes here, including the nul termination.
116  * We use 99 for the max value to allow for the nul.
117  *
118  * We could probably also do sizeof (addr.sun_path)
119  * but this way we are the same on all platforms
120  * which is probably a good idea.
121  */
122
123 /**
124  * @typedef DBusForeachFunction
125  * 
126  * Used to iterate over each item in a collection, such as
127  * a DBusList.
128  */
129
130 /**
131  * Fixed "out of memory" error message, just to avoid
132  * making up a different string every time and wasting
133  * space.
134  */
135 const char _dbus_no_memory_message[] = "Not enough memory";
136
137 /**
138  * Prints a warning message to stderr.
139  *
140  * @param format printf-style format string.
141  */
142 void
143 _dbus_warn (const char *format,
144             ...)
145 {
146   /* FIXME not portable enough? */
147   va_list args;
148
149   va_start (args, format);
150   vfprintf (stderr, format, args);
151   va_end (args);
152 }
153
154 /**
155  * Prints a warning message to stderr
156  * if the user has enabled verbose mode.
157  * This is the real function implementation,
158  * use _dbus_verbose() macro in code.
159  *
160  * @param format printf-style format string.
161  */
162 void
163 _dbus_verbose_real (const char *format,
164                     ...)
165 {
166   va_list args;
167   static dbus_bool_t verbose = TRUE;
168   static dbus_bool_t initted = FALSE;
169
170   /* things are written a bit oddly here so that
171    * in the non-verbose case we just have the one
172    * conditional and return immediately.
173    */
174   if (!verbose)
175     return;
176   
177   if (!initted)
178     {
179       verbose = _dbus_getenv ("DBUS_VERBOSE") != NULL;
180       initted = TRUE;
181       if (!verbose)
182         return;
183     }
184   
185   va_start (args, format);
186   vfprintf (stderr, format, args);
187   va_end (args);
188 }
189
190 /**
191  * Duplicates a string. Result must be freed with
192  * dbus_free(). Returns #NULL if memory allocation fails.
193  * If the string to be duplicated is #NULL, returns #NULL.
194  * 
195  * @param str string to duplicate.
196  * @returns newly-allocated copy.
197  */
198 char*
199 _dbus_strdup (const char *str)
200 {
201   int len;
202   char *copy;
203   
204   if (str == NULL)
205     return NULL;
206   
207   len = strlen (str);
208
209   copy = dbus_malloc (len + 1);
210   if (copy == NULL)
211     return NULL;
212
213   memcpy (copy, str, len + 1);
214   
215   return copy;
216 }
217
218 /**
219  * Sets a file descriptor to be nonblocking.
220  *
221  * @param fd the file descriptor.
222  * @param result address of result code.
223  * @returns #TRUE on success.
224  */
225 dbus_bool_t
226 _dbus_set_fd_nonblocking (int             fd,
227                           DBusResultCode *result)
228 {
229   int val;
230
231   val = fcntl (fd, F_GETFL, 0);
232   if (val < 0)
233     {
234       dbus_set_result (result, _dbus_result_from_errno (errno));
235       _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
236                      _dbus_strerror (errno));
237       return FALSE;
238     }
239
240   if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
241     {
242       dbus_set_result (result, _dbus_result_from_errno (errno));      
243       _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
244                      fd, _dbus_strerror (errno));
245
246       return FALSE;
247     }
248
249   return TRUE;
250 }
251
252 /**
253  * Returns a string describing the given type.
254  *
255  * @param type the type to describe
256  * @returns a constant string describing the type
257  */
258 const char *
259 _dbus_type_to_string (int type)
260 {
261   switch (type)
262     {
263     case DBUS_TYPE_INVALID:
264       return "invalid";
265     case DBUS_TYPE_NIL:
266       return "nil";
267     case DBUS_TYPE_BOOLEAN:
268       return "boolean";
269     case DBUS_TYPE_INT32:
270       return "int32";
271     case DBUS_TYPE_UINT32:
272       return "uint32";
273     case DBUS_TYPE_DOUBLE:
274       return "double";
275     case DBUS_TYPE_STRING:
276       return "string";
277     case DBUS_TYPE_BOOLEAN_ARRAY:
278       return "boolean array";
279     case DBUS_TYPE_INT32_ARRAY:
280       return "int32 array";
281     case DBUS_TYPE_UINT32_ARRAY:
282       return "uint32 array";
283     case DBUS_TYPE_DOUBLE_ARRAY:
284       return "double array";
285     case DBUS_TYPE_BYTE_ARRAY:
286       return "byte array";
287     case DBUS_TYPE_STRING_ARRAY:
288       return "string array";
289     default:
290       return "unknown";
291     }
292 }
293
294 #ifdef DBUS_BUILD_TESTS
295 static int fail_alloc_counter = _DBUS_INT_MAX;
296 /**
297  * Sets the number of allocations until we simulate a failed
298  * allocation. If set to 0, the next allocation to run
299  * fails; if set to 1, one succeeds then the next fails; etc.
300  * Set to _DBUS_INT_MAX to not fail anything. 
301  *
302  * @param until_next_fail number of successful allocs before one fails
303  */
304 void
305 _dbus_set_fail_alloc_counter (int until_next_fail)
306 {
307   fail_alloc_counter = until_next_fail;
308 }
309
310 /**
311  * Gets the number of successful allocs until we'll simulate
312  * a failed alloc.
313  *
314  * @returns current counter value
315  */
316 int
317 _dbus_get_fail_alloc_counter (void)
318 {
319   return fail_alloc_counter;
320 }
321
322 /**
323  * Called when about to alloc some memory; if
324  * it returns #TRUE, then the allocation should
325  * fail. If it returns #FALSE, then the allocation
326  * should not fail.
327  *
328  * @returns #TRUE if this alloc should fail
329  */
330 dbus_bool_t
331 _dbus_decrement_fail_alloc_counter (void)
332 {
333   if (fail_alloc_counter <= 0)
334     {
335       fail_alloc_counter = _DBUS_INT_MAX;
336       return TRUE;
337     }
338   else
339     {
340       fail_alloc_counter -= 1;
341       return FALSE;
342     }
343 }
344 #endif /* DBUS_BUILD_TESTS */
345
346 /** @} */