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