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