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