4aa85d068c4c69d20c58c78c41dae0ad54cf8dc3
[metze/samba/wip.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                                 memmove(pool_tc->pool, tc, old_used);
1325                                 new_ptr = pool_tc->pool;
1326
1327                                 pool_tc->pool = new_chunk_size + (char *)new_ptr;
1328                                 goto got_new_ptr;
1329                         }
1330
1331                         next_tc = NULL;
1332                 }
1333
1334                 if (new_chunk_size == old_chunk_size) {
1335                         tc->flags &= ~TALLOC_FLAG_FREE;
1336                         tc->size = size;
1337                         return ptr;
1338                 }
1339
1340                 if (next_tc == pool_tc->pool) {
1341                         /*
1342                          * optimize for the case where 'tc' is the last
1343                          * chunk in the pool.
1344                          */
1345                         space_needed = new_chunk_size - old_chunk_size;
1346                         space_left = TC_POOL_SPACE_LEFT(pool_tc);
1347
1348                         if (space_left >= space_needed) {
1349                                 tc->flags &= ~TALLOC_FLAG_FREE;
1350                                 tc->size = size;
1351                                 pool_tc->pool = TC_POOLMEM_NEXT_CHUNK(tc);
1352                                 return ptr;
1353                         }
1354                 }
1355
1356                 new_ptr = talloc_alloc_pool(tc, size + TC_HDR_SIZE);
1357                 *talloc_pool_objectcount(pool_tc) -= 1;
1358
1359                 if (new_ptr == NULL) {
1360                         new_ptr = malloc(TC_HDR_SIZE+size);
1361                         malloced = true;
1362                 }
1363
1364                 if (new_ptr) {
1365                         memcpy(new_ptr, tc, MIN(tc->size,size) + TC_HDR_SIZE);
1366
1367                         if (*talloc_pool_objectcount(pool_tc) == 1) {
1368                                 /*
1369                                  * If the pool is empty now reclaim everything.
1370                                  */
1371                                 pool_tc->pool = TC_POOL_FIRST_CHUNK(pool_tc);
1372                         } else if (next_tc == pool_tc->pool) {
1373                                 /*
1374                                  * If it was reallocated and tc was the last
1375                                  * chunk, we can reclaim the memory of tc.
1376                                  */
1377                                 pool_tc->pool = tc;
1378                         }
1379                 }
1380         }
1381         else {
1382                 new_ptr = realloc(tc, size + TC_HDR_SIZE);
1383         }
1384 got_new_ptr:
1385 #endif
1386         if (unlikely(!new_ptr)) {       
1387                 tc->flags &= ~TALLOC_FLAG_FREE; 
1388                 return NULL; 
1389         }
1390
1391         tc = (struct talloc_chunk *)new_ptr;
1392         tc->flags &= ~TALLOC_FLAG_FREE;
1393         if (malloced) {
1394                 tc->flags &= ~TALLOC_FLAG_POOLMEM;
1395         }
1396         if (tc->parent) {
1397                 tc->parent->child = tc;
1398         }
1399         if (tc->child) {
1400                 tc->child->parent = tc;
1401         }
1402
1403         if (tc->prev) {
1404                 tc->prev->next = tc;
1405         }
1406         if (tc->next) {
1407                 tc->next->prev = tc;
1408         }
1409
1410         tc->size = size;
1411         _talloc_set_name_const(TC_PTR_FROM_CHUNK(tc), name);
1412
1413         return TC_PTR_FROM_CHUNK(tc);
1414 }
1415
1416 /*
1417   a wrapper around talloc_steal() for situations where you are moving a pointer
1418   between two structures, and want the old pointer to be set to NULL
1419 */
1420 _PUBLIC_ void *_talloc_move(const void *new_ctx, const void *_pptr)
1421 {
1422         const void **pptr = discard_const_p(const void *,_pptr);
1423         void *ret = talloc_steal(new_ctx, discard_const_p(void, *pptr));
1424         (*pptr) = NULL;
1425         return ret;
1426 }
1427
1428 /*
1429   return the total size of a talloc pool (subtree)
1430 */
1431 _PUBLIC_ size_t talloc_total_size(const void *ptr)
1432 {
1433         size_t total = 0;
1434         struct talloc_chunk *c, *tc;
1435
1436         if (ptr == NULL) {
1437                 ptr = null_context;
1438         }
1439         if (ptr == NULL) {
1440                 return 0;
1441         }
1442
1443         tc = talloc_chunk_from_ptr(ptr);
1444
1445         if (tc->flags & TALLOC_FLAG_LOOP) {
1446                 return 0;
1447         }
1448
1449         tc->flags |= TALLOC_FLAG_LOOP;
1450
1451         if (likely(tc->name != TALLOC_MAGIC_REFERENCE)) {
1452                 total = tc->size;
1453         }
1454         for (c=tc->child;c;c=c->next) {
1455                 total += talloc_total_size(TC_PTR_FROM_CHUNK(c));
1456         }
1457
1458         tc->flags &= ~TALLOC_FLAG_LOOP;
1459
1460         return total;
1461 }
1462
1463 /*
1464   return the total number of blocks in a talloc pool (subtree)
1465 */
1466 _PUBLIC_ size_t talloc_total_blocks(const void *ptr)
1467 {
1468         size_t total = 0;
1469         struct talloc_chunk *c, *tc;
1470
1471         if (ptr == NULL) {
1472                 ptr = null_context;
1473         }
1474         if (ptr == NULL) {
1475                 return 0;
1476         }
1477
1478         tc = talloc_chunk_from_ptr(ptr);
1479
1480         if (tc->flags & TALLOC_FLAG_LOOP) {
1481                 return 0;
1482         }
1483
1484         tc->flags |= TALLOC_FLAG_LOOP;
1485
1486         total++;
1487         for (c=tc->child;c;c=c->next) {
1488                 total += talloc_total_blocks(TC_PTR_FROM_CHUNK(c));
1489         }
1490
1491         tc->flags &= ~TALLOC_FLAG_LOOP;
1492
1493         return total;
1494 }
1495
1496 /*
1497   return the number of external references to a pointer
1498 */
1499 _PUBLIC_ size_t talloc_reference_count(const void *ptr)
1500 {
1501         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
1502         struct talloc_reference_handle *h;
1503         size_t ret = 0;
1504
1505         for (h=tc->refs;h;h=h->next) {
1506                 ret++;
1507         }
1508         return ret;
1509 }
1510
1511 /*
1512   report on memory usage by all children of a pointer, giving a full tree view
1513 */
1514 _PUBLIC_ void talloc_report_depth_cb(const void *ptr, int depth, int max_depth,
1515                             void (*callback)(const void *ptr,
1516                                              int depth, int max_depth,
1517                                              int is_ref,
1518                                              void *private_data),
1519                             void *private_data)
1520 {
1521         struct talloc_chunk *c, *tc;
1522
1523         if (ptr == NULL) {
1524                 ptr = null_context;
1525         }
1526         if (ptr == NULL) return;
1527
1528         tc = talloc_chunk_from_ptr(ptr);
1529
1530         if (tc->flags & TALLOC_FLAG_LOOP) {
1531                 return;
1532         }
1533
1534         callback(ptr, depth, max_depth, 0, private_data);
1535
1536         if (max_depth >= 0 && depth >= max_depth) {
1537                 return;
1538         }
1539
1540         tc->flags |= TALLOC_FLAG_LOOP;
1541         for (c=tc->child;c;c=c->next) {
1542                 if (c->name == TALLOC_MAGIC_REFERENCE) {
1543                         struct talloc_reference_handle *h = (struct talloc_reference_handle *)TC_PTR_FROM_CHUNK(c);
1544                         callback(h->ptr, depth + 1, max_depth, 1, private_data);
1545                 } else {
1546                         talloc_report_depth_cb(TC_PTR_FROM_CHUNK(c), depth + 1, max_depth, callback, private_data);
1547                 }
1548         }
1549         tc->flags &= ~TALLOC_FLAG_LOOP;
1550 }
1551
1552 static void talloc_report_depth_FILE_helper(const void *ptr, int depth, int max_depth, int is_ref, void *_f)
1553 {
1554         const char *name = talloc_get_name(ptr);
1555         FILE *f = (FILE *)_f;
1556
1557         if (is_ref) {
1558                 fprintf(f, "%*sreference to: %s\n", depth*4, "", name);
1559                 return;
1560         }
1561
1562         if (depth == 0) {
1563                 fprintf(f,"%stalloc report on '%s' (total %6lu bytes in %3lu blocks)\n", 
1564                         (max_depth < 0 ? "full " :""), name,
1565                         (unsigned long)talloc_total_size(ptr),
1566                         (unsigned long)talloc_total_blocks(ptr));
1567                 return;
1568         }
1569
1570         fprintf(f, "%*s%-30s contains %6lu bytes in %3lu blocks (ref %d) %p\n", 
1571                 depth*4, "",
1572                 name,
1573                 (unsigned long)talloc_total_size(ptr),
1574                 (unsigned long)talloc_total_blocks(ptr),
1575                 (int)talloc_reference_count(ptr), ptr);
1576
1577 #if 0
1578         fprintf(f, "content: ");
1579         if (talloc_total_size(ptr)) {
1580                 int tot = talloc_total_size(ptr);
1581                 int i;
1582
1583                 for (i = 0; i < tot; i++) {
1584                         if ((((char *)ptr)[i] > 31) && (((char *)ptr)[i] < 126)) {
1585                                 fprintf(f, "%c", ((char *)ptr)[i]);
1586                         } else {
1587                                 fprintf(f, "~%02x", ((char *)ptr)[i]);
1588                         }
1589                 }
1590         }
1591         fprintf(f, "\n");
1592 #endif
1593 }
1594
1595 /*
1596   report on memory usage by all children of a pointer, giving a full tree view
1597 */
1598 _PUBLIC_ void talloc_report_depth_file(const void *ptr, int depth, int max_depth, FILE *f)
1599 {
1600         if (f) {
1601                 talloc_report_depth_cb(ptr, depth, max_depth, talloc_report_depth_FILE_helper, f);
1602                 fflush(f);
1603         }
1604 }
1605
1606 /*
1607   report on memory usage by all children of a pointer, giving a full tree view
1608 */
1609 _PUBLIC_ void talloc_report_full(const void *ptr, FILE *f)
1610 {
1611         talloc_report_depth_file(ptr, 0, -1, f);
1612 }
1613
1614 /*
1615   report on memory usage by all children of a pointer
1616 */
1617 _PUBLIC_ void talloc_report(const void *ptr, FILE *f)
1618 {
1619         talloc_report_depth_file(ptr, 0, 1, f);
1620 }
1621
1622 /*
1623   report on any memory hanging off the null context
1624 */
1625 static void talloc_report_null(void)
1626 {
1627         if (talloc_total_size(null_context) != 0) {
1628                 talloc_report(null_context, stderr);
1629         }
1630 }
1631
1632 /*
1633   report on any memory hanging off the null context
1634 */
1635 static void talloc_report_null_full(void)
1636 {
1637         if (talloc_total_size(null_context) != 0) {
1638                 talloc_report_full(null_context, stderr);
1639         }
1640 }
1641
1642 /*
1643   enable tracking of the NULL context
1644 */
1645 _PUBLIC_ void talloc_enable_null_tracking(void)
1646 {
1647         if (null_context == NULL) {
1648                 null_context = _talloc_named_const(NULL, 0, "null_context");
1649                 if (autofree_context != NULL) {
1650                         talloc_reparent(NULL, null_context, autofree_context);
1651                 }
1652         }
1653 }
1654
1655 /*
1656   enable tracking of the NULL context, not moving the autofree context
1657   into the NULL context. This is needed for the talloc testsuite
1658 */
1659 _PUBLIC_ void talloc_enable_null_tracking_no_autofree(void)
1660 {
1661         if (null_context == NULL) {
1662                 null_context = _talloc_named_const(NULL, 0, "null_context");
1663         }
1664 }
1665
1666 /*
1667   disable tracking of the NULL context
1668 */
1669 _PUBLIC_ void talloc_disable_null_tracking(void)
1670 {
1671         if (null_context != NULL) {
1672                 /* we have to move any children onto the real NULL
1673                    context */
1674                 struct talloc_chunk *tc, *tc2;
1675                 tc = talloc_chunk_from_ptr(null_context);
1676                 for (tc2 = tc->child; tc2; tc2=tc2->next) {
1677                         if (tc2->parent == tc) tc2->parent = NULL;
1678                         if (tc2->prev == tc) tc2->prev = NULL;
1679                 }
1680                 for (tc2 = tc->next; tc2; tc2=tc2->next) {
1681                         if (tc2->parent == tc) tc2->parent = NULL;
1682                         if (tc2->prev == tc) tc2->prev = NULL;
1683                 }
1684                 tc->child = NULL;
1685                 tc->next = NULL;
1686         }
1687         talloc_free(null_context);
1688         null_context = NULL;
1689 }
1690
1691 /*
1692   enable leak reporting on exit
1693 */
1694 _PUBLIC_ void talloc_enable_leak_report(void)
1695 {
1696         talloc_enable_null_tracking();
1697         atexit(talloc_report_null);
1698 }
1699
1700 /*
1701   enable full leak reporting on exit
1702 */
1703 _PUBLIC_ void talloc_enable_leak_report_full(void)
1704 {
1705         talloc_enable_null_tracking();
1706         atexit(talloc_report_null_full);
1707 }
1708
1709 /* 
1710    talloc and zero memory. 
1711 */
1712 _PUBLIC_ void *_talloc_zero(const void *ctx, size_t size, const char *name)
1713 {
1714         void *p = _talloc_named_const(ctx, size, name);
1715
1716         if (p) {
1717                 memset(p, '\0', size);
1718         }
1719
1720         return p;
1721 }
1722
1723 /*
1724   memdup with a talloc. 
1725 */
1726 _PUBLIC_ void *_talloc_memdup(const void *t, const void *p, size_t size, const char *name)
1727 {
1728         void *newp = _talloc_named_const(t, size, name);
1729
1730         if (likely(newp)) {
1731                 memcpy(newp, p, size);
1732         }
1733
1734         return newp;
1735 }
1736
1737 static inline char *__talloc_strlendup(const void *t, const char *p, size_t len)
1738 {
1739         char *ret;
1740
1741         ret = (char *)__talloc(t, len + 1);
1742         if (unlikely(!ret)) return NULL;
1743
1744         memcpy(ret, p, len);
1745         ret[len] = 0;
1746
1747         _talloc_set_name_const(ret, ret);
1748         return ret;
1749 }
1750
1751 /*
1752   strdup with a talloc
1753 */
1754 _PUBLIC_ char *talloc_strdup(const void *t, const char *p)
1755 {
1756         if (unlikely(!p)) return NULL;
1757         return __talloc_strlendup(t, p, strlen(p));
1758 }
1759
1760 /*
1761   strndup with a talloc
1762 */
1763 _PUBLIC_ char *talloc_strndup(const void *t, const char *p, size_t n)
1764 {
1765         if (unlikely(!p)) return NULL;
1766         return __talloc_strlendup(t, p, strnlen(p, n));
1767 }
1768
1769 static inline char *__talloc_strlendup_append(char *s, size_t slen,
1770                                               const char *a, size_t alen)
1771 {
1772         char *ret;
1773
1774         ret = talloc_realloc(NULL, s, char, slen + alen + 1);
1775         if (unlikely(!ret)) return NULL;
1776
1777         /* append the string and the trailing \0 */
1778         memcpy(&ret[slen], a, alen);
1779         ret[slen+alen] = 0;
1780
1781         _talloc_set_name_const(ret, ret);
1782         return ret;
1783 }
1784
1785 /*
1786  * Appends at the end of the string.
1787  */
1788 _PUBLIC_ char *talloc_strdup_append(char *s, const char *a)
1789 {
1790         if (unlikely(!s)) {
1791                 return talloc_strdup(NULL, a);
1792         }
1793
1794         if (unlikely(!a)) {
1795                 return s;
1796         }
1797
1798         return __talloc_strlendup_append(s, strlen(s), a, strlen(a));
1799 }
1800
1801 /*
1802  * Appends at the end of the talloc'ed buffer,
1803  * not the end of the string.
1804  */
1805 _PUBLIC_ char *talloc_strdup_append_buffer(char *s, const char *a)
1806 {
1807         size_t slen;
1808
1809         if (unlikely(!s)) {
1810                 return talloc_strdup(NULL, a);
1811         }
1812
1813         if (unlikely(!a)) {
1814                 return s;
1815         }
1816
1817         slen = talloc_get_size(s);
1818         if (likely(slen > 0)) {
1819                 slen--;
1820         }
1821
1822         return __talloc_strlendup_append(s, slen, a, strlen(a));
1823 }
1824
1825 /*
1826  * Appends at the end of the string.
1827  */
1828 _PUBLIC_ char *talloc_strndup_append(char *s, const char *a, size_t n)
1829 {
1830         if (unlikely(!s)) {
1831                 return talloc_strdup(NULL, a);
1832         }
1833
1834         if (unlikely(!a)) {
1835                 return s;
1836         }
1837
1838         return __talloc_strlendup_append(s, strlen(s), a, strnlen(a, n));
1839 }
1840
1841 /*
1842  * Appends at the end of the talloc'ed buffer,
1843  * not the end of the string.
1844  */
1845 _PUBLIC_ char *talloc_strndup_append_buffer(char *s, const char *a, size_t n)
1846 {
1847         size_t slen;
1848
1849         if (unlikely(!s)) {
1850                 return talloc_strdup(NULL, a);
1851         }
1852
1853         if (unlikely(!a)) {
1854                 return s;
1855         }
1856
1857         slen = talloc_get_size(s);
1858         if (likely(slen > 0)) {
1859                 slen--;
1860         }
1861
1862         return __talloc_strlendup_append(s, slen, a, strnlen(a, n));
1863 }
1864
1865 #ifndef HAVE_VA_COPY
1866 #ifdef HAVE___VA_COPY
1867 #define va_copy(dest, src) __va_copy(dest, src)
1868 #else
1869 #define va_copy(dest, src) (dest) = (src)
1870 #endif
1871 #endif
1872
1873 _PUBLIC_ char *talloc_vasprintf(const void *t, const char *fmt, va_list ap)
1874 {
1875         int len;
1876         char *ret;
1877         va_list ap2;
1878         char c;
1879
1880         /* this call looks strange, but it makes it work on older solaris boxes */
1881         va_copy(ap2, ap);
1882         len = vsnprintf(&c, 1, fmt, ap2);
1883         va_end(ap2);
1884         if (unlikely(len < 0)) {
1885                 return NULL;
1886         }
1887
1888         ret = (char *)__talloc(t, len+1);
1889         if (unlikely(!ret)) return NULL;
1890
1891         va_copy(ap2, ap);
1892         vsnprintf(ret, len+1, fmt, ap2);
1893         va_end(ap2);
1894
1895         _talloc_set_name_const(ret, ret);
1896         return ret;
1897 }
1898
1899
1900 /*
1901   Perform string formatting, and return a pointer to newly allocated
1902   memory holding the result, inside a memory pool.
1903  */
1904 _PUBLIC_ char *talloc_asprintf(const void *t, const char *fmt, ...)
1905 {
1906         va_list ap;
1907         char *ret;
1908
1909         va_start(ap, fmt);
1910         ret = talloc_vasprintf(t, fmt, ap);
1911         va_end(ap);
1912         return ret;
1913 }
1914
1915 static inline char *__talloc_vaslenprintf_append(char *s, size_t slen,
1916                                                  const char *fmt, va_list ap)
1917                                                  PRINTF_ATTRIBUTE(3,0);
1918
1919 static inline char *__talloc_vaslenprintf_append(char *s, size_t slen,
1920                                                  const char *fmt, va_list ap)
1921 {
1922         ssize_t alen;
1923         va_list ap2;
1924         char c;
1925
1926         va_copy(ap2, ap);
1927         alen = vsnprintf(&c, 1, fmt, ap2);
1928         va_end(ap2);
1929
1930         if (alen <= 0) {
1931                 /* Either the vsnprintf failed or the format resulted in
1932                  * no characters being formatted. In the former case, we
1933                  * ought to return NULL, in the latter we ought to return
1934                  * the original string. Most current callers of this
1935                  * function expect it to never return NULL.
1936                  */
1937                 return s;
1938         }
1939
1940         s = talloc_realloc(NULL, s, char, slen + alen + 1);
1941         if (!s) return NULL;
1942
1943         va_copy(ap2, ap);
1944         vsnprintf(s + slen, alen + 1, fmt, ap2);
1945         va_end(ap2);
1946
1947         _talloc_set_name_const(s, s);
1948         return s;
1949 }
1950
1951 /**
1952  * Realloc @p s to append the formatted result of @p fmt and @p ap,
1953  * and return @p s, which may have moved.  Good for gradually
1954  * accumulating output into a string buffer. Appends at the end
1955  * of the string.
1956  **/
1957 _PUBLIC_ char *talloc_vasprintf_append(char *s, const char *fmt, va_list ap)
1958 {
1959         if (unlikely(!s)) {
1960                 return talloc_vasprintf(NULL, fmt, ap);
1961         }
1962
1963         return __talloc_vaslenprintf_append(s, strlen(s), fmt, ap);
1964 }
1965
1966 /**
1967  * Realloc @p s to append the formatted result of @p fmt and @p ap,
1968  * and return @p s, which may have moved. Always appends at the
1969  * end of the talloc'ed buffer, not the end of the string.
1970  **/
1971 _PUBLIC_ char *talloc_vasprintf_append_buffer(char *s, const char *fmt, va_list ap)
1972 {
1973         size_t slen;
1974
1975         if (unlikely(!s)) {
1976                 return talloc_vasprintf(NULL, fmt, ap);
1977         }
1978
1979         slen = talloc_get_size(s);
1980         if (likely(slen > 0)) {
1981                 slen--;
1982         }
1983
1984         return __talloc_vaslenprintf_append(s, slen, fmt, ap);
1985 }
1986
1987 /*
1988   Realloc @p s to append the formatted result of @p fmt and return @p
1989   s, which may have moved.  Good for gradually accumulating output
1990   into a string buffer.
1991  */
1992 _PUBLIC_ char *talloc_asprintf_append(char *s, const char *fmt, ...)
1993 {
1994         va_list ap;
1995
1996         va_start(ap, fmt);
1997         s = talloc_vasprintf_append(s, fmt, ap);
1998         va_end(ap);
1999         return s;
2000 }
2001
2002 /*
2003   Realloc @p s to append the formatted result of @p fmt and return @p
2004   s, which may have moved.  Good for gradually accumulating output
2005   into a buffer.
2006  */
2007 _PUBLIC_ char *talloc_asprintf_append_buffer(char *s, const char *fmt, ...)
2008 {
2009         va_list ap;
2010
2011         va_start(ap, fmt);
2012         s = talloc_vasprintf_append_buffer(s, fmt, ap);
2013         va_end(ap);
2014         return s;
2015 }
2016
2017 /*
2018   alloc an array, checking for integer overflow in the array size
2019 */
2020 _PUBLIC_ void *_talloc_array(const void *ctx, size_t el_size, unsigned count, const char *name)
2021 {
2022         if (count >= MAX_TALLOC_SIZE/el_size) {
2023                 return NULL;
2024         }
2025         return _talloc_named_const(ctx, el_size * count, name);
2026 }
2027
2028 /*
2029   alloc an zero array, checking for integer overflow in the array size
2030 */
2031 _PUBLIC_ void *_talloc_zero_array(const void *ctx, size_t el_size, unsigned count, const char *name)
2032 {
2033         if (count >= MAX_TALLOC_SIZE/el_size) {
2034                 return NULL;
2035         }
2036         return _talloc_zero(ctx, el_size * count, name);
2037 }
2038
2039 /*
2040   realloc an array, checking for integer overflow in the array size
2041 */
2042 _PUBLIC_ void *_talloc_realloc_array(const void *ctx, void *ptr, size_t el_size, unsigned count, const char *name)
2043 {
2044         if (count >= MAX_TALLOC_SIZE/el_size) {
2045                 return NULL;
2046         }
2047         return _talloc_realloc(ctx, ptr, el_size * count, name);
2048 }
2049
2050 /*
2051   a function version of talloc_realloc(), so it can be passed as a function pointer
2052   to libraries that want a realloc function (a realloc function encapsulates
2053   all the basic capabilities of an allocation library, which is why this is useful)
2054 */
2055 _PUBLIC_ void *talloc_realloc_fn(const void *context, void *ptr, size_t size)
2056 {
2057         return _talloc_realloc(context, ptr, size, NULL);
2058 }
2059
2060
2061 static int talloc_autofree_destructor(void *ptr)
2062 {
2063         autofree_context = NULL;
2064         return 0;
2065 }
2066
2067 static void talloc_autofree(void)
2068 {
2069         talloc_free(autofree_context);
2070 }
2071
2072 /*
2073   return a context which will be auto-freed on exit
2074   this is useful for reducing the noise in leak reports
2075 */
2076 _PUBLIC_ void *talloc_autofree_context(void)
2077 {
2078         if (autofree_context == NULL) {
2079                 autofree_context = _talloc_named_const(NULL, 0, "autofree_context");
2080                 talloc_set_destructor(autofree_context, talloc_autofree_destructor);
2081                 atexit(talloc_autofree);
2082         }
2083         return autofree_context;
2084 }
2085
2086 _PUBLIC_ size_t talloc_get_size(const void *context)
2087 {
2088         struct talloc_chunk *tc;
2089
2090         if (context == NULL) {
2091                 context = null_context;
2092         }
2093         if (context == NULL) {
2094                 return 0;
2095         }
2096
2097         tc = talloc_chunk_from_ptr(context);
2098
2099         return tc->size;
2100 }
2101
2102 /*
2103   find a parent of this context that has the given name, if any
2104 */
2105 _PUBLIC_ void *talloc_find_parent_byname(const void *context, const char *name)
2106 {
2107         struct talloc_chunk *tc;
2108
2109         if (context == NULL) {
2110                 return NULL;
2111         }
2112
2113         tc = talloc_chunk_from_ptr(context);
2114         while (tc) {
2115                 if (tc->name && strcmp(tc->name, name) == 0) {
2116                         return TC_PTR_FROM_CHUNK(tc);
2117                 }
2118                 while (tc && tc->prev) tc = tc->prev;
2119                 if (tc) {
2120                         tc = tc->parent;
2121                 }
2122         }
2123         return NULL;
2124 }
2125
2126 /*
2127   show the parentage of a context
2128 */
2129 _PUBLIC_ void talloc_show_parents(const void *context, FILE *file)
2130 {
2131         struct talloc_chunk *tc;
2132
2133         if (context == NULL) {
2134                 fprintf(file, "talloc no parents for NULL\n");
2135                 return;
2136         }
2137
2138         tc = talloc_chunk_from_ptr(context);
2139         fprintf(file, "talloc parents of '%s'\n", talloc_get_name(context));
2140         while (tc) {
2141                 fprintf(file, "\t'%s'\n", talloc_get_name(TC_PTR_FROM_CHUNK(tc)));
2142                 while (tc && tc->prev) tc = tc->prev;
2143                 if (tc) {
2144                         tc = tc->parent;
2145                 }
2146         }
2147         fflush(file);
2148 }
2149
2150 /*
2151   return 1 if ptr is a parent of context
2152 */
2153 static int _talloc_is_parent(const void *context, const void *ptr, int depth)
2154 {
2155         struct talloc_chunk *tc;
2156
2157         if (context == NULL) {
2158                 return 0;
2159         }
2160
2161         tc = talloc_chunk_from_ptr(context);
2162         while (tc && depth > 0) {
2163                 if (TC_PTR_FROM_CHUNK(tc) == ptr) return 1;
2164                 while (tc && tc->prev) tc = tc->prev;
2165                 if (tc) {
2166                         tc = tc->parent;
2167                         depth--;
2168                 }
2169         }
2170         return 0;
2171 }
2172
2173 /*
2174   return 1 if ptr is a parent of context
2175 */
2176 _PUBLIC_ int talloc_is_parent(const void *context, const void *ptr)
2177 {
2178         return _talloc_is_parent(context, ptr, TALLOC_MAX_DEPTH);
2179 }