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