]> git.ozlabs.org Git - ccan/blob - ccan/tal/tal.h
b047b3894c95786e71face627907506bb7a34ff9
[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_TAKE - fake tal_t to indicate function will own arguments.
23  *
24  * Various functions take a context on which to allocate: if you use
25  * TAL_TAKE there instead, it means that the argument(s) are actually
26  * tal objects.  The returned value will share the same parent; it may
27  * even be the same pointer as the arguments.  The arguments themselves
28  * will be reused, freed, or made a child of the return value: they are
29  * no longer valid for external use.
30  */
31 #define TAL_TAKE ((tal_t *)-2L)
32
33 /**
34  * tal - basic allocator function
35  * @ctx: NULL, or tal allocated object to be parent.
36  * @type: the type to allocate.
37  *
38  * Allocates a specific type, with a given parent context.  The name
39  * of the object is a string of the type, but if CCAN_TAL_DEBUG is
40  * defined it also contains the file and line which allocated it.
41  *
42  * Example:
43  *      int *p = tal(NULL, int);
44  *      *p = 1;
45  */
46 #define tal(ctx, type) \
47         ((type *)tal_alloc_((ctx), sizeof(type), false, TAL_LABEL(type, "")))
48
49 /**
50  * talz - zeroing allocator function
51  * @ctx: NULL, or tal allocated object to be parent.
52  * @type: the type to allocate.
53  *
54  * Equivalent to tal() followed by memset() to zero.
55  *
56  * Example:
57  *      p = talz(NULL, int);
58  *      assert(*p == 0);
59  */
60 #define talz(ctx, type) \
61         ((type *)tal_alloc_((ctx), sizeof(type), true, TAL_LABEL(type, "")))
62
63 /**
64  * tal_free - free a tal-allocated pointer.
65  * @p: NULL, or tal allocated object to free.
66  *
67  * This calls the destructors for p (if any), then does the same for all its
68  * children (recursively) before finally freeing the memory.
69  *
70  * Note: errno is preserved by this call.
71  *
72  * Example:
73  *      tal_free(p);
74  */
75 void tal_free(const tal_t *p);
76
77 /**
78  * tal_arr - allocate an array of objects.
79  * @ctx: NULL, or tal allocated object to be parent.
80  * @type: the type to allocate.
81  * @count: the number to allocate.
82  *
83  * Example:
84  *      p = tal_arr(NULL, int, 2);
85  *      p[0] = 0;
86  *      p[1] = 1;
87  */
88 #define tal_arr(ctx, type, count) \
89         ((type *)tal_alloc_((ctx), tal_sizeof_(sizeof(type), (count)), false, \
90                             TAL_LABEL(type, "[]")))
91
92 /**
93  * tal_arrz - allocate an array of zeroed objects.
94  * @ctx: NULL, or tal allocated object to be parent.
95  * @type: the type to allocate.
96  * @count: the number to allocate.
97  *
98  * Example:
99  *      p = tal_arrz(NULL, int, 2);
100  *      assert(p[0] == 0 && p[1] == 0);
101  */
102 #define tal_arrz(ctx, type, count) \
103         ((type *)tal_alloc_((ctx), tal_sizeof_(sizeof(type), (count)), true, \
104                             TAL_LABEL(type, "[]")))
105
106 /**
107  * tal_resize - enlarge or reduce a tal_arr[z].
108  * @p: A pointer to the tal allocated array to resize.
109  * @count: the number to allocate.
110  *
111  * This returns true on success (and may move *@p), or false on failure.
112  *
113  * Example:
114  *      tal_resize(&p, 100);
115  */
116 #define tal_resize(p, count) \
117         tal_resize_((void **)(p), tal_sizeof_(sizeof**(p), (count)))
118
119 /**
120  * tal_steal - change the parent of a tal-allocated pointer.
121  * @ctx: The new parent.
122  * @ptr: The tal allocated object to move.
123  *
124  * This may need to perform an allocation, in which case it may fail; thus
125  * it can return NULL, otherwise returns @ptr.
126  *
127  * Note: weird macro avoids gcc's 'warning: value computed is not used'.
128  */
129 #if HAVE_STATEMENT_EXPR
130 #define tal_steal(ctx, ptr) \
131         ({ (tal_typeof(ptr) tal_steal_((ctx),(ptr))); })
132 #else
133 #define tal_steal(ctx, ptr) \
134         (tal_typeof(ptr) tal_steal_((ctx),(ptr)))
135 #endif
136
137 /**
138  * tal_add_destructor - add a callback function when this context is destroyed.
139  * @ptr: The tal allocated object.
140  * @function: the function to call before it's freed.
141  */
142 #define tal_add_destructor(ptr, function)                                     \
143         tal_add_destructor_((ptr), typesafe_cb(void, void *, (function), (ptr)))
144
145 /**
146  * tal_set_name - attach a name to a tal pointer.
147  * @ptr: The tal allocated object.
148  * @name: The name to use.
149  *
150  * The name is copied, unless we're certain it's a string literal.
151  */
152 #define tal_set_name(ptr, name)                               \
153     tal_set_name_((ptr), (name), TAL_IS_LITERAL(name))
154
155 /**
156  * tal_name - get the name for a tal pointer.
157  * @ptr: The tal allocated object.
158  *
159  * Returns NULL if no name has been set.
160  */
161 const char *tal_name(const tal_t *ptr);
162
163 /**
164  * tal_first - get the first tal object child.
165  * @root: The tal allocated object to start with, or NULL.
166  *
167  * Returns NULL if there are no children.
168  */
169 tal_t *tal_first(const tal_t *root);
170
171 /**
172  * tal_next - get the next tal object child.
173  * @root: The tal allocated object to start with, or NULL.
174  * @prev: The return value from tal_first or tal_next.
175  *
176  * Returns NULL if there are no more children.  This should be safe to
177  * call on an altering tree unless @prev is no longer a descendent of
178  * @root.
179  */
180 tal_t *tal_next(const tal_t *root, const tal_t *prev);
181
182 /**
183  * tal_parent - get the parent of a tal object.
184  * @ctx: The tal allocated object.
185  *
186  * Returns the parent, which may be NULL.  Returns NULL if @ctx is NULL.
187  */
188 tal_t *tal_parent(const tal_t *ctx);
189
190 /**
191  * tal_dup - duplicate an array.
192  * @ctx: NULL, or tal allocated object to be parent (or TAL_TAKE).
193  * @type: the type (should match type of @p!)
194  * @p: the array to copy
195  * @n: the number of sizeof(type) entries to copy.
196  * @extra: the number of extra sizeof(type) entries to allocate.
197  */
198 #define tal_dup(ctx, type, p, n, extra)                         \
199         ((type *)tal_dup_((ctx), tal_typechk_(p, type *),       \
200                           tal_sizeof_(sizeof(type), (n)),       \
201                           tal_sizeof_(sizeof(type), (extra)),   \
202                           TAL_LABEL(type, "[]")))
203
204 /**
205  * tal_strdup - duplicate a string
206  * @ctx: NULL, or tal allocated object to be parent (or TAL_TAKE).
207  * @p: the string to copy
208  */
209 char *tal_strdup(const tal_t *ctx, const char *p);
210
211 /**
212  * tal_strndup - duplicate a limited amount of a string.
213  * @ctx: NULL, or tal allocated object to be parent (or TAL_TAKE).
214  * @p: the string to copy
215  * @n: the maximum length to copy.
216  *
217  * Always gives a nul-terminated string, with strlen() <= @n.
218  */
219 char *tal_strndup(const tal_t *ctx, const char *p, size_t n);
220
221 /**
222  * tal_asprintf - allocate a formatted string
223  * @ctx: NULL, or tal allocated object to be parent (or TAL_TAKE).
224  * @fmt: the printf-style format.
225  *
226  * If @ctx is TAL_TAKE, @fmt is freed and its parent will be the parent
227  * of the return value.
228  */
229 char *tal_asprintf(const tal_t *ctx, const char *fmt, ...) PRINTF_FMT(2,3);
230
231 /**
232  * tal_vasprintf - allocate a formatted string (va_list version)
233  * @ctx: NULL, or tal allocated object to be parent (or TAL_TAKE).
234  * @fmt: the printf-style format.
235  * @va: the va_list containing the format args.
236  *
237  * If @ctx is TAL_TAKE, @fmt is freed and its parent will be the parent
238  * of the return value.
239  */
240 char *tal_vasprintf(const tal_t *ctx, const char *fmt, va_list ap)
241         PRINTF_FMT(2,0);
242
243
244 /**
245  * tal_set_backend - set the allocation or error functions to use
246  * @alloc_fn: allocator or NULL (default is malloc)
247  * @resize_fn: re-allocator or NULL (default is realloc)
248  * @free_fn: free function or NULL (default is free)
249  * @error_fn: called on errors or NULL (default is abort)
250  *
251  * The defaults are set up so tal functions never return NULL, but you
252  * can override erorr_fn to change that.  error_fn can return, and is
253  * called if alloc_fn or resize_fn fail.
254  *
255  * If any parameter is NULL, that function is unchanged.
256  */
257 void tal_set_backend(void *(*alloc_fn)(size_t size),
258                      void *(*resize_fn)(void *, size_t size),
259                      void (*free_fn)(void *),
260                      void (*error_fn)(const char *msg));
261
262
263 /**
264  * tal_check - set the allocation or error functions to use
265  * @ctx: a tal context, or NULL.
266  * @errorstr: a string to prepend calls to error_fn, or NULL.
267  *
268  * This sanity-checks a tal tree (unless NDEBUG is defined, in which case
269  * it simply returns true).  If errorstr is not null, error_fn is called
270  * when a problem is found, otherwise it is not.
271  */
272 bool tal_check(const tal_t *ctx, const char *errorstr);
273
274 #ifdef CCAN_TAL_DEBUG
275 /**
276  * tal_dump - dump entire tal tree.
277  *
278  * This is a helper for debugging tal itself, which dumps all the tal internal
279  * state.
280  */
281 void tal_dump(void);
282 #endif
283
284 /* Internal support functions */
285 #ifndef TAL_LABEL
286 #ifdef CCAN_TAL_NO_LABELS
287 #define TAL_LABEL(type, arr) NULL
288 #else
289 #ifdef CCAN_TAL_DEBUG
290 #define TAL_LABEL(type, arr) \
291         __FILE__ ":" stringify(__LINE__) ":" stringify(type) arr
292 #else
293 #define TAL_LABEL(type, arr) stringify(type) arr
294 #endif /* CCAN_TAL_DEBUG */
295 #endif
296 #endif
297
298 #if HAVE_BUILTIN_CONSTANT_P
299 #define TAL_IS_LITERAL(str) __builtin_constant_p(str)
300 #else
301 #define TAL_IS_LITERAL(str) (sizeof(&*(str)) != sizeof(char *))
302 #endif
303
304 bool tal_set_name_(tal_t *ctx, const char *name, bool literal);
305
306 static inline size_t tal_sizeof_(size_t size, size_t count)
307 {
308         /* Multiplication wrap */
309         if (count && unlikely(size * count / size != count))
310                 return (size_t)-1024;
311
312         size *= count;
313
314         /* Make sure we don't wrap adding header. */
315         if (size > (size_t)-1024)
316                 return (size_t)-1024;
317
318         return size;
319 }
320
321 #if HAVE_TYPEOF
322 #define tal_typeof(ptr) (__typeof__(ptr))
323 #if HAVE_STATEMENT_EXPR
324 /* Careful: ptr can be const foo *, ptype is foo *.  Also, ptr could
325  * be an array, eg "hello". */
326 #define tal_typechk_(ptr, ptype) ({ __typeof__(&*(ptr)) _p = (ptype)(ptr); _p; })
327 #else
328 #define tal_typechk_(ptr, ptype) (ptr)
329 #endif
330 #else /* !HAVE_TYPEOF */
331 #define tal_typeof(ptr)
332 #define tal_typechk_(ptr, ptype) (ptr)
333 #endif
334
335 void *tal_alloc_(const tal_t *ctx, size_t bytes, bool clear, const char *label);
336
337 void *tal_dup_(const tal_t *ctx, const void *p, size_t n, size_t extra,
338                const char *label);
339
340 tal_t *tal_steal_(const tal_t *new_parent, const tal_t *t);
341
342 bool tal_resize_(tal_t **ctxp, size_t size);
343
344 bool tal_add_destructor_(tal_t *ctx, void (*destroy)(void *me));
345
346 #endif /* CCAN_TAL_H */