TMP: add a ctdb snapshot of current ctdb master (git://git.samba.org/ctdb.git) to...
[obnox/samba/samba-obnox.git] / ctdb / lib / talloc / talloc.c
1 /* 
2    Samba Unix SMB/CIFS implementation.
3
4    Samba trivial allocation library - new interface
5
6    NOTE: Please read talloc_guide.txt for full documentation
7
8    Copyright (C) Andrew Tridgell 2004
9    Copyright (C) Stefan Metzmacher 2006
10    
11      ** NOTE! The following LGPL license applies to the talloc
12      ** library. This does NOT imply that all of Samba is released
13      ** under the LGPL
14    
15    This library is free software; you can redistribute it and/or
16    modify it under the terms of the GNU Lesser General Public
17    License as published by the Free Software Foundation; either
18    version 3 of the License, or (at your option) any later version.
19
20    This library is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23    Lesser General Public License for more details.
24
25    You should have received a copy of the GNU Lesser General Public
26    License along with this library; if not, see <http://www.gnu.org/licenses/>.
27 */
28
29 /*
30   inspired by http://swapped.cc/halloc/
31 */
32
33 #include "replace.h"
34 #include "talloc.h"
35 #include "includes.h"
36
37 #ifdef TALLOC_BUILD_VERSION_MAJOR
38 #if (TALLOC_VERSION_MAJOR != TALLOC_BUILD_VERSION_MAJOR)
39 #error "TALLOC_VERSION_MAJOR != TALLOC_BUILD_VERSION_MAJOR"
40 #endif
41 #endif
42
43 #ifdef TALLOC_BUILD_VERSION_MINOR
44 #if (TALLOC_VERSION_MINOR != TALLOC_BUILD_VERSION_MINOR)
45 #error "TALLOC_VERSION_MINOR != TALLOC_BUILD_VERSION_MINOR"
46 #endif
47 #endif
48
49 /* use this to force every realloc to change the pointer, to stress test
50    code that might not cope */
51 #define ALWAYS_REALLOC 0
52
53
54 #define MAX_TALLOC_SIZE 0x10000000
55 #define TALLOC_MAGIC_BASE 0xe814ec70
56 #define TALLOC_MAGIC ( \
57         TALLOC_MAGIC_BASE + \
58         (TALLOC_VERSION_MAJOR << 12) + \
59         (TALLOC_VERSION_MINOR << 4) \
60 )
61
62 #define TALLOC_FLAG_FREE 0x01
63 #define TALLOC_FLAG_LOOP 0x02
64 #define TALLOC_FLAG_POOL 0x04           /* This is a talloc pool */
65 #define TALLOC_FLAG_POOLMEM 0x08        /* This is allocated in a pool */
66 #define TALLOC_MAGIC_REFERENCE ((const char *)1)
67
68 /* by default we abort when given a bad pointer (such as when talloc_free() is called 
69    on a pointer that came from malloc() */
70 #ifndef TALLOC_ABORT
71 #define TALLOC_ABORT(reason) abort()
72 #endif
73
74 #ifndef discard_const_p
75 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
76 # define discard_const_p(type, ptr) ((type *)((intptr_t)(ptr)))
77 #else
78 # define discard_const_p(type, ptr) ((type *)(ptr))
79 #endif
80 #endif
81
82 /* these macros gain us a few percent of speed on gcc */
83 #if (__GNUC__ >= 3)
84 /* the strange !! is to ensure that __builtin_expect() takes either 0 or 1
85    as its first argument */
86 #ifndef likely
87 #define likely(x)   __builtin_expect(!!(x), 1)
88 #endif
89 #ifndef unlikely
90 #define unlikely(x) __builtin_expect(!!(x), 0)
91 #endif
92 #else
93 #ifndef likely
94 #define likely(x) (x)
95 #endif
96 #ifndef unlikely
97 #define unlikely(x) (x)
98 #endif
99 #endif
100
101 /* this null_context is only used if talloc_enable_leak_report() or
102    talloc_enable_leak_report_full() is called, otherwise it remains
103    NULL
104 */
105 static void *null_context;
106 static void *autofree_context;
107
108 struct talloc_reference_handle {
109         struct talloc_reference_handle *next, *prev;
110         void *ptr;
111         const char *location;
112 };
113
114 typedef int (*talloc_destructor_t)(void *);
115
116 struct talloc_chunk {
117         struct talloc_chunk *next, *prev;
118         struct talloc_chunk *parent, *child;
119         struct talloc_reference_handle *refs;
120         talloc_destructor_t destructor;
121         const char *name;
122         size_t size;
123         unsigned flags;
124
125         /*
126          * "pool" has dual use:
127          *
128          * For the talloc pool itself (i.e. TALLOC_FLAG_POOL is set), "pool"
129          * marks the end of the currently allocated area.
130          *
131          * For members of the pool (i.e. TALLOC_FLAG_POOLMEM is set), "pool"
132          * is a pointer to the struct talloc_chunk of the pool that it was
133          * allocated from. This way children can quickly find the pool to chew
134          * from.
135          */
136         void *pool;
137 };
138
139 /* 16 byte alignment seems to keep everyone happy */
140 #define TC_HDR_SIZE ((sizeof(struct talloc_chunk)+15)&~15)
141 #define TC_PTR_FROM_CHUNK(tc) ((void *)(TC_HDR_SIZE + (char*)tc))
142
143 _PUBLIC_ int talloc_version_major(void)
144 {
145         return TALLOC_VERSION_MAJOR;
146 }
147
148 _PUBLIC_ int talloc_version_minor(void)
149 {
150         return TALLOC_VERSION_MINOR;
151 }
152
153 static void (*talloc_log_fn)(const char *message);
154
155 _PUBLIC_ void talloc_set_log_fn(void (*log_fn)(const char *message))
156 {
157         talloc_log_fn = log_fn;
158 }
159
160 static void talloc_log(const char *fmt, ...) PRINTF_ATTRIBUTE(1,2);
161 static void talloc_log(const char *fmt, ...)
162 {
163         va_list ap;
164         char *message;
165
166         if (!talloc_log_fn) {
167                 return;
168         }
169
170         va_start(ap, fmt);
171         message = talloc_vasprintf(NULL, fmt, ap);
172         va_end(ap);
173
174         talloc_log_fn(message);
175         talloc_free(message);
176 }
177
178 static void talloc_log_stderr(const char *message)
179 {
180         fprintf(stderr, "%s", message);
181 }
182
183 _PUBLIC_ void talloc_set_log_stderr(void)
184 {
185         talloc_set_log_fn(talloc_log_stderr);
186 }
187
188 static void (*talloc_abort_fn)(const char *reason);
189
190 _PUBLIC_ void talloc_set_abort_fn(void (*abort_fn)(const char *reason))
191 {
192         talloc_abort_fn = abort_fn;
193 }
194
195 static void talloc_abort(const char *reason)
196 {
197         talloc_log("%s\n", reason);
198
199         if (!talloc_abort_fn) {
200                 TALLOC_ABORT(reason);
201         }
202
203         talloc_abort_fn(reason);
204 }
205
206 static void talloc_abort_magic(unsigned magic)
207 {
208         unsigned striped = magic - TALLOC_MAGIC_BASE;
209         unsigned major = (striped & 0xFFFFF000) >> 12;
210         unsigned minor = (striped & 0x00000FF0) >> 4;
211         talloc_log("Bad talloc magic[0x%08X/%u/%u] expected[0x%08X/%u/%u]\n",
212                    magic, major, minor,
213                    TALLOC_MAGIC, TALLOC_VERSION_MAJOR, TALLOC_VERSION_MINOR);
214         talloc_abort("Bad talloc magic value - wrong talloc version used/mixed");
215 }
216
217 static void talloc_abort_double_free(void)
218 {
219         talloc_abort("Bad talloc magic value - double free");
220 }
221
222 static void talloc_abort_unknown_value(void)
223 {
224         talloc_abort("Bad talloc magic value - unknown value");
225 }
226
227 /* panic if we get a bad magic value */
228 static inline struct talloc_chunk *talloc_chunk_from_ptr(const void *ptr)
229 {
230         const char *pp = (const char *)ptr;
231         struct talloc_chunk *tc = discard_const_p(struct talloc_chunk, pp - TC_HDR_SIZE);
232         if (unlikely((tc->flags & (TALLOC_FLAG_FREE | ~0xF)) != TALLOC_MAGIC)) { 
233                 if ((tc->flags & (~0xFFF)) == TALLOC_MAGIC_BASE) {
234                         talloc_abort_magic(tc->flags & (~0xF));
235                         return NULL;
236                 }
237
238                 if (tc->flags & TALLOC_FLAG_FREE) {
239                         talloc_log("talloc: double free error - first free may be at %s\n", tc->name);
240                         talloc_abort_double_free();
241                         return NULL;
242                 } else {
243                         talloc_abort_unknown_value();
244                         return NULL;
245                 }
246         }
247         return tc;
248 }
249
250 /* hook into the front of the list */
251 #define _TLIST_ADD(list, p) \
252 do { \
253         if (!(list)) { \
254                 (list) = (p); \
255                 (p)->next = (p)->prev = NULL; \
256         } else { \
257                 (list)->prev = (p); \
258                 (p)->next = (list); \
259                 (p)->prev = NULL; \
260                 (list) = (p); \
261         }\
262 } while (0)
263
264 /* remove an element from a list - element doesn't have to be in list. */
265 #define _TLIST_REMOVE(list, p) \
266 do { \
267         if ((p) == (list)) { \
268                 (list) = (p)->next; \
269                 if (list) (list)->prev = NULL; \
270         } else { \
271                 if ((p)->prev) (p)->prev->next = (p)->next; \
272                 if ((p)->next) (p)->next->prev = (p)->prev; \
273         } \
274         if ((p) && ((p) != (list))) (p)->next = (p)->prev = NULL; \
275 } while (0)
276
277
278 /*
279   return the parent chunk of a pointer
280 */
281 static inline struct talloc_chunk *talloc_parent_chunk(const void *ptr)
282 {
283         struct talloc_chunk *tc;
284
285         if (unlikely(ptr == NULL)) {
286                 return NULL;
287         }
288
289         tc = talloc_chunk_from_ptr(ptr);
290         while (tc->prev) tc=tc->prev;
291
292         return tc->parent;
293 }
294
295 _PUBLIC_ void *talloc_parent(const void *ptr)
296 {
297         struct talloc_chunk *tc = talloc_parent_chunk(ptr);
298         return tc? TC_PTR_FROM_CHUNK(tc) : NULL;
299 }
300
301 /*
302   find parents name
303 */
304 _PUBLIC_ const char *talloc_parent_name(const void *ptr)
305 {
306         struct talloc_chunk *tc = talloc_parent_chunk(ptr);
307         return tc? tc->name : NULL;
308 }
309
310 /*
311   A pool carries an in-pool object count count in the first 16 bytes.
312   bytes. This is done to support talloc_steal() to a parent outside of the
313   pool. The count includes the pool itself, so a talloc_free() on a pool will
314   only destroy the pool if the count has dropped to zero. A talloc_free() of a
315   pool member will reduce the count, and eventually also call free(3) on the
316   pool memory.
317
318   The object count is not put into "struct talloc_chunk" because it is only
319   relevant for talloc pools and the alignment to 16 bytes would increase the
320   memory footprint of each talloc chunk by those 16 bytes.
321 */
322
323 #define TALLOC_POOL_HDR_SIZE 16
324
325 static unsigned int *talloc_pool_objectcount(struct talloc_chunk *tc)
326 {
327         return (unsigned int *)((char *)tc + sizeof(struct talloc_chunk));
328 }
329
330 /*
331   Allocate from a pool
332 */
333
334 static struct talloc_chunk *talloc_alloc_pool(struct talloc_chunk *parent,
335                                               size_t size)
336 {
337         struct talloc_chunk *pool_ctx = NULL;
338         size_t space_left;
339         struct talloc_chunk *result;
340         size_t chunk_size;
341
342         if (parent == NULL) {
343                 return NULL;
344         }
345
346         if (parent->flags & TALLOC_FLAG_POOL) {
347                 pool_ctx = parent;
348         }
349         else if (parent->flags & TALLOC_FLAG_POOLMEM) {
350                 pool_ctx = (struct talloc_chunk *)parent->pool;
351         }
352
353         if (pool_ctx == NULL) {
354                 return NULL;
355         }
356
357         space_left = ((char *)pool_ctx + TC_HDR_SIZE + pool_ctx->size)
358                 - ((char *)pool_ctx->pool);
359
360         /*
361          * Align size to 16 bytes
362          */
363         chunk_size = ((size + 15) & ~15);
364
365         if (space_left < chunk_size) {
366                 return NULL;
367         }
368
369         result = (struct talloc_chunk *)pool_ctx->pool;
370
371 #if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_UNDEFINED)
372         VALGRIND_MAKE_MEM_UNDEFINED(result, size);
373 #endif
374
375         pool_ctx->pool = (void *)((char *)result + chunk_size);
376
377         result->flags = TALLOC_MAGIC | TALLOC_FLAG_POOLMEM;
378         result->pool = pool_ctx;
379
380         *talloc_pool_objectcount(pool_ctx) += 1;
381
382         return result;
383 }
384
385 /* 
386    Allocate a bit of memory as a child of an existing pointer
387 */
388 static inline void *__talloc(const void *context, size_t size)
389 {
390         struct talloc_chunk *tc = NULL;
391
392         if (unlikely(context == NULL)) {
393                 context = null_context;
394         }
395
396         if (unlikely(size >= MAX_TALLOC_SIZE)) {
397                 return NULL;
398         }
399
400         if (context != NULL) {
401                 tc = talloc_alloc_pool(talloc_chunk_from_ptr(context),
402                                        TC_HDR_SIZE+size);
403         }
404
405         if (tc == NULL) {
406                 tc = (struct talloc_chunk *)malloc(TC_HDR_SIZE+size);
407                 if (unlikely(tc == NULL)) return NULL;
408                 tc->flags = TALLOC_MAGIC;
409                 tc->pool  = NULL;
410         }
411
412         tc->size = size;
413         tc->destructor = NULL;
414         tc->child = NULL;
415         tc->name = NULL;
416         tc->refs = NULL;
417
418         if (likely(context)) {
419                 struct talloc_chunk *parent = talloc_chunk_from_ptr(context);
420
421                 if (parent->child) {
422                         parent->child->parent = NULL;
423                         tc->next = parent->child;
424                         tc->next->prev = tc;
425                 } else {
426                         tc->next = NULL;
427                 }
428                 tc->parent = parent;
429                 tc->prev = NULL;
430                 parent->child = tc;
431         } else {
432                 tc->next = tc->prev = tc->parent = NULL;
433         }
434
435         return TC_PTR_FROM_CHUNK(tc);
436 }
437
438 /*
439  * Create a talloc pool
440  */
441
442 _PUBLIC_ void *talloc_pool(const void *context, size_t size)
443 {
444         void *result = __talloc(context, size + TALLOC_POOL_HDR_SIZE);
445         struct talloc_chunk *tc;
446
447         if (unlikely(result == NULL)) {
448                 return NULL;
449         }
450
451         tc = talloc_chunk_from_ptr(result);
452
453         tc->flags |= TALLOC_FLAG_POOL;
454         tc->pool = (char *)result + TALLOC_POOL_HDR_SIZE;
455
456         *talloc_pool_objectcount(tc) = 1;
457
458 #if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_NOACCESS)
459         VALGRIND_MAKE_MEM_NOACCESS(tc->pool, size);
460 #endif
461
462         return result;
463 }
464
465 /*
466   setup a destructor to be called on free of a pointer
467   the destructor should return 0 on success, or -1 on failure.
468   if the destructor fails then the free is failed, and the memory can
469   be continued to be used
470 */
471 _PUBLIC_ void _talloc_set_destructor(const void *ptr, int (*destructor)(void *))
472 {
473         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
474         tc->destructor = destructor;
475 }
476
477 /*
478   increase the reference count on a piece of memory. 
479 */
480 _PUBLIC_ int talloc_increase_ref_count(const void *ptr)
481 {
482         if (unlikely(!talloc_reference(null_context, ptr))) {
483                 return -1;
484         }
485         return 0;
486 }
487
488 /*
489   helper for talloc_reference()
490
491   this is referenced by a function pointer and should not be inline
492 */
493 static int talloc_reference_destructor(struct talloc_reference_handle *handle)
494 {
495         struct talloc_chunk *ptr_tc = talloc_chunk_from_ptr(handle->ptr);
496         _TLIST_REMOVE(ptr_tc->refs, handle);
497         return 0;
498 }
499
500 /*
501    more efficient way to add a name to a pointer - the name must point to a 
502    true string constant
503 */
504 static inline void _talloc_set_name_const(const void *ptr, const char *name)
505 {
506         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
507         tc->name = name;
508 }
509
510 /*
511   internal talloc_named_const()
512 */
513 static inline void *_talloc_named_const(const void *context, size_t size, const char *name)
514 {
515         void *ptr;
516
517         ptr = __talloc(context, size);
518         if (unlikely(ptr == NULL)) {
519                 return NULL;
520         }
521
522         _talloc_set_name_const(ptr, name);
523
524         return ptr;
525 }
526
527 /*
528   make a secondary reference to a pointer, hanging off the given context.
529   the pointer remains valid until both the original caller and this given
530   context are freed.
531   
532   the major use for this is when two different structures need to reference the 
533   same underlying data, and you want to be able to free the two instances separately,
534   and in either order
535 */
536 _PUBLIC_ void *_talloc_reference_loc(const void *context, const void *ptr, const char *location)
537 {
538         struct talloc_chunk *tc;
539         struct talloc_reference_handle *handle;
540         if (unlikely(ptr == NULL)) return NULL;
541
542         tc = talloc_chunk_from_ptr(ptr);
543         handle = (struct talloc_reference_handle *)_talloc_named_const(context,
544                                                    sizeof(struct talloc_reference_handle),
545                                                    TALLOC_MAGIC_REFERENCE);
546         if (unlikely(handle == NULL)) return NULL;
547
548         /* note that we hang the destructor off the handle, not the
549            main context as that allows the caller to still setup their
550            own destructor on the context if they want to */
551         talloc_set_destructor(handle, talloc_reference_destructor);
552         handle->ptr = discard_const_p(void, ptr);
553         handle->location = location;
554         _TLIST_ADD(tc->refs, handle);
555         return handle->ptr;
556 }
557
558 static void *_talloc_steal_internal(const void *new_ctx, const void *ptr);
559
560 /* 
561    internal talloc_free call
562 */
563 static inline int _talloc_free_internal(void *ptr, const char *location)
564 {
565         struct talloc_chunk *tc;
566
567         if (unlikely(ptr == NULL)) {
568                 return -1;
569         }
570
571         tc = talloc_chunk_from_ptr(ptr);
572
573         if (unlikely(tc->refs)) {
574                 int is_child;
575                 /* check this is a reference from a child or grantchild
576                  * back to it's parent or grantparent
577                  *
578                  * in that case we need to remove the reference and
579                  * call another instance of talloc_free() on the current
580                  * pointer.
581                  */
582                 is_child = talloc_is_parent(tc->refs, ptr);
583                 _talloc_free_internal(tc->refs, location);
584                 if (is_child) {
585                         return _talloc_free_internal(ptr, location);
586                 }
587                 return -1;
588         }
589
590         if (unlikely(tc->flags & TALLOC_FLAG_LOOP)) {
591                 /* we have a free loop - stop looping */
592                 return 0;
593         }
594
595         if (unlikely(tc->destructor)) {
596                 talloc_destructor_t d = tc->destructor;
597                 if (d == (talloc_destructor_t)-1) {
598                         return -1;
599                 }
600                 tc->destructor = (talloc_destructor_t)-1;
601                 if (d(ptr) == -1) {
602                         tc->destructor = d;
603                         return -1;
604                 }
605                 tc->destructor = NULL;
606         }
607
608         if (tc->parent) {
609                 _TLIST_REMOVE(tc->parent->child, tc);
610                 if (tc->parent->child) {
611                         tc->parent->child->parent = tc->parent;
612                 }
613         } else {
614                 if (tc->prev) tc->prev->next = tc->next;
615                 if (tc->next) tc->next->prev = tc->prev;
616         }
617
618         tc->flags |= TALLOC_FLAG_LOOP;
619
620         while (tc->child) {
621                 /* we need to work out who will own an abandoned child
622                    if it cannot be freed. In priority order, the first
623                    choice is owner of any remaining reference to this
624                    pointer, the second choice is our parent, and the
625                    final choice is the null context. */
626                 void *child = TC_PTR_FROM_CHUNK(tc->child);
627                 const void *new_parent = null_context;
628                 if (unlikely(tc->child->refs)) {
629                         struct talloc_chunk *p = talloc_parent_chunk(tc->child->refs);
630                         if (p) new_parent = TC_PTR_FROM_CHUNK(p);
631                 }
632                 if (unlikely(_talloc_free_internal(child, location) == -1)) {
633                         if (new_parent == null_context) {
634                                 struct talloc_chunk *p = talloc_parent_chunk(ptr);
635                                 if (p) new_parent = TC_PTR_FROM_CHUNK(p);
636                         }
637                         _talloc_steal_internal(new_parent, child);
638                 }
639         }
640
641         tc->flags |= TALLOC_FLAG_FREE;
642
643         /* we mark the freed memory with where we called the free
644          * from. This means on a double free error we can report where
645          * the first free came from
646          */
647         tc->name = location;
648
649         if (tc->flags & (TALLOC_FLAG_POOL|TALLOC_FLAG_POOLMEM)) {
650                 struct talloc_chunk *pool;
651                 unsigned int *pool_object_count;
652
653                 pool = (tc->flags & TALLOC_FLAG_POOL)
654                         ? tc : (struct talloc_chunk *)tc->pool;
655
656                 pool_object_count = talloc_pool_objectcount(pool);
657
658                 if (*pool_object_count == 0) {
659                         talloc_abort("Pool object count zero!");
660                         return 0;
661                 }
662
663                 *pool_object_count -= 1;
664
665                 if (*pool_object_count == 0) {
666                         free(pool);
667                 }
668         }
669         else {
670                 free(tc);
671         }
672         return 0;
673 }
674
675 /* 
676    move a lump of memory from one talloc context to another return the
677    ptr on success, or NULL if it could not be transferred.
678    passing NULL as ptr will always return NULL with no side effects.
679 */
680 static void *_talloc_steal_internal(const void *new_ctx, const void *ptr)
681 {
682         struct talloc_chunk *tc, *new_tc;
683
684         if (unlikely(!ptr)) {
685                 return NULL;
686         }
687
688         if (unlikely(new_ctx == NULL)) {
689                 new_ctx = null_context;
690         }
691
692         tc = talloc_chunk_from_ptr(ptr);
693
694         if (unlikely(new_ctx == NULL)) {
695                 if (tc->parent) {
696                         _TLIST_REMOVE(tc->parent->child, tc);
697                         if (tc->parent->child) {
698                                 tc->parent->child->parent = tc->parent;
699                         }
700                 } else {
701                         if (tc->prev) tc->prev->next = tc->next;
702                         if (tc->next) tc->next->prev = tc->prev;
703                 }
704                 
705                 tc->parent = tc->next = tc->prev = NULL;
706                 return discard_const_p(void, ptr);
707         }
708
709         new_tc = talloc_chunk_from_ptr(new_ctx);
710
711         if (unlikely(tc == new_tc || tc->parent == new_tc)) {
712                 return discard_const_p(void, ptr);
713         }
714
715         if (tc->parent) {
716                 _TLIST_REMOVE(tc->parent->child, tc);
717                 if (tc->parent->child) {
718                         tc->parent->child->parent = tc->parent;
719                 }
720         } else {
721                 if (tc->prev) tc->prev->next = tc->next;
722                 if (tc->next) tc->next->prev = tc->prev;
723         }
724
725         tc->parent = new_tc;
726         if (new_tc->child) new_tc->child->parent = NULL;
727         _TLIST_ADD(new_tc->child, tc);
728
729         return discard_const_p(void, ptr);
730 }
731
732 /*
733    move a lump of memory from one talloc context to another return the
734    ptr on success, or NULL if it could not be transferred.
735    passing NULL as ptr will always return NULL with no side effects.
736 */
737 _PUBLIC_ void *_talloc_steal_loc(const void *new_ctx, const void *ptr, const char *location)
738 {
739         struct talloc_chunk *tc;
740
741         if (unlikely(ptr == NULL)) {
742                 return NULL;
743         }
744
745         tc = talloc_chunk_from_ptr(ptr);
746
747         if (unlikely(tc->refs != NULL) && talloc_parent(ptr) != new_ctx) {
748                 struct talloc_reference_handle *h;
749
750                 talloc_log("WARNING: talloc_steal with references at %s\n",
751                            location);
752
753                 for (h=tc->refs; h; h=h->next) {
754                         talloc_log("\treference at %s\n",
755                                    h->location);
756                 }
757         }
758
759 #if 0
760         /* this test is probably too expensive to have on in the
761            normal build, but it useful for debugging */
762         if (talloc_is_parent(new_ctx, ptr)) {
763                 talloc_log("WARNING: stealing into talloc child at %s\n", location);
764         }
765 #endif
766
767         return _talloc_steal_internal(new_ctx, ptr);
768 }
769
770 /*
771    this is like a talloc_steal(), but you must supply the old
772    parent. This resolves the ambiguity in a talloc_steal() which is
773    called on a context that has more than one parent (via references)
774
775    The old parent can be either a reference or a parent
776 */
777 _PUBLIC_ void *talloc_reparent(const void *old_parent, const void *new_parent, const void *ptr)
778 {
779         struct talloc_chunk *tc;
780         struct talloc_reference_handle *h;
781
782         if (unlikely(ptr == NULL)) {
783                 return NULL;
784         }
785
786         if (old_parent == talloc_parent(ptr)) {
787                 return _talloc_steal_internal(new_parent, ptr);
788         }
789
790         tc = talloc_chunk_from_ptr(ptr);
791         for (h=tc->refs;h;h=h->next) {
792                 if (talloc_parent(h) == old_parent) {
793                         if (_talloc_steal_internal(new_parent, h) != h) {
794                                 return NULL;
795                         }
796                         return discard_const_p(void, ptr);
797                 }
798         }
799
800         /* it wasn't a parent */
801         return NULL;
802 }
803
804 /*
805   remove a secondary reference to a pointer. This undo's what
806   talloc_reference() has done. The context and pointer arguments
807   must match those given to a talloc_reference()
808 */
809 static inline int talloc_unreference(const void *context, const void *ptr)
810 {
811         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
812         struct talloc_reference_handle *h;
813
814         if (unlikely(context == NULL)) {
815                 context = null_context;
816         }
817
818         for (h=tc->refs;h;h=h->next) {
819                 struct talloc_chunk *p = talloc_parent_chunk(h);
820                 if (p == NULL) {
821                         if (context == NULL) break;
822                 } else if (TC_PTR_FROM_CHUNK(p) == context) {
823                         break;
824                 }
825         }
826         if (h == NULL) {
827                 return -1;
828         }
829
830         return _talloc_free_internal(h, __location__);
831 }
832
833 /*
834   remove a specific parent context from a pointer. This is a more
835   controlled varient of talloc_free()
836 */
837 _PUBLIC_ int talloc_unlink(const void *context, void *ptr)
838 {
839         struct talloc_chunk *tc_p, *new_p;
840         void *new_parent;
841
842         if (ptr == NULL) {
843                 return -1;
844         }
845
846         if (context == NULL) {
847                 context = null_context;
848         }
849
850         if (talloc_unreference(context, ptr) == 0) {
851                 return 0;
852         }
853
854         if (context == NULL) {
855                 if (talloc_parent_chunk(ptr) != NULL) {
856                         return -1;
857                 }
858         } else {
859                 if (talloc_chunk_from_ptr(context) != talloc_parent_chunk(ptr)) {
860                         return -1;
861                 }
862         }
863         
864         tc_p = talloc_chunk_from_ptr(ptr);
865
866         if (tc_p->refs == NULL) {
867                 return _talloc_free_internal(ptr, __location__);
868         }
869
870         new_p = talloc_parent_chunk(tc_p->refs);
871         if (new_p) {
872                 new_parent = TC_PTR_FROM_CHUNK(new_p);
873         } else {
874                 new_parent = NULL;
875         }
876
877         if (talloc_unreference(new_parent, ptr) != 0) {
878                 return -1;
879         }
880
881         _talloc_steal_internal(new_parent, ptr);
882
883         return 0;
884 }
885
886 /*
887   add a name to an existing pointer - va_list version
888 */
889 static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(2,0);
890
891 static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va_list ap)
892 {
893         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
894         tc->name = talloc_vasprintf(ptr, fmt, ap);
895         if (likely(tc->name)) {
896                 _talloc_set_name_const(tc->name, ".name");
897         }
898         return tc->name;
899 }
900
901 /*
902   add a name to an existing pointer
903 */
904 _PUBLIC_ const char *talloc_set_name(const void *ptr, const char *fmt, ...)
905 {
906         const char *name;
907         va_list ap;
908         va_start(ap, fmt);
909         name = talloc_set_name_v(ptr, fmt, ap);
910         va_end(ap);
911         return name;
912 }
913
914
915 /*
916   create a named talloc pointer. Any talloc pointer can be named, and
917   talloc_named() operates just like talloc() except that it allows you
918   to name the pointer.
919 */
920 _PUBLIC_ void *talloc_named(const void *context, size_t size, const char *fmt, ...)
921 {
922         va_list ap;
923         void *ptr;
924         const char *name;
925
926         ptr = __talloc(context, size);
927         if (unlikely(ptr == NULL)) return NULL;
928
929         va_start(ap, fmt);
930         name = talloc_set_name_v(ptr, fmt, ap);
931         va_end(ap);
932
933         if (unlikely(name == NULL)) {
934                 _talloc_free_internal(ptr, __location__);
935                 return NULL;
936         }
937
938         return ptr;
939 }
940
941 /*
942   return the name of a talloc ptr, or "UNNAMED"
943 */
944 _PUBLIC_ const char *talloc_get_name(const void *ptr)
945 {
946         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
947         if (unlikely(tc->name == TALLOC_MAGIC_REFERENCE)) {
948                 return ".reference";
949         }
950         if (likely(tc->name)) {
951                 return tc->name;
952         }
953         return "UNNAMED";
954 }
955
956
957 /*
958   check if a pointer has the given name. If it does, return the pointer,
959   otherwise return NULL
960 */
961 _PUBLIC_ void *talloc_check_name(const void *ptr, const char *name)
962 {
963         const char *pname;
964         if (unlikely(ptr == NULL)) return NULL;
965         pname = talloc_get_name(ptr);
966         if (likely(pname == name || strcmp(pname, name) == 0)) {
967                 return discard_const_p(void, ptr);
968         }
969         return NULL;
970 }
971
972 static void talloc_abort_type_missmatch(const char *location,
973                                         const char *name,
974                                         const char *expected)
975 {
976         const char *reason;
977
978         reason = talloc_asprintf(NULL,
979                                  "%s: Type mismatch: name[%s] expected[%s]",
980                                  location,
981                                  name?name:"NULL",
982                                  expected);
983         if (!reason) {
984                 reason = "Type mismatch";
985         }
986
987         talloc_abort(reason);
988 }
989
990 _PUBLIC_ void *_talloc_get_type_abort(const void *ptr, const char *name, const char *location)
991 {
992         const char *pname;
993
994         if (unlikely(ptr == NULL)) {
995                 talloc_abort_type_missmatch(location, NULL, name);
996                 return NULL;
997         }
998
999         pname = talloc_get_name(ptr);
1000         if (likely(pname == name || strcmp(pname, name) == 0)) {
1001                 return discard_const_p(void, ptr);
1002         }
1003
1004         talloc_abort_type_missmatch(location, pname, name);
1005         return NULL;
1006 }
1007
1008 /*
1009   this is for compatibility with older versions of talloc
1010 */
1011 _PUBLIC_ void *talloc_init(const char *fmt, ...)
1012 {
1013         va_list ap;
1014         void *ptr;
1015         const char *name;
1016
1017         /*
1018          * samba3 expects talloc_report_depth_cb(NULL, ...)
1019          * reports all talloc'ed memory, so we need to enable
1020          * null_tracking
1021          */
1022         talloc_enable_null_tracking();
1023
1024         ptr = __talloc(NULL, 0);
1025         if (unlikely(ptr == NULL)) return NULL;
1026
1027         va_start(ap, fmt);
1028         name = talloc_set_name_v(ptr, fmt, ap);
1029         va_end(ap);
1030
1031         if (unlikely(name == NULL)) {
1032                 _talloc_free_internal(ptr, __location__);
1033                 return NULL;
1034         }
1035
1036         return ptr;
1037 }
1038
1039 /*
1040   this is a replacement for the Samba3 talloc_destroy_pool functionality. It
1041   should probably not be used in new code. It's in here to keep the talloc
1042   code consistent across Samba 3 and 4.
1043 */
1044 _PUBLIC_ void talloc_free_children(void *ptr)
1045 {
1046         struct talloc_chunk *tc;
1047
1048         if (unlikely(ptr == NULL)) {
1049                 return;
1050         }
1051
1052         tc = talloc_chunk_from_ptr(ptr);
1053
1054         while (tc->child) {
1055                 /* we need to work out who will own an abandoned child
1056                    if it cannot be freed. In priority order, the first
1057                    choice is owner of any remaining reference to this
1058                    pointer, the second choice is our parent, and the
1059                    final choice is the null context. */
1060                 void *child = TC_PTR_FROM_CHUNK(tc->child);
1061                 const void *new_parent = null_context;
1062                 if (unlikely(tc->child->refs)) {
1063                         struct talloc_chunk *p = talloc_parent_chunk(tc->child->refs);
1064                         if (p) new_parent = TC_PTR_FROM_CHUNK(p);
1065                 }
1066                 if (unlikely(talloc_free(child) == -1)) {
1067                         if (new_parent == null_context) {
1068                                 struct talloc_chunk *p = talloc_parent_chunk(ptr);
1069                                 if (p) new_parent = TC_PTR_FROM_CHUNK(p);
1070                         }
1071                         _talloc_steal_internal(new_parent, child);
1072                 }
1073         }
1074
1075         if ((tc->flags & TALLOC_FLAG_POOL)
1076             && (*talloc_pool_objectcount(tc) == 1)) {
1077                 tc->pool = ((char *)tc + TC_HDR_SIZE + TALLOC_POOL_HDR_SIZE);
1078 #if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_NOACCESS)
1079                 VALGRIND_MAKE_MEM_NOACCESS(
1080                         tc->pool, tc->size - TALLOC_POOL_HDR_SIZE);
1081 #endif
1082         }
1083 }
1084
1085 /* 
1086    Allocate a bit of memory as a child of an existing pointer
1087 */
1088 _PUBLIC_ void *_talloc(const void *context, size_t size)
1089 {
1090         return __talloc(context, size);
1091 }
1092
1093 /*
1094   externally callable talloc_set_name_const()
1095 */
1096 _PUBLIC_ void talloc_set_name_const(const void *ptr, const char *name)
1097 {
1098         _talloc_set_name_const(ptr, name);
1099 }
1100
1101 /*
1102   create a named talloc pointer. Any talloc pointer can be named, and
1103   talloc_named() operates just like talloc() except that it allows you
1104   to name the pointer.
1105 */
1106 _PUBLIC_ void *talloc_named_const(const void *context, size_t size, const char *name)
1107 {
1108         return _talloc_named_const(context, size, name);
1109 }
1110
1111 /* 
1112    free a talloc pointer. This also frees all child pointers of this 
1113    pointer recursively
1114
1115    return 0 if the memory is actually freed, otherwise -1. The memory
1116    will not be freed if the ref_count is > 1 or the destructor (if
1117    any) returns non-zero
1118 */
1119 _PUBLIC_ int _talloc_free(void *ptr, const char *location)
1120 {
1121         struct talloc_chunk *tc;
1122
1123         if (unlikely(ptr == NULL)) {
1124                 return -1;
1125         }
1126
1127         tc = talloc_chunk_from_ptr(ptr);
1128
1129         if (unlikely(tc->refs != NULL)) {
1130                 struct talloc_reference_handle *h;
1131
1132                 if (talloc_parent(ptr) == null_context && tc->refs->next == NULL) {
1133                         /* in this case we do know which parent should
1134                            get this pointer, as there is really only
1135                            one parent */
1136                         return talloc_unlink(null_context, ptr);
1137                 }
1138
1139                 talloc_log("ERROR: talloc_free with references at %s\n",
1140                            location);
1141
1142                 for (h=tc->refs; h; h=h->next) {
1143                         talloc_log("\treference at %s\n",
1144                                    h->location);
1145                 }
1146                 return -1;
1147         }
1148
1149         return _talloc_free_internal(ptr, location);
1150 }
1151
1152
1153
1154 /*
1155   A talloc version of realloc. The context argument is only used if
1156   ptr is NULL
1157 */
1158 _PUBLIC_ void *_talloc_realloc(const void *context, void *ptr, size_t size, const char *name)
1159 {
1160         struct talloc_chunk *tc;
1161         void *new_ptr;
1162         bool malloced = false;
1163
1164         /* size zero is equivalent to free() */
1165         if (unlikely(size == 0)) {
1166                 talloc_unlink(context, ptr);
1167                 return NULL;
1168         }
1169
1170         if (unlikely(size >= MAX_TALLOC_SIZE)) {
1171                 return NULL;
1172         }
1173
1174         /* realloc(NULL) is equivalent to malloc() */
1175         if (ptr == NULL) {
1176                 return _talloc_named_const(context, size, name);
1177         }
1178
1179         tc = talloc_chunk_from_ptr(ptr);
1180
1181         /* don't allow realloc on referenced pointers */
1182         if (unlikely(tc->refs)) {
1183                 return NULL;
1184         }
1185
1186         /* don't let anybody try to realloc a talloc_pool */
1187         if (unlikely(tc->flags & TALLOC_FLAG_POOL)) {
1188                 return NULL;
1189         }
1190
1191         /* don't shrink if we have less than 1k to gain */
1192         if ((size < tc->size) && ((tc->size - size) < 1024)) {
1193                 tc->size = size;
1194                 return ptr;
1195         }
1196
1197         /* by resetting magic we catch users of the old memory */
1198         tc->flags |= TALLOC_FLAG_FREE;
1199
1200 #if ALWAYS_REALLOC
1201         new_ptr = malloc(size + TC_HDR_SIZE);
1202         if (new_ptr) {
1203                 memcpy(new_ptr, tc, MIN(tc->size, size) + TC_HDR_SIZE);
1204                 free(tc);
1205         }
1206 #else
1207         if (tc->flags & TALLOC_FLAG_POOLMEM) {
1208
1209                 new_ptr = talloc_alloc_pool(tc, size + TC_HDR_SIZE);
1210                 *talloc_pool_objectcount((struct talloc_chunk *)
1211                                          (tc->pool)) -= 1;
1212
1213                 if (new_ptr == NULL) {
1214                         new_ptr = malloc(TC_HDR_SIZE+size);
1215                         malloced = true;
1216                 }
1217
1218                 if (new_ptr) {
1219                         memcpy(new_ptr, tc, MIN(tc->size,size) + TC_HDR_SIZE);
1220                 }
1221         }
1222         else {
1223                 new_ptr = realloc(tc, size + TC_HDR_SIZE);
1224         }
1225 #endif
1226         if (unlikely(!new_ptr)) {       
1227                 tc->flags &= ~TALLOC_FLAG_FREE; 
1228                 return NULL; 
1229         }
1230
1231         tc = (struct talloc_chunk *)new_ptr;
1232         tc->flags &= ~TALLOC_FLAG_FREE;
1233         if (malloced) {
1234                 tc->flags &= ~TALLOC_FLAG_POOLMEM;
1235         }
1236         if (tc->parent) {
1237                 tc->parent->child = tc;
1238         }
1239         if (tc->child) {
1240                 tc->child->parent = tc;
1241         }
1242
1243         if (tc->prev) {
1244                 tc->prev->next = tc;
1245         }
1246         if (tc->next) {
1247                 tc->next->prev = tc;
1248         }
1249
1250         tc->size = size;
1251         _talloc_set_name_const(TC_PTR_FROM_CHUNK(tc), name);
1252
1253         return TC_PTR_FROM_CHUNK(tc);
1254 }
1255
1256 /*
1257   a wrapper around talloc_steal() for situations where you are moving a pointer
1258   between two structures, and want the old pointer to be set to NULL
1259 */
1260 _PUBLIC_ void *_talloc_move(const void *new_ctx, const void *_pptr)
1261 {
1262         const void **pptr = discard_const_p(const void *,_pptr);
1263         void *ret = talloc_steal(new_ctx, discard_const_p(void, *pptr));
1264         (*pptr) = NULL;
1265         return ret;
1266 }
1267
1268 /*
1269   return the total size of a talloc pool (subtree)
1270 */
1271 _PUBLIC_ size_t talloc_total_size(const void *ptr)
1272 {
1273         size_t total = 0;
1274         struct talloc_chunk *c, *tc;
1275
1276         if (ptr == NULL) {
1277                 ptr = null_context;
1278         }
1279         if (ptr == NULL) {
1280                 return 0;
1281         }
1282
1283         tc = talloc_chunk_from_ptr(ptr);
1284
1285         if (tc->flags & TALLOC_FLAG_LOOP) {
1286                 return 0;
1287         }
1288
1289         tc->flags |= TALLOC_FLAG_LOOP;
1290
1291         if (likely(tc->name != TALLOC_MAGIC_REFERENCE)) {
1292                 total = tc->size;
1293         }
1294         for (c=tc->child;c;c=c->next) {
1295                 total += talloc_total_size(TC_PTR_FROM_CHUNK(c));
1296         }
1297
1298         tc->flags &= ~TALLOC_FLAG_LOOP;
1299
1300         return total;
1301 }
1302
1303 /*
1304   return the total number of blocks in a talloc pool (subtree)
1305 */
1306 _PUBLIC_ size_t talloc_total_blocks(const void *ptr)
1307 {
1308         size_t total = 0;
1309         struct talloc_chunk *c, *tc;
1310
1311         if (ptr == NULL) {
1312                 ptr = null_context;
1313         }
1314         if (ptr == NULL) {
1315                 return 0;
1316         }
1317
1318         tc = talloc_chunk_from_ptr(ptr);
1319
1320         if (tc->flags & TALLOC_FLAG_LOOP) {
1321                 return 0;
1322         }
1323
1324         tc->flags |= TALLOC_FLAG_LOOP;
1325
1326         total++;
1327         for (c=tc->child;c;c=c->next) {
1328                 total += talloc_total_blocks(TC_PTR_FROM_CHUNK(c));
1329         }
1330
1331         tc->flags &= ~TALLOC_FLAG_LOOP;
1332
1333         return total;
1334 }
1335
1336 /*
1337   return the number of external references to a pointer
1338 */
1339 _PUBLIC_ size_t talloc_reference_count(const void *ptr)
1340 {
1341         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
1342         struct talloc_reference_handle *h;
1343         size_t ret = 0;
1344
1345         for (h=tc->refs;h;h=h->next) {
1346                 ret++;
1347         }
1348         return ret;
1349 }
1350
1351 /*
1352   report on memory usage by all children of a pointer, giving a full tree view
1353 */
1354 _PUBLIC_ void talloc_report_depth_cb(const void *ptr, int depth, int max_depth,
1355                             void (*callback)(const void *ptr,
1356                                              int depth, int max_depth,
1357                                              int is_ref,
1358                                              void *private_data),
1359                             void *private_data)
1360 {
1361         struct talloc_chunk *c, *tc;
1362
1363         if (ptr == NULL) {
1364                 ptr = null_context;
1365         }
1366         if (ptr == NULL) return;
1367
1368         tc = talloc_chunk_from_ptr(ptr);
1369
1370         if (tc->flags & TALLOC_FLAG_LOOP) {
1371                 return;
1372         }
1373
1374         callback(ptr, depth, max_depth, 0, private_data);
1375
1376         if (max_depth >= 0 && depth >= max_depth) {
1377                 return;
1378         }
1379
1380         tc->flags |= TALLOC_FLAG_LOOP;
1381         for (c=tc->child;c;c=c->next) {
1382                 if (c->name == TALLOC_MAGIC_REFERENCE) {
1383                         struct talloc_reference_handle *h = (struct talloc_reference_handle *)TC_PTR_FROM_CHUNK(c);
1384                         callback(h->ptr, depth + 1, max_depth, 1, private_data);
1385                 } else {
1386                         talloc_report_depth_cb(TC_PTR_FROM_CHUNK(c), depth + 1, max_depth, callback, private_data);
1387                 }
1388         }
1389         tc->flags &= ~TALLOC_FLAG_LOOP;
1390 }
1391
1392 static void talloc_report_depth_FILE_helper(const void *ptr, int depth, int max_depth, int is_ref, void *_f)
1393 {
1394         const char *name = talloc_get_name(ptr);
1395         FILE *f = (FILE *)_f;
1396
1397         if (is_ref) {
1398                 fprintf(f, "%*sreference to: %s\n", depth*4, "", name);
1399                 return;
1400         }
1401
1402         if (depth == 0) {
1403                 fprintf(f,"%stalloc report on '%s' (total %6lu bytes in %3lu blocks)\n", 
1404                         (max_depth < 0 ? "full " :""), name,
1405                         (unsigned long)talloc_total_size(ptr),
1406                         (unsigned long)talloc_total_blocks(ptr));
1407                 return;
1408         }
1409
1410         fprintf(f, "%*s%-30s contains %6lu bytes in %3lu blocks (ref %d) %p\n", 
1411                 depth*4, "",
1412                 name,
1413                 (unsigned long)talloc_total_size(ptr),
1414                 (unsigned long)talloc_total_blocks(ptr),
1415                 (int)talloc_reference_count(ptr), ptr);
1416
1417 #if 0
1418         fprintf(f, "content: ");
1419         if (talloc_total_size(ptr)) {
1420                 int tot = talloc_total_size(ptr);
1421                 int i;
1422
1423                 for (i = 0; i < tot; i++) {
1424                         if ((((char *)ptr)[i] > 31) && (((char *)ptr)[i] < 126)) {
1425                                 fprintf(f, "%c", ((char *)ptr)[i]);
1426                         } else {
1427                                 fprintf(f, "~%02x", ((char *)ptr)[i]);
1428                         }
1429                 }
1430         }
1431         fprintf(f, "\n");
1432 #endif
1433 }
1434
1435 /*
1436   report on memory usage by all children of a pointer, giving a full tree view
1437 */
1438 _PUBLIC_ void talloc_report_depth_file(const void *ptr, int depth, int max_depth, FILE *f)
1439 {
1440         if (f) {
1441                 talloc_report_depth_cb(ptr, depth, max_depth, talloc_report_depth_FILE_helper, f);
1442                 fflush(f);
1443         }
1444 }
1445
1446 /*
1447   report on memory usage by all children of a pointer, giving a full tree view
1448 */
1449 _PUBLIC_ void talloc_report_full(const void *ptr, FILE *f)
1450 {
1451         talloc_report_depth_file(ptr, 0, -1, f);
1452 }
1453
1454 /*
1455   report on memory usage by all children of a pointer
1456 */
1457 _PUBLIC_ void talloc_report(const void *ptr, FILE *f)
1458 {
1459         talloc_report_depth_file(ptr, 0, 1, f);
1460 }
1461
1462 /*
1463   report on any memory hanging off the null context
1464 */
1465 static void talloc_report_null(void)
1466 {
1467         if (talloc_total_size(null_context) != 0) {
1468                 talloc_report(null_context, stderr);
1469         }
1470 }
1471
1472 /*
1473   report on any memory hanging off the null context
1474 */
1475 static void talloc_report_null_full(void)
1476 {
1477         if (talloc_total_size(null_context) != 0) {
1478                 talloc_report_full(null_context, stderr);
1479         }
1480 }
1481
1482 /*
1483   enable tracking of the NULL context
1484 */
1485 _PUBLIC_ void talloc_enable_null_tracking(void)
1486 {
1487         if (null_context == NULL) {
1488                 null_context = _talloc_named_const(NULL, 0, "null_context");
1489                 if (autofree_context != NULL) {
1490                         talloc_reparent(NULL, null_context, autofree_context);
1491                 }
1492         }
1493 }
1494
1495 /*
1496   enable tracking of the NULL context, not moving the autofree context
1497   into the NULL context. This is needed for the talloc testsuite
1498 */
1499 _PUBLIC_ void talloc_enable_null_tracking_no_autofree(void)
1500 {
1501         if (null_context == NULL) {
1502                 null_context = _talloc_named_const(NULL, 0, "null_context");
1503         }
1504 }
1505
1506 /*
1507   disable tracking of the NULL context
1508 */
1509 _PUBLIC_ void talloc_disable_null_tracking(void)
1510 {
1511         if (null_context != NULL) {
1512                 /* we have to move any children onto the real NULL
1513                    context */
1514                 struct talloc_chunk *tc, *tc2;
1515                 tc = talloc_chunk_from_ptr(null_context);
1516                 for (tc2 = tc->child; tc2; tc2=tc2->next) {
1517                         if (tc2->parent == tc) tc2->parent = NULL;
1518                         if (tc2->prev == tc) tc2->prev = NULL;
1519                 }
1520                 for (tc2 = tc->next; tc2; tc2=tc2->next) {
1521                         if (tc2->parent == tc) tc2->parent = NULL;
1522                         if (tc2->prev == tc) tc2->prev = NULL;
1523                 }
1524                 tc->child = NULL;
1525                 tc->next = NULL;
1526         }
1527         talloc_free(null_context);
1528         null_context = NULL;
1529 }
1530
1531 /*
1532   enable leak reporting on exit
1533 */
1534 _PUBLIC_ void talloc_enable_leak_report(void)
1535 {
1536         talloc_enable_null_tracking();
1537         atexit(talloc_report_null);
1538 }
1539
1540 /*
1541   enable full leak reporting on exit
1542 */
1543 _PUBLIC_ void talloc_enable_leak_report_full(void)
1544 {
1545         talloc_enable_null_tracking();
1546         atexit(talloc_report_null_full);
1547 }
1548
1549 /* 
1550    talloc and zero memory. 
1551 */
1552 _PUBLIC_ void *_talloc_zero(const void *ctx, size_t size, const char *name)
1553 {
1554         void *p = _talloc_named_const(ctx, size, name);
1555
1556         if (p) {
1557                 memset(p, '\0', size);
1558         }
1559
1560         return p;
1561 }
1562
1563 /*
1564   memdup with a talloc. 
1565 */
1566 _PUBLIC_ void *_talloc_memdup(const void *t, const void *p, size_t size, const char *name)
1567 {
1568         void *newp = _talloc_named_const(t, size, name);
1569
1570         if (likely(newp)) {
1571                 memcpy(newp, p, size);
1572         }
1573
1574         return newp;
1575 }
1576
1577 static inline char *__talloc_strlendup(const void *t, const char *p, size_t len)
1578 {
1579         char *ret;
1580
1581         ret = (char *)__talloc(t, len + 1);
1582         if (unlikely(!ret)) return NULL;
1583
1584         memcpy(ret, p, len);
1585         ret[len] = 0;
1586
1587         _talloc_set_name_const(ret, ret);
1588         return ret;
1589 }
1590
1591 /*
1592   strdup with a talloc
1593 */
1594 _PUBLIC_ char *talloc_strdup(const void *t, const char *p)
1595 {
1596         if (unlikely(!p)) return NULL;
1597         return __talloc_strlendup(t, p, strlen(p));
1598 }
1599
1600 /*
1601   strndup with a talloc
1602 */
1603 _PUBLIC_ char *talloc_strndup(const void *t, const char *p, size_t n)
1604 {
1605         if (unlikely(!p)) return NULL;
1606         return __talloc_strlendup(t, p, strnlen(p, n));
1607 }
1608
1609 static inline char *__talloc_strlendup_append(char *s, size_t slen,
1610                                               const char *a, size_t alen)
1611 {
1612         char *ret;
1613
1614         ret = talloc_realloc(NULL, s, char, slen + alen + 1);
1615         if (unlikely(!ret)) return NULL;
1616
1617         /* append the string and the trailing \0 */
1618         memcpy(&ret[slen], a, alen);
1619         ret[slen+alen] = 0;
1620
1621         _talloc_set_name_const(ret, ret);
1622         return ret;
1623 }
1624
1625 /*
1626  * Appends at the end of the string.
1627  */
1628 _PUBLIC_ char *talloc_strdup_append(char *s, const char *a)
1629 {
1630         if (unlikely(!s)) {
1631                 return talloc_strdup(NULL, a);
1632         }
1633
1634         if (unlikely(!a)) {
1635                 return s;
1636         }
1637
1638         return __talloc_strlendup_append(s, strlen(s), a, strlen(a));
1639 }
1640
1641 /*
1642  * Appends at the end of the talloc'ed buffer,
1643  * not the end of the string.
1644  */
1645 _PUBLIC_ char *talloc_strdup_append_buffer(char *s, const char *a)
1646 {
1647         size_t slen;
1648
1649         if (unlikely(!s)) {
1650                 return talloc_strdup(NULL, a);
1651         }
1652
1653         if (unlikely(!a)) {
1654                 return s;
1655         }
1656
1657         slen = talloc_get_size(s);
1658         if (likely(slen > 0)) {
1659                 slen--;
1660         }
1661
1662         return __talloc_strlendup_append(s, slen, a, strlen(a));
1663 }
1664
1665 /*
1666  * Appends at the end of the string.
1667  */
1668 _PUBLIC_ char *talloc_strndup_append(char *s, const char *a, size_t n)
1669 {
1670         if (unlikely(!s)) {
1671                 return talloc_strdup(NULL, a);
1672         }
1673
1674         if (unlikely(!a)) {
1675                 return s;
1676         }
1677
1678         return __talloc_strlendup_append(s, strlen(s), a, strnlen(a, n));
1679 }
1680
1681 /*
1682  * Appends at the end of the talloc'ed buffer,
1683  * not the end of the string.
1684  */
1685 _PUBLIC_ char *talloc_strndup_append_buffer(char *s, const char *a, size_t n)
1686 {
1687         size_t slen;
1688
1689         if (unlikely(!s)) {
1690                 return talloc_strdup(NULL, a);
1691         }
1692
1693         if (unlikely(!a)) {
1694                 return s;
1695         }
1696
1697         slen = talloc_get_size(s);
1698         if (likely(slen > 0)) {
1699                 slen--;
1700         }
1701
1702         return __talloc_strlendup_append(s, slen, a, strnlen(a, n));
1703 }
1704
1705 #ifndef HAVE_VA_COPY
1706 #ifdef HAVE___VA_COPY
1707 #define va_copy(dest, src) __va_copy(dest, src)
1708 #else
1709 #define va_copy(dest, src) (dest) = (src)
1710 #endif
1711 #endif
1712
1713 _PUBLIC_ char *talloc_vasprintf(const void *t, const char *fmt, va_list ap)
1714 {
1715         int len;
1716         char *ret;
1717         va_list ap2;
1718         char c;
1719
1720         /* this call looks strange, but it makes it work on older solaris boxes */
1721         va_copy(ap2, ap);
1722         len = vsnprintf(&c, 1, fmt, ap2);
1723         va_end(ap2);
1724         if (unlikely(len < 0)) {
1725                 return NULL;
1726         }
1727
1728         ret = (char *)__talloc(t, len+1);
1729         if (unlikely(!ret)) return NULL;
1730
1731         va_copy(ap2, ap);
1732         vsnprintf(ret, len+1, fmt, ap2);
1733         va_end(ap2);
1734
1735         _talloc_set_name_const(ret, ret);
1736         return ret;
1737 }
1738
1739
1740 /*
1741   Perform string formatting, and return a pointer to newly allocated
1742   memory holding the result, inside a memory pool.
1743  */
1744 _PUBLIC_ char *talloc_asprintf(const void *t, const char *fmt, ...)
1745 {
1746         va_list ap;
1747         char *ret;
1748
1749         va_start(ap, fmt);
1750         ret = talloc_vasprintf(t, fmt, ap);
1751         va_end(ap);
1752         return ret;
1753 }
1754
1755 static inline char *__talloc_vaslenprintf_append(char *s, size_t slen,
1756                                                  const char *fmt, va_list ap)
1757                                                  PRINTF_ATTRIBUTE(3,0);
1758
1759 static inline char *__talloc_vaslenprintf_append(char *s, size_t slen,
1760                                                  const char *fmt, va_list ap)
1761 {
1762         ssize_t alen;
1763         va_list ap2;
1764         char c;
1765
1766         va_copy(ap2, ap);
1767         alen = vsnprintf(&c, 1, fmt, ap2);
1768         va_end(ap2);
1769
1770         if (alen <= 0) {
1771                 /* Either the vsnprintf failed or the format resulted in
1772                  * no characters being formatted. In the former case, we
1773                  * ought to return NULL, in the latter we ought to return
1774                  * the original string. Most current callers of this
1775                  * function expect it to never return NULL.
1776                  */
1777                 return s;
1778         }
1779
1780         s = talloc_realloc(NULL, s, char, slen + alen + 1);
1781         if (!s) return NULL;
1782
1783         va_copy(ap2, ap);
1784         vsnprintf(s + slen, alen + 1, fmt, ap2);
1785         va_end(ap2);
1786
1787         _talloc_set_name_const(s, s);
1788         return s;
1789 }
1790
1791 /**
1792  * Realloc @p s to append the formatted result of @p fmt and @p ap,
1793  * and return @p s, which may have moved.  Good for gradually
1794  * accumulating output into a string buffer. Appends at the end
1795  * of the string.
1796  **/
1797 _PUBLIC_ char *talloc_vasprintf_append(char *s, const char *fmt, va_list ap)
1798 {
1799         if (unlikely(!s)) {
1800                 return talloc_vasprintf(NULL, fmt, ap);
1801         }
1802
1803         return __talloc_vaslenprintf_append(s, strlen(s), fmt, ap);
1804 }
1805
1806 /**
1807  * Realloc @p s to append the formatted result of @p fmt and @p ap,
1808  * and return @p s, which may have moved. Always appends at the
1809  * end of the talloc'ed buffer, not the end of the string.
1810  **/
1811 _PUBLIC_ char *talloc_vasprintf_append_buffer(char *s, const char *fmt, va_list ap)
1812 {
1813         size_t slen;
1814
1815         if (unlikely(!s)) {
1816                 return talloc_vasprintf(NULL, fmt, ap);
1817         }
1818
1819         slen = talloc_get_size(s);
1820         if (likely(slen > 0)) {
1821                 slen--;
1822         }
1823
1824         return __talloc_vaslenprintf_append(s, slen, fmt, ap);
1825 }
1826
1827 /*
1828   Realloc @p s to append the formatted result of @p fmt and return @p
1829   s, which may have moved.  Good for gradually accumulating output
1830   into a string buffer.
1831  */
1832 _PUBLIC_ char *talloc_asprintf_append(char *s, const char *fmt, ...)
1833 {
1834         va_list ap;
1835
1836         va_start(ap, fmt);
1837         s = talloc_vasprintf_append(s, fmt, ap);
1838         va_end(ap);
1839         return s;
1840 }
1841
1842 /*
1843   Realloc @p s to append the formatted result of @p fmt and return @p
1844   s, which may have moved.  Good for gradually accumulating output
1845   into a buffer.
1846  */
1847 _PUBLIC_ char *talloc_asprintf_append_buffer(char *s, const char *fmt, ...)
1848 {
1849         va_list ap;
1850
1851         va_start(ap, fmt);
1852         s = talloc_vasprintf_append_buffer(s, fmt, ap);
1853         va_end(ap);
1854         return s;
1855 }
1856
1857 /*
1858   alloc an array, checking for integer overflow in the array size
1859 */
1860 _PUBLIC_ void *_talloc_array(const void *ctx, size_t el_size, unsigned count, const char *name)
1861 {
1862         if (count >= MAX_TALLOC_SIZE/el_size) {
1863                 return NULL;
1864         }
1865         return _talloc_named_const(ctx, el_size * count, name);
1866 }
1867
1868 /*
1869   alloc an zero array, checking for integer overflow in the array size
1870 */
1871 _PUBLIC_ void *_talloc_zero_array(const void *ctx, size_t el_size, unsigned count, const char *name)
1872 {
1873         if (count >= MAX_TALLOC_SIZE/el_size) {
1874                 return NULL;
1875         }
1876         return _talloc_zero(ctx, el_size * count, name);
1877 }
1878
1879 /*
1880   realloc an array, checking for integer overflow in the array size
1881 */
1882 _PUBLIC_ void *_talloc_realloc_array(const void *ctx, void *ptr, size_t el_size, unsigned count, const char *name)
1883 {
1884         if (count >= MAX_TALLOC_SIZE/el_size) {
1885                 return NULL;
1886         }
1887         return _talloc_realloc(ctx, ptr, el_size * count, name);
1888 }
1889
1890 /*
1891   a function version of talloc_realloc(), so it can be passed as a function pointer
1892   to libraries that want a realloc function (a realloc function encapsulates
1893   all the basic capabilities of an allocation library, which is why this is useful)
1894 */
1895 _PUBLIC_ void *talloc_realloc_fn(const void *context, void *ptr, size_t size)
1896 {
1897         return _talloc_realloc(context, ptr, size, NULL);
1898 }
1899
1900
1901 static int talloc_autofree_destructor(void *ptr)
1902 {
1903         autofree_context = NULL;
1904         return 0;
1905 }
1906
1907 static void talloc_autofree(void)
1908 {
1909         talloc_free(autofree_context);
1910 }
1911
1912 /*
1913   return a context which will be auto-freed on exit
1914   this is useful for reducing the noise in leak reports
1915 */
1916 _PUBLIC_ void *talloc_autofree_context(void)
1917 {
1918         if (autofree_context == NULL) {
1919                 autofree_context = _talloc_named_const(NULL, 0, "autofree_context");
1920                 talloc_set_destructor(autofree_context, talloc_autofree_destructor);
1921                 atexit(talloc_autofree);
1922         }
1923         return autofree_context;
1924 }
1925
1926 _PUBLIC_ size_t talloc_get_size(const void *context)
1927 {
1928         struct talloc_chunk *tc;
1929
1930         if (context == NULL) {
1931                 context = null_context;
1932         }
1933         if (context == NULL) {
1934                 return 0;
1935         }
1936
1937         tc = talloc_chunk_from_ptr(context);
1938
1939         return tc->size;
1940 }
1941
1942 /*
1943   find a parent of this context that has the given name, if any
1944 */
1945 _PUBLIC_ void *talloc_find_parent_byname(const void *context, const char *name)
1946 {
1947         struct talloc_chunk *tc;
1948
1949         if (context == NULL) {
1950                 return NULL;
1951         }
1952
1953         tc = talloc_chunk_from_ptr(context);
1954         while (tc) {
1955                 if (tc->name && strcmp(tc->name, name) == 0) {
1956                         return TC_PTR_FROM_CHUNK(tc);
1957                 }
1958                 while (tc && tc->prev) tc = tc->prev;
1959                 if (tc) {
1960                         tc = tc->parent;
1961                 }
1962         }
1963         return NULL;
1964 }
1965
1966 /*
1967   show the parentage of a context
1968 */
1969 _PUBLIC_ void talloc_show_parents(const void *context, FILE *file)
1970 {
1971         struct talloc_chunk *tc;
1972
1973         if (context == NULL) {
1974                 fprintf(file, "talloc no parents for NULL\n");
1975                 return;
1976         }
1977
1978         tc = talloc_chunk_from_ptr(context);
1979         fprintf(file, "talloc parents of '%s'\n", talloc_get_name(context));
1980         while (tc) {
1981                 fprintf(file, "\t'%s'\n", talloc_get_name(TC_PTR_FROM_CHUNK(tc)));
1982                 while (tc && tc->prev) tc = tc->prev;
1983                 if (tc) {
1984                         tc = tc->parent;
1985                 }
1986         }
1987         fflush(file);
1988 }
1989
1990 /*
1991   return 1 if ptr is a parent of context
1992 */
1993 static int _talloc_is_parent(const void *context, const void *ptr, int depth)
1994 {
1995         struct talloc_chunk *tc;
1996
1997         if (context == NULL) {
1998                 return 0;
1999         }
2000
2001         tc = talloc_chunk_from_ptr(context);
2002         while (tc && depth > 0) {
2003                 if (TC_PTR_FROM_CHUNK(tc) == ptr) return 1;
2004                 while (tc && tc->prev) tc = tc->prev;
2005                 if (tc) {
2006                         tc = tc->parent;
2007                         depth--;
2008                 }
2009         }
2010         return 0;
2011 }
2012
2013 /*
2014   return 1 if ptr is a parent of context
2015 */
2016 _PUBLIC_ int talloc_is_parent(const void *context, const void *ptr)
2017 {
2018         return _talloc_is_parent(context, ptr, TALLOC_MAX_DEPTH);
2019 }