prevent git ref/unref mismatches. 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: INSTEAD:
513         Rather than delete child references,
514                 If a node descends from no_owner_context and so do all his references then it can be deleted
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                 /* we need to work out who will own an abandoned child
567                    if it cannot be freed. In priority order, the first
568                    choice is owner of any remaining reference to this
569                    pointer, the second choice is our parent, and the
570                    final choice is the null context. */
571                 void *child = TC_PTR_FROM_CHUNK(tc->child);
572                 const void *new_parent = talloc_no_owner_context();
573 /* we are moving this problem of who should own the can't-free to the top of the function */
574 //HERE
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 talloc_free fails because of refs and not due to the destructor,
580                    it will already have a new owner no_owner_context */
581                 if (unlikely(_talloc_free(child) == -1)) {
582 // making dead mans parent the owner could be a memory leak. no_owner_context will destroy with refs going
583 //                      if (new_parent == null_context) {
584 //                              struct talloc_chunk *p = talloc_parent_chunk(ptr);
585 //                              if (p) new_parent = TC_PTR_FROM_CHUNK(p);
586 //                      }
587                         talloc_steal(new_parent, child);
588                 }
589         }
590
591         tc->flags |= TALLOC_FLAG_FREE;
592
593         if (tc->flags & (TALLOC_FLAG_POOL|TALLOC_FLAG_POOLMEM)) {
594                 struct talloc_chunk *pool;
595                 unsigned int *pool_object_count;
596
597                 pool = (tc->flags & TALLOC_FLAG_POOL)
598                         ? tc : (struct talloc_chunk *)tc->pool;
599
600                 pool_object_count = talloc_pool_objectcount(pool);
601
602                 if (*pool_object_count == 0) {
603                         talloc_abort("Pool object count zero!");
604                 }
605
606                 *pool_object_count -= 1;
607
608                 if (*pool_object_count == 0) {
609                         free(pool);
610                 }
611         }
612         else {
613                 free(tc);
614         }
615         return 0;
616 }
617
618 /* 
619    move a lump of memory from one talloc context to another return the
620    ptr on success, or NULL if it could not be transferred.
621    passing NULL as ptr will always return NULL with no side effects.
622 */
623 void *_talloc_steal(const void *new_ctx, const void *ptr)
624 {
625         struct talloc_chunk *tc, *new_tc;
626
627         if (unlikely(!ptr)) {
628                 return NULL;
629         }
630
631         if (unlikely(new_ctx == NULL)) {
632                 new_ctx = null_context;
633         }
634
635         tc = talloc_chunk_from_ptr(ptr);
636
637         if (unlikely(new_ctx == NULL)) {
638                 if (tc->parent) {
639                         _TLIST_REMOVE(tc->parent->child, tc);
640                         if (tc->parent->child) {
641                                 tc->parent->child->parent = tc->parent;
642                         }
643                 } else {
644                         if (tc->prev) tc->prev->next = tc->next;
645                         if (tc->next) tc->next->prev = tc->prev;
646                 }
647                 
648                 tc->parent = tc->next = tc->prev = NULL;
649                 return discard_const_p(void, ptr);
650         }
651         new_tc = talloc_chunk_from_ptr(new_ctx);
652
653         if (unlikely(tc == new_tc || tc->parent == new_tc)) {
654                 return discard_const_p(void, ptr);
655         }
656
657         if (tc->parent) {
658                 _TLIST_REMOVE(tc->parent->child, tc);
659                 if (tc->parent->child) {
660                         tc->parent->child->parent = tc->parent;
661                 }
662         } else {
663                 if (tc->prev) tc->prev->next = tc->next;
664                 if (tc->next) tc->next->prev = tc->prev;
665         }
666
667         tc->parent = new_tc;
668         if (new_tc->child) new_tc->child->parent = NULL;
669         _TLIST_ADD(new_tc->child, tc);
670
671         return discard_const_p(void, ptr);
672 }
673
674
675
676 /*
677   remove a secondary reference to a pointer. This undo's what
678   talloc_reference() has done. The context and pointer arguments
679   must match those given to a talloc_reference()
680 */
681 static inline int talloc_unreference(const void *context, const void *ptr)
682 {
683         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
684         struct talloc_reference_handle *h;
685
686         if (unlikely(context == NULL)) {
687                 context = null_context;
688         }
689
690         for (h=tc->refs;h;h=h->next) {
691                 struct talloc_chunk *p = talloc_parent_chunk(h);
692                 if (p == NULL) {
693                         if (context == NULL) break;
694                 } else if (TC_PTR_FROM_CHUNK(p) == context) {
695                         break;
696                 }
697         }
698         if (h == NULL) {
699                 return -1;
700         }
701
702         return _talloc_free(h);
703 }
704
705 /*
706   remove a specific parent context from a pointer. This is a more
707   controlled varient of talloc_free()
708 */
709 int talloc_unlink(const void *context, void *ptr)
710 {
711         struct talloc_chunk *tc_p, *new_p;
712         void *new_parent;
713
714         if (ptr == NULL) {
715                 return -1;
716         }
717
718         if (context == NULL) {
719                 context = null_context;
720         }
721
722         if (talloc_unreference(context, ptr) == 0) {
723                 return 0;
724         }
725
726         if (context == NULL) {
727                 if (talloc_parent_chunk(ptr) != NULL) {
728                         return -1;
729                 }
730         } else {
731                 if (talloc_chunk_from_ptr(context) != talloc_parent_chunk(ptr)) {
732                         return -1;
733                 }
734         }
735         
736         tc_p = talloc_chunk_from_ptr(ptr);
737
738         if (tc_p->refs == NULL) {
739                 return _talloc_free(ptr);
740         }
741
742 //HERE
743 //      new_p = talloc_parent_chunk(tc_p->refs);
744 //      if (new_p) {
745 //              new_parent = TC_PTR_FROM_CHUNK(new_p);
746 //      } else {
747 //              new_parent = NULL;
748 //      }
749
750 //      if (talloc_unreference(new_parent, ptr) != 0) {
751 //              return -1;
752 //      }
753 //
754 //      talloc_steal(new_parent, ptr);
755         talloc_steal(talloc_no_owner_context(), ptr);
756         return 0;
757 }
758
759 /*
760   add a name to an existing pointer - va_list version
761 */
762 static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(2,0);
763
764 static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va_list ap)
765 {
766         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
767         tc->name = talloc_vasprintf(ptr, fmt, ap);
768         if (likely(tc->name)) {
769                 _talloc_set_name_const(tc->name, ".name");
770         }
771         return tc->name;
772 }
773
774 /*
775   add a name to an existing pointer
776 */
777 const char *talloc_set_name(const void *ptr, const char *fmt, ...)
778 {
779         const char *name;
780         va_list ap;
781         va_start(ap, fmt);
782         name = talloc_set_name_v(ptr, fmt, ap);
783         va_end(ap);
784         return name;
785 }
786
787
788 /*
789   create a named talloc pointer. Any talloc pointer can be named, and
790   talloc_named() operates just like talloc() except that it allows you
791   to name the pointer.
792 */
793 void *talloc_named(const void *context, size_t size, const char *fmt, ...)
794 {
795         va_list ap;
796         void *ptr;
797         const char *name;
798
799         ptr = __talloc(context, size);
800         if (unlikely(ptr == NULL)) return NULL;
801
802         va_start(ap, fmt);
803         name = talloc_set_name_v(ptr, fmt, ap);
804         va_end(ap);
805
806         if (unlikely(name == NULL)) {
807                 _talloc_free(ptr);
808                 return NULL;
809         }
810
811         return ptr;
812 }
813
814 /*
815   return the name of a talloc ptr, or "UNNAMED"
816 */
817 const char *talloc_get_name(const void *ptr)
818 {
819         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
820         if (unlikely(tc->name == TALLOC_MAGIC_REFERENCE)) {
821                 return ".reference";
822         }
823         if (likely(tc->name)) {
824                 return tc->name;
825         }
826         return "UNNAMED";
827 }
828
829
830 /*
831   check if a pointer has the given name. If it does, return the pointer,
832   otherwise return NULL
833 */
834 void *talloc_check_name(const void *ptr, const char *name)
835 {
836         const char *pname;
837         if (unlikely(ptr == NULL)) return NULL;
838         pname = talloc_get_name(ptr);
839         if (likely(pname == name || strcmp(pname, name) == 0)) {
840                 return discard_const_p(void, ptr);
841         }
842         return NULL;
843 }
844
845 static void talloc_abort_type_missmatch(const char *location,
846                                         const char *name,
847                                         const char *expected)
848 {
849         const char *reason;
850
851         reason = talloc_asprintf(NULL,
852                                  "%s: Type mismatch: name[%s] expected[%s]",
853                                  location,
854                                  name?name:"NULL",
855                                  expected);
856         if (!reason) {
857                 reason = "Type mismatch";
858         }
859
860         talloc_abort(reason);
861 }
862
863 void *_talloc_get_type_abort(const void *ptr, const char *name, const char *location)
864 {
865         const char *pname;
866
867         if (unlikely(ptr == NULL)) {
868                 talloc_abort_type_missmatch(location, NULL, name);
869                 return NULL;
870         }
871
872         pname = talloc_get_name(ptr);
873         if (likely(pname == name || strcmp(pname, name) == 0)) {
874                 return discard_const_p(void, ptr);
875         }
876
877         talloc_abort_type_missmatch(location, pname, name);
878         return NULL;
879 }
880
881 /*
882   this is for compatibility with older versions of talloc
883 */
884 void *talloc_init(const char *fmt, ...)
885 {
886         va_list ap;
887         void *ptr;
888         const char *name;
889
890         /*
891          * samba3 expects talloc_report_depth_cb(NULL, ...)
892          * reports all talloc'ed memory, so we need to enable
893          * null_tracking
894          */
895         talloc_enable_null_tracking();
896
897         ptr = __talloc(NULL, 0);
898         if (unlikely(ptr == NULL)) return NULL;
899
900         va_start(ap, fmt);
901         name = talloc_set_name_v(ptr, fmt, ap);
902         va_end(ap);
903
904         if (unlikely(name == NULL)) {
905                 _talloc_free(ptr);
906                 return NULL;
907         }
908
909         return ptr;
910 }
911
912 /*
913   this is a replacement for the Samba3 talloc_destroy_pool functionality. It
914   should probably not be used in new code. It's in here to keep the talloc
915   code consistent across Samba 3 and 4.
916 */
917 void talloc_free_children(void *ptr)
918 {
919         struct talloc_chunk *tc;
920
921         if (unlikely(ptr == NULL)) {
922                 return;
923         }
924
925         tc = talloc_chunk_from_ptr(ptr);
926
927         while (tc->child) {
928                 /* we need to work out who will own an abandoned child
929                    if it cannot be freed. In priority order, the first
930                    choice is owner of any remaining reference to this
931                    pointer, the second choice is our parent, and the
932                    final choice is the null context. */
933                 void *child = TC_PTR_FROM_CHUNK(tc->child);
934                 const void *new_parent = talloc_no_owner_context();
935 //HERE
936                 if (unlikely(tc->child->refs)) {
937 //                      struct talloc_chunk *p = talloc_parent_chunk(tc->child->refs);
938 //                      if (p) new_parent = TC_PTR_FROM_CHUNK(p);
939                         new_parent = talloc_no_owner_context();
940                 }
941                 if (unlikely(_talloc_free(child) == -1)) {
942                         if (new_parent == null_context) {
943                                 struct talloc_chunk *p = talloc_parent_chunk(ptr);
944                                 if (p) new_parent = TC_PTR_FROM_CHUNK(p);
945                         }
946                         talloc_steal(new_parent, child);
947                 }
948         }
949
950         if ((tc->flags & TALLOC_FLAG_POOL)
951             && (*talloc_pool_objectcount(tc) == 1)) {
952                 tc->pool = ((char *)tc + TC_HDR_SIZE + TALLOC_POOL_HDR_SIZE);
953 #if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_NOACCESS)
954                 VALGRIND_MAKE_MEM_NOACCESS(
955                         tc->pool, tc->size - TALLOC_POOL_HDR_SIZE);
956 #endif
957         }
958 }
959
960 /* 
961    Allocate a bit of memory as a child of an existing pointer
962 */
963 void *_talloc(const void *context, size_t size)
964 {
965         return __talloc(context, size);
966 }
967
968 /*
969   externally callable talloc_set_name_const()
970 */
971 void talloc_set_name_const(const void *ptr, const char *name)
972 {
973         _talloc_set_name_const(ptr, name);
974 }
975
976 /*
977   create a named talloc pointer. Any talloc pointer can be named, and
978   talloc_named() operates just like talloc() except that it allows you
979   to name the pointer.
980 */
981 void *talloc_named_const(const void *context, size_t size, const char *name)
982 {
983         return _talloc_named_const(context, size, name);
984 }
985
986 /* 
987    free a talloc pointer. This also frees all child pointers of this 
988    pointer recursively
989
990    return 0 if the memory is actually freed, otherwise -1. The memory
991    will not be freed if the ref_count is > 1 or the destructor (if
992    any) returns non-zero
993 */
994 int talloc_free(void *ptr)
995 {
996         return _talloc_free(ptr);
997 }
998
999
1000
1001 /*
1002   A talloc version of realloc. The context argument is only used if
1003   ptr is NULL
1004 */
1005 void *_talloc_realloc(const void *context, void *ptr, size_t size, const char *name)
1006 {
1007         struct talloc_chunk *tc;
1008         void *new_ptr;
1009         bool malloced = false;
1010
1011         /* size zero is equivalent to free() */
1012         if (unlikely(size == 0)) {
1013                 _talloc_free(ptr);
1014                 return NULL;
1015         }
1016
1017         if (unlikely(size >= MAX_TALLOC_SIZE)) {
1018                 return NULL;
1019         }
1020
1021         /* realloc(NULL) is equivalent to malloc() */
1022         if (ptr == NULL) {
1023                 return _talloc_named_const(context, size, name);
1024         }
1025
1026         tc = talloc_chunk_from_ptr(ptr);
1027
1028         /* don't allow realloc on referenced pointers */
1029         if (unlikely(tc->refs)) {
1030                 return NULL;
1031         }
1032
1033         /* don't let anybody try to realloc a talloc_pool */
1034         if (unlikely(tc->flags & TALLOC_FLAG_POOL)) {
1035                 return NULL;
1036         }
1037
1038         /* don't shrink if we have less than 1k to gain */
1039         if ((size < tc->size) && ((tc->size - size) < 1024)) {
1040                 tc->size = size;
1041                 return ptr;
1042         }
1043
1044         /* by resetting magic we catch users of the old memory */
1045         tc->flags |= TALLOC_FLAG_FREE;
1046
1047 #if ALWAYS_REALLOC
1048         new_ptr = malloc(size + TC_HDR_SIZE);
1049         if (new_ptr) {
1050                 memcpy(new_ptr, tc, tc->size + TC_HDR_SIZE);
1051                 free(tc);
1052         }
1053 #else
1054         if (tc->flags & TALLOC_FLAG_POOLMEM) {
1055
1056                 new_ptr = talloc_alloc_pool(tc, size + TC_HDR_SIZE);
1057                 *talloc_pool_objectcount((struct talloc_chunk *)
1058                                          (tc->pool)) -= 1;
1059
1060                 if (new_ptr == NULL) {
1061                         new_ptr = malloc(TC_HDR_SIZE+size);
1062                         malloced = true;
1063                 }
1064
1065                 if (new_ptr) {
1066                         memcpy(new_ptr, tc, MIN(tc->size,size) + TC_HDR_SIZE);
1067                 }
1068         }
1069         else {
1070                 new_ptr = realloc(tc, size + TC_HDR_SIZE);
1071         }
1072 #endif
1073         if (unlikely(!new_ptr)) {       
1074                 tc->flags &= ~TALLOC_FLAG_FREE; 
1075                 return NULL; 
1076         }
1077
1078         tc = (struct talloc_chunk *)new_ptr;
1079         tc->flags &= ~TALLOC_FLAG_FREE;
1080         if (malloced) {
1081                 tc->flags &= ~TALLOC_FLAG_POOLMEM;
1082         }
1083         if (tc->parent) {
1084                 tc->parent->child = tc;
1085         }
1086         if (tc->child) {
1087                 tc->child->parent = tc;
1088         }
1089
1090         if (tc->prev) {
1091                 tc->prev->next = tc;
1092         }
1093         if (tc->next) {
1094                 tc->next->prev = tc;
1095         }
1096
1097         tc->size = size;
1098         _talloc_set_name_const(TC_PTR_FROM_CHUNK(tc), name);
1099
1100         return TC_PTR_FROM_CHUNK(tc);
1101 }
1102
1103 /*
1104   a wrapper around talloc_steal() for situations where you are moving a pointer
1105   between two structures, and want the old pointer to be set to NULL
1106 */
1107 void *_talloc_move(const void *new_ctx, const void *_pptr)
1108 {
1109         const void **pptr = discard_const_p(const void *,_pptr);
1110         void *ret = _talloc_steal(new_ctx, *pptr);
1111         (*pptr) = NULL;
1112         return ret;
1113 }
1114
1115 /*
1116   return the total size of a talloc pool (subtree)
1117 */
1118 size_t talloc_total_size(const void *ptr)
1119 {
1120         size_t total = 0;
1121         struct talloc_chunk *c, *tc;
1122
1123         if (ptr == NULL) {
1124                 ptr = null_context;
1125         }
1126         if (ptr == NULL) {
1127                 return 0;
1128         }
1129
1130         tc = talloc_chunk_from_ptr(ptr);
1131
1132         if (tc->flags & TALLOC_FLAG_LOOP) {
1133                 return 0;
1134         }
1135
1136         tc->flags |= TALLOC_FLAG_LOOP;
1137
1138         total = tc->size;
1139         for (c=tc->child;c;c=c->next) {
1140                 total += talloc_total_size(TC_PTR_FROM_CHUNK(c));
1141         }
1142
1143         tc->flags &= ~TALLOC_FLAG_LOOP;
1144
1145         return total;
1146 }
1147
1148 /*
1149   return the total number of blocks in a talloc pool (subtree)
1150 */
1151 size_t talloc_total_blocks(const void *ptr)
1152 {
1153         size_t total = 0;
1154         struct talloc_chunk *c, *tc = talloc_chunk_from_ptr(ptr);
1155
1156         if (tc->flags & TALLOC_FLAG_LOOP) {
1157                 return 0;
1158         }
1159
1160         tc->flags |= TALLOC_FLAG_LOOP;
1161
1162         total++;
1163         for (c=tc->child;c;c=c->next) {
1164                 total += talloc_total_blocks(TC_PTR_FROM_CHUNK(c));
1165         }
1166
1167         tc->flags &= ~TALLOC_FLAG_LOOP;
1168
1169         return total;
1170 }
1171
1172 /*
1173   return the number of external references to a pointer
1174 */
1175 size_t talloc_reference_count(const void *ptr)
1176 {
1177         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
1178         struct talloc_reference_handle *h;
1179         size_t ret = 0;
1180
1181         for (h=tc->refs;h;h=h->next) {
1182                 ret++;
1183         }
1184         return ret;
1185 }
1186
1187 /*
1188   report on memory usage by all children of a pointer, giving a full tree view
1189 */
1190 void talloc_report_depth_cb(const void *ptr, int depth, int max_depth,
1191                             void (*callback)(const void *ptr,
1192                                              int depth, int max_depth,
1193                                              int is_ref,
1194                                              void *private_data),
1195                             void *private_data)
1196 {
1197         struct talloc_chunk *c, *tc;
1198
1199         if (ptr == NULL) {
1200                 ptr = null_context;
1201         }
1202         if (ptr == NULL) return;
1203
1204         tc = talloc_chunk_from_ptr(ptr);
1205
1206         if (tc->flags & TALLOC_FLAG_LOOP) {
1207                 return;
1208         }
1209
1210         callback(ptr, depth, max_depth, 0, private_data);
1211
1212         if (max_depth >= 0 && depth >= max_depth) {
1213                 return;
1214         }
1215
1216         tc->flags |= TALLOC_FLAG_LOOP;
1217         for (c=tc->child;c;c=c->next) {
1218                 if (c->name == TALLOC_MAGIC_REFERENCE) {
1219                         struct talloc_reference_handle *h = (struct talloc_reference_handle *)TC_PTR_FROM_CHUNK(c);
1220                         callback(h->ptr, depth + 1, max_depth, 1, private_data);
1221                 } else {
1222                         talloc_report_depth_cb(TC_PTR_FROM_CHUNK(c), depth + 1, max_depth, callback, private_data);
1223                 }
1224         }
1225         tc->flags &= ~TALLOC_FLAG_LOOP;
1226 }
1227
1228 static void talloc_report_depth_FILE_helper(const void *ptr, int depth, int max_depth, int is_ref, void *_f)
1229 {
1230         const char *name = talloc_get_name(ptr);
1231         FILE *f = (FILE *)_f;
1232
1233         if (is_ref) {
1234                 if (talloc_parent(ptr) == no_owner_context && no_owner_context) {
1235                         fprintf(f, "%*sreference to: %s [no owner]\n", depth*4, "", name);
1236                 } else {
1237                         fprintf(f, "%*sreference to: %s\n", depth*4, "", name);
1238                 }
1239                 return;
1240         }
1241
1242         if (depth == 0) {
1243                 fprintf(f,"%stalloc report on '%s' (total %6lu bytes in %3lu blocks)\n", 
1244                         (max_depth < 0 ? "full " :""), name,
1245                         (unsigned long)talloc_total_size(ptr),
1246                         (unsigned long)talloc_total_blocks(ptr));
1247                 return;
1248         }
1249
1250         fprintf(f, "%*s%-30s contains %6lu bytes in %3lu blocks (ref %d) %p\n", 
1251                 depth*4, "",
1252                 name,
1253                 (unsigned long)talloc_total_size(ptr),
1254                 (unsigned long)talloc_total_blocks(ptr),
1255                 (int)talloc_reference_count(ptr), ptr);
1256
1257 #if 0
1258         fprintf(f, "content: ");
1259         if (talloc_total_size(ptr)) {
1260                 int tot = talloc_total_size(ptr);
1261                 int i;
1262
1263                 for (i = 0; i < tot; i++) {
1264                         if ((((char *)ptr)[i] > 31) && (((char *)ptr)[i] < 126)) {
1265                                 fprintf(f, "%c", ((char *)ptr)[i]);
1266                         } else {
1267                                 fprintf(f, "~%02x", ((char *)ptr)[i]);
1268                         }
1269                 }
1270         }
1271         fprintf(f, "\n");
1272 #endif
1273 }
1274
1275 /*
1276   report on memory usage by all children of a pointer, giving a full tree view
1277 */
1278 void talloc_report_depth_file(const void *ptr, int depth, int max_depth, FILE *f)
1279 {
1280         talloc_report_depth_cb(ptr, depth, max_depth, talloc_report_depth_FILE_helper, f);
1281         fflush(f);
1282 }
1283
1284 /*
1285   report on memory usage by all children of a pointer, giving a full tree view
1286 */
1287 void talloc_report_full(const void *ptr, FILE *f)
1288 {
1289         talloc_report_depth_file(ptr, 0, -1, f);
1290 }
1291
1292 /*
1293   report on memory usage by all children of a pointer
1294 */
1295 void talloc_report(const void *ptr, FILE *f)
1296 {
1297         talloc_report_depth_file(ptr, 0, 1, f);
1298 }
1299
1300 /*
1301   report on any memory hanging off the null context
1302 */
1303 static void talloc_report_null(void)
1304 {
1305         if (talloc_total_size(null_context) != 0) {
1306                 talloc_report(null_context, stderr);
1307         }
1308 }
1309
1310 /*
1311   report on any memory hanging off the null context
1312 */
1313 static void talloc_report_null_full(void)
1314 {
1315         if (talloc_total_size(null_context) != 0) {
1316                 talloc_report_full(null_context, stderr);
1317         }
1318 }
1319
1320 /*
1321   enable tracking of the NULL context
1322 */
1323 void talloc_enable_null_tracking(void)
1324 {
1325         if (null_context == NULL) {
1326                 null_context = _talloc_named_const(NULL, 0, "null_context");
1327         }
1328 }
1329
1330 /*
1331   disable tracking of the NULL context
1332 */
1333 void talloc_disable_null_tracking(void)
1334 {
1335         _talloc_free(null_context);
1336         null_context = NULL;
1337 }
1338
1339 /*
1340   enable leak reporting on exit
1341 */
1342 void talloc_enable_leak_report(void)
1343 {
1344         talloc_enable_null_tracking();
1345         atexit(talloc_report_null);
1346 }
1347
1348 /*
1349   enable full leak reporting on exit
1350 */
1351 void talloc_enable_leak_report_full(void)
1352 {
1353         talloc_enable_null_tracking();
1354         atexit(talloc_report_null_full);
1355 }
1356
1357 /* 
1358    talloc and zero memory. 
1359 */
1360 void *_talloc_zero(const void *ctx, size_t size, const char *name)
1361 {
1362         void *p = _talloc_named_const(ctx, size, name);
1363
1364         if (p) {
1365                 memset(p, '\0', size);
1366         }
1367
1368         return p;
1369 }
1370
1371 /*
1372   memdup with a talloc. 
1373 */
1374 void *_talloc_memdup(const void *t, const void *p, size_t size, const char *name)
1375 {
1376         void *newp = _talloc_named_const(t, size, name);
1377
1378         if (likely(newp)) {
1379                 memcpy(newp, p, size);
1380         }
1381
1382         return newp;
1383 }
1384
1385 static inline char *__talloc_strlendup(const void *t, const char *p, size_t len)
1386 {
1387         char *ret;
1388
1389         ret = (char *)__talloc(t, len + 1);
1390         if (unlikely(!ret)) return NULL;
1391
1392         memcpy(ret, p, len);
1393         ret[len] = 0;
1394
1395         _talloc_set_name_const(ret, ret);
1396         return ret;
1397 }
1398
1399 /*
1400   strdup with a talloc
1401 */
1402 char *talloc_strdup(const void *t, const char *p)
1403 {
1404         if (unlikely(!p)) return NULL;
1405         return __talloc_strlendup(t, p, strlen(p));
1406 }
1407
1408 /*
1409   strndup with a talloc
1410 */
1411 char *talloc_strndup(const void *t, const char *p, size_t n)
1412 {
1413         if (unlikely(!p)) return NULL;
1414         return __talloc_strlendup(t, p, strnlen(p, n));
1415 }
1416
1417 static inline char *__talloc_strlendup_append(char *s, size_t slen,
1418                                               const char *a, size_t alen)
1419 {
1420         char *ret;
1421
1422         ret = talloc_realloc(NULL, s, char, slen + alen + 1);
1423         if (unlikely(!ret)) return NULL;
1424
1425         /* append the string and the trailing \0 */
1426         memcpy(&ret[slen], a, alen);
1427         ret[slen+alen] = 0;
1428
1429         _talloc_set_name_const(ret, ret);
1430         return ret;
1431 }
1432
1433 /*
1434  * Appends at the end of the string.
1435  */
1436 char *talloc_strdup_append(char *s, const char *a)
1437 {
1438         if (unlikely(!s)) {
1439                 return talloc_strdup(NULL, a);
1440         }
1441
1442         if (unlikely(!a)) {
1443                 return s;
1444         }
1445
1446         return __talloc_strlendup_append(s, strlen(s), a, strlen(a));
1447 }
1448
1449 /*
1450  * Appends at the end of the talloc'ed buffer,
1451  * not the end of the string.
1452  */
1453 char *talloc_strdup_append_buffer(char *s, const char *a)
1454 {
1455         size_t slen;
1456
1457         if (unlikely(!s)) {
1458                 return talloc_strdup(NULL, a);
1459         }
1460
1461         if (unlikely(!a)) {
1462                 return s;
1463         }
1464
1465         slen = talloc_get_size(s);
1466         if (likely(slen > 0)) {
1467                 slen--;
1468         }
1469
1470         return __talloc_strlendup_append(s, slen, a, strlen(a));
1471 }
1472
1473 /*
1474  * Appends at the end of the string.
1475  */
1476 char *talloc_strndup_append(char *s, const char *a, size_t n)
1477 {
1478         if (unlikely(!s)) {
1479                 return talloc_strdup(NULL, a);
1480         }
1481
1482         if (unlikely(!a)) {
1483                 return s;
1484         }
1485
1486         return __talloc_strlendup_append(s, strlen(s), a, strnlen(a, n));
1487 }
1488
1489 /*
1490  * Appends at the end of the talloc'ed buffer,
1491  * not the end of the string.
1492  */
1493 char *talloc_strndup_append_buffer(char *s, const char *a, size_t n)
1494 {
1495         size_t slen;
1496
1497         if (unlikely(!s)) {
1498                 return talloc_strdup(NULL, a);
1499         }
1500
1501         if (unlikely(!a)) {
1502                 return s;
1503         }
1504
1505         slen = talloc_get_size(s);
1506         if (likely(slen > 0)) {
1507                 slen--;
1508         }
1509
1510         return __talloc_strlendup_append(s, slen, a, strnlen(a, n));
1511 }
1512
1513 #ifndef HAVE_VA_COPY
1514 #ifdef HAVE___VA_COPY
1515 #define va_copy(dest, src) __va_copy(dest, src)
1516 #else
1517 #define va_copy(dest, src) (dest) = (src)
1518 #endif
1519 #endif
1520
1521 char *talloc_vasprintf(const void *t, const char *fmt, va_list ap)
1522 {
1523         int len;
1524         char *ret;
1525         va_list ap2;
1526         char c;
1527
1528         /* this call looks strange, but it makes it work on older solaris boxes */
1529         va_copy(ap2, ap);
1530         len = vsnprintf(&c, 1, fmt, ap2);
1531         va_end(ap2);
1532         if (unlikely(len < 0)) {
1533                 return NULL;
1534         }
1535
1536         ret = (char *)__talloc(t, len+1);
1537         if (unlikely(!ret)) return NULL;
1538
1539         va_copy(ap2, ap);
1540         vsnprintf(ret, len+1, fmt, ap2);
1541         va_end(ap2);
1542
1543         _talloc_set_name_const(ret, ret);
1544         return ret;
1545 }
1546
1547
1548 /*
1549   Perform string formatting, and return a pointer to newly allocated
1550   memory holding the result, inside a memory pool.
1551  */
1552 char *talloc_asprintf(const void *t, const char *fmt, ...)
1553 {
1554         va_list ap;
1555         char *ret;
1556
1557         va_start(ap, fmt);
1558         ret = talloc_vasprintf(t, fmt, ap);
1559         va_end(ap);
1560         return ret;
1561 }
1562
1563 static inline char *__talloc_vaslenprintf_append(char *s, size_t slen,
1564                                                  const char *fmt, va_list ap)
1565                                                  PRINTF_ATTRIBUTE(3,0);
1566
1567 static inline char *__talloc_vaslenprintf_append(char *s, size_t slen,
1568                                                  const char *fmt, va_list ap)
1569 {
1570         ssize_t alen;
1571         va_list ap2;
1572         char c;
1573
1574         va_copy(ap2, ap);
1575         alen = vsnprintf(&c, 1, fmt, ap2);
1576         va_end(ap2);
1577
1578         if (alen <= 0) {
1579                 /* Either the vsnprintf failed or the format resulted in
1580                  * no characters being formatted. In the former case, we
1581                  * ought to return NULL, in the latter we ought to return
1582                  * the original string. Most current callers of this
1583                  * function expect it to never return NULL.
1584                  */
1585                 return s;
1586         }
1587
1588         s = talloc_realloc(NULL, s, char, slen + alen + 1);
1589         if (!s) return NULL;
1590
1591         va_copy(ap2, ap);
1592         vsnprintf(s + slen, alen + 1, fmt, ap2);
1593         va_end(ap2);
1594
1595         _talloc_set_name_const(s, s);
1596         return s;
1597 }
1598
1599 /**
1600  * Realloc @p s to append the formatted result of @p fmt and @p ap,
1601  * and return @p s, which may have moved.  Good for gradually
1602  * accumulating output into a string buffer. Appends at the end
1603  * of the string.
1604  **/
1605 char *talloc_vasprintf_append(char *s, const char *fmt, va_list ap)
1606 {
1607         if (unlikely(!s)) {
1608                 return talloc_vasprintf(NULL, fmt, ap);
1609         }
1610
1611         return __talloc_vaslenprintf_append(s, strlen(s), fmt, ap);
1612 }
1613
1614 /**
1615  * Realloc @p s to append the formatted result of @p fmt and @p ap,
1616  * and return @p s, which may have moved. Always appends at the
1617  * end of the talloc'ed buffer, not the end of the string.
1618  **/
1619 char *talloc_vasprintf_append_buffer(char *s, const char *fmt, va_list ap)
1620 {
1621         size_t slen;
1622
1623         if (unlikely(!s)) {
1624                 return talloc_vasprintf(NULL, fmt, ap);
1625         }
1626
1627         slen = talloc_get_size(s);
1628         if (likely(slen > 0)) {
1629                 slen--;
1630         }
1631
1632         return __talloc_vaslenprintf_append(s, slen, fmt, ap);
1633 }
1634
1635 /*
1636   Realloc @p s to append the formatted result of @p fmt and return @p
1637   s, which may have moved.  Good for gradually accumulating output
1638   into a string buffer.
1639  */
1640 char *talloc_asprintf_append(char *s, const char *fmt, ...)
1641 {
1642         va_list ap;
1643
1644         va_start(ap, fmt);
1645         s = talloc_vasprintf_append(s, fmt, ap);
1646         va_end(ap);
1647         return s;
1648 }
1649
1650 /*
1651   Realloc @p s to append the formatted result of @p fmt and return @p
1652   s, which may have moved.  Good for gradually accumulating output
1653   into a buffer.
1654  */
1655 char *talloc_asprintf_append_buffer(char *s, const char *fmt, ...)
1656 {
1657         va_list ap;
1658
1659         va_start(ap, fmt);
1660         s = talloc_vasprintf_append_buffer(s, fmt, ap);
1661         va_end(ap);
1662         return s;
1663 }
1664
1665 /*
1666   alloc an array, checking for integer overflow in the array size
1667 */
1668 void *_talloc_array(const void *ctx, size_t el_size, unsigned count, const char *name)
1669 {
1670         if (count >= MAX_TALLOC_SIZE/el_size) {
1671                 return NULL;
1672         }
1673         return _talloc_named_const(ctx, el_size * count, name);
1674 }
1675
1676 /*
1677   alloc an zero array, checking for integer overflow in the array size
1678 */
1679 void *_talloc_zero_array(const void *ctx, size_t el_size, unsigned count, const char *name)
1680 {
1681         if (count >= MAX_TALLOC_SIZE/el_size) {
1682                 return NULL;
1683         }
1684         return _talloc_zero(ctx, el_size * count, name);
1685 }
1686
1687 /*
1688   realloc an array, checking for integer overflow in the array size
1689 */
1690 void *_talloc_realloc_array(const void *ctx, void *ptr, size_t el_size, unsigned count, const char *name)
1691 {
1692         if (count >= MAX_TALLOC_SIZE/el_size) {
1693                 return NULL;
1694         }
1695         return _talloc_realloc(ctx, ptr, el_size * count, name);
1696 }
1697
1698 /*
1699   a function version of talloc_realloc(), so it can be passed as a function pointer
1700   to libraries that want a realloc function (a realloc function encapsulates
1701   all the basic capabilities of an allocation library, which is why this is useful)
1702 */
1703 void *talloc_realloc_fn(const void *context, void *ptr, size_t size)
1704 {
1705         return _talloc_realloc(context, ptr, size, NULL);
1706 }
1707
1708
1709 static int talloc_autofree_destructor(void *ptr)
1710 {
1711         autofree_context = NULL;
1712         return 0;
1713 }
1714
1715 static void talloc_autofree(void)
1716 {
1717         _talloc_free(autofree_context);
1718 }
1719
1720 /*
1721   return a context which will be auto-freed on exit
1722   this is useful for reducing the noise in leak reports
1723 */
1724 void *talloc_autofree_context(void)
1725 {
1726         if (autofree_context == NULL) {
1727                 autofree_context = _talloc_named_const(NULL, 0, "autofree_context");
1728                 talloc_set_destructor(autofree_context, talloc_autofree_destructor);
1729                 atexit(talloc_autofree);
1730         }
1731         return autofree_context;
1732 }
1733
1734 /* this is only used by the test suite so that failures from on test don't
1735    confuse the results of the next test */
1736 void talloc_erase_no_owner_context(void)
1737 {
1738         /* force free all children */
1739         if (no_owner_context) {
1740                 struct talloc_chunk *tc;
1741                 tc = talloc_chunk_from_ptr(no_owner_context);
1742                 tc->child=NULL;
1743                 tc->refs=NULL;
1744                 _talloc_free(no_owner_context);
1745                 no_owner_context=NULL;
1746         }
1747 }
1748
1749 void *talloc_no_owner_context(void)
1750 {
1751         if (no_owner_context == NULL) {
1752                 no_owner_context = _talloc_named_const(NULL, 0, "no_owner_context");
1753         }
1754         return no_owner_context;
1755 }
1756
1757 size_t talloc_get_size(const void *context)
1758 {
1759         struct talloc_chunk *tc;
1760
1761         if (context == NULL)
1762                 return 0;
1763
1764         tc = talloc_chunk_from_ptr(context);
1765
1766         return tc->size;
1767 }
1768
1769 /*
1770   find a parent of this context that has the given name, if any
1771 */
1772 void *talloc_find_parent_byname(const void *context, const char *name)
1773 {
1774         struct talloc_chunk *tc;
1775
1776         if (context == NULL) {
1777                 return NULL;
1778         }
1779
1780         tc = talloc_chunk_from_ptr(context);
1781         while (tc) {
1782                 if (tc->name && strcmp(tc->name, name) == 0) {
1783                         return TC_PTR_FROM_CHUNK(tc);
1784                 }
1785                 while (tc && tc->prev) tc = tc->prev;
1786                 if (tc) {
1787                         tc = tc->parent;
1788                 }
1789         }
1790         return NULL;
1791 }
1792
1793 /*
1794   show the parentage of a context
1795 */
1796 void talloc_show_parents(const void *context, FILE *file)
1797 {
1798         struct talloc_chunk *tc;
1799
1800         if (context == NULL) {
1801                 fprintf(file, "talloc no parents for NULL\n");
1802                 return;
1803         }
1804
1805         tc = talloc_chunk_from_ptr(context);
1806         fprintf(file, "talloc parents of '%s'\n", talloc_get_name(context));
1807         while (tc) {
1808                 fprintf(file, "\t'%s'\n", talloc_get_name(TC_PTR_FROM_CHUNK(tc)));
1809                 while (tc && tc->prev) tc = tc->prev;
1810                 if (tc) {
1811                         tc = tc->parent;
1812                 }
1813         }
1814         fflush(file);
1815 }
1816
1817 /*
1818   return 1 if ptr is a parent of context
1819 */
1820 int talloc_is_parent(const void *context, const void *ptr)
1821 {
1822         struct talloc_chunk *tc;
1823
1824         if (context == NULL) {
1825                 return 0;
1826         }
1827
1828         tc = talloc_chunk_from_ptr(context);
1829         while (tc) {
1830                 if (TC_PTR_FROM_CHUNK(tc) == ptr) return 1;
1831                 while (tc && tc->prev) tc = tc->prev;
1832                 if (tc) {
1833                         tc = tc->parent;
1834                 }
1835         }
1836         return 0;
1837 }