1 #include <ccan/list/list.h>
2 #include <ccan/talloc/talloc.h>
3 #include <ccan/talloc_link/talloc_link.h>
6 /* Fake parent, if they care. */
7 static void *talloc_links = NULL;
9 /* This is the parent of the linked object, so we can implement delink. */
10 struct talloc_linked {
11 struct list_head links;
15 /* This is a child of the linker, but not a parent of ref. */
17 struct list_node list;
18 struct talloc_linked *linked;
21 static int destroy_link(struct talloc_link *link)
23 list_del(&link->list);
24 if (list_empty(&link->linked->links))
25 talloc_free(link->linked);
29 static bool add_link(const void *ctx, struct talloc_linked *linked)
31 struct talloc_link *link = talloc(ctx, struct talloc_link);
35 link->linked = linked;
36 list_add(&linked->links, &link->list);
37 talloc_set_destructor(link, destroy_link);
41 void *_talloc_linked(const void *ctx, const void *newobj)
43 struct talloc_linked *linked;
45 if (talloc_parent(newobj)) {
46 /* Assume leak reporting is on: create dummy parent. */
48 talloc_links = talloc_named_const(NULL, 0,
50 /* This should now have same pseudo-NULL parent. */
51 assert(talloc_parent(newobj) == talloc_parent(talloc_links));
54 linked = talloc(talloc_links, struct talloc_linked);
59 list_head_init(&linked->links);
60 linked->obj = talloc_steal(linked, newobj);
62 if (!add_link(ctx, linked)) {
67 return (void *)newobj;
70 void *_talloc_link(const void *ctx, const void *obj)
72 struct talloc_linked *linked;
74 linked = talloc_get_type(talloc_parent(obj), struct talloc_linked);
75 assert(!list_empty(&linked->links));
76 return add_link(ctx, linked) ? (void *)obj : NULL;
79 void talloc_delink(const void *ctx, const void *obj)
81 struct talloc_linked *linked;
82 struct talloc_link *i;
87 linked = talloc_get_type(talloc_parent(obj), struct talloc_linked);
88 list_for_each(&linked->links, i, list) {
89 if (talloc_is_parent(i, ctx)) {