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