c78185be01aa12715a0499088974ab8f561ccee6
[ccan] / ccan / tal / tal.c
1 /* Licensed under BSD-MIT - see LICENSE file for details */
2 #include <ccan/tal/tal.h>
3 #include <ccan/compiler/compiler.h>
4 #include <ccan/list/list.h>
5 #include <ccan/take/take.h>
6 #include <assert.h>
7 #include <stdio.h>
8 #include <stdarg.h>
9 #include <stddef.h>
10 #include <string.h>
11 #include <limits.h>
12 #include <errno.h>
13
14 //#define TAL_DEBUG 1
15
16 #define NOTIFY_IS_DESTRUCTOR 512
17
18 /* 32-bit type field, first byte 0 in either endianness. */
19 enum prop_type {
20         CHILDREN = 0x00c1d500,
21         NAME = 0x00111100,
22         NOTIFIER = 0x00071f00,
23         LENGTH = 0x00515300
24 };
25
26 struct tal_hdr {
27         struct list_node list;
28         struct prop_hdr *prop;
29         struct children *parent_child;
30 };
31
32 struct prop_hdr {
33         enum prop_type type;
34         struct prop_hdr *next;
35 };
36
37 struct children {
38         struct prop_hdr hdr; /* CHILDREN */
39         struct tal_hdr *parent;
40         struct list_head children; /* Head of siblings. */
41 };
42
43 struct name {
44         struct prop_hdr hdr; /* NAME */
45         char name[];
46 };
47
48 struct length {
49         struct prop_hdr hdr; /* LENGTH */
50         size_t count;
51 };
52
53 struct notifier {
54         struct prop_hdr hdr; /* NOTIFIER */
55         enum tal_notify_type types;
56         union {
57                 void (*notifyfn)(tal_t *, enum tal_notify_type, void *);
58                 void (*destroy)(tal_t *); /* If NOTIFY_IS_DESTRUCTOR set */
59         } u;
60 };
61
62 static struct {
63         struct tal_hdr hdr;
64         struct children c;
65 } null_parent = { { { &null_parent.hdr.list, &null_parent.hdr.list },
66                     &null_parent.c.hdr, NULL },
67                   { { CHILDREN, NULL },
68                     &null_parent.hdr,
69                     { { &null_parent.c.children.n,
70                         &null_parent.c.children.n } }
71                   }
72 };
73
74
75 static void *(*allocfn)(size_t size) = malloc;
76 static void *(*resizefn)(void *, size_t size) = realloc;
77 static void (*freefn)(void *) = free;
78 static void (*errorfn)(const char *msg) = (void *)abort;
79 static bool initialized = false;
80 /* Count on non-destrutor notifiers; often stays zero. */
81 static size_t notifiers = 0;
82
83 static inline void COLD call_error(const char *msg)
84 {
85         errorfn(msg);
86 }
87
88 static bool get_destroying_bit(struct children *parent_child)
89 {
90         return (size_t)parent_child & 1;
91 }
92
93 static void set_destroying_bit(struct children **parent_child)
94 {
95         *parent_child = (void *)((size_t)*parent_child | 1);
96 }
97
98 static struct children *ignore_destroying_bit(struct children *parent_child)
99 {
100         return (void *)((size_t)parent_child & ~(size_t)1);
101 }
102
103 /* This means valgrind can see leaks. */
104 static void tal_cleanup(void)
105 {
106         struct tal_hdr *i;
107
108         while ((i = list_top(&null_parent.c.children, struct tal_hdr, list)))
109                 list_del(&i->list);
110
111         /* Cleanup any taken pointers. */
112         take_cleanup();
113 }
114
115 /* For allocation failures inside ccan/take */
116 static void take_alloc_failed(const void *p)
117 {
118         tal_free(p);
119 }
120
121 /* We carefully start all real properties with a zero byte. */
122 static bool is_literal(const struct prop_hdr *prop)
123 {
124         return ((char *)prop)[0] != 0;
125 }
126
127 #ifndef NDEBUG
128 static const void *bounds_start, *bounds_end;
129
130 static void update_bounds(const void *new, size_t size)
131 {
132         if (unlikely(!bounds_start)) {
133                 bounds_start = new;
134                 bounds_end = (char *)new + size;
135         } else if (new < bounds_start)
136                 bounds_start = new;
137         else if ((char *)new + size > (char *)bounds_end)
138                 bounds_end = (char *)new + size;
139 }
140
141 static bool in_bounds(const void *p)
142 {
143         return !p
144                 || (p >= (void *)&null_parent && p <= (void *)(&null_parent + 1))
145                 || (p >= bounds_start && p <= bounds_end);
146 }
147 #else
148 static void update_bounds(const void *new, size_t size)
149 {
150 }
151
152 static bool in_bounds(const void *p)
153 {
154         return true;
155 }
156 #endif
157
158 static void check_bounds(const void *p)
159 {
160         if (!in_bounds(p))
161                 call_error("Not a valid header");
162 }
163
164 static struct tal_hdr *to_tal_hdr(const void *ctx)
165 {
166         struct tal_hdr *t;
167
168         t = (struct tal_hdr *)((char *)ctx - sizeof(struct tal_hdr));
169         check_bounds(t);
170         check_bounds(ignore_destroying_bit(t->parent_child));
171         check_bounds(t->list.next);
172         check_bounds(t->list.prev);
173         if (t->prop && !is_literal(t->prop))
174                 check_bounds(t->prop);
175         return t;
176 }
177
178 static struct tal_hdr *to_tal_hdr_or_null(const void *ctx)
179 {
180         if (!ctx)
181                 return &null_parent.hdr;
182         return to_tal_hdr(ctx);
183 }
184
185 static void *from_tal_hdr(const struct tal_hdr *hdr)
186 {
187         return (void *)(hdr + 1);
188 }
189
190 #ifdef TAL_DEBUG
191 static void *from_tal_hdr_or_null(struct tal_hdr *hdr)
192 {
193         if (hdr == &null_parent.hdr)
194                 return NULL;
195         return from_tal_hdr(hdr);
196 }
197
198 static struct tal_hdr *debug_tal(struct tal_hdr *tal)
199 {
200         tal_check(from_tal_hdr_or_null(tal), "TAL_DEBUG ");
201         return tal;
202 }
203 #else
204 static struct tal_hdr *debug_tal(struct tal_hdr *tal)
205 {
206         return tal;
207 }
208 #endif
209
210 static void notify(const struct tal_hdr *ctx,
211                    enum tal_notify_type type, const void *info)
212 {
213         const struct prop_hdr *p;
214
215         for (p = ctx->prop; p; p = p->next) {
216                 struct notifier *n;
217
218                 if (is_literal(p))
219                         break;
220                 if (p->type != NOTIFIER)
221                         continue;
222                 n = (struct notifier *)p;
223                 if (n->types & type) {
224                         if (n->types & NOTIFY_IS_DESTRUCTOR)
225                                 n->u.destroy(from_tal_hdr(ctx));
226                         else
227                                 n->u.notifyfn(from_tal_hdr(ctx), type,
228                                               (void *)info);
229                 }
230         }
231 }
232
233 static void *allocate(size_t size)
234 {
235         void *ret = allocfn(size);
236         if (!ret)
237                 call_error("allocation failed");
238         else
239                 update_bounds(ret, size);
240         return ret;
241 }
242
243 static struct prop_hdr **find_property_ptr(const struct tal_hdr *t,
244                                            enum prop_type type)
245 {
246         struct prop_hdr **p;
247
248         for (p = (struct prop_hdr **)&t->prop; *p; p = &(*p)->next) {
249                 if (is_literal(*p)) {
250                         if (type == NAME)
251                                 return p;
252                         break;
253                 }
254                 if ((*p)->type == type)
255                         return p;
256         }
257         return NULL;
258 }
259
260 static void *find_property(const struct tal_hdr *parent, enum prop_type type)
261 {
262         struct prop_hdr **p = find_property_ptr(parent, type);
263
264         if (p)
265                 return *p;
266         return NULL;
267 }
268
269 static void init_property(struct prop_hdr *hdr,
270                           struct tal_hdr *parent,
271                           enum prop_type type)
272 {
273         hdr->type = type;
274         hdr->next = parent->prop;
275         parent->prop = hdr;
276 }
277
278 static struct notifier *add_notifier_property(struct tal_hdr *t,
279                                               enum tal_notify_type types,
280                                               void (*fn)(void *,
281                                                          enum tal_notify_type,
282                                                          void *))
283 {
284         struct notifier *prop = allocate(sizeof(*prop));
285         if (prop) {
286                 init_property(&prop->hdr, t, NOTIFIER);
287                 prop->types = types;
288                 prop->u.notifyfn = fn;
289         }
290         return prop;
291 }
292
293 static enum tal_notify_type del_notifier_property(struct tal_hdr *t,
294                                                   void (*fn)(tal_t *,
295                                                              enum tal_notify_type,
296                                                              void *))
297 {
298         struct prop_hdr **p;
299
300         for (p = (struct prop_hdr **)&t->prop; *p; p = &(*p)->next) {
301                 struct notifier *n;
302
303                 if (is_literal(*p))
304                         break;
305                 if ((*p)->type != NOTIFIER)
306                         continue;
307                 n = (struct notifier *)*p;
308                 if (n->u.notifyfn == fn) {
309                         enum tal_notify_type types = n->types;
310                         *p = (*p)->next;
311                         freefn(n);
312                         return types & ~NOTIFY_IS_DESTRUCTOR;
313                 }
314         }
315         return 0;
316 }
317
318 static struct name *add_name_property(struct tal_hdr *t, const char *name)
319 {
320         struct name *prop;
321
322         prop = allocate(sizeof(*prop) + strlen(name) + 1);
323         if (prop) {
324                 init_property(&prop->hdr, t, NAME);
325                 strcpy(prop->name, name);
326         }
327         return prop;
328 }
329
330 static struct length *add_length_property(struct tal_hdr *t, size_t count)
331 {
332         struct length *prop;
333
334         prop = allocate(sizeof(*prop));
335         if (prop) {
336                 init_property(&prop->hdr, t, LENGTH);
337                 prop->count = count;
338         }
339         return prop;
340 }
341
342 static struct children *add_child_property(struct tal_hdr *parent,
343                                            struct tal_hdr *child)
344 {
345         struct children *prop = allocate(sizeof(*prop));
346         if (prop) {
347                 init_property(&prop->hdr, parent, CHILDREN);
348                 prop->parent = parent;
349                 list_head_init(&prop->children);
350         }
351         return prop;
352 }
353
354 static bool add_child(struct tal_hdr *parent, struct tal_hdr *child)
355 {
356         struct children *children = find_property(parent, CHILDREN);
357
358         if (!children) {
359                 if (unlikely(!initialized)) {
360                         atexit(tal_cleanup);
361                         take_allocfail(take_alloc_failed);
362                         initialized = true;
363                 }
364                 children = add_child_property(parent, child);
365                 if (!children)
366                         return false;
367         }
368         list_add(&children->children, &child->list);
369         child->parent_child = children;
370         return true;
371 }
372
373 static void del_tree(struct tal_hdr *t, const tal_t *orig)
374 {
375         struct prop_hdr **prop, *p, *next;
376
377         /* Already being destroyed?  Don't loop. */
378         if (unlikely(get_destroying_bit(t->parent_child)))
379                 return;
380
381         set_destroying_bit(&t->parent_child);
382
383         /* Call free notifiers. */
384         notify(t, TAL_NOTIFY_FREE, (tal_t *)orig);
385
386         /* Now free children and groups. */
387         prop = find_property_ptr(t, CHILDREN);
388         if (prop) {
389                 struct tal_hdr *i;
390                 struct children *c = (struct children *)*prop;
391
392                 while ((i = list_top(&c->children, struct tal_hdr, list))) {
393                         list_del(&i->list);
394                         del_tree(i, orig);
395                 }
396         }
397
398         /* Finally free our properties. */
399         for (p = t->prop; p && !is_literal(p); p = next) {
400                 next = p->next;
401                 freefn(p);
402         }
403         freefn(t);
404 }
405
406 void *tal_alloc_(const tal_t *ctx, size_t size, bool clear, const char *label)
407 {
408         struct tal_hdr *child, *parent = debug_tal(to_tal_hdr_or_null(ctx));
409
410         child = allocate(sizeof(struct tal_hdr) + size);
411         if (!child)
412                 return NULL;
413         if (clear)
414                 memset(from_tal_hdr(child), 0, size);
415         child->prop = (void *)label;
416         if (!add_child(parent, child)) {
417                 freefn(child);
418                 return NULL;
419         }
420         debug_tal(parent);
421         if (notifiers)
422                 notify(parent, TAL_NOTIFY_ADD_CHILD, from_tal_hdr(child));
423         return from_tal_hdr(debug_tal(child));
424 }
425
426 static bool adjust_size(size_t *size, size_t count)
427 {
428         /* Multiplication wrap */
429         if (count && unlikely(*size * count / *size != count))
430                 goto overflow;
431
432         *size *= count;
433
434         /* Make sure we don't wrap adding header. */
435         if (*size + sizeof(struct tal_hdr) < sizeof(struct tal_hdr))
436                 goto overflow;
437         return true;
438 overflow:
439         call_error("allocation size overflow");
440         return false;
441 }
442
443 void *tal_alloc_arr_(const tal_t *ctx, size_t size, size_t count, bool clear,
444                      bool add_count, const char *label)
445 {
446         void *ret;
447
448         if (!adjust_size(&size, count))
449                 return NULL;
450
451         ret = tal_alloc_(ctx, size, clear, label);
452         if (likely(ret) && add_count) {
453                 if (unlikely(!add_length_property(to_tal_hdr(ret), count)))
454                         ret = tal_free(ret);
455         }
456         return ret;
457 }
458
459 void *tal_free(const tal_t *ctx)
460 {
461         if (ctx) {
462                 struct tal_hdr *t;
463                 int saved_errno = errno;
464                 t = debug_tal(to_tal_hdr(ctx));
465                 if (notifiers)
466                         notify(ignore_destroying_bit(t->parent_child)->parent,
467                                TAL_NOTIFY_DEL_CHILD, ctx);
468                 list_del(&t->list);
469                 del_tree(t, ctx);
470                 errno = saved_errno;
471         }
472         return NULL;
473 }
474
475 void *tal_steal_(const tal_t *new_parent, const tal_t *ctx)
476 {
477         if (ctx) {
478                 struct tal_hdr *newpar, *t, *old_parent;
479
480                 newpar = debug_tal(to_tal_hdr_or_null(new_parent));
481                 t = debug_tal(to_tal_hdr(ctx));
482
483                 /* Unlink it from old parent. */
484                 list_del(&t->list);
485                 old_parent = ignore_destroying_bit(t->parent_child)->parent;
486
487                 if (unlikely(!add_child(newpar, t))) {
488                         /* We can always add to old parent, becuase it has a
489                          * children property already. */
490                         if (!add_child(old_parent, t))
491                                 abort();
492                         return NULL;
493                 }
494                 debug_tal(newpar);
495                 if (notifiers)
496                         notify(t, TAL_NOTIFY_STEAL, new_parent);
497         }
498         return (void *)ctx;
499 }
500
501 bool tal_add_destructor_(const tal_t *ctx, void (*destroy)(void *me))
502 {
503         tal_t *t = debug_tal(to_tal_hdr(ctx));
504         return add_notifier_property(t, TAL_NOTIFY_FREE|NOTIFY_IS_DESTRUCTOR,
505                                      (void *)destroy);
506 }
507
508 bool tal_add_notifier_(const tal_t *ctx, enum tal_notify_type types,
509                        void (*callback)(tal_t *, enum tal_notify_type, void *))
510 {
511         tal_t *t = debug_tal(to_tal_hdr(ctx));
512         struct notifier *n;
513
514         assert(types);
515         assert((types & ~(TAL_NOTIFY_FREE | TAL_NOTIFY_STEAL | TAL_NOTIFY_MOVE
516                           | TAL_NOTIFY_RESIZE | TAL_NOTIFY_RENAME
517                           | TAL_NOTIFY_ADD_CHILD | TAL_NOTIFY_DEL_CHILD
518                           | TAL_NOTIFY_ADD_NOTIFIER
519                           | TAL_NOTIFY_DEL_NOTIFIER)) == 0);
520
521         /* Don't call notifier about itself: set types after! */
522         n = add_notifier_property(t, 0, callback);
523         if (unlikely(!n))
524                 return false;
525
526         if (notifiers)
527                 notify(t, TAL_NOTIFY_ADD_NOTIFIER, callback);
528
529         n->types = types;
530         if (types != TAL_NOTIFY_FREE)
531                 notifiers++;
532         return true;
533 }
534
535 bool tal_del_notifier_(const tal_t *ctx,
536                        void (*callback)(tal_t *, enum tal_notify_type, void *))
537 {
538         struct tal_hdr *t = debug_tal(to_tal_hdr(ctx));
539         enum tal_notify_type types;
540
541         types = del_notifier_property(t, callback);
542         if (types) {
543                 notify(t, TAL_NOTIFY_DEL_NOTIFIER, callback);
544                 if (types != TAL_NOTIFY_FREE)
545                         notifiers--;
546                 return true;
547         }
548         return false;
549 }
550
551 bool tal_del_destructor_(const tal_t *ctx, void (*destroy)(void *me))
552 {
553         return tal_del_notifier_(ctx, (void *)destroy);
554 }
555
556 bool tal_set_name_(tal_t *ctx, const char *name, bool literal)
557 {
558         struct tal_hdr *t = debug_tal(to_tal_hdr(ctx));
559         struct prop_hdr **prop = find_property_ptr(t, NAME);
560
561         /* Get rid of any old name */
562         if (prop) {
563                 struct name *name = (struct name *)*prop;
564                 if (is_literal(&name->hdr))
565                         *prop = NULL;
566                 else {
567                         *prop = name->hdr.next;
568                         freefn(name);
569                 }
570         }
571
572         if (literal && name[0]) {
573                 struct prop_hdr **p;
574
575                 /* Append literal. */
576                 for (p = &t->prop; *p && !is_literal(*p); p = &(*p)->next);
577                 *p = (struct prop_hdr *)name;
578         } else if (!add_name_property(t, name))
579                 return false;
580
581         debug_tal(t);
582         if (notifiers)
583                 notify(t, TAL_NOTIFY_RENAME, name);
584         return true;
585 }
586
587 const char *tal_name(const tal_t *t)
588 {
589         struct name *n;
590
591         n = find_property(debug_tal(to_tal_hdr(t)), NAME);
592         if (!n)
593                 return NULL;
594
595         if (is_literal(&n->hdr))
596                 return (const char *)n;
597         return n->name;
598 }
599
600 size_t tal_count(const tal_t *ptr)
601 {
602         struct length *l;
603
604         l = find_property(debug_tal(to_tal_hdr(ptr)), LENGTH);
605         if (!l)
606                 return 0;
607         return l->count;
608 }
609
610 /* Start one past first child: make stopping natural in circ. list. */
611 static struct tal_hdr *first_child(struct tal_hdr *parent)
612 {
613         struct children *child;
614
615         child = find_property(parent, CHILDREN);
616         if (!child)
617                 return NULL;
618
619         return list_top(&child->children, struct tal_hdr, list);
620 }
621
622 tal_t *tal_first(const tal_t *root)
623 {
624         struct tal_hdr *c, *t = debug_tal(to_tal_hdr_or_null(root));
625
626         c = first_child(t);
627         if (!c)
628                 return NULL;
629         return from_tal_hdr(c);
630 }
631
632 tal_t *tal_next(const tal_t *root, const tal_t *prev)
633 {
634         struct tal_hdr *c, *t = debug_tal(to_tal_hdr(prev)), *top;
635
636         /* Children? */
637         c = first_child(t);
638         if (c)
639                 return from_tal_hdr(c);
640
641         top = to_tal_hdr_or_null(root);
642         do {
643                 struct tal_hdr *next;
644                 struct list_node *end;
645
646                 end = &ignore_destroying_bit(t->parent_child)->children.n;
647
648                 next = list_entry(t->list.next, struct tal_hdr, list);
649                 if (&next->list != end)
650                         return from_tal_hdr(next);
651
652                 /* OK, go back to parent. */
653                 t = ignore_destroying_bit(t->parent_child)->parent;
654         } while (t != top);
655
656         return NULL;
657 }
658
659 tal_t *tal_parent(const tal_t *ctx)
660 {
661         struct tal_hdr *t;
662
663         if (!ctx)
664                 return NULL;
665
666         t = debug_tal(to_tal_hdr(ctx));
667         if (ignore_destroying_bit(t->parent_child)->parent == &null_parent.hdr)
668                 return NULL;
669         return from_tal_hdr(ignore_destroying_bit(t->parent_child)->parent);
670 }
671
672 bool tal_resize_(tal_t **ctxp, size_t size, size_t count)
673 {
674         struct tal_hdr *old_t, *t;
675         struct children *child;
676         struct length *len;
677
678         old_t = debug_tal(to_tal_hdr(*ctxp));
679
680         if (!adjust_size(&size, count))
681                 return false;
682
683         t = resizefn(old_t, size + sizeof(struct tal_hdr));
684         if (!t) {
685                 call_error("Reallocation failure");
686                 return false;
687         }
688
689         /* If it didn't move, we're done! */
690         if (t != old_t) {
691                 update_bounds(t, size + sizeof(struct tal_hdr));
692
693                 /* Fix up linked list pointers. */
694                 if (list_entry(t->list.next, struct tal_hdr, list) != old_t)
695                         t->list.next->prev = t->list.prev->next = &t->list;
696
697                 /* Fix up child property's parent pointer. */
698                 child = find_property(t, CHILDREN);
699                 if (child) {
700                         assert(child->parent == old_t);
701                         child->parent = t;
702                 }
703                 *ctxp = from_tal_hdr(debug_tal(t));
704                 if (notifiers)
705                         notify(t, TAL_NOTIFY_MOVE, from_tal_hdr(old_t));
706         }
707         len = find_property(t, LENGTH);
708         if (len)
709                 len->count = count;
710         if (notifiers)
711                 notify(t, TAL_NOTIFY_RESIZE, (void *)size);
712
713         return true;
714 }
715
716 char *tal_strdup(const tal_t *ctx, const char *p)
717 {
718         /* We have to let through NULL for take(). */
719         return tal_dup_(ctx, p, 1, p ? strlen(p) + 1: 1, 0, false,
720                         TAL_LABEL(char, "[]"));
721 }
722
723 char *tal_strndup(const tal_t *ctx, const char *p, size_t n)
724 {
725         size_t len;
726         char *ret;
727
728         /* We have to let through NULL for take(). */
729         if (likely(p)) {
730                 len = strlen(p);
731                 if (len > n)
732                         len = n;
733         } else
734                 len = n;
735
736         ret = tal_dup_(ctx, p, 1, len, 1, false, TAL_LABEL(char, "[]"));
737         if (ret)
738                 ret[len] = '\0';
739         return ret;
740 }
741
742 void *tal_dup_(const tal_t *ctx, const void *p, size_t size,
743                size_t n, size_t extra, bool add_count,
744                const char *label)
745 {
746         void *ret;
747         size_t nbytes = size;
748
749         if (!adjust_size(&nbytes, n)) {
750                 if (taken(p))
751                         tal_free(p);
752                 return NULL;
753         }
754
755         /* Beware addition overflow! */
756         if (n + extra < n) {
757                 call_error("dup size overflow");
758                 if (taken(p))
759                         tal_free(p);
760                 return NULL;
761         }
762
763         if (taken(p)) {
764                 if (unlikely(!p))
765                         return NULL;
766                 if (unlikely(!tal_resize_((void **)&p, size, n + extra)))
767                         return tal_free(p);
768                 if (unlikely(!tal_steal(ctx, p)))
769                         return tal_free(p);
770                 return (void *)p;
771         }
772
773         ret = tal_alloc_arr_(ctx, size, n + extra, false, add_count, label);
774         if (ret)
775                 memcpy(ret, p, nbytes);
776         return ret;
777 }
778
779 char *tal_asprintf(const tal_t *ctx, const char *fmt, ...)
780 {
781         va_list ap;
782         char *ret;
783
784         va_start(ap, fmt);
785         ret = tal_vasprintf(ctx, fmt, ap);
786         va_end(ap);
787
788         return ret;
789 }
790
791 char *tal_vasprintf(const tal_t *ctx, const char *fmt, va_list ap)
792 {
793         size_t max;
794         char *buf;
795         int ret;
796
797         if (!fmt && taken(fmt))
798                 return NULL;
799
800         /* A decent guess to start. */
801         max = strlen(fmt) * 2;
802         buf = tal_arr(ctx, char, max);
803         while (buf) {
804                 va_list ap2;
805
806                 va_copy(ap2, ap);
807                 ret = vsnprintf(buf, max, fmt, ap2);
808                 va_end(ap2);
809
810                 if (ret < max)
811                         break;
812                 if (!tal_resize(&buf, max *= 2))
813                         buf = tal_free(buf);
814         }
815         if (taken(fmt))
816                 tal_free(fmt);
817         return buf;
818 }
819
820 void tal_set_backend(void *(*alloc_fn)(size_t size),
821                      void *(*resize_fn)(void *, size_t size),
822                      void (*free_fn)(void *),
823                      void (*error_fn)(const char *msg))
824 {
825         if (alloc_fn)
826                 allocfn = alloc_fn;
827         if (resize_fn)
828                 resizefn = resize_fn;
829         if (free_fn)
830                 freefn = free_fn;
831         if (error_fn)
832                 errorfn = error_fn;
833 }
834
835 #ifdef CCAN_TAL_DEBUG
836 static void dump_node(unsigned int indent, const struct tal_hdr *t)
837 {
838         unsigned int i;
839         const struct prop_hdr *p;
840
841         for (i = 0; i < indent; i++)
842                 printf("  ");
843         printf("%p", t);
844         for (p = t->prop; p; p = p->next) {
845                 struct children *c;
846                 struct name *n;
847                 struct notifier *no;
848                 struct length *l;
849                 if (is_literal(p)) {
850                         printf(" \"%s\"", (const char *)p);
851                         break;
852                 }
853                 switch (p->type) {
854                 case CHILDREN:
855                         c = (struct children *)p;
856                         printf(" CHILDREN(%p):parent=%p,children={%p,%p}\n",
857                                p, c->parent,
858                                c->children.n.prev, c->children.n.next);
859                         break;
860                 case NAME:
861                         n = (struct name *)p;
862                         printf(" NAME(%p):%s", p, n->name);
863                         break;
864                 case NOTIFIER:
865                         no = (struct notifier *)p;
866                         printf(" NOTIFIER(%p):fn=%p", p, no->u.notifyfn);
867                         break;
868                 case LENGTH:
869                         l = (struct length *)p;
870                         printf(" LENGTH(%p):count=%zu", p, l->count);
871                         break;
872                 default:
873                         printf(" **UNKNOWN(%p):%i**", p, p->type);
874                 }
875         }
876         printf("\n");
877 }
878
879 static void tal_dump_(unsigned int level, const struct tal_hdr *t)
880 {
881         struct children *children;
882
883         dump_node(level, t);
884
885         children = find_property(t, CHILDREN);
886         if (children) {
887                 struct tal_hdr *i;
888
889                 list_for_each(&children->children, i, list)
890                         tal_dump_(level + 1, i);
891         }
892 }
893
894 void tal_dump(void)
895 {
896         tal_dump_(0, &null_parent.hdr);
897 }
898 #endif /* CCAN_TAL_DEBUG */
899
900 #ifndef NDEBUG
901 static bool check_err(struct tal_hdr *t, const char *errorstr,
902                       const char *errmsg)
903 {
904         if (errorstr) {
905                 /* Try not to malloc: it may be corrupted. */
906                 char msg[strlen(errorstr) + 20 + strlen(errmsg) + 1];
907                 sprintf(msg, "%s:%p %s", errorstr, from_tal_hdr(t), errmsg);
908                 call_error(msg);
909         }
910         return false;
911 }
912
913 static bool check_node(struct children *parent_child,
914                        struct tal_hdr *t, const char *errorstr)
915 {
916         struct prop_hdr *p;
917         struct name *name = NULL;
918         struct children *children = NULL;
919         struct length *length = NULL;
920
921         if (!in_bounds(t))
922                 return check_err(t, errorstr, "invalid pointer");
923
924         if (ignore_destroying_bit(t->parent_child) != parent_child)
925                 return check_err(t, errorstr, "incorrect parent");
926
927         for (p = t->prop; p; p = p->next) {
928                 if (is_literal(p)) {
929                         if (name)
930                                 return check_err(t, errorstr,
931                                                  "has extra literal");
932                         name = (struct name *)p;
933                         break;
934                 }
935                 if (!in_bounds(p))
936                         return check_err(t, errorstr,
937                                          "has bad property pointer");
938
939                 switch (p->type) {
940                 case CHILDREN:
941                         if (children)
942                                 return check_err(t, errorstr,
943                                                  "has two child nodes");
944                         children = (struct children *)p;
945                         break;
946                 case LENGTH:
947                         if (length)
948                                 return check_err(t, errorstr,
949                                                  "has two lengths");
950                         length = (struct length *)p;
951                         break;
952                 case NOTIFIER:
953                         break;
954                 case NAME:
955                         if (name)
956                                 return check_err(t, errorstr,
957                                                  "has two names");
958                         name = (struct name *)p;
959                         break;
960                 default:
961                         return check_err(t, errorstr, "has unknown property");
962                 }
963         }
964         if (children) {
965                 struct tal_hdr *i;
966
967                 if (!list_check(&children->children, errorstr))
968                         return false;
969                 list_for_each(&children->children, i, list) {
970                         if (!check_node(children, i, errorstr))
971                                 return false;
972                 }
973         }
974         return true;
975 }
976
977 bool tal_check(const tal_t *ctx, const char *errorstr)
978 {
979         struct tal_hdr *t = to_tal_hdr_or_null(ctx);
980
981         return check_node(ignore_destroying_bit(t->parent_child), t, errorstr);
982 }
983 #else /* NDEBUG */
984 bool tal_check(const tal_t *ctx, const char *errorstr)
985 {
986         return true;
987 }
988 #endif