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