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