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