]> git.ozlabs.org Git - ccan/blob - ccan/tal/tal.h
fdpass: fix complilation on FreeBSD.
[ccan] / ccan / tal / tal.h
1 /* Licensed under BSD-MIT - see LICENSE file for details */
2 #ifndef CCAN_TAL_H
3 #define CCAN_TAL_H
4 #include "config.h"
5 #include <ccan/compiler/compiler.h>
6 #include <ccan/likely/likely.h>
7 #include <ccan/typesafe_cb/typesafe_cb.h>
8 #include <ccan/str/str.h>
9 #include <ccan/take/take.h>
10 #include <stdlib.h>
11 #include <stdbool.h>
12 #include <stdarg.h>
13
14 /* Define this for better optimization if you never override errfn
15  * to something tat returns */
16 #ifdef CCAN_TAL_NEVER_RETURN_NULL
17 #define TAL_RETURN_PTR RETURNS_NONNULL
18 #else
19 #define TAL_RETURN_PTR
20 #endif /* CCAN_TAL_NEVER_RETURN_NULL */
21
22 /**
23  * tal_t - convenient alias for void to mark tal pointers.
24  *
25  * Since any pointer can be a tal-allocated pointer, it's often
26  * useful to use this typedef to mark them explicitly.
27  */
28 typedef void tal_t;
29
30 /**
31  * tal - basic allocator function
32  * @ctx: NULL, or tal allocated object to be parent.
33  * @type: the type to allocate.
34  *
35  * Allocates a specific type, with a given parent context.  The name
36  * of the object is a string of the type, but if CCAN_TAL_DEBUG is
37  * defined it also contains the file and line which allocated it.
38  *
39  * tal_count() of the return will be 1.
40  *
41  * Example:
42  *      int *p = tal(NULL, int);
43  *      *p = 1;
44  */
45 #define tal(ctx, type)                                                  \
46         tal_label(ctx, type, TAL_LABEL(type, ""))
47
48 /**
49  * talz - zeroing allocator function
50  * @ctx: NULL, or tal allocated object to be parent.
51  * @type: the type to allocate.
52  *
53  * Equivalent to tal() followed by memset() to zero.
54  *
55  * Example:
56  *      p = talz(NULL, int);
57  *      assert(*p == 0);
58  */
59 #define talz(ctx, type)                                                 \
60         talz_label(ctx, type, TAL_LABEL(type, ""))
61
62 /**
63  * tal_free - free a tal-allocated pointer.
64  * @p: NULL, or tal allocated object to free.
65  *
66  * This calls the destructors for p (if any), then does the same for all its
67  * children (recursively) before finally freeing the memory.  It returns
68  * NULL, for convenience.
69  *
70  * Note: errno is preserved by this call, and also saved and restored
71  * for any destructors or notifiers.
72  *
73  * Example:
74  *      p = tal_free(p);
75  */
76 void *tal_free(const tal_t *p);
77
78 /**
79  * tal_arr - allocate an array of objects.
80  * @ctx: NULL, or tal allocated object to be parent.
81  * @type: the type to allocate.
82  * @count: the number to allocate.
83  *
84  * tal_count() of the returned pointer will be @count.
85  *
86  * Example:
87  *      p = tal_arr(NULL, int, 2);
88  *      p[0] = 0;
89  *      p[1] = 1;
90  */
91 #define tal_arr(ctx, type, count)                                       \
92         tal_arr_label(ctx, type, count, TAL_LABEL(type, "[]"))
93
94 /**
95  * tal_arrz - allocate an array of zeroed objects.
96  * @ctx: NULL, or tal allocated object to be parent.
97  * @type: the type to allocate.
98  * @count: the number to allocate.
99  *
100  * Equivalent to tal_arr() followed by memset() to zero.
101  *
102  * Example:
103  *      p = tal_arrz(NULL, int, 2);
104  *      assert(p[0] == 0 && p[1] == 0);
105  */
106 #define tal_arrz(ctx, type, count) \
107         tal_arrz_label(ctx, type, count, TAL_LABEL(type, "[]"))
108
109 /**
110  * tal_resize - enlarge or reduce a tal object.
111  * @p: A pointer to the tal allocated array to resize.
112  * @count: the number to allocate.
113  *
114  * This returns true on success (and may move *@p), or false on failure.
115  * On success, tal_count() of *@p will be @count.
116  *
117  * Note: if *p is take(), it will still be take() upon return, even if it
118  * has been moved.
119  *
120  * Example:
121  *      tal_resize(&p, 100);
122  */
123 #define tal_resize(p, count) \
124         tal_resize_((void **)(p), sizeof**(p), (count), false)
125
126 /**
127  * tal_resizez - enlarge or reduce a tal object; zero out extra.
128  * @p: A pointer to the tal allocated array to resize.
129  * @count: the number to allocate.
130  *
131  * This returns true on success (and may move *@p), or false on failure.
132  *
133  * Example:
134  *      tal_resizez(&p, 200);
135  */
136 #define tal_resizez(p, count) \
137         tal_resize_((void **)(p), sizeof**(p), (count), true)
138
139 /**
140  * tal_steal - change the parent of a tal-allocated pointer.
141  * @ctx: The new parent.
142  * @ptr: The tal allocated object to move, or NULL.
143  *
144  * This may need to perform an allocation, in which case it may fail; thus
145  * it can return NULL, otherwise returns @ptr.  If @ptr is NULL, this function does
146  * nothing.
147  */
148 #if HAVE_STATEMENT_EXPR
149 /* Weird macro avoids gcc's 'warning: value computed is not used'. */
150 #define tal_steal(ctx, ptr) \
151         ({ (tal_typeof(ptr) tal_steal_((ctx),(ptr))); })
152 #else
153 #define tal_steal(ctx, ptr) \
154         (tal_typeof(ptr) tal_steal_((ctx),(ptr)))
155 #endif
156
157 /**
158  * tal_add_destructor - add a callback function when this context is destroyed.
159  * @ptr: The tal allocated object.
160  * @function: the function to call before it's freed.
161  *
162  * This is a more convenient form of tal_add_notifier(@ptr,
163  * TAL_NOTIFY_FREE, ...), in that the function prototype takes only @ptr.
164  *
165  * Note that this can only fail if your allocfn fails and your errorfn returns.
166  */
167 #define tal_add_destructor(ptr, function)                                     \
168         tal_add_destructor_((ptr), typesafe_cb(void, void *, (function), (ptr)))
169
170 /**
171  * tal_del_destructor - remove a destructor callback function.
172  * @ptr: The tal allocated object.
173  * @function: the function to call before it's freed.
174  *
175  * If @function has not been successfully added as a destructor, this returns
176  * false.  Note that if we're inside the destructor call itself, this will
177  * return false.
178  */
179 #define tal_del_destructor(ptr, function)                                     \
180         tal_del_destructor_((ptr), typesafe_cb(void, void *, (function), (ptr)))
181
182 /**
183  * tal_add_destructor2 - add a 2-arg callback function when context is destroyed.
184  * @ptr: The tal allocated object.
185  * @function: the function to call before it's freed.
186  * @arg: the extra argument to the function.
187  *
188  * Sometimes an extra argument is required for a destructor; this
189  * saves the extra argument internally to avoid the caller having to
190  * do an extra allocation.
191  *
192  * Note that this can only fail if your allocfn fails and your errorfn returns.
193  */
194 #define tal_add_destructor2(ptr, function, arg)                         \
195         tal_add_destructor2_((ptr),                                     \
196                              typesafe_cb_cast(void (*)(tal_t *, void *), \
197                                               void (*)(__typeof__(ptr), \
198                                                        __typeof__(arg)), \
199                                               (function)),              \
200                              (arg))
201
202 /**
203  * tal_del_destructor - remove a destructor callback function.
204  * @ptr: The tal allocated object.
205  * @function: the function to call before it's freed.
206  *
207  * If @function has not been successfully added as a destructor, this returns
208  * false.  Note that if we're inside the destructor call itself, this will
209  * return false.
210  */
211 #define tal_del_destructor(ptr, function)                                     \
212         tal_del_destructor_((ptr), typesafe_cb(void, void *, (function), (ptr)))
213
214 /**
215  * tal_del_destructor2 - remove 2-arg callback function.
216  * @ptr: The tal allocated object.
217  * @function: the function to call before it's freed.
218  * @arg: the extra argument to the function.
219  *
220  * If @function has not been successfully added as a destructor with
221  * @arg, this returns false.
222  */
223 #define tal_del_destructor2(ptr, function, arg)                         \
224         tal_del_destructor2_((ptr),                                     \
225                              typesafe_cb_cast(void (*)(tal_t *, void *), \
226                                               void (*)(__typeof__(ptr), \
227                                                        __typeof__(arg)), \
228                                               (function)),              \
229                              (arg))
230 enum tal_notify_type {
231         TAL_NOTIFY_FREE = 1,
232         TAL_NOTIFY_STEAL = 2,
233         TAL_NOTIFY_MOVE = 4,
234         TAL_NOTIFY_RESIZE = 8,
235         TAL_NOTIFY_RENAME = 16,
236         TAL_NOTIFY_ADD_CHILD = 32,
237         TAL_NOTIFY_DEL_CHILD = 64,
238         TAL_NOTIFY_ADD_NOTIFIER = 128,
239         TAL_NOTIFY_DEL_NOTIFIER = 256
240 };
241
242 /**
243  * tal_add_notifier - add a callback function when this context changes.
244  * @ptr: The tal allocated object, or NULL.
245  * @types: Bitwise OR of the types the callback is interested in.
246  * @callback: the function to call.
247  *
248  * Note that this can only fail if your allocfn fails and your errorfn
249  * returns.  Also note that notifiers are not reliable in the case
250  * where an allocation fails, as they may be called before any
251  * allocation is actually done.
252  *
253  * TAL_NOTIFY_FREE is called when @ptr is freed, either directly or
254  * because an ancestor is freed: @info is the argument to tal_free().
255  * It is exactly equivalent to a destructor, with more information.
256  * errno is set to the value it was at the call of tal_free().
257  *
258  * TAL_NOTIFY_STEAL is called when @ptr's parent changes: @info is the
259  * new parent.
260  *
261  * TAL_NOTIFY_MOVE is called when @ptr is realloced (via tal_resize)
262  * and moved.  In this case, @ptr arg here is the new memory, and
263  * @info is the old pointer.
264  *
265  * TAL_NOTIFY_RESIZE is called when @ptr is realloced via tal_resize:
266  * @info is the new size, in bytes.  If the pointer has moved,
267  * TAL_NOTIFY_MOVE callbacks are called first.
268  *
269  * TAL_NOTIFY_ADD_CHILD/TAL_NOTIFY_DEL_CHILD are called when @ptr is
270  * the context for a tal() allocating call, or a direct child is
271  * tal_free()d: @info is the child.  Note that TAL_NOTIFY_DEL_CHILD is
272  * not called when this context is tal_free()d: TAL_NOTIFY_FREE is
273  * considered sufficient for that case.
274  *
275  * TAL_NOTIFY_ADD_NOTIFIER/TAL_NOTIFIER_DEL_NOTIFIER are called when a
276  * notifier is added or removed (not for this notifier): @info is the
277  * callback.  This is also called for tal_add_destructor and
278  * tal_del_destructor.
279  */
280 #define tal_add_notifier(ptr, types, callback)                          \
281         tal_add_notifier_((ptr), (types),                               \
282                           typesafe_cb_postargs(void, tal_t *, (callback), \
283                                                (ptr),                   \
284                                                enum tal_notify_type, void *))
285
286 /**
287  * tal_del_notifier - remove a notifier callback function.
288  * @ptr: The tal allocated object.
289  * @callback: the function to call.
290  */
291 #define tal_del_notifier(ptr, callback)                                 \
292         tal_del_notifier_((ptr),                                        \
293                           typesafe_cb_postargs(void, void *, (callback), \
294                                                (ptr),                   \
295                                                enum tal_notify_type, void *), \
296                           false, NULL)
297
298 /**
299  * tal_set_name - attach a name to a tal pointer.
300  * @ptr: The tal allocated object.
301  * @name: The name to use.
302  *
303  * The name is copied, unless we're certain it's a string literal.
304  */
305 #define tal_set_name(ptr, name)                               \
306     tal_set_name_((ptr), (name), TAL_IS_LITERAL(name))
307
308 /**
309  * tal_name - get the name for a tal pointer.
310  * @ptr: The tal allocated object.
311  *
312  * Returns NULL if no name has been set.
313  */
314 const char *tal_name(const tal_t *ptr);
315
316 /**
317  * tal_count - get the count of objects in a tal object.
318  * @ptr: The tal allocated object (or NULL)
319  *
320  * Returns 0 if @ptr is NULL.  Note that if the allocation was done as a
321  * different type to @ptr, the result may not match the @count argument
322  * (or implied 1) of that allocation!
323  */
324 #define tal_count(p) (tal_bytelen(p) / sizeof(*p))
325
326 /**
327  * tal_bytelen - get the count of bytes in a tal object.
328  * @ptr: The tal allocated object (or NULL)
329  *
330  * Returns 0 if @ptr is NULL.
331  */
332 size_t tal_bytelen(const tal_t *ptr);
333
334 /**
335  * tal_first - get the first immediate tal object child.
336  * @root: The tal allocated object to start with, or NULL.
337  *
338  * Returns NULL if there are no children.
339  */
340 tal_t *tal_first(const tal_t *root);
341
342 /**
343  * tal_next - get the next immediate tal object child.
344  * @prev: The return value from tal_first or tal_next.
345  *
346  * Returns NULL if there are no more immediate children.  This should be safe to
347  * call on an altering tree unless @prev is no longer valid.
348  */
349 tal_t *tal_next(const tal_t *prev);
350
351 /**
352  * tal_parent - get the parent of a tal object.
353  * @ctx: The tal allocated object.
354  *
355  * Returns the parent, which may be NULL.  Returns NULL if @ctx is NULL.
356  */
357 tal_t *tal_parent(const tal_t *ctx);
358
359 /**
360  * tal_dup - duplicate an object.
361  * @ctx: The tal allocated object to be parent of the result (may be NULL).
362  * @type: the type (should match type of @p!)
363  * @p: the object to copy (or reparented if take()).  Must not be NULL.
364  */
365 #define tal_dup(ctx, type, p)                                   \
366         tal_dup_label(ctx, type, p, TAL_LABEL(type, ""), false)
367
368 /**
369  * tal_dup_or_null - duplicate an object, or just pass NULL.
370  * @ctx: The tal allocated object to be parent of the result (may be NULL).
371  * @type: the type (should match type of @p!)
372  * @p: the object to copy (or reparented if take())
373  *
374  * if @p is NULL, just return NULL, otherwise to tal_dup().
375  */
376 #define tal_dup_or_null(ctx, type, p)                                   \
377         tal_dup_label(ctx, type, p, TAL_LABEL(type, ""), true)
378
379 /**
380  * tal_dup_arr - duplicate an array.
381  * @ctx: The tal allocated object to be parent of the result (may be NULL).
382  * @type: the type (should match type of @p!)
383  * @p: the array to copy (or resized & reparented if take())
384  * @n: the number of sizeof(type) entries to copy.
385  * @extra: the number of extra sizeof(type) entries to allocate.
386  */
387 #define tal_dup_arr(ctx, type, p, n, extra)                     \
388         tal_dup_arr_label(ctx, type, p, n, extra, TAL_LABEL(type, "[]"))
389
390
391 /**
392  * tal_dup_arr - duplicate a tal array.
393  * @ctx: The tal allocated object to be parent of the result (may be NULL).
394  * @type: the type (should match type of @p!)
395  * @p: the tal array to copy (or resized & reparented if take())
396  *
397  * The comon case of duplicating an entire tal array.
398  */
399 #define tal_dup_talarr(ctx, type, p)                                    \
400         ((type *)tal_dup_talarr_((ctx), tal_typechk_(p, type *),        \
401                                  TAL_LABEL(type, "[]")))
402 /* Lower-level interfaces, where you want to supply your own label string. */
403 #define tal_label(ctx, type, label)                                             \
404         ((type *)tal_alloc_((ctx), sizeof(type), false, label))
405 #define talz_label(ctx, type, label)                                            \
406         ((type *)tal_alloc_((ctx), sizeof(type), true, label))
407 #define tal_arr_label(ctx, type, count, label)                                  \
408         ((type *)tal_alloc_arr_((ctx), sizeof(type), (count), false, label))
409 #define tal_arrz_label(ctx, type, count, label)                                 \
410         ((type *)tal_alloc_arr_((ctx), sizeof(type), (count), true, label))
411 #define tal_dup_label(ctx, type, p, label, nullok)                      \
412         ((type *)tal_dup_((ctx), tal_typechk_(p, type *),       \
413                           sizeof(type), 1, 0, nullok,           \
414                           label))
415 #define tal_dup_arr_label(ctx, type, p, n, extra, label)        \
416         ((type *)tal_dup_((ctx), tal_typechk_(p, type *),       \
417                           sizeof(type), (n), (extra), false,    \
418                           label))
419
420 /**
421  * tal_set_backend - set the allocation or error functions to use
422  * @alloc_fn: allocator or NULL (default is malloc)
423  * @resize_fn: re-allocator or NULL (default is realloc)
424  * @free_fn: free function or NULL (default is free)
425  * @error_fn: called on errors or NULL (default is abort)
426  *
427  * The defaults are set up so tal functions never return NULL, but you
428  * can override error_fn to change that.  error_fn can return (only if
429  * you haven't defined CCAN_TAL_NEVER_RETURN_NULL!), and is
430  * called if alloc_fn or resize_fn fail.
431  *
432  * If any parameter is NULL, that function is unchanged.
433  */
434 void tal_set_backend(void *(*alloc_fn)(size_t size),
435                      void *(*resize_fn)(void *, size_t size),
436                      void (*free_fn)(void *),
437                      void (*error_fn)(const char *msg));
438
439 /**
440  * tal_expand - expand a tal array with contents.
441  * @a1p: a pointer to the tal array to expand.
442  * @a2: the second array (can be take()).
443  * @num2: the number of elements in the second array.
444  *
445  * Note that *@a1 and @a2 should be the same type.  tal_count(@a1) will
446  * be increased by @num2.
447  *
448  * Example:
449  *      int *arr1 = tal_arrz(NULL, int, 2);
450  *      int arr2[2] = { 1, 3 };
451  *
452  *      tal_expand(&arr1, arr2, 2);
453  *      assert(tal_count(arr1) == 4);
454  *      assert(arr1[2] == 1);
455  *      assert(arr1[3] == 3);
456  */
457 #define tal_expand(a1p, a2, num2)                               \
458         tal_expand_((void **)(a1p), (a2), sizeof**(a1p),        \
459                     (num2) + 0*sizeof(*(a1p) == (a2)))
460
461 /**
462  * tal_cleanup - remove pointers from NULL node
463  *
464  * Internally, tal keeps a list of nodes allocated from @ctx NULL; this
465  * prevents valgrind from noticing memory leaks.  This re-initializes
466  * that list to empty.
467  *
468  * It also calls take_cleanup() for you.
469  */
470 void tal_cleanup(void);
471
472
473 /**
474  * tal_check - sanity check a tal context and its children.
475  * @ctx: a tal context, or NULL.
476  * @errorstr: a string to prepend calls to error_fn, or NULL.
477  *
478  * This sanity-checks a tal tree (unless NDEBUG is defined, in which case
479  * it simply returns true).  If errorstr is not null, error_fn is called
480  * when a problem is found, otherwise it is not.
481  *
482  * See also:
483  *      tal_set_backend()
484  */
485 bool tal_check(const tal_t *ctx, const char *errorstr);
486
487 #ifdef CCAN_TAL_DEBUG
488 /**
489  * tal_dump - dump entire tal tree to stderr.
490  *
491  * This is a helper for debugging tal itself, which dumps all the tal internal
492  * state.
493  */
494 void tal_dump(void);
495 #endif
496
497 /* Internal support functions */
498 #ifndef TAL_LABEL
499 #ifdef CCAN_TAL_NO_LABELS
500 #define TAL_LABEL(type, arr) NULL
501 #else
502 #ifdef CCAN_TAL_DEBUG
503 #define TAL_LABEL(type, arr) \
504         __FILE__ ":" stringify(__LINE__) ":" stringify(type) arr
505 #else
506 #define TAL_LABEL(type, arr) stringify(type) arr
507 #endif /* CCAN_TAL_DEBUG */
508 #endif
509 #endif
510
511 #if HAVE_BUILTIN_CONSTANT_P
512 #define TAL_IS_LITERAL(str) __builtin_constant_p(str)
513 #else
514 #define TAL_IS_LITERAL(str) (sizeof(&*(str)) != sizeof(char *))
515 #endif
516
517 bool tal_set_name_(tal_t *ctx, const char *name, bool literal);
518
519 #if HAVE_TYPEOF
520 #define tal_typeof(ptr) (__typeof__(ptr))
521 #if HAVE_STATEMENT_EXPR
522 /* Careful: ptr can be const foo *, ptype is foo *.  Also, ptr could
523  * be an array, eg "hello". */
524 #define tal_typechk_(ptr, ptype) ({ __typeof__((ptr)+0) _p = (ptype)(ptr); _p; })
525 #else
526 #define tal_typechk_(ptr, ptype) (ptr)
527 #endif
528 #else /* !HAVE_TYPEOF */
529 #define tal_typeof(ptr)
530 #define tal_typechk_(ptr, ptype) (ptr)
531 #endif
532
533 void *tal_alloc_(const tal_t *ctx, size_t bytes, bool clear, const char *label)
534         TAL_RETURN_PTR;
535 void *tal_alloc_arr_(const tal_t *ctx, size_t bytes, size_t count, bool clear,
536                      const char *label)
537         TAL_RETURN_PTR;
538
539 void *tal_dup_(const tal_t *ctx, const void *p TAKES, size_t size,
540                size_t n, size_t extra, bool nullok, const char *label);
541 void *tal_dup_talarr_(const tal_t *ctx, const tal_t *src TAKES,
542                       const char *label);
543
544 tal_t *tal_steal_(const tal_t *new_parent, const tal_t *t);
545
546 bool tal_resize_(tal_t **ctxp, size_t size, size_t count, bool clear);
547 bool tal_expand_(tal_t **ctxp, const void *src TAKES, size_t size, size_t count);
548
549 bool tal_add_destructor_(const tal_t *ctx, void (*destroy)(void *me));
550 bool tal_add_destructor2_(const tal_t *ctx, void (*destroy)(void *me, void *arg),
551                           void *arg);
552 bool tal_del_destructor_(const tal_t *ctx, void (*destroy)(void *me));
553 bool tal_del_destructor2_(const tal_t *ctx, void (*destroy)(void *me, void *arg),
554                           void *arg);
555
556 bool tal_add_notifier_(const tal_t *ctx, enum tal_notify_type types,
557                        void (*notify)(tal_t *ctx, enum tal_notify_type,
558                                       void *info));
559 bool tal_del_notifier_(const tal_t *ctx,
560                        void (*notify)(tal_t *ctx, enum tal_notify_type,
561                                       void *info),
562                        bool match_extra_arg, void *arg);
563 #endif /* CCAN_TAL_H */