incomplete code for finger and friend tables
[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 0x000A0000
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 (*GNUNET_FileNameCallback) (void *cls, const char *filename);
263
264
265 /* ****************************** logging ***************************** */
266
267 /**
268  * @ingroup logging
269  * Types of errors.
270  */
271 enum GNUNET_ErrorType
272 {
273   GNUNET_ERROR_TYPE_UNSPECIFIED = -1,
274   GNUNET_ERROR_TYPE_NONE = 0,
275   GNUNET_ERROR_TYPE_ERROR = 1,
276   GNUNET_ERROR_TYPE_WARNING = 2,
277   GNUNET_ERROR_TYPE_INFO = 4,
278   GNUNET_ERROR_TYPE_DEBUG = 8,
279   GNUNET_ERROR_TYPE_INVALID = 16,
280   GNUNET_ERROR_TYPE_BULK = 32
281 };
282
283
284 /**
285  * @ingroup logging
286  * User-defined handler for log messages.
287  *
288  * @param cls closure
289  * @param kind severeity
290  * @param component what component is issuing the message?
291  * @param date when was the message logged?
292  * @param message what is the message
293  */
294 typedef void (*GNUNET_Logger) (void *cls, enum GNUNET_ErrorType kind,
295                                const char *component, const char *date,
296                                const char *message);
297
298
299 /**
300  * @ingroup logging
301  * Get the number of log calls that are going to be skipped
302  *
303  * @return number of log calls to be ignored
304  */
305 int
306 GNUNET_get_log_skip ();
307
308 #if !defined(GNUNET_CULL_LOGGING)
309 int
310 GNUNET_get_log_call_status (int caller_level,
311                             const char *comp,
312                             const char *file,
313                             const char *function, int line);
314 #endif
315
316
317 /**
318  * @ingroup logging
319  * Main log function.
320  *
321  * @param kind how serious is the error?
322  * @param message what is the message (format string)
323  * @param ... arguments for format string
324  */
325 void
326 GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...);
327
328 /* from glib */
329 #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
330 #define _GNUNET_BOOLEAN_EXPR(expr)              \
331  __extension__ ({                               \
332    int _gnunet_boolean_var_;                    \
333    if (expr)                                    \
334       _gnunet_boolean_var_ = 1;                 \
335    else                                         \
336       _gnunet_boolean_var_ = 0;                 \
337    _gnunet_boolean_var_;                        \
338 })
339 #define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 1))
340 #define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR(expr), 0))
341 #else
342 #define GN_LIKELY(expr) (expr)
343 #define GN_UNLIKELY(expr) (expr)
344 #endif
345
346 #if !defined(GNUNET_LOG_CALL_STATUS)
347 #define GNUNET_LOG_CALL_STATUS -1
348 #endif
349
350
351 /**
352  * @ingroup logging
353  * Log function that specifies an alternative component.
354  * This function should be used by plugins.
355  *
356  * @param kind how serious is the error?
357  * @param comp component responsible for generating the message
358  * @param message what is the message (format string)
359  * @param ... arguments for format string
360  */
361 void
362 GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, const char *comp,
363                          const char *message, ...);
364
365 #if !defined(GNUNET_CULL_LOGGING)
366 #define GNUNET_log_from(kind,comp,...) do { int log_line = __LINE__;\
367   static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
368   if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
369     if (GN_UNLIKELY(log_call_enabled == -1))\
370       log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), (comp), __FILE__, __FUNCTION__, log_line); \
371     if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
372     else {\
373       if (GN_UNLIKELY(log_call_enabled))\
374         GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__);    \
375     }\
376   }\
377 } while (0)
378
379  #define GNUNET_log(kind,...) do { int log_line = __LINE__;\
380   static int log_call_enabled = GNUNET_LOG_CALL_STATUS;\
381   if ((GNUNET_EXTRA_LOGGING > 0) || ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) { \
382     if (GN_UNLIKELY(log_call_enabled == -1))\
383       log_call_enabled = GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), NULL, __FILE__, __FUNCTION__, log_line);\
384     if (GN_UNLIKELY(GNUNET_get_log_skip () > 0)) { GNUNET_log_skip (-1, GNUNET_NO); }\
385     else {\
386       if (GN_UNLIKELY(log_call_enabled))\
387         GNUNET_log_nocheck ((kind), __VA_ARGS__);       \
388     }\
389   }\
390 } while (0)
391 #else
392 #define GNUNET_log(...)
393 #define GNUNET_log_from(...)
394 #endif
395
396
397 /**
398  * @ingroup logging
399  * Log error message about missing configuration option.
400  *
401  * @param kind log level
402  * @param section section with missing option
403  * @param option name of missing option
404  */
405 void
406 GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
407                            const char *section,
408                            const char *option);
409
410
411 /**
412  * @ingroup logging
413  * Log error message about invalid configuration option value.
414  *
415  * @param kind log level
416  * @param section section with invalid option
417  * @param option name of invalid option
418  * @param required what is required that is invalid about the option
419  */
420 void
421 GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
422                            const char *section,
423                            const char *option,
424                            const char *required);
425
426
427 /**
428  * @ingroup logging
429  * Abort the process, generate a core dump if possible.
430  */
431 void
432 GNUNET_abort (void) GNUNET_NORETURN;
433
434
435 /**
436  * @ingroup logging
437  * Ignore the next @a n calls to the log function.
438  *
439  * @param n number of log calls to ignore (could be negative)
440  * @param check_reset GNUNET_YES to assert that the log skip counter is currently zero
441  */
442 void
443 GNUNET_log_skip (int n, int check_reset);
444
445
446 /**
447  * @ingroup logging
448  * Setup logging.
449  *
450  * @param comp default component to use
451  * @param loglevel what types of messages should be logged
452  * @param logfile change logging to logfile (use NULL to keep stderr)
453  * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened
454  */
455 int
456 GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile);
457
458
459 /**
460  * @ingroup logging
461  * Add a custom logger.
462  *
463  * @param logger log function
464  * @param logger_cls closure for @a logger
465  */
466 void
467 GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls);
468
469
470 /**
471  * @ingroup logging
472  * Remove a custom logger.
473  *
474  * @param logger log function
475  * @param logger_cls closure for logger
476  */
477 void
478 GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls);
479
480
481 /**
482  * @ingroup logging
483  * Convert a hash value to a string (for printing debug messages).
484  * This is one of the very few calls in the entire API that is
485  * NOT reentrant!
486  *
487  * @param hc the hash code
488  * @return string
489  */
490 const char *
491 GNUNET_h2s (const struct GNUNET_HashCode * hc);
492
493
494 /**
495  * @ingroup logging
496  * Convert a hash value to a string (for printing debug messages).
497  * This prints all 104 characters of a hashcode!
498  * This is one of the very few calls in the entire API that is
499  * NOT reentrant!
500  *
501  * @param hc the hash code
502  * @return string
503  */
504 const char *
505 GNUNET_h2s_full (const struct GNUNET_HashCode * hc);
506
507
508 /**
509  * @ingroup logging
510  * Convert a peer identity to a string (for printing debug messages).
511  * This is one of the very few calls in the entire API that is
512  * NOT reentrant!
513  *
514  * @param pid the peer identity
515  * @return string form of the pid; will be overwritten by next
516  *         call to #GNUNET_i2s.
517  */
518 const char *
519 GNUNET_i2s (const struct GNUNET_PeerIdentity *pid);
520
521
522 /**
523  * @ingroup logging
524  * Convert a peer identity to a string (for printing debug messages).
525  * This is one of the very few calls in the entire API that is
526  * NOT reentrant!
527  *
528  * @param pid the peer identity
529  * @return string form of the pid; will be overwritten by next
530  *         call to #GNUNET_i2s.
531  */
532 const char *
533 GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid);
534
535
536 /**
537  * @ingroup logging
538  * Convert a "struct sockaddr*" (IPv4 or IPv6 address) to a string
539  * (for printing debug messages).  This is one of the very few calls
540  * in the entire API that is NOT reentrant!
541  *
542  * @param addr the address
543  * @param addrlen the length of the address
544  * @return nicely formatted string for the address
545  *  will be overwritten by next call to GNUNET_a2s.
546  */
547 const char *
548 GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen);
549
550
551 /**
552  * @ingroup logging
553  * Convert error type to string.
554  *
555  * @param kind type to convert
556  * @return string corresponding to the type
557  */
558 const char *
559 GNUNET_error_type_to_string (enum GNUNET_ErrorType kind);
560
561
562 /**
563  * @ingroup logging
564  * Use this for fatal errors that cannot be handled
565  */
566 #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)
567
568
569 /**
570  * @ingroup logging
571  * Use this for fatal errors that cannot be handled
572  */
573 #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)
574
575
576 /**
577  * @ingroup logging
578  * Use this for internal assertion violations that are
579  * not fatal (can be handled) but should not occur.
580  */
581 #define GNUNET_break(cond)  do { if (! (cond)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Assertion failed at %s:%d.\n"), __FILE__, __LINE__); } } while(0)
582
583
584 /**
585  * @ingroup logging
586  * Use this for assertion violations caused by other
587  * peers (i.e. protocol violations).  We do not want to
588  * confuse end-users (say, some other peer runs an
589  * older, broken or incompatible GNUnet version), but
590  * we still want to see these problems during
591  * development and testing.  "OP == other peer".
592  */
593 #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)
594
595
596 /**
597  * @ingroup logging
598  * Log an error message at log-level 'level' that indicates
599  * a failure of the command 'cmd' with the message given
600  * by strerror(errno).
601  */
602 #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)
603
604
605 /**
606  * @ingroup logging
607  * Log an error message at log-level 'level' that indicates
608  * a failure of the command 'cmd' with the message given
609  * by strerror(errno).
610  */
611 #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)
612
613
614 /**
615  * @ingroup logging
616  * Log an error message at log-level 'level' that indicates
617  * a failure of the command 'cmd' with the message given
618  * by strerror(errno).
619  */
620 #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)
621
622
623 /**
624  * @ingroup logging
625  * Log an error message at log-level 'level' that indicates
626  * a failure of the command 'cmd' with the message given
627  * by strerror(errno).
628  */
629 #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)
630
631 /* ************************* endianess conversion ****************** */
632
633 /**
634  * Convert unsigned 64-bit integer to host-byte-order.
635  * @param n the value in network byte order
636  * @return the same value in host byte order
637  */
638 uint64_t
639 GNUNET_ntohll (uint64_t n);
640
641 /**
642  * Convert unsigned 64-bit integer to network-byte-order.
643  * @param n the value in host byte order
644  * @return the same value in network byte order
645  */
646 uint64_t
647 GNUNET_htonll (uint64_t n);
648
649 /**
650  * Convert double to network-byte-order.
651  * @param d the value in network byte order
652  * @return the same value in host byte order
653  */
654 double
655 GNUNET_hton_double (double d);
656
657 /**
658  * Convert double to host-byte-order
659  * @param d the value in network byte order
660  * @return the same value in host byte order
661  */
662 double
663 GNUNET_ntoh_double (double d);
664
665 /* ************************* allocation functions ****************** */
666
667 /**
668  * @ingroup memory
669  * Maximum allocation with GNUNET_malloc macro.
670  */
671 #define GNUNET_MAX_MALLOC_CHECKED (1024 * 1024 * 40)
672
673 /**
674  * @ingroup memory
675  * Allocate a struct or union of the given @a type.
676  * Wrapper around #GNUNET_malloc that returns a pointer
677  * to the newly created object of the correct type.
678  *
679  * @param type name of the struct or union, i.e. pass 'struct Foo'.
680  */
681 #define GNUNET_new(type) (type *) GNUNET_malloc (sizeof (type))
682
683 /**
684  * @ingroup memory
685  * Allocate a size @a n array with structs or unions of the given @a type.
686  * Wrapper around #GNUNET_malloc that returns a pointer
687  * to the newly created objects of the correct type.
688  *
689  * @param n number of elements in the array
690  * @param type name of the struct or union, i.e. pass 'struct Foo'.
691  */
692 #define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof (type))
693
694 /**
695  * @ingroup memory
696  * Wrapper around malloc. Allocates size bytes of memory.
697  * The memory will be zero'ed out.
698  *
699  * @param size the number of bytes to allocate, must be
700  *        smaller than 40 MB.
701  * @return pointer to size bytes of memory, never NULL (!)
702  */
703 #define GNUNET_malloc(size) GNUNET_xmalloc_(size, __FILE__, __LINE__)
704
705 /**
706  * @ingroup memory
707  * Allocate and initialize a block of memory.
708  *
709  * @param buf data to initalize the block with
710  * @param size the number of bytes in buf (and size of the allocation)
711  * @return pointer to size bytes of memory, never NULL (!)
712  */
713 #define GNUNET_memdup(buf,size) GNUNET_xmemdup_(buf, size, __FILE__, __LINE__)
714
715 /**
716  * @ingroup memory
717  * Wrapper around malloc. Allocates size bytes of memory.
718  * The memory will be zero'ed out.
719  *
720  * @param size the number of bytes to allocate
721  * @return pointer to size bytes of memory, NULL if we do not have enough memory
722  */
723 #define GNUNET_malloc_large(size) GNUNET_xmalloc_unchecked_(size, __FILE__, __LINE__)
724
725 /**
726  * @ingroup memory
727  * Wrapper around realloc. Rellocates size bytes of memory.
728  *
729  * @param ptr the pointer to reallocate
730  * @param size the number of bytes to reallocate
731  * @return pointer to size bytes of memory
732  */
733 #define GNUNET_realloc(ptr, size) GNUNET_xrealloc_(ptr, size, __FILE__, __LINE__)
734
735 /**
736  * @ingroup memory
737  * Wrapper around free. Frees the memory referred to by ptr.
738  * Note that is is generally better to free memory that was
739  * allocated with #GNUNET_array_grow using #GNUNET_array_grow(mem, size, 0) instead of #GNUNET_free.
740  *
741  * @param ptr location where to free the memory. ptr must have
742  *     been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier.
743  */
744 #define GNUNET_free(ptr) GNUNET_xfree_(ptr, __FILE__, __LINE__)
745
746 /**
747  * @ingroup memory
748  * Free the memory pointed to by ptr if ptr is not NULL.
749  * Equivalent to `if (NULL != ptr) GNUNET_free(ptr)`.
750  *
751  * @param ptr the location in memory to free
752  */
753 #define GNUNET_free_non_null(ptr) do { void * __x__ = ptr; if (__x__ != NULL) { GNUNET_free(__x__); } } while(0)
754
755 /**
756  * @ingroup memory
757  * Wrapper around #GNUNET_xstrdup_.  Makes a copy of the zero-terminated string
758  * pointed to by a.
759  *
760  * @param a pointer to a zero-terminated string
761  * @return a copy of the string including zero-termination
762  */
763 #define GNUNET_strdup(a) GNUNET_xstrdup_(a,__FILE__,__LINE__)
764
765 /**
766  * @ingroup memory
767  * Wrapper around #GNUNET_xstrndup_.  Makes a partial copy of the string
768  * pointed to by a.
769  *
770  * @param a pointer to a string
771  * @param length of the string to duplicate
772  * @return a partial copy of the string including zero-termination
773  */
774 #define GNUNET_strndup(a,length) GNUNET_xstrndup_(a,length,__FILE__,__LINE__)
775
776 /**
777  * @ingroup memory
778  * Grow a well-typed (!) array.  This is a convenience
779  * method to grow a vector @a arr of size @a size
780  * to the new (target) size @a tsize.
781  * <p>
782  *
783  * Example (simple, well-typed stack):
784  *
785  * <pre>
786  * static struct foo * myVector = NULL;
787  * static int myVecLen = 0;
788  *
789  * static void push(struct foo * elem) {
790  *   GNUNET_array_grow(myVector, myVecLen, myVecLen+1);
791  *   memcpy(&myVector[myVecLen-1], elem, sizeof(struct foo));
792  * }
793  *
794  * static void pop(struct foo * elem) {
795  *   if (myVecLen == 0) die();
796  *   memcpy(elem, myVector[myVecLen-1], sizeof(struct foo));
797  *   GNUNET_array_grow(myVector, myVecLen, myVecLen-1);
798  * }
799  * </pre>
800  *
801  * @param arr base-pointer of the vector, may be NULL if size is 0;
802  *        will be updated to reflect the new address. The TYPE of
803  *        arr is important since size is the number of elements and
804  *        not the size in bytes
805  * @param size the number of elements in the existing vector (number
806  *        of elements to copy over)
807  * @param tsize the target size for the resulting vector, use 0 to
808  *        free the vector (then, arr will be NULL afterwards).
809  */
810 #define GNUNET_array_grow(arr,size,tsize) GNUNET_xgrow_((void**)&arr, sizeof(arr[0]), &size, tsize, __FILE__, __LINE__)
811
812 /**
813  * @ingroup memory
814  * Append an element to a list (growing the
815  * list by one).
816  */
817 #define GNUNET_array_append(arr,size,element) do { GNUNET_array_grow(arr,size,size+1); arr[size-1] = element; } while(0)
818
819 /**
820  * @ingroup memory
821  * Like snprintf, just aborts if the buffer is of insufficient size.
822  *
823  * @param buf pointer to buffer that is written to
824  * @param size number of bytes in @a buf
825  * @param format format strings
826  * @param ... data for format string
827  * @return number of bytes written to buf or negative value on error
828  */
829 int
830 GNUNET_snprintf (char *buf, size_t size, const char *format, ...);
831
832
833 /**
834  * @ingroup memory
835  * Like asprintf, just portable.
836  *
837  * @param buf set to a buffer of sufficient size (allocated, caller must free)
838  * @param format format string (see printf, fprintf, etc.)
839  * @param ... data for format string
840  * @return number of bytes in "*buf" excluding 0-termination
841  */
842 int
843 GNUNET_asprintf (char **buf, const char *format, ...);
844
845
846 /* ************** internal implementations, use macros above! ************** */
847
848 /**
849  * Allocate memory. Checks the return value, aborts if no more
850  * memory is available.  Don't use GNUNET_xmalloc_ directly. Use the
851  * #GNUNET_malloc macro.
852  * The memory will be zero'ed out.
853  *
854  * @param size number of bytes to allocate
855  * @param filename where is this call being made (for debugging)
856  * @param linenumber line where this call is being made (for debugging)
857  * @return allocated memory, never NULL
858  */
859 void *
860 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber);
861
862
863 /**
864  * Allocate and initialize memory. Checks the return value, aborts if no more
865  * memory is available.  Don't use GNUNET_xmemdup_ directly. Use the
866  * #GNUNET_memdup macro.
867  *
868  * @param buf buffer to initialize from (must contain size bytes)
869  * @param size number of bytes to allocate
870  * @param filename where is this call being made (for debugging)
871  * @param linenumber line where this call is being made (for debugging)
872  * @return allocated memory, never NULL
873  */
874 void *
875 GNUNET_xmemdup_ (const void *buf, size_t size, const char *filename,
876                  int linenumber);
877
878
879 /**
880  * Allocate memory.  This function does not check if the allocation
881  * request is within reasonable bounds, allowing allocations larger
882  * than 40 MB.  If you don't expect the possibility of very large
883  * allocations, use #GNUNET_malloc instead.  The memory will be zero'ed
884  * out.
885  *
886  * @param size number of bytes to allocate
887  * @param filename where is this call being made (for debugging)
888  * @param linenumber line where this call is being made (for debugging)
889  * @return pointer to size bytes of memory, NULL if we do not have enough memory
890  */
891 void *
892 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber);
893
894
895 /**
896  * Reallocate memory. Checks the return value, aborts if no more
897  * memory is available.
898  */
899 void *
900 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber);
901
902
903 /**
904  * Free memory. Merely a wrapper for the case that we
905  * want to keep track of allocations.  Don't use GNUNET_xfree_
906  * directly. Use the #GNUNET_free macro.
907  *
908  * @param ptr pointer to memory to free
909  * @param filename where is this call being made (for debugging)
910  * @param linenumber line where this call is being made (for debugging)
911  */
912 void
913 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber);
914
915
916 /**
917  * Dup a string. Don't call GNUNET_xstrdup_ directly. Use the #GNUNET_strdup macro.
918  * @param str string to duplicate
919  * @param filename where is this call being made (for debugging)
920  * @param linenumber line where this call is being made (for debugging)
921  * @return the duplicated string
922  */
923 char *
924 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber);
925
926 /**
927  * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro.
928  *
929  * @param str string to duplicate
930  * @param len length of the string to duplicate
931  * @param filename where is this call being made (for debugging)
932  * @param linenumber line where this call is being made (for debugging)
933  * @return the duplicated string
934  */
935 char *
936 GNUNET_xstrndup_ (const char *str, size_t len, const char *filename,
937                   int linenumber);
938
939 /**
940  * Grow an array, the new elements are zeroed out.
941  * Grows old by (*oldCount-newCount)*elementSize
942  * bytes and sets *oldCount to newCount.
943  *
944  * Don't call GNUNET_xgrow_ directly. Use the #GNUNET_array_grow macro.
945  *
946  * @param old address of the pointer to the array
947  *        *old may be NULL
948  * @param elementSize the size of the elements of the array
949  * @param oldCount address of the number of elements in the *old array
950  * @param newCount number of elements in the new array, may be 0 (then *old will be NULL afterwards)
951  * @param filename where is this call being made (for debugging)
952  * @param linenumber line where this call is being made (for debugging)
953  */
954 void
955 GNUNET_xgrow_ (void **old, size_t elementSize, unsigned int *oldCount,
956                unsigned int newCount, const char *filename, int linenumber);
957
958
959 /**
960  * @ingroup memory
961  * Create a copy of the given message.
962  *
963  * @param msg message to copy
964  * @return duplicate of the message
965  */
966 struct GNUNET_MessageHeader *
967 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg);
968
969
970 #if __STDC_VERSION__ < 199901L
971 #if __GNUC__ >= 2
972 #define __func__ __FUNCTION__
973 #else
974 #define __func__ "<unknown>"
975 #endif
976 #endif
977
978
979 #if 0                           /* keep Emacsens' auto-indent happy */
980 {
981 #endif
982 #ifdef __cplusplus
983 }
984 #endif
985
986
987
988
989 #endif /*GNUNET_COMMON_H_ */