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