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