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