-simplify logic
[oweals/gnunet.git] / src / include / gnunet_common.h
1 /*
2      This file is part of GNUnet.
3      (C) 2006-2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file include/gnunet_common.h
23  * @brief commonly used definitions; globals in this file
24  *        are exempt from the rule that the module name ("common")
25  *        must be part of the symbol name.
26  *
27  * @author Christian Grothoff
28  * @author Nils Durner
29  *
30  * @defgroup logging Logging
31  * @defgroup memory Memory management
32  */
33 #ifndef GNUNET_COMMON_H
34 #define GNUNET_COMMON_H
35
36 #if HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
38 #endif
39 #if HAVE_NETINET_IN_H
40 #include <netinet/in.h>
41 #endif
42 #ifdef MINGW
43 #include "winproc.h"
44 #endif
45 #ifdef HAVE_STDINT_H
46 #include <stdint.h>
47 #endif
48 #ifdef HAVE_STDARG_H
49 #include <stdarg.h>
50 #endif
51
52 #ifdef __cplusplus
53 extern "C"
54 {
55 #if 0                           /* keep Emacsens' auto-indent happy */
56 }
57 #endif
58 #endif
59
60 /**
61  * Version of the API (for entire gnunetutil.so library).
62  */
63 #define GNUNET_UTIL_VERSION 0x000A0100
64
65 /**
66  * Named constants for return values.  The following invariants hold:
67  * `GNUNET_NO == 0` (to allow `if (GNUNET_NO)`) `GNUNET_OK !=
68  * GNUNET_SYSERR`, `GNUNET_OK != GNUNET_NO`, `GNUNET_NO !=
69  * GNUNET_SYSERR` and finally `GNUNET_YES != GNUNET_NO`.
70  */
71 #define GNUNET_OK      1
72 #define GNUNET_SYSERR -1
73 #define GNUNET_YES     1
74 #define GNUNET_NO      0
75
76 #define GNUNET_MIN(a,b) (((a) < (b)) ? (a) : (b))
77
78 #define GNUNET_MAX(a,b) (((a) > (b)) ? (a) : (b))
79
80 /* some systems use one underscore only, and mingw uses no underscore... */
81 #ifndef __BYTE_ORDER
82 #ifdef _BYTE_ORDER
83 #define __BYTE_ORDER _BYTE_ORDER
84 #else
85 #ifdef BYTE_ORDER
86 #define __BYTE_ORDER BYTE_ORDER
87 #endif
88 #endif
89 #endif
90 #ifndef __BIG_ENDIAN
91 #ifdef _BIG_ENDIAN
92 #define __BIG_ENDIAN _BIG_ENDIAN
93 #else
94 #ifdef BIG_ENDIAN
95 #define __BIG_ENDIAN BIG_ENDIAN
96 #endif
97 #endif
98 #endif
99 #ifndef __LITTLE_ENDIAN
100 #ifdef _LITTLE_ENDIAN
101 #define __LITTLE_ENDIAN _LITTLE_ENDIAN
102 #else
103 #ifdef LITTLE_ENDIAN
104 #define __LITTLE_ENDIAN LITTLE_ENDIAN
105 #endif
106 #endif
107 #endif
108
109 /**
110  * @ingroup logging
111  * define #GNUNET_EXTRA_LOGGING if using this header outside the GNUnet source
112  * tree where gnunet_config.h is unavailable
113  */
114 #ifndef GNUNET_EXTRA_LOGGING
115 #define GNUNET_EXTRA_LOGGING 0
116 #endif
117
118 /**
119  * Endian operations
120  */
121
122 # if __BYTE_ORDER == __LITTLE_ENDIAN
123 #  define GNUNET_htobe16(x) __bswap_16 (x)
124 #  define GNUNET_htole16(x) (x)
125 #  define GNUNET_be16toh(x) __bswap_16 (x)
126 #  define GNUNET_le16toh(x) (x)
127
128 #  define GNUNET_htobe32(x) __bswap_32 (x)
129 #  define GNUNET_htole32(x) (x)
130 #  define GNUNET_be32toh(x) __bswap_32 (x)
131 #  define GNUNET_le32toh(x) (x)
132
133 #  define GNUNET_htobe64(x) __bswap_64 (x)
134 #  define GNUNET_htole64(x) (x)
135 #  define GNUNET_be64toh(x) __bswap_64 (x)
136 #  define GNUNET_le64toh(x) (x)
137 #endif
138 # if __BYTE_ORDER == __BIG_ENDIAN
139 #  define GNUNET_htobe16(x) (x)
140 #  define GNUNET_htole16(x) __bswap_16 (x)
141 #  define GNUNET_be16toh(x) (x)
142 #  define GNUNET_le16toh(x) __bswap_16 (x)
143
144 #  define GNUNET_htobe32(x) (x)
145 #  define GNUNET_htole32(x) __bswap_32 (x)
146 #  define GNUNET_be32toh(x) (x)
147 #  define GNUNET_le32toh(x) __bswap_32 (x)
148
149 #  define GNUNET_htobe64(x) (x)
150 #  define GNUNET_htole64(x) __bswap_64 (x)
151 #  define GNUNET_be64toh(x) (x)
152 #  define GNUNET_le64toh(x) __bswap_64 (x)
153 #endif
154
155
156
157
158 /**
159  * gcc-ism to get packed structs.
160  */
161 #define GNUNET_PACKED __attribute__((packed))
162
163 /**
164  * gcc-ism to get gcc bitfield layout when compiling with -mms-bitfields
165  */
166 #if MINGW
167 #define GNUNET_GCC_STRUCT_LAYOUT __attribute__((gcc_struct))
168 #else
169 #define GNUNET_GCC_STRUCT_LAYOUT
170 #endif
171
172 /**
173  * gcc-ism to force alignment; we use this to align char-arrays
174  * that may then be cast to 'struct's.  See also gcc
175  * bug #33594.
176  */
177 #ifdef __BIGGEST_ALIGNMENT__
178 #define GNUNET_ALIGN __attribute__((aligned (__BIGGEST_ALIGNMENT__)))
179 #else
180 #define GNUNET_ALIGN __attribute__((aligned (8)))
181 #endif
182
183 /**
184  * gcc-ism to document unused arguments
185  */
186 #define GNUNET_UNUSED __attribute__((unused))
187
188 /**
189  * gcc-ism to document functions that don't return
190  */
191 #define GNUNET_NORETURN __attribute__((noreturn))
192
193 #if MINGW
194 #if __GNUC__ > 3
195 /**
196  * gcc 4.x-ism to pack structures even on W32 (to be used before structs);
197  * Using this would cause structs to be unaligned on the stack on Sparc,
198  * so we *only* use this on W32 (see #670578 from Debian); fortunately,
199  * W32 doesn't run on sparc anyway.
200  */
201 #define GNUNET_NETWORK_STRUCT_BEGIN \
202   _Pragma("pack(push)") \
203   _Pragma("pack(1)")
204
205 /**
206  * gcc 4.x-ism to pack structures even on W32 (to be used after structs)
207  * Using this would cause structs to be unaligned on the stack on Sparc,
208  * so we *only* use this on W32 (see #670578 from Debian); fortunately,
209  * W32 doesn't run on sparc anyway.
210  */
211 #define GNUNET_NETWORK_STRUCT_END _Pragma("pack(pop)")
212
213 #else
214 #error gcc 4.x or higher required on W32 systems
215 #endif
216 #else
217 /**
218  * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32
219  */
220 #define GNUNET_NETWORK_STRUCT_BEGIN
221
222 /**
223  * Define as empty, GNUNET_PACKED should suffice, but this won't work on W32;
224  */
225 #define GNUNET_NETWORK_STRUCT_END
226 #endif
227
228 /* ************************ super-general types *********************** */
229
230 GNUNET_NETWORK_STRUCT_BEGIN
231
232 /**
233  * Header for all communications.
234  */
235 struct GNUNET_MessageHeader
236 {
237
238   /**
239    * The length of the struct (in bytes, including the length field itself),
240    * in big-endian format.
241    */
242   uint16_t size GNUNET_PACKED;
243
244   /**
245    * The type of the message (GNUNET_MESSAGE_TYPE_XXXX), in big-endian format.
246    */
247   uint16_t type GNUNET_PACKED;
248
249 };
250
251 GNUNET_NETWORK_STRUCT_END
252
253 /**
254  * Function called with a filename.
255  *
256  * @param cls closure
257  * @param filename complete filename (absolute path)
258  * @return #GNUNET_OK to continue to iterate,
259  *  #GNUNET_NO to stop iteration with no error,
260  *  #GNUNET_SYSERR to abort iteration with error!
261  */
262 typedef int
263 (*GNUNET_FileNameCallback) (void *cls,
264                             const char *filename);
265
266
267 /**
268  * Generic continuation callback.
269  *
270  * @param cls  Closure.
271  */
272 typedef void
273 (*GNUNET_ContinuationCallback) (void *cls);
274
275
276 /* ****************************** logging ***************************** */
277
278 /**
279  * @ingroup logging
280  * Types of errors.
281  */
282 enum GNUNET_ErrorType
283 {
284   GNUNET_ERROR_TYPE_UNSPECIFIED = -1,
285   GNUNET_ERROR_TYPE_NONE = 0,
286   GNUNET_ERROR_TYPE_ERROR = 1,
287   GNUNET_ERROR_TYPE_WARNING = 2,
288   GNUNET_ERROR_TYPE_INFO = 4,
289   GNUNET_ERROR_TYPE_DEBUG = 8,
290   GNUNET_ERROR_TYPE_INVALID = 16,
291   GNUNET_ERROR_TYPE_BULK = 32
292 };
293
294
295 /**
296  * @ingroup logging
297  * User-defined handler for log messages.
298  *
299  * @param cls closure
300  * @param kind severeity
301  * @param component what component is issuing the message?
302  * @param date when was the message logged?
303  * @param message what is the message
304  */
305 typedef void (*GNUNET_Logger) (void *cls,
306                                enum GNUNET_ErrorType kind,
307                                const char *component,
308                                const char *date,
309                                const char *message);
310
311
312 /**
313  * @ingroup logging
314  * Get the number of log calls that are going to be skipped
315  *
316  * @return number of log calls to be ignored
317  */
318 int
319 GNUNET_get_log_skip ();
320
321 #if !defined(GNUNET_CULL_LOGGING)
322 int
323 GNUNET_get_log_call_status (int caller_level,
324                             const char *comp,
325                             const char *file,
326                             const char *function,
327                             int line);
328 #endif
329
330
331 /**
332  * @ingroup logging
333  * Main log function.
334  *
335  * @param kind how serious is the error?
336  * @param message what is the message (format string)
337  * @param ... arguments for format string
338  */
339 void
340 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...);
341
342 /* from glib */
343 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
344 #define _GNUNET_BOOLEAN_EXPR(expr)              \
345  __extension__ ({                               \
346    int _gnunet_boolean_var_;                    \
347    if (expr)                                    \
348       _gnunet_boolean_var_ = 1;                 \
349    else                                         \
350       _gnunet_boolean_var_ = 0;                 \
351    _gnunet_boolean_var_;                        \
352 })
353 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 1))
354 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 0))
355 #else
356 #define GN_LIKELY(expr) (expr)
357 #define GN_UNLIKELY(expr) (expr)
358 #endif
359
360 #if !defined(GNUNET_LOG_CALL_STATUS)
361 #define GNUNET_LOG_CALL_STATUS -1
362 #endif
363
364
365 /**
366  * @ingroup logging
367  * Log function that specifies an alternative component.
368  * This function should be used by plugins.
369  *
370  * @param kind how serious is the error?
371  * @param comp component responsible for generating the message
372  * @param message what is the message (format string)
373  * @param ... arguments for format string
374  */
375 void
376 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
377                          const char *message, ...);
378
379 #if !defined(GNUNET_CULL_LOGGING)
380 #define GNUNET_log_from(kind,comp,...) do { int log_line = __LINE__;\
381   static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
382   if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
383     if (GN_UNLIKELY(log_call_enabled == -1))\
384       log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), (comp), __FILE__, __FUNCTION__, log_line); \
385     if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
386     else {\
387       if (GN_UNLIKELY(log_call_enabled))\
388         GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__);    \
389     }\
390   }\
391 } while (0)
392
393  #define GNUNET_log(kind,...) do { int log_line = __LINE__;\
394   static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
395   if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
396     if (GN_UNLIKELY(log_call_enabled == -1))\
397       log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), NULL, __FILE__, __FUNCTION__, log_line);\
398     if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
399     else {\
400       if (GN_UNLIKELY(log_call_enabled))\
401         GNUNET_log_nocheck ((kind), __VA_ARGS__);       \
402     }\
403   }\
404 } while (0)
405 #else
406 #define GNUNET_log(...)
407 #define GNUNET_log_from(...)
408 #endif
409
410
411 /**
412  * @ingroup logging
413  * Log error message about missing configuration option.
414  *
415  * @param kind log level
416  * @param section section with missing option
417  * @param option name of missing option
418  */
419 void
420 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
421                            const char *section,
422                            const char *option);
423
424
425 /**
426  * @ingroup logging
427  * Log error message about invalid configuration option value.
428  *
429  * @param kind log level
430  * @param section section with invalid option
431  * @param option name of invalid option
432  * @param required what is required that is invalid about the option
433  */
434 void
435 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
436                            const char *section,
437                            const char *option,
438                            const char *required);
439
440
441 /**
442  * @ingroup logging
443  * Abort the process, generate a core dump if possible.
444  */
445 void
446 GNUNET_abort (void) GNUNET_NORETURN;
447
448
449 /**
450  * @ingroup logging
451  * Ignore the next @a n calls to the log function.
452  *
453  * @param n number of log calls to ignore (could be negative)
454  * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
455  */
456 void
457 GNUNET_log_skip (int n,
458                  int check_reset);
459
460
461 /**
462  * @ingroup logging
463  * Setup logging.
464  *
465  * @param comp default component to use
466  * @param loglevel what types of messages should be logged
467  * @param logfile change logging to logfile (use NULL to keep stderr)
468  * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
469  */
470 int
471 GNUNET_log_setup (const char *comp,
472                   const char *loglevel,
473                   const char *logfile);
474
475
476 /**
477  * @ingroup logging
478  * Add a custom logger.
479  *
480  * @param logger log function
481  * @param logger_cls closure for @a logger
482  */
483 void
484 GNUNET_logger_add (GNUNET_Logger logger,
485                    void *logger_cls);
486
487
488 /**
489  * @ingroup logging
490  * Remove a custom logger.
491  *
492  * @param logger log function
493  * @param logger_cls closure for @a logger
494  */
495 void
496 GNUNET_logger_remove (GNUNET_Logger logger,
497                       void *logger_cls);
498
499
500 /**
501  * @ingroup logging
502  * Convert a hash value to a string (for printing debug messages).
503  * This is one of the very few calls in the entire API that is
504  * NOT reentrant!
505  *
506  * @param hc the hash code
507  * @return string
508  */
509 const char *
510 GNUNET_h2s (const struct GNUNET_HashCode * hc);
511
512
513 /**
514  * @ingroup logging
515  * Convert a hash value to a string (for printing debug messages).
516  * This prints all 104 characters of a hashcode!
517  * This is one of the very few calls in the entire API that is
518  * NOT reentrant!
519  *
520  * @param hc the hash code
521  * @return string
522  */
523 const char *
524 GNUNET_h2s_full (const struct GNUNET_HashCode * hc);
525
526
527 /**
528  * @ingroup logging
529  * Convert a peer identity to a string (for printing debug messages).
530  * This is one of the very few calls in the entire API that is
531  * NOT reentrant!
532  *
533  * @param pid the peer identity
534  * @return string form of the pid; will be overwritten by next
535  *         call to #GNUNET_i2s().
536  */
537 const char *
538 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
539
540
541 /**
542  * @ingroup logging
543  * Convert a peer identity to a string (for printing debug messages).
544  * This is one of the very few calls in the entire API that is
545  * NOT reentrant!
546  *
547  * @param pid the peer identity
548  * @return string form of the pid; will be overwritten by next
549  *         call to #GNUNET_i2s_full().
550  */
551 const char *
552 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
553
554
555 /**
556  * @ingroup logging
557  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
558  * (for printing debug messages).  This is one of the very few calls
559  * in the entire API that is NOT reentrant!
560  *
561  * @param addr the address
562  * @param addrlen the length of the @a addr
563  * @return nicely formatted string for the address
564  *  will be overwritten by next call to #GNUNET_a2s().
565  */
566 const char *
567 GNUNET_a2s (const struct sockaddr *addr,
568             socklen_t addrlen);
569
570
571 /**
572  * @ingroup logging
573  * Convert error type to string.
574  *
575  * @param kind type to convert
576  * @return string corresponding to the type
577  */
578 const char *
579 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
580
581
582 /**
583  * @ingroup logging
584  * Use this for fatal errors that cannot be handled
585  */
586 #define GNUNET_assert(cond) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); GNUNET_abort(); } } while(0)
587
588
589 /**
590  * @ingroup logging
591  * Use this for fatal errors that cannot be handled
592  */
593 #define GNUNET_assert_at(cond, f, l) do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), f, l); GNUNET_abort(); } } while(0)
594
595
596 /**
597  * @ingroup logging
598  * Use this for internal assertion violations that are
599  * not fatal (can be handled) but should not occur.
600  */
601 #define GNUNET_break(cond)  do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
602
603
604 /**
605  * @ingroup logging
606  * Use this for assertion violations caused by other
607  * peers (i.e. protocol violations).  We do not want to
608  * confuse end-users (say, some other peer runs an
609  * older, broken or incompatible GNUnet version), but
610  * we still want to see these problems during
611  * development and testing.  "OP == other peer".
612  */
613 #define GNUNET_break_op(cond)  do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, _("External protocol violation detected at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
614
615
616 /**
617  * @ingroup logging
618  * Log an error message at log-level 'level' that indicates
619  * a failure of the command 'cmd' with the message given
620  * by strerror(errno).
621  */
622 #define GNUNET_log_strerror(level, cmd) do { GNUNET_log(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, STRERROR(errno)); } while(0)
623
624
625 /**
626  * @ingroup logging
627  * Log an error message at log-level 'level' that indicates
628  * a failure of the command 'cmd' with the message given
629  * by strerror(errno).
630  */
631 #define GNUNET_log_from_strerror(level, component, cmd) do { GNUNET_log_from (level, component, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, STRERROR(errno)); } while(0)
632
633
634 /**
635  * @ingroup logging
636  * Log an error message at log-level 'level' that indicates
637  * a failure of the command 'cmd' with the message given
638  * by strerror(errno).
639  */
640 #define GNUNET_log_strerror_file(level, cmd, filename) do { GNUNET_log(level, _("`%s' failed on file `%s' at %s:%d with error: %s\n"), cmd, filename,__FILE__, __LINE__, STRERROR(errno)); } while(0)
641
642
643 /**
644  * @ingroup logging
645  * Log an error message at log-level 'level' that indicates
646  * a failure of the command 'cmd' with the message given
647  * by strerror(errno).
648  */
649 #define GNUNET_log_from_strerror_file(level, component, cmd, filename) do { GNUNET_log_from (level, component, _("`%s' failed on file `%s' at %s:%d with error: %s\n"), cmd, filename,__FILE__, __LINE__, STRERROR(errno)); } while(0)
650
651 /* ************************* endianess conversion ****************** */
652
653 /**
654  * Convert unsigned 64-bit integer to host-byte-order.
655  * @param n the value in network byte order
656  * @return the same value in host byte order
657  */
658 uint64_t
659 GNUNET_ntohll (uint64_t n);
660
661 /**
662  * Convert unsigned 64-bit integer to network-byte-order.
663  * @param n the value in host byte order
664  * @return the same value in network byte order
665  */
666 uint64_t
667 GNUNET_htonll (uint64_t n);
668
669 /**
670  * Convert double to network-byte-order.
671  * @param d the value in network byte order
672  * @return the same value in host byte order
673  */
674 double
675 GNUNET_hton_double (double d);
676
677 /**
678  * Convert double to host-byte-order
679  * @param d the value in network byte order
680  * @return the same value in host byte order
681  */
682 double
683 GNUNET_ntoh_double (double d);
684
685 /* ************************* allocation functions ****************** */
686
687 /**
688  * @ingroup memory
689  * Maximum allocation with GNUNET_malloc macro.
690  */
691 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
692
693 /**
694  * @ingroup memory
695  * Allocate a struct or union of the given @a type.
696  * Wrapper around #GNUNET_malloc that returns a pointer
697  * to the newly created object of the correct type.
698  *
699  * @param type name of the struct or union, i.e. pass 'struct Foo'.
700  */
701 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof (type))
702
703 /**
704  * @ingroup memory
705  * Allocate a size @a n array with structs or unions of the given @a type.
706  * Wrapper around #GNUNET_malloc that returns a pointer
707  * to the newly created objects of the correct type.
708  *
709  * @param n number of elements in the array
710  * @param type name of the struct or union, i.e. pass 'struct Foo'.
711  */
712 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof (type))
713
714 /**
715  * @ingroup memory
716  * Wrapper around malloc. Allocates size bytes of memory.
717  * The memory will be zero'ed out.
718  *
719  * @param size the number of bytes to allocate, must be
720  *        smaller than 40 MB.
721  * @return pointer to size bytes of memory, never NULL (!)
722  */
723 #define GNUNET_malloc(size) GNUNET_xmalloc_(size, __FILE__, __LINE__)
724
725 /**
726  * @ingroup memory
727  * Allocate and initialize a block of memory.
728  *
729  * @param buf data to initalize the block with
730  * @param size the number of bytes in buf (and size of the allocation)
731  * @return pointer to size bytes of memory, never NULL (!)
732  */
733 #define GNUNET_memdup(buf,size) GNUNET_xmemdup_(buf, size, __FILE__, __LINE__)
734
735 /**
736  * @ingroup memory
737  * Wrapper around malloc. Allocates size bytes of memory.
738  * The memory will be zero'ed out.
739  *
740  * @param size the number of bytes to allocate
741  * @return pointer to size bytes of memory, NULL if we do not have enough memory
742  */
743 #define GNUNET_malloc_large(size) GNUNET_xmalloc_unchecked_(size, __FILE__, __LINE__)
744
745 /**
746  * @ingroup memory
747  * Wrapper around realloc. Rellocates size bytes of memory.
748  *
749  * @param ptr the pointer to reallocate
750  * @param size the number of bytes to reallocate
751  * @return pointer to size bytes of memory
752  */
753 #define GNUNET_realloc(ptr, size) GNUNET_xrealloc_(ptr, size, __FILE__, __LINE__)
754
755 /**
756  * @ingroup memory
757  * Wrapper around free. Frees the memory referred to by ptr.
758  * Note that is is generally better to free memory that was
759  * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
760  *
761  * @param ptr location where to free the memory. ptr must have
762  *     been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
763  */
764 #define GNUNET_free(ptr) GNUNET_xfree_(ptr, __FILE__, __LINE__)
765
766 /**
767  * @ingroup memory
768  * Free the memory pointed to by ptr if ptr is not NULL.
769  * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
770  *
771  * @param ptr the location in memory to free
772  */
773 #define GNUNET_free_non_null(ptr) do { void * __x__ = ptr; if (__x__ != NULL) { GNUNET_free(__x__); } } while(0)
774
775 /**
776  * @ingroup memory
777  * Wrapper around #GNUNET_xstrdup_.  Makes a copy of the zero-terminated string
778  * pointed to by a.
779  *
780  * @param a pointer to a zero-terminated string
781  * @return a copy of the string including zero-termination
782  */
783 #define GNUNET_strdup(a) GNUNET_xstrdup_(a,__FILE__,__LINE__)
784
785 /**
786  * @ingroup memory
787  * Wrapper around #GNUNET_xstrndup_.  Makes a partial copy of the string
788  * pointed to by a.
789  *
790  * @param a pointer to a string
791  * @param length of the string to duplicate
792  * @return a partial copy of the string including zero-termination
793  */
794 #define GNUNET_strndup(a,length) GNUNET_xstrndup_(a,length,__FILE__,__LINE__)
795
796 /**
797  * @ingroup memory
798  * Grow a well-typed (!) array.  This is a convenience
799  * method to grow a vector @a arr of size @a size
800  * to the new (target) size @a tsize.
801  * <p>
802  *
803  * Example (simple, well-typed stack):
804  *
805  * <pre>
806  * static struct foo * myVector = NULL;
807  * static int myVecLen = 0;
808  *
809  * static void push(struct foo * elem) {
810  *   GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
811  *   memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
812  * }
813  *
814  * static void pop(struct foo * elem) {
815  *   if (myVecLen == 0) die();
816  *   memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
817  *   GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
818  * }
819  * </pre>
820  *
821  * @param arr base-pointer of the vector, may be NULL if size is 0;
822  *        will be updated to reflect the new address. The TYPE of
823  *        arr is important since size is the number of elements and
824  *        not the size in bytes
825  * @param size the number of elements in the existing vector (number
826  *        of elements to copy over)
827  * @param tsize the target size for the resulting vector, use 0 to
828  *        free the vector (then, arr will be NULL afterwards).
829  */
830 #define GNUNET_array_grow(arr,size,tsize) GNUNET_xgrow_((void**)&arr, sizeof(arr[0]), &size, tsize, __FILE__, __LINE__)
831
832 /**
833  * @ingroup memory
834  * Append an element to a list (growing the
835  * list by one).
836  */
837 #define GNUNET_array_append(arr,size,element) do { GNUNET_array_grow(arr,size,size+1); arr[size-1] = element; } while(0)
838
839 /**
840  * @ingroup memory
841  * Like snprintf, just aborts if the buffer is of insufficient size.
842  *
843  * @param buf pointer to buffer that is written to
844  * @param size number of bytes in @a buf
845  * @param format format strings
846  * @param ... data for format string
847  * @return number of bytes written to buf or negative value on error
848  */
849 int
850 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
851
852
853 /**
854  * @ingroup memory
855  * Like asprintf, just portable.
856  *
857  * @param buf set to a buffer of sufficient size (allocated, caller must free)
858  * @param format format string (see printf, fprintf, etc.)
859  * @param ... data for format string
860  * @return number of bytes in "*buf" excluding 0-termination
861  */
862 int
863 GNUNET_asprintf (char **buf, const char *format, ...);
864
865
866 /* ************** internal implementations, use macros above! ************** */
867
868 /**
869  * Allocate memory. Checks the return value, aborts if no more
870  * memory is available.  Don't use GNUNET_xmalloc_ directly. Use the
871  * #GNUNET_malloc macro.
872  * The memory will be zero'ed out.
873  *
874  * @param size number of bytes to allocate
875  * @param filename where is this call being made (for debugging)
876  * @param linenumber line where this call is being made (for debugging)
877  * @return allocated memory, never NULL
878  */
879 void *
880 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
881
882
883 /**
884  * Allocate and initialize memory. Checks the return value, aborts if no more
885  * memory is available.  Don't use GNUNET_xmemdup_ directly. Use the
886  * #GNUNET_memdup macro.
887  *
888  * @param buf buffer to initialize from (must contain size bytes)
889  * @param size number of bytes to allocate
890  * @param filename where is this call being made (for debugging)
891  * @param linenumber line where this call is being made (for debugging)
892  * @return allocated memory, never NULL
893  */
894 void *
895 GNUNET_xmemdup_ (const void *buf, size_t size, const char *filename,
896                  int linenumber);
897
898
899 /**
900  * Allocate memory.  This function does not check if the allocation
901  * request is within reasonable bounds, allowing allocations larger
902  * than 40 MB.  If you don't expect the possibility of very large
903  * allocations, use #GNUNET_malloc instead.  The memory will be zero'ed
904  * out.
905  *
906  * @param size number of bytes to allocate
907  * @param filename where is this call being made (for debugging)
908  * @param linenumber line where this call is being made (for debugging)
909  * @return pointer to size bytes of memory, NULL if we do not have enough memory
910  */
911 void *
912 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
913
914
915 /**
916  * Reallocate memory. Checks the return value, aborts if no more
917  * memory is available.
918  */
919 void *
920 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
921
922
923 /**
924  * Free memory. Merely a wrapper for the case that we
925  * want to keep track of allocations.  Don't use GNUNET_xfree_
926  * directly. Use the #GNUNET_free macro.
927  *
928  * @param ptr pointer to memory to free
929  * @param filename where is this call being made (for debugging)
930  * @param linenumber line where this call is being made (for debugging)
931  */
932 void
933 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
934
935
936 /**
937  * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
938  * @param str string to duplicate
939  * @param filename where is this call being made (for debugging)
940  * @param linenumber line where this call is being made (for debugging)
941  * @return the duplicated string
942  */
943 char *
944 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
945
946 /**
947  * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
948  *
949  * @param str string to duplicate
950  * @param len length of the string to duplicate
951  * @param filename where is this call being made (for debugging)
952  * @param linenumber line where this call is being made (for debugging)
953  * @return the duplicated string
954  */
955 char *
956 GNUNET_xstrndup_ (const char *str, size_t len, const char *filename,
957                   int linenumber);
958
959 /**
960  * Grow an array, the new elements are zeroed out.
961  * Grows old by (*oldCount-newCount)*elementSize
962  * bytes and sets *oldCount to newCount.
963  *
964  * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
965  *
966  * @param old address of the pointer to the array
967  *        *old may be NULL
968  * @param elementSize the size of the elements of the array
969  * @param oldCount address of the number of elements in the *old array
970  * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
971  * @param filename where is this call being made (for debugging)
972  * @param linenumber line where this call is being made (for debugging)
973  */
974 void
975 GNUNET_xgrow_ (void **old, size_t elementSize, unsigned int *oldCount,
976                unsigned int newCount, const char *filename, int linenumber);
977
978
979 /**
980  * @ingroup memory
981  * Create a copy of the given message.
982  *
983  * @param msg message to copy
984  * @return duplicate of the message
985  */
986 struct GNUNET_MessageHeader *
987 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
988
989
990 #if __STDC_VERSION__ < 199901L
991 #if __GNUC__ >= 2
992 #define __func__ __FUNCTION__
993 #else
994 #define __func__ "<unknown>"
995 #endif
996 #endif
997
998
999 #if 0                           /* keep Emacsens' auto-indent happy */
1000 {
1001 #endif
1002 #ifdef __cplusplus
1003 }
1004 #endif
1005
1006
1007
1008
1009 #endif /*GNUNET_COMMON_H_ */