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