]> git.ozlabs.org Git - ccan/blob - ccan/tal/tal.h
tal: add general notifiers.
[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  * Example:
73  *      p = tal_arr(NULL, int, 2);
74  *      p[0] = 0;
75  *      p[1] = 1;
76  */
77 #define tal_arr(ctx, type, count) \
78         ((type *)tal_alloc_((ctx), tal_sizeof_(sizeof(type), (count)), false, \
79                             TAL_LABEL(type, "[]")))
80
81 /**
82  * tal_arrz - allocate an array of zeroed objects.
83  * @ctx: NULL, or tal allocated object to be parent.
84  * @type: the type to allocate.
85  * @count: the number to allocate.
86  *
87  * Example:
88  *      p = tal_arrz(NULL, int, 2);
89  *      assert(p[0] == 0 && p[1] == 0);
90  */
91 #define tal_arrz(ctx, type, count) \
92         ((type *)tal_alloc_((ctx), tal_sizeof_(sizeof(type), (count)), true, \
93                             TAL_LABEL(type, "[]")))
94
95 /**
96  * tal_resize - enlarge or reduce a tal_arr[z].
97  * @p: A pointer to the tal allocated array to resize.
98  * @count: the number to allocate.
99  *
100  * This returns true on success (and may move *@p), or false on failure.
101  *
102  * Example:
103  *      tal_resize(&p, 100);
104  */
105 #define tal_resize(p, count) \
106         tal_resize_((void **)(p), tal_sizeof_(sizeof**(p), (count)))
107
108 /**
109  * tal_steal - change the parent of a tal-allocated pointer.
110  * @ctx: The new parent.
111  * @ptr: The tal allocated object to move.
112  *
113  * This may need to perform an allocation, in which case it may fail; thus
114  * it can return NULL, otherwise returns @ptr.
115  */
116 #if HAVE_STATEMENT_EXPR
117 /* Weird macro avoids gcc's 'warning: value computed is not used'. */
118 #define tal_steal(ctx, ptr) \
119         ({ (tal_typeof(ptr) tal_steal_((ctx),(ptr))); })
120 #else
121 #define tal_steal(ctx, ptr) \
122         (tal_typeof(ptr) tal_steal_((ctx),(ptr)))
123 #endif
124
125 /**
126  * tal_add_destructor - add a callback function when this context is destroyed.
127  * @ptr: The tal allocated object.
128  * @function: the function to call before it's freed.
129  *
130  * Note that this can only fail if your allocfn fails and your errorfn returns.
131  */
132 #define tal_add_destructor(ptr, function)                                     \
133         tal_add_destructor_((ptr), typesafe_cb(void, void *, (function), (ptr)))
134
135 /**
136  * tal_del_destructor - remove a destructor callback function.
137  * @ptr: The tal allocated object.
138  * @function: the function to call before it's freed.
139  *
140  * If @function has not been successfully added as a destructor, this returns
141  * false.
142  */
143 #define tal_del_destructor(ptr, function)                                     \
144         tal_del_destructor_((ptr), typesafe_cb(void, void *, (function), (ptr)))
145
146 enum tal_notify_type {
147         TAL_NOTIFY_FREE = 1,
148         TAL_NOTIFY_STEAL = 2,
149         TAL_NOTIFY_MOVE = 4,
150         TAL_NOTIFY_RESIZE = 8,
151         TAL_NOTIFY_RENAME = 16,
152         TAL_NOTIFY_ADD_CHILD = 32,
153         TAL_NOTIFY_DEL_CHILD = 64,
154         TAL_NOTIFY_ADD_NOTIFIER = 128,
155         TAL_NOTIFY_DEL_NOTIFIER = 256
156 };
157
158 /**
159  * tal_add_notifier - add a callback function when this context changes.
160  * @ptr: The tal allocated object.
161  * @types: Bitwise OR of the types the callback is interested in.
162  * @callback: the function to call.
163  *
164  * Note that this can only fail if your allocfn fails and your errorfn
165  * returns.  Also note that notifiers are not reliable in the case
166  * where an allocation fails, as they may be called before any
167  * allocation is actually done.
168  *
169  * TAL_NOTIFY_FREE is called when @ptr is freed, either directly or
170  * because an ancestor is freed: @info is the argument to tal_free().
171  * It is exactly equivalent to a destructor, with more information.
172  *
173  * TAL_NOTIFY_STEAL is called when @ptr's parent changes: @info is the
174  * new parent.
175  *
176  * TAL_NOTIFY_MOVE is called when @ptr is realloced (via tal_resize)
177  * and moved.  In this case, @ptr arg here is the new memory, and
178  * @info is the old pointer.
179  *
180  * TAL_NOTIFY_RESIZE is called when @ptr is realloced via tal_resize:
181  * @info is the new size, in bytes.  If the pointer has moved,
182  * TAL_NOTIFY_MOVE callbacks are called first.
183  *
184  * TAL_NOTIFY_ADD_CHILD/TAL_NOTIFY_DEL_CHILD are called when @ptr is
185  * the context for a tal() allocating call, or a direct child is
186  * tal_free()d: @info is the child.  Note that TAL_NOTIFY_DEL_CHILD is
187  * not called when this context is tal_free()d: TAL_NOTIFY_FREE is
188  * considered sufficient for that case.
189  *
190  * TAL_NOTIFY_ADD_NOTIFIER/TAL_NOTIFIER_DEL_NOTIFIER are called when
191  * a notifier is added or removed (not for this notifier): @info is the
192  * callback.
193  */
194 #define tal_add_notifier(ptr, types, callback)                          \
195         tal_add_notifier_((ptr), (types),                               \
196                           typesafe_cb_postargs(void, tal_t *, (callback), \
197                                                (ptr),                   \
198                                                enum tal_notify_type, void *))
199
200 /**
201  * tal_del_notifier - remove a notifier callback function.
202  * @ptr: The tal allocated object.
203  * @callback: the function to call.
204  */
205 #define tal_del_notifier(ptr, callback)                                 \
206         tal_del_notifier_((ptr),                                        \
207                           typesafe_cb_postargs(void, void *, (callback), \
208                                                (ptr),                   \
209                                                enum tal_notify_type, void *))
210
211 /**
212  * tal_set_name - attach a name to a tal pointer.
213  * @ptr: The tal allocated object.
214  * @name: The name to use.
215  *
216  * The name is copied, unless we're certain it's a string literal.
217  */
218 #define tal_set_name(ptr, name)                               \
219     tal_set_name_((ptr), (name), TAL_IS_LITERAL(name))
220
221 /**
222  * tal_name - get the name for a tal pointer.
223  * @ptr: The tal allocated object.
224  *
225  * Returns NULL if no name has been set.
226  */
227 const char *tal_name(const tal_t *ptr);
228
229 /**
230  * tal_first - get the first tal object child.
231  * @root: The tal allocated object to start with, or NULL.
232  *
233  * Returns NULL if there are no children.
234  */
235 tal_t *tal_first(const tal_t *root);
236
237 /**
238  * tal_next - get the next tal object child.
239  * @root: The tal allocated object to start with, or NULL.
240  * @prev: The return value from tal_first or tal_next.
241  *
242  * Returns NULL if there are no more children.  This should be safe to
243  * call on an altering tree unless @prev is no longer a descendent of
244  * @root.
245  */
246 tal_t *tal_next(const tal_t *root, const tal_t *prev);
247
248 /**
249  * tal_parent - get the parent of a tal object.
250  * @ctx: The tal allocated object.
251  *
252  * Returns the parent, which may be NULL.  Returns NULL if @ctx is NULL.
253  */
254 tal_t *tal_parent(const tal_t *ctx);
255
256 /**
257  * tal_dup - duplicate an array.
258  * @ctx: The tal allocated object to be parent of the result (may be NULL).
259  * @type: the type (should match type of @p!)
260  * @p: the array to copy (or resized & reparented if take())
261  * @n: the number of sizeof(type) entries to copy.
262  * @extra: the number of extra sizeof(type) entries to allocate.
263  */
264 #define tal_dup(ctx, type, p, n, extra)                         \
265         ((type *)tal_dup_((ctx), tal_typechk_(p, type *),       \
266                           tal_sizeof_(sizeof(type), (n)),       \
267                           tal_sizeof_(sizeof(type), (extra)),   \
268                           TAL_LABEL(type, "[]")))
269
270 /**
271  * tal_strdup - duplicate a string
272  * @ctx: NULL, or tal allocated object to be parent.
273  * @p: the string to copy (can be take()).
274  */
275 char *tal_strdup(const tal_t *ctx, const char *p);
276
277 /**
278  * tal_strndup - duplicate a limited amount of a string.
279  * @ctx: NULL, or tal allocated object to be parent.
280  * @p: the string to copy (can be take()).
281  * @n: the maximum length to copy.
282  *
283  * Always gives a nul-terminated string, with strlen() <= @n.
284  */
285 char *tal_strndup(const tal_t *ctx, const char *p, size_t n);
286
287 /**
288  * tal_asprintf - allocate a formatted string
289  * @ctx: NULL, or tal allocated object to be parent.
290  * @fmt: the printf-style format (can be take()).
291  */
292 char *tal_asprintf(const tal_t *ctx, const char *fmt, ...) PRINTF_FMT(2,3);
293
294 /**
295  * tal_vasprintf - allocate a formatted string (va_list version)
296  * @ctx: NULL, or tal allocated object to be parent.
297  * @fmt: the printf-style format (can be take()).
298  * @va: the va_list containing the format args.
299  */
300 char *tal_vasprintf(const tal_t *ctx, const char *fmt, va_list ap)
301         PRINTF_FMT(2,0);
302
303
304 /**
305  * tal_set_backend - set the allocation or error functions to use
306  * @alloc_fn: allocator or NULL (default is malloc)
307  * @resize_fn: re-allocator or NULL (default is realloc)
308  * @free_fn: free function or NULL (default is free)
309  * @error_fn: called on errors or NULL (default is abort)
310  *
311  * The defaults are set up so tal functions never return NULL, but you
312  * can override erorr_fn to change that.  error_fn can return, and is
313  * called if alloc_fn or resize_fn fail.
314  *
315  * If any parameter is NULL, that function is unchanged.
316  */
317 void tal_set_backend(void *(*alloc_fn)(size_t size),
318                      void *(*resize_fn)(void *, size_t size),
319                      void (*free_fn)(void *),
320                      void (*error_fn)(const char *msg));
321
322
323 /**
324  * tal_check - set the allocation or error functions to use
325  * @ctx: a tal context, or NULL.
326  * @errorstr: a string to prepend calls to error_fn, or NULL.
327  *
328  * This sanity-checks a tal tree (unless NDEBUG is defined, in which case
329  * it simply returns true).  If errorstr is not null, error_fn is called
330  * when a problem is found, otherwise it is not.
331  */
332 bool tal_check(const tal_t *ctx, const char *errorstr);
333
334 #ifdef CCAN_TAL_DEBUG
335 /**
336  * tal_dump - dump entire tal tree.
337  *
338  * This is a helper for debugging tal itself, which dumps all the tal internal
339  * state.
340  */
341 void tal_dump(void);
342 #endif
343
344 /* Internal support functions */
345 #ifndef TAL_LABEL
346 #ifdef CCAN_TAL_NO_LABELS
347 #define TAL_LABEL(type, arr) NULL
348 #else
349 #ifdef CCAN_TAL_DEBUG
350 #define TAL_LABEL(type, arr) \
351         __FILE__ ":" stringify(__LINE__) ":" stringify(type) arr
352 #else
353 #define TAL_LABEL(type, arr) stringify(type) arr
354 #endif /* CCAN_TAL_DEBUG */
355 #endif
356 #endif
357
358 #if HAVE_BUILTIN_CONSTANT_P
359 #define TAL_IS_LITERAL(str) __builtin_constant_p(str)
360 #else
361 #define TAL_IS_LITERAL(str) (sizeof(&*(str)) != sizeof(char *))
362 #endif
363
364 bool tal_set_name_(tal_t *ctx, const char *name, bool literal);
365
366 static inline size_t tal_sizeof_(size_t size, size_t count)
367 {
368         /* Multiplication wrap */
369         if (count && unlikely(size * count / size != count))
370                 return (size_t)-1024;
371
372         size *= count;
373
374         /* Make sure we don't wrap adding header. */
375         if (size > (size_t)-1024)
376                 return (size_t)-1024;
377
378         return size;
379 }
380
381 #if HAVE_TYPEOF
382 #define tal_typeof(ptr) (__typeof__(ptr))
383 #if HAVE_STATEMENT_EXPR
384 /* Careful: ptr can be const foo *, ptype is foo *.  Also, ptr could
385  * be an array, eg "hello". */
386 #define tal_typechk_(ptr, ptype) ({ __typeof__((ptr)+0) _p = (ptype)(ptr); _p; })
387 #else
388 #define tal_typechk_(ptr, ptype) (ptr)
389 #endif
390 #else /* !HAVE_TYPEOF */
391 #define tal_typeof(ptr)
392 #define tal_typechk_(ptr, ptype) (ptr)
393 #endif
394
395 void *tal_alloc_(const tal_t *ctx, size_t bytes, bool clear, const char *label);
396
397 void *tal_dup_(const tal_t *ctx, const void *p, size_t n, size_t extra,
398                const char *label);
399
400 tal_t *tal_steal_(const tal_t *new_parent, const tal_t *t);
401
402 bool tal_resize_(tal_t **ctxp, size_t size);
403
404 bool tal_add_destructor_(tal_t *ctx, void (*destroy)(void *me));
405 bool tal_del_destructor_(tal_t *ctx, void (*destroy)(void *me));
406
407 bool tal_add_notifier_(tal_t *ctx, enum tal_notify_type types,
408                        void (*notify)(tal_t *ctx, enum tal_notify_type,
409                                       void *info));
410 bool tal_del_notifier_(tal_t *ctx,
411                        void (*notify)(tal_t *ctx, enum tal_notify_type,
412                                       void *info));
413 #endif /* CCAN_TAL_H */