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