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