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