tal.h 12 KB

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