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