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