]> git.ozlabs.org Git - ccan/blob - ccan/tal/tal.h
f360a9611a8730838b6af1a9b23a2381b3bbc294
[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, 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, 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.
60  *
61  * Example:
62  *      p = tal_free(p);
63  */
64 void *tal_free(const tal_t *p);
65
66 /**
67  * tal_arr - allocate an array of objects.
68  * @ctx: NULL, or tal allocated object to be parent.
69  * @type: the type to allocate.
70  * @count: the number to allocate.
71  *
72  * Note that an object allocated with tal_arr() has a length property;
73  * see tal_count().
74  *
75  * Example:
76  *      p = tal_arr(NULL, int, 2);
77  *      p[0] = 0;
78  *      p[1] = 1;
79  */
80 #define tal_arr(ctx, type, count)                                       \
81         ((type *)tal_alloc_arr_((ctx), sizeof(type), (count), false,    \
82                                 true, TAL_LABEL(type, "[]")))
83
84 /**
85  * tal_arrz - allocate an array of zeroed objects.
86  * @ctx: NULL, or tal allocated object to be parent.
87  * @type: the type to allocate.
88  * @count: the number to allocate.
89  *
90  * Note that an object allocated with tal_arrz() has a length property;
91  * see tal_count().
92  *
93  * Example:
94  *      p = tal_arrz(NULL, int, 2);
95  *      assert(p[0] == 0 && p[1] == 0);
96  */
97 #define tal_arrz(ctx, type, count) \
98         ((type *)tal_alloc_arr_((ctx), sizeof(type), (count), true,     \
99                                 true, 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 enum tal_notify_type {
172         TAL_NOTIFY_FREE = 1,
173         TAL_NOTIFY_STEAL = 2,
174         TAL_NOTIFY_MOVE = 4,
175         TAL_NOTIFY_RESIZE = 8,
176         TAL_NOTIFY_RENAME = 16,
177         TAL_NOTIFY_ADD_CHILD = 32,
178         TAL_NOTIFY_DEL_CHILD = 64,
179         TAL_NOTIFY_ADD_NOTIFIER = 128,
180         TAL_NOTIFY_DEL_NOTIFIER = 256
181 };
182
183 /**
184  * tal_add_notifier - add a callback function when this context changes.
185  * @ptr: The tal allocated object.
186  * @types: Bitwise OR of the types the callback is interested in.
187  * @callback: the function to call.
188  *
189  * Note that this can only fail if your allocfn fails and your errorfn
190  * returns.  Also note that notifiers are not reliable in the case
191  * where an allocation fails, as they may be called before any
192  * allocation is actually done.
193  *
194  * TAL_NOTIFY_FREE is called when @ptr is freed, either directly or
195  * because an ancestor is freed: @info is the argument to tal_free().
196  * It is exactly equivalent to a destructor, with more information.
197  *
198  * TAL_NOTIFY_STEAL is called when @ptr's parent changes: @info is the
199  * new parent.
200  *
201  * TAL_NOTIFY_MOVE is called when @ptr is realloced (via tal_resize)
202  * and moved.  In this case, @ptr arg here is the new memory, and
203  * @info is the old pointer.
204  *
205  * TAL_NOTIFY_RESIZE is called when @ptr is realloced via tal_resize:
206  * @info is the new size, in bytes.  If the pointer has moved,
207  * TAL_NOTIFY_MOVE callbacks are called first.
208  *
209  * TAL_NOTIFY_ADD_CHILD/TAL_NOTIFY_DEL_CHILD are called when @ptr is
210  * the context for a tal() allocating call, or a direct child is
211  * tal_free()d: @info is the child.  Note that TAL_NOTIFY_DEL_CHILD is
212  * not called when this context is tal_free()d: TAL_NOTIFY_FREE is
213  * considered sufficient for that case.
214  *
215  * TAL_NOTIFY_ADD_NOTIFIER/TAL_NOTIFIER_DEL_NOTIFIER are called when a
216  * notifier is added or removed (not for this notifier): @info is the
217  * callback.  This is also called for tal_add_destructor and
218  * tal_del_destructor.
219  */
220 #define tal_add_notifier(ptr, types, callback)                          \
221         tal_add_notifier_((ptr), (types),                               \
222                           typesafe_cb_postargs(void, tal_t *, (callback), \
223                                                (ptr),                   \
224                                                enum tal_notify_type, void *))
225
226 /**
227  * tal_del_notifier - remove a notifier callback function.
228  * @ptr: The tal allocated object.
229  * @callback: the function to call.
230  */
231 #define tal_del_notifier(ptr, callback)                                 \
232         tal_del_notifier_((ptr),                                        \
233                           typesafe_cb_postargs(void, void *, (callback), \
234                                                (ptr),                   \
235                                                enum tal_notify_type, void *))
236
237 /**
238  * tal_set_name - attach a name to a tal pointer.
239  * @ptr: The tal allocated object.
240  * @name: The name to use.
241  *
242  * The name is copied, unless we're certain it's a string literal.
243  */
244 #define tal_set_name(ptr, name)                               \
245     tal_set_name_((ptr), (name), TAL_IS_LITERAL(name))
246
247 /**
248  * tal_name - get the name for a tal pointer.
249  * @ptr: The tal allocated object.
250  *
251  * Returns NULL if no name has been set.
252  */
253 const char *tal_name(const tal_t *ptr);
254
255 /**
256  * tal_count - get the count of objects in a tal_arr.
257  * @ptr: The tal allocated object array.
258  *
259  * Returns 0 if @ptr has no length property, but be aware that that is
260  * also a valid size!
261  */
262 size_t tal_count(const tal_t *ptr);
263
264 /**
265  * tal_first - get the first tal object child.
266  * @root: The tal allocated object to start with, or NULL.
267  *
268  * Returns NULL if there are no children.
269  */
270 tal_t *tal_first(const tal_t *root);
271
272 /**
273  * tal_next - get the next tal object child.
274  * @root: The tal allocated object to start with, or NULL.
275  * @prev: The return value from tal_first or tal_next.
276  *
277  * Returns NULL if there are no more children.  This should be safe to
278  * call on an altering tree unless @prev is no longer a descendent of
279  * @root.
280  */
281 tal_t *tal_next(const tal_t *root, const tal_t *prev);
282
283 /**
284  * tal_parent - get the parent of a tal object.
285  * @ctx: The tal allocated object.
286  *
287  * Returns the parent, which may be NULL.  Returns NULL if @ctx is NULL.
288  */
289 tal_t *tal_parent(const tal_t *ctx);
290
291 /**
292  * tal_dup - duplicate an object.
293  * @ctx: The tal allocated object to be parent of the result (may be NULL).
294  * @type: the type (should match type of @p!)
295  * @p: the object to copy (or reparented if take())
296  */
297 #define tal_dup(ctx, type, p)                   \
298         ((type *)tal_dup_((ctx), tal_typechk_(p, type *),       \
299                           sizeof(type), 1, 0,                   \
300                           false, TAL_LABEL(type, "")))
301
302 /**
303  * tal_dup_arr - duplicate an array.
304  * @ctx: The tal allocated object to be parent of the result (may be NULL).
305  * @type: the type (should match type of @p!)
306  * @p: the array to copy (or resized & reparented if take())
307  * @n: the number of sizeof(type) entries to copy.
308  * @extra: the number of extra sizeof(type) entries to allocate.
309  */
310 #define tal_dup_arr(ctx, type, p, n, extra)                     \
311         ((type *)tal_dup_((ctx), tal_typechk_(p, type *),       \
312                           sizeof(type), (n), (extra),           \
313                           true, TAL_LABEL(type, "[]")))
314
315
316 /**
317  * tal_set_backend - set the allocation or error functions to use
318  * @alloc_fn: allocator or NULL (default is malloc)
319  * @resize_fn: re-allocator or NULL (default is realloc)
320  * @free_fn: free function or NULL (default is free)
321  * @error_fn: called on errors or NULL (default is abort)
322  *
323  * The defaults are set up so tal functions never return NULL, but you
324  * can override erorr_fn to change that.  error_fn can return, and is
325  * called if alloc_fn or resize_fn fail.
326  *
327  * If any parameter is NULL, that function is unchanged.
328  */
329 void tal_set_backend(void *(*alloc_fn)(size_t size),
330                      void *(*resize_fn)(void *, size_t size),
331                      void (*free_fn)(void *),
332                      void (*error_fn)(const char *msg));
333
334 /**
335  * tal_expand - expand a tal array with contents.
336  * @a1p: a pointer to the tal array to expand.
337  * @a2: the second array (can be take()).
338  * @num2: the number of elements in the second array.
339  *
340  * Note that *@a1 and @a2 should be the same type.  tal_count(@a1) will
341  * be increased by @num2.
342  *
343  * Example:
344  *      int *arr1 = tal_arrz(NULL, int, 2);
345  *      int arr2[2] = { 1, 3 };
346  *
347  *      tal_expand(&arr1, arr2, 2);
348  *      assert(tal_count(arr1) == 4);
349  *      assert(arr1[2] == 1);
350  *      assert(arr1[3] == 3);
351  */
352 #define tal_expand(a1p, a2, num2)                               \
353         tal_expand_((void **)(a1p), (a2), sizeof**(a1p),        \
354                     (num2) + 0*sizeof(*(a1p) == (a2)))
355
356 /**
357  * tal_cleanup - remove pointers from NULL node
358  *
359  * Internally, tal keeps a list of nodes allocated from @ctx NULL; this
360  * prevents valgrind from noticing memory leaks.  This re-initializes
361  * that list to empty.
362  *
363  * It also calls take_cleanup() for you.
364  */
365 void tal_cleanup(void);
366
367
368 /**
369  * tal_check - sanity check a tal context and its children.
370  * @ctx: a tal context, or NULL.
371  * @errorstr: a string to prepend calls to error_fn, or NULL.
372  *
373  * This sanity-checks a tal tree (unless NDEBUG is defined, in which case
374  * it simply returns true).  If errorstr is not null, error_fn is called
375  * when a problem is found, otherwise it is not.
376  *
377  * See also:
378  *      tal_set_backend()
379  */
380 bool tal_check(const tal_t *ctx, const char *errorstr);
381
382 #ifdef CCAN_TAL_DEBUG
383 /**
384  * tal_dump - dump entire tal tree.
385  *
386  * This is a helper for debugging tal itself, which dumps all the tal internal
387  * state.
388  */
389 void tal_dump(void);
390 #endif
391
392 /* Internal support functions */
393 #ifndef TAL_LABEL
394 #ifdef CCAN_TAL_NO_LABELS
395 #define TAL_LABEL(type, arr) NULL
396 #else
397 #ifdef CCAN_TAL_DEBUG
398 #define TAL_LABEL(type, arr) \
399         __FILE__ ":" stringify(__LINE__) ":" stringify(type) arr
400 #else
401 #define TAL_LABEL(type, arr) stringify(type) arr
402 #endif /* CCAN_TAL_DEBUG */
403 #endif
404 #endif
405
406 #if HAVE_BUILTIN_CONSTANT_P
407 #define TAL_IS_LITERAL(str) __builtin_constant_p(str)
408 #else
409 #define TAL_IS_LITERAL(str) (sizeof(&*(str)) != sizeof(char *))
410 #endif
411
412 bool tal_set_name_(tal_t *ctx, const char *name, bool literal);
413
414 #if HAVE_TYPEOF
415 #define tal_typeof(ptr) (__typeof__(ptr))
416 #if HAVE_STATEMENT_EXPR
417 /* Careful: ptr can be const foo *, ptype is foo *.  Also, ptr could
418  * be an array, eg "hello". */
419 #define tal_typechk_(ptr, ptype) ({ __typeof__((ptr)+0) _p = (ptype)(ptr); _p; })
420 #else
421 #define tal_typechk_(ptr, ptype) (ptr)
422 #endif
423 #else /* !HAVE_TYPEOF */
424 #define tal_typeof(ptr)
425 #define tal_typechk_(ptr, ptype) (ptr)
426 #endif
427
428 void *tal_alloc_(const tal_t *ctx, size_t bytes, bool clear, const char *label);
429 void *tal_alloc_arr_(const tal_t *ctx, size_t bytes, size_t count, bool clear,
430                      bool add_count, const char *label);
431
432 void *tal_dup_(const tal_t *ctx, const void *p, size_t size,
433                size_t n, size_t extra, bool add_count,
434                const char *label);
435
436 tal_t *tal_steal_(const tal_t *new_parent, const tal_t *t);
437
438 bool tal_resize_(tal_t **ctxp, size_t size, size_t count, bool clear);
439 bool tal_expand_(tal_t **ctxp, const void *src, size_t size, size_t count);
440
441 bool tal_add_destructor_(const tal_t *ctx, void (*destroy)(void *me));
442 bool tal_del_destructor_(const tal_t *ctx, void (*destroy)(void *me));
443
444 bool tal_add_notifier_(const tal_t *ctx, enum tal_notify_type types,
445                        void (*notify)(tal_t *ctx, enum tal_notify_type,
446                                       void *info));
447 bool tal_del_notifier_(const tal_t *ctx,
448                        void (*notify)(tal_t *ctx, enum tal_notify_type,
449                                       void *info));
450 #endif /* CCAN_TAL_H */