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