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