r23798: updated old Temple Place FSF addresses to new URL
[gd/samba/.git] / source4 / 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_MAGIC_REFERENCE ((const char *)1)
64
65 /* by default we abort when given a bad pointer (such as when talloc_free() is called 
66    on a pointer that came from malloc() */
67 #ifndef TALLOC_ABORT
68 #define TALLOC_ABORT(reason) abort()
69 #endif
70
71 #ifndef discard_const_p
72 #if defined(__intptr_t_defined) || defined(HAVE_INTPTR_T)
73 # define discard_const_p(type, ptr) ((type *)((intptr_t)(ptr)))
74 #else
75 # define discard_const_p(type, ptr) ((type *)(ptr))
76 #endif
77 #endif
78
79 /* these macros gain us a few percent of speed on gcc */
80 #if (__GNUC__ >= 3)
81 /* the strange !! is to ensure that __builtin_expect() takes either 0 or 1
82    as its first argument */
83 #define likely(x)   __builtin_expect(!!(x), 1)
84 #define unlikely(x) __builtin_expect(!!(x), 0)
85 #else
86 #define likely(x) x
87 #define unlikely(x) x
88 #endif
89
90 /* this null_context is only used if talloc_enable_leak_report() or
91    talloc_enable_leak_report_full() is called, otherwise it remains
92    NULL
93 */
94 static void *null_context;
95 static void *autofree_context;
96
97 struct talloc_reference_handle {
98         struct talloc_reference_handle *next, *prev;
99         void *ptr;
100 };
101
102 typedef int (*talloc_destructor_t)(void *);
103
104 struct talloc_chunk {
105         struct talloc_chunk *next, *prev;
106         struct talloc_chunk *parent, *child;
107         struct talloc_reference_handle *refs;
108         talloc_destructor_t destructor;
109         const char *name;
110         size_t size;
111         unsigned flags;
112 };
113
114 /* 16 byte alignment seems to keep everyone happy */
115 #define TC_HDR_SIZE ((sizeof(struct talloc_chunk)+15)&~15)
116 #define TC_PTR_FROM_CHUNK(tc) ((void *)(TC_HDR_SIZE + (char*)tc))
117
118 /* panic if we get a bad magic value */
119 static inline struct talloc_chunk *talloc_chunk_from_ptr(const void *ptr)
120 {
121         const char *pp = (const char *)ptr;
122         struct talloc_chunk *tc = discard_const_p(struct talloc_chunk, pp - TC_HDR_SIZE);
123         if (unlikely((tc->flags & (TALLOC_FLAG_FREE | ~0xF)) != TALLOC_MAGIC)) { 
124                 if (tc->flags & TALLOC_FLAG_FREE) {
125                         TALLOC_ABORT("Bad talloc magic value - double free"); 
126                 } else {
127                         TALLOC_ABORT("Bad talloc magic value - unknown value"); 
128                 }
129         }
130         return tc;
131 }
132
133 /* hook into the front of the list */
134 #define _TLIST_ADD(list, p) \
135 do { \
136         if (!(list)) { \
137                 (list) = (p); \
138                 (p)->next = (p)->prev = NULL; \
139         } else { \
140                 (list)->prev = (p); \
141                 (p)->next = (list); \
142                 (p)->prev = NULL; \
143                 (list) = (p); \
144         }\
145 } while (0)
146
147 /* remove an element from a list - element doesn't have to be in list. */
148 #define _TLIST_REMOVE(list, p) \
149 do { \
150         if ((p) == (list)) { \
151                 (list) = (p)->next; \
152                 if (list) (list)->prev = NULL; \
153         } else { \
154                 if ((p)->prev) (p)->prev->next = (p)->next; \
155                 if ((p)->next) (p)->next->prev = (p)->prev; \
156         } \
157         if ((p) && ((p) != (list))) (p)->next = (p)->prev = NULL; \
158 } while (0)
159
160
161 /*
162   return the parent chunk of a pointer
163 */
164 static inline struct talloc_chunk *talloc_parent_chunk(const void *ptr)
165 {
166         struct talloc_chunk *tc;
167
168         if (unlikely(ptr == NULL)) {
169                 return NULL;
170         }
171
172         tc = talloc_chunk_from_ptr(ptr);
173         while (tc->prev) tc=tc->prev;
174
175         return tc->parent;
176 }
177
178 void *talloc_parent(const void *ptr)
179 {
180         struct talloc_chunk *tc = talloc_parent_chunk(ptr);
181         return tc? TC_PTR_FROM_CHUNK(tc) : NULL;
182 }
183
184 /*
185   find parents name
186 */
187 const char *talloc_parent_name(const void *ptr)
188 {
189         struct talloc_chunk *tc = talloc_parent_chunk(ptr);
190         return tc? tc->name : NULL;
191 }
192
193 /* 
194    Allocate a bit of memory as a child of an existing pointer
195 */
196 static inline void *__talloc(const void *context, size_t size)
197 {
198         struct talloc_chunk *tc;
199
200         if (unlikely(context == NULL)) {
201                 context = null_context;
202         }
203
204         if (unlikely(size >= MAX_TALLOC_SIZE)) {
205                 return NULL;
206         }
207
208         tc = (struct talloc_chunk *)malloc(TC_HDR_SIZE+size);
209         if (unlikely(tc == NULL)) return NULL;
210
211         tc->size = size;
212         tc->flags = TALLOC_MAGIC;
213         tc->destructor = NULL;
214         tc->child = NULL;
215         tc->name = NULL;
216         tc->refs = NULL;
217
218         if (likely(context)) {
219                 struct talloc_chunk *parent = talloc_chunk_from_ptr(context);
220
221                 if (parent->child) {
222                         parent->child->parent = NULL;
223                         tc->next = parent->child;
224                         tc->next->prev = tc;
225                 } else {
226                         tc->next = NULL;
227                 }
228                 tc->parent = parent;
229                 tc->prev = NULL;
230                 parent->child = tc;
231         } else {
232                 tc->next = tc->prev = tc->parent = NULL;
233         }
234
235         return TC_PTR_FROM_CHUNK(tc);
236 }
237
238 /*
239   setup a destructor to be called on free of a pointer
240   the destructor should return 0 on success, or -1 on failure.
241   if the destructor fails then the free is failed, and the memory can
242   be continued to be used
243 */
244 void _talloc_set_destructor(const void *ptr, int (*destructor)(void *))
245 {
246         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
247         tc->destructor = destructor;
248 }
249
250 /*
251   increase the reference count on a piece of memory. 
252 */
253 int talloc_increase_ref_count(const void *ptr)
254 {
255         if (unlikely(!talloc_reference(null_context, ptr))) {
256                 return -1;
257         }
258         return 0;
259 }
260
261 /*
262   helper for talloc_reference()
263
264   this is referenced by a function pointer and should not be inline
265 */
266 static int talloc_reference_destructor(struct talloc_reference_handle *handle)
267 {
268         struct talloc_chunk *ptr_tc = talloc_chunk_from_ptr(handle->ptr);
269         _TLIST_REMOVE(ptr_tc->refs, handle);
270         return 0;
271 }
272
273 /*
274    more efficient way to add a name to a pointer - the name must point to a 
275    true string constant
276 */
277 static inline void _talloc_set_name_const(const void *ptr, const char *name)
278 {
279         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
280         tc->name = name;
281 }
282
283 /*
284   internal talloc_named_const()
285 */
286 static inline void *_talloc_named_const(const void *context, size_t size, const char *name)
287 {
288         void *ptr;
289
290         ptr = __talloc(context, size);
291         if (unlikely(ptr == NULL)) {
292                 return NULL;
293         }
294
295         _talloc_set_name_const(ptr, name);
296
297         return ptr;
298 }
299
300 /*
301   make a secondary reference to a pointer, hanging off the given context.
302   the pointer remains valid until both the original caller and this given
303   context are freed.
304   
305   the major use for this is when two different structures need to reference the 
306   same underlying data, and you want to be able to free the two instances separately,
307   and in either order
308 */
309 void *_talloc_reference(const void *context, const void *ptr)
310 {
311         struct talloc_chunk *tc;
312         struct talloc_reference_handle *handle;
313         if (unlikely(ptr == NULL)) return NULL;
314
315         tc = talloc_chunk_from_ptr(ptr);
316         handle = (struct talloc_reference_handle *)_talloc_named_const(context,
317                                                    sizeof(struct talloc_reference_handle),
318                                                    TALLOC_MAGIC_REFERENCE);
319         if (unlikely(handle == NULL)) return NULL;
320
321         /* note that we hang the destructor off the handle, not the
322            main context as that allows the caller to still setup their
323            own destructor on the context if they want to */
324         talloc_set_destructor(handle, talloc_reference_destructor);
325         handle->ptr = discard_const_p(void, ptr);
326         _TLIST_ADD(tc->refs, handle);
327         return handle->ptr;
328 }
329
330
331 /* 
332    internal talloc_free call
333 */
334 static inline int _talloc_free(void *ptr)
335 {
336         struct talloc_chunk *tc;
337
338         if (unlikely(ptr == NULL)) {
339                 return -1;
340         }
341
342         tc = talloc_chunk_from_ptr(ptr);
343
344         if (unlikely(tc->refs)) {
345                 int is_child;
346                 /* check this is a reference from a child or grantchild
347                  * back to it's parent or grantparent
348                  *
349                  * in that case we need to remove the reference and
350                  * call another instance of talloc_free() on the current
351                  * pointer.
352                  */
353                 is_child = talloc_is_parent(tc->refs, ptr);
354                 _talloc_free(tc->refs);
355                 if (is_child) {
356                         return _talloc_free(ptr);
357                 }
358                 return -1;
359         }
360
361         if (unlikely(tc->flags & TALLOC_FLAG_LOOP)) {
362                 /* we have a free loop - stop looping */
363                 return 0;
364         }
365
366         if (unlikely(tc->destructor)) {
367                 talloc_destructor_t d = tc->destructor;
368                 if (d == (talloc_destructor_t)-1) {
369                         return -1;
370                 }
371                 tc->destructor = (talloc_destructor_t)-1;
372                 if (d(ptr) == -1) {
373                         tc->destructor = d;
374                         return -1;
375                 }
376                 tc->destructor = NULL;
377         }
378
379         if (tc->parent) {
380                 _TLIST_REMOVE(tc->parent->child, tc);
381                 if (tc->parent->child) {
382                         tc->parent->child->parent = tc->parent;
383                 }
384         } else {
385                 if (tc->prev) tc->prev->next = tc->next;
386                 if (tc->next) tc->next->prev = tc->prev;
387         }
388
389         tc->flags |= TALLOC_FLAG_LOOP;
390
391         while (tc->child) {
392                 /* we need to work out who will own an abandoned child
393                    if it cannot be freed. In priority order, the first
394                    choice is owner of any remaining reference to this
395                    pointer, the second choice is our parent, and the
396                    final choice is the null context. */
397                 void *child = TC_PTR_FROM_CHUNK(tc->child);
398                 const void *new_parent = null_context;
399                 if (unlikely(tc->child->refs)) {
400                         struct talloc_chunk *p = talloc_parent_chunk(tc->child->refs);
401                         if (p) new_parent = TC_PTR_FROM_CHUNK(p);
402                 }
403                 if (unlikely(_talloc_free(child) == -1)) {
404                         if (new_parent == null_context) {
405                                 struct talloc_chunk *p = talloc_parent_chunk(ptr);
406                                 if (p) new_parent = TC_PTR_FROM_CHUNK(p);
407                         }
408                         talloc_steal(new_parent, child);
409                 }
410         }
411
412         tc->flags |= TALLOC_FLAG_FREE;
413         free(tc);
414         return 0;
415 }
416
417 /* 
418    move a lump of memory from one talloc context to another return the
419    ptr on success, or NULL if it could not be transferred.
420    passing NULL as ptr will always return NULL with no side effects.
421 */
422 void *_talloc_steal(const void *new_ctx, const void *ptr)
423 {
424         struct talloc_chunk *tc, *new_tc;
425
426         if (unlikely(!ptr)) {
427                 return NULL;
428         }
429
430         if (unlikely(new_ctx == NULL)) {
431                 new_ctx = null_context;
432         }
433
434         tc = talloc_chunk_from_ptr(ptr);
435
436         if (unlikely(new_ctx == NULL)) {
437                 if (tc->parent) {
438                         _TLIST_REMOVE(tc->parent->child, tc);
439                         if (tc->parent->child) {
440                                 tc->parent->child->parent = tc->parent;
441                         }
442                 } else {
443                         if (tc->prev) tc->prev->next = tc->next;
444                         if (tc->next) tc->next->prev = tc->prev;
445                 }
446                 
447                 tc->parent = tc->next = tc->prev = NULL;
448                 return discard_const_p(void, ptr);
449         }
450
451         new_tc = talloc_chunk_from_ptr(new_ctx);
452
453         if (unlikely(tc == new_tc || tc->parent == new_tc)) {
454                 return discard_const_p(void, ptr);
455         }
456
457         if (tc->parent) {
458                 _TLIST_REMOVE(tc->parent->child, tc);
459                 if (tc->parent->child) {
460                         tc->parent->child->parent = tc->parent;
461                 }
462         } else {
463                 if (tc->prev) tc->prev->next = tc->next;
464                 if (tc->next) tc->next->prev = tc->prev;
465         }
466
467         tc->parent = new_tc;
468         if (new_tc->child) new_tc->child->parent = NULL;
469         _TLIST_ADD(new_tc->child, tc);
470
471         return discard_const_p(void, ptr);
472 }
473
474
475
476 /*
477   remove a secondary reference to a pointer. This undo's what
478   talloc_reference() has done. The context and pointer arguments
479   must match those given to a talloc_reference()
480 */
481 static inline int talloc_unreference(const void *context, const void *ptr)
482 {
483         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
484         struct talloc_reference_handle *h;
485
486         if (unlikely(context == NULL)) {
487                 context = null_context;
488         }
489
490         for (h=tc->refs;h;h=h->next) {
491                 struct talloc_chunk *p = talloc_parent_chunk(h);
492                 if (p == NULL) {
493                         if (context == NULL) break;
494                 } else if (TC_PTR_FROM_CHUNK(p) == context) {
495                         break;
496                 }
497         }
498         if (h == NULL) {
499                 return -1;
500         }
501
502         return _talloc_free(h);
503 }
504
505 /*
506   remove a specific parent context from a pointer. This is a more
507   controlled varient of talloc_free()
508 */
509 int talloc_unlink(const void *context, void *ptr)
510 {
511         struct talloc_chunk *tc_p, *new_p;
512         void *new_parent;
513
514         if (ptr == NULL) {
515                 return -1;
516         }
517
518         if (context == NULL) {
519                 context = null_context;
520         }
521
522         if (talloc_unreference(context, ptr) == 0) {
523                 return 0;
524         }
525
526         if (context == NULL) {
527                 if (talloc_parent_chunk(ptr) != NULL) {
528                         return -1;
529                 }
530         } else {
531                 if (talloc_chunk_from_ptr(context) != talloc_parent_chunk(ptr)) {
532                         return -1;
533                 }
534         }
535         
536         tc_p = talloc_chunk_from_ptr(ptr);
537
538         if (tc_p->refs == NULL) {
539                 return _talloc_free(ptr);
540         }
541
542         new_p = talloc_parent_chunk(tc_p->refs);
543         if (new_p) {
544                 new_parent = TC_PTR_FROM_CHUNK(new_p);
545         } else {
546                 new_parent = NULL;
547         }
548
549         if (talloc_unreference(new_parent, ptr) != 0) {
550                 return -1;
551         }
552
553         talloc_steal(new_parent, ptr);
554
555         return 0;
556 }
557
558 /*
559   add a name to an existing pointer - va_list version
560 */
561 static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(2,0);
562
563 static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va_list ap)
564 {
565         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
566         tc->name = talloc_vasprintf(ptr, fmt, ap);
567         if (likely(tc->name)) {
568                 _talloc_set_name_const(tc->name, ".name");
569         }
570         return tc->name;
571 }
572
573 /*
574   add a name to an existing pointer
575 */
576 const char *talloc_set_name(const void *ptr, const char *fmt, ...)
577 {
578         const char *name;
579         va_list ap;
580         va_start(ap, fmt);
581         name = talloc_set_name_v(ptr, fmt, ap);
582         va_end(ap);
583         return name;
584 }
585
586
587 /*
588   create a named talloc pointer. Any talloc pointer can be named, and
589   talloc_named() operates just like talloc() except that it allows you
590   to name the pointer.
591 */
592 void *talloc_named(const void *context, size_t size, const char *fmt, ...)
593 {
594         va_list ap;
595         void *ptr;
596         const char *name;
597
598         ptr = __talloc(context, size);
599         if (unlikely(ptr == NULL)) return NULL;
600
601         va_start(ap, fmt);
602         name = talloc_set_name_v(ptr, fmt, ap);
603         va_end(ap);
604
605         if (unlikely(name == NULL)) {
606                 _talloc_free(ptr);
607                 return NULL;
608         }
609
610         return ptr;
611 }
612
613 /*
614   return the name of a talloc ptr, or "UNNAMED"
615 */
616 const char *talloc_get_name(const void *ptr)
617 {
618         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
619         if (unlikely(tc->name == TALLOC_MAGIC_REFERENCE)) {
620                 return ".reference";
621         }
622         if (likely(tc->name)) {
623                 return tc->name;
624         }
625         return "UNNAMED";
626 }
627
628
629 /*
630   check if a pointer has the given name. If it does, return the pointer,
631   otherwise return NULL
632 */
633 void *talloc_check_name(const void *ptr, const char *name)
634 {
635         const char *pname;
636         if (unlikely(ptr == NULL)) return NULL;
637         pname = talloc_get_name(ptr);
638         if (likely(pname == name || strcmp(pname, name) == 0)) {
639                 return discard_const_p(void, ptr);
640         }
641         return NULL;
642 }
643
644
645 /*
646   this is for compatibility with older versions of talloc
647 */
648 void *talloc_init(const char *fmt, ...)
649 {
650         va_list ap;
651         void *ptr;
652         const char *name;
653
654         /*
655          * samba3 expects talloc_report_depth_cb(NULL, ...)
656          * reports all talloc'ed memory, so we need to enable
657          * null_tracking
658          */
659         talloc_enable_null_tracking();
660
661         ptr = __talloc(NULL, 0);
662         if (unlikely(ptr == NULL)) return NULL;
663
664         va_start(ap, fmt);
665         name = talloc_set_name_v(ptr, fmt, ap);
666         va_end(ap);
667
668         if (unlikely(name == NULL)) {
669                 _talloc_free(ptr);
670                 return NULL;
671         }
672
673         return ptr;
674 }
675
676 /*
677   this is a replacement for the Samba3 talloc_destroy_pool functionality. It
678   should probably not be used in new code. It's in here to keep the talloc
679   code consistent across Samba 3 and 4.
680 */
681 void talloc_free_children(void *ptr)
682 {
683         struct talloc_chunk *tc;
684
685         if (unlikely(ptr == NULL)) {
686                 return;
687         }
688
689         tc = talloc_chunk_from_ptr(ptr);
690
691         while (tc->child) {
692                 /* we need to work out who will own an abandoned child
693                    if it cannot be freed. In priority order, the first
694                    choice is owner of any remaining reference to this
695                    pointer, the second choice is our parent, and the
696                    final choice is the null context. */
697                 void *child = TC_PTR_FROM_CHUNK(tc->child);
698                 const void *new_parent = null_context;
699                 if (unlikely(tc->child->refs)) {
700                         struct talloc_chunk *p = talloc_parent_chunk(tc->child->refs);
701                         if (p) new_parent = TC_PTR_FROM_CHUNK(p);
702                 }
703                 if (unlikely(_talloc_free(child) == -1)) {
704                         if (new_parent == null_context) {
705                                 struct talloc_chunk *p = talloc_parent_chunk(ptr);
706                                 if (p) new_parent = TC_PTR_FROM_CHUNK(p);
707                         }
708                         talloc_steal(new_parent, child);
709                 }
710         }
711 }
712
713 /* 
714    Allocate a bit of memory as a child of an existing pointer
715 */
716 void *_talloc(const void *context, size_t size)
717 {
718         return __talloc(context, size);
719 }
720
721 /*
722   externally callable talloc_set_name_const()
723 */
724 void talloc_set_name_const(const void *ptr, const char *name)
725 {
726         _talloc_set_name_const(ptr, name);
727 }
728
729 /*
730   create a named talloc pointer. Any talloc pointer can be named, and
731   talloc_named() operates just like talloc() except that it allows you
732   to name the pointer.
733 */
734 void *talloc_named_const(const void *context, size_t size, const char *name)
735 {
736         return _talloc_named_const(context, size, name);
737 }
738
739 /* 
740    free a talloc pointer. This also frees all child pointers of this 
741    pointer recursively
742
743    return 0 if the memory is actually freed, otherwise -1. The memory
744    will not be freed if the ref_count is > 1 or the destructor (if
745    any) returns non-zero
746 */
747 int talloc_free(void *ptr)
748 {
749         return _talloc_free(ptr);
750 }
751
752
753
754 /*
755   A talloc version of realloc. The context argument is only used if
756   ptr is NULL
757 */
758 void *_talloc_realloc(const void *context, void *ptr, size_t size, const char *name)
759 {
760         struct talloc_chunk *tc;
761         void *new_ptr;
762
763         /* size zero is equivalent to free() */
764         if (unlikely(size == 0)) {
765                 _talloc_free(ptr);
766                 return NULL;
767         }
768
769         if (unlikely(size >= MAX_TALLOC_SIZE)) {
770                 return NULL;
771         }
772
773         /* realloc(NULL) is equivalent to malloc() */
774         if (ptr == NULL) {
775                 return _talloc_named_const(context, size, name);
776         }
777
778         tc = talloc_chunk_from_ptr(ptr);
779
780         /* don't allow realloc on referenced pointers */
781         if (unlikely(tc->refs)) {
782                 return NULL;
783         }
784
785         /* by resetting magic we catch users of the old memory */
786         tc->flags |= TALLOC_FLAG_FREE;
787
788 #if ALWAYS_REALLOC
789         new_ptr = malloc(size + TC_HDR_SIZE);
790         if (new_ptr) {
791                 memcpy(new_ptr, tc, tc->size + TC_HDR_SIZE);
792                 free(tc);
793         }
794 #else
795         new_ptr = realloc(tc, size + TC_HDR_SIZE);
796 #endif
797         if (unlikely(!new_ptr)) {       
798                 tc->flags &= ~TALLOC_FLAG_FREE; 
799                 return NULL; 
800         }
801
802         tc = (struct talloc_chunk *)new_ptr;
803         tc->flags &= ~TALLOC_FLAG_FREE; 
804         if (tc->parent) {
805                 tc->parent->child = tc;
806         }
807         if (tc->child) {
808                 tc->child->parent = tc;
809         }
810
811         if (tc->prev) {
812                 tc->prev->next = tc;
813         }
814         if (tc->next) {
815                 tc->next->prev = tc;
816         }
817
818         tc->size = size;
819         _talloc_set_name_const(TC_PTR_FROM_CHUNK(tc), name);
820
821         return TC_PTR_FROM_CHUNK(tc);
822 }
823
824 /*
825   a wrapper around talloc_steal() for situations where you are moving a pointer
826   between two structures, and want the old pointer to be set to NULL
827 */
828 void *_talloc_move(const void *new_ctx, const void *_pptr)
829 {
830         const void **pptr = discard_const_p(const void *,_pptr);
831         void *ret = _talloc_steal(new_ctx, *pptr);
832         (*pptr) = NULL;
833         return ret;
834 }
835
836 /*
837   return the total size of a talloc pool (subtree)
838 */
839 size_t talloc_total_size(const void *ptr)
840 {
841         size_t total = 0;
842         struct talloc_chunk *c, *tc;
843
844         if (ptr == NULL) {
845                 ptr = null_context;
846         }
847         if (ptr == NULL) {
848                 return 0;
849         }
850
851         tc = talloc_chunk_from_ptr(ptr);
852
853         if (tc->flags & TALLOC_FLAG_LOOP) {
854                 return 0;
855         }
856
857         tc->flags |= TALLOC_FLAG_LOOP;
858
859         total = tc->size;
860         for (c=tc->child;c;c=c->next) {
861                 total += talloc_total_size(TC_PTR_FROM_CHUNK(c));
862         }
863
864         tc->flags &= ~TALLOC_FLAG_LOOP;
865
866         return total;
867 }
868
869 /*
870   return the total number of blocks in a talloc pool (subtree)
871 */
872 size_t talloc_total_blocks(const void *ptr)
873 {
874         size_t total = 0;
875         struct talloc_chunk *c, *tc = talloc_chunk_from_ptr(ptr);
876
877         if (tc->flags & TALLOC_FLAG_LOOP) {
878                 return 0;
879         }
880
881         tc->flags |= TALLOC_FLAG_LOOP;
882
883         total++;
884         for (c=tc->child;c;c=c->next) {
885                 total += talloc_total_blocks(TC_PTR_FROM_CHUNK(c));
886         }
887
888         tc->flags &= ~TALLOC_FLAG_LOOP;
889
890         return total;
891 }
892
893 /*
894   return the number of external references to a pointer
895 */
896 size_t talloc_reference_count(const void *ptr)
897 {
898         struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
899         struct talloc_reference_handle *h;
900         size_t ret = 0;
901
902         for (h=tc->refs;h;h=h->next) {
903                 ret++;
904         }
905         return ret;
906 }
907
908 /*
909   report on memory usage by all children of a pointer, giving a full tree view
910 */
911 void talloc_report_depth_cb(const void *ptr, int depth, int max_depth,
912                             void (*callback)(const void *ptr,
913                                              int depth, int max_depth,
914                                              int is_ref,
915                                              void *private_data),
916                             void *private_data)
917 {
918         struct talloc_chunk *c, *tc;
919
920         if (ptr == NULL) {
921                 ptr = null_context;
922         }
923         if (ptr == NULL) return;
924
925         tc = talloc_chunk_from_ptr(ptr);
926
927         if (tc->flags & TALLOC_FLAG_LOOP) {
928                 return;
929         }
930
931         callback(ptr, depth, max_depth, 0, private_data);
932
933         if (max_depth >= 0 && depth >= max_depth) {
934                 return;
935         }
936
937         tc->flags |= TALLOC_FLAG_LOOP;
938         for (c=tc->child;c;c=c->next) {
939                 if (c->name == TALLOC_MAGIC_REFERENCE) {
940                         struct talloc_reference_handle *h = (struct talloc_reference_handle *)TC_PTR_FROM_CHUNK(c);
941                         callback(h->ptr, depth + 1, max_depth, 1, private_data);
942                 } else {
943                         talloc_report_depth_cb(TC_PTR_FROM_CHUNK(c), depth + 1, max_depth, callback, private_data);
944                 }
945         }
946         tc->flags &= ~TALLOC_FLAG_LOOP;
947 }
948
949 static void talloc_report_depth_FILE_helper(const void *ptr, int depth, int max_depth, int is_ref, void *_f)
950 {
951         const char *name = talloc_get_name(ptr);
952         FILE *f = (FILE *)_f;
953
954         if (is_ref) {
955                 fprintf(f, "%*sreference to: %s\n", depth*4, "", name);
956                 return;
957         }
958
959         if (depth == 0) {
960                 fprintf(f,"%stalloc report on '%s' (total %6lu bytes in %3lu blocks)\n", 
961                         (max_depth < 0 ? "full " :""), name,
962                         (unsigned long)talloc_total_size(ptr),
963                         (unsigned long)talloc_total_blocks(ptr));
964                 return;
965         }
966
967         fprintf(f, "%*s%-30s contains %6lu bytes in %3lu blocks (ref %d) %p\n", 
968                 depth*4, "",
969                 name,
970                 (unsigned long)talloc_total_size(ptr),
971                 (unsigned long)talloc_total_blocks(ptr),
972                 (int)talloc_reference_count(ptr), ptr);
973
974 #if 0
975         fprintf(f, "content: ");
976         if (talloc_total_size(ptr)) {
977                 int tot = talloc_total_size(ptr);
978                 int i;
979
980                 for (i = 0; i < tot; i++) {
981                         if ((((char *)ptr)[i] > 31) && (((char *)ptr)[i] < 126)) {
982                                 fprintf(f, "%c", ((char *)ptr)[i]);
983                         } else {
984                                 fprintf(f, "~%02x", ((char *)ptr)[i]);
985                         }
986                 }
987         }
988         fprintf(f, "\n");
989 #endif
990 }
991
992 /*
993   report on memory usage by all children of a pointer, giving a full tree view
994 */
995 void talloc_report_depth_file(const void *ptr, int depth, int max_depth, FILE *f)
996 {
997         talloc_report_depth_cb(ptr, depth, max_depth, talloc_report_depth_FILE_helper, f);
998         fflush(f);
999 }
1000
1001 /*
1002   report on memory usage by all children of a pointer, giving a full tree view
1003 */
1004 void talloc_report_full(const void *ptr, FILE *f)
1005 {
1006         talloc_report_depth_file(ptr, 0, -1, f);
1007 }
1008
1009 /*
1010   report on memory usage by all children of a pointer
1011 */
1012 void talloc_report(const void *ptr, FILE *f)
1013 {
1014         talloc_report_depth_file(ptr, 0, 1, f);
1015 }
1016
1017 /*
1018   report on any memory hanging off the null context
1019 */
1020 static void talloc_report_null(void)
1021 {
1022         if (talloc_total_size(null_context) != 0) {
1023                 talloc_report(null_context, stderr);
1024         }
1025 }
1026
1027 /*
1028   report on any memory hanging off the null context
1029 */
1030 static void talloc_report_null_full(void)
1031 {
1032         if (talloc_total_size(null_context) != 0) {
1033                 talloc_report_full(null_context, stderr);
1034         }
1035 }
1036
1037 /*
1038   enable tracking of the NULL context
1039 */
1040 void talloc_enable_null_tracking(void)
1041 {
1042         if (null_context == NULL) {
1043                 null_context = _talloc_named_const(NULL, 0, "null_context");
1044         }
1045 }
1046
1047 /*
1048   disable tracking of the NULL context
1049 */
1050 void talloc_disable_null_tracking(void)
1051 {
1052         _talloc_free(null_context);
1053         null_context = NULL;
1054 }
1055
1056 /*
1057   enable leak reporting on exit
1058 */
1059 void talloc_enable_leak_report(void)
1060 {
1061         talloc_enable_null_tracking();
1062         atexit(talloc_report_null);
1063 }
1064
1065 /*
1066   enable full leak reporting on exit
1067 */
1068 void talloc_enable_leak_report_full(void)
1069 {
1070         talloc_enable_null_tracking();
1071         atexit(talloc_report_null_full);
1072 }
1073
1074 /* 
1075    talloc and zero memory. 
1076 */
1077 void *_talloc_zero(const void *ctx, size_t size, const char *name)
1078 {
1079         void *p = _talloc_named_const(ctx, size, name);
1080
1081         if (p) {
1082                 memset(p, '\0', size);
1083         }
1084
1085         return p;
1086 }
1087
1088 /*
1089   memdup with a talloc. 
1090 */
1091 void *_talloc_memdup(const void *t, const void *p, size_t size, const char *name)
1092 {
1093         void *newp = _talloc_named_const(t, size, name);
1094
1095         if (likely(newp)) {
1096                 memcpy(newp, p, size);
1097         }
1098
1099         return newp;
1100 }
1101
1102 /*
1103   strdup with a talloc 
1104 */
1105 char *talloc_strdup(const void *t, const char *p)
1106 {
1107         char *ret;
1108         if (!p) {
1109                 return NULL;
1110         }
1111         ret = (char *)talloc_memdup(t, p, strlen(p) + 1);
1112         if (likely(ret)) {
1113                 _talloc_set_name_const(ret, ret);
1114         }
1115         return ret;
1116 }
1117
1118 /*
1119  append to a talloced string 
1120 */
1121 char *talloc_append_string(const void *t, char *orig, const char *append)
1122 {
1123         char *ret;
1124         size_t olen = strlen(orig);
1125         size_t alenz;
1126
1127         if (!append)
1128                 return orig;
1129
1130         alenz = strlen(append) + 1;
1131
1132         ret = talloc_realloc(t, orig, char, olen + alenz);
1133         if (!ret)
1134                 return NULL;
1135
1136         /* append the string with the trailing \0 */
1137         memcpy(&ret[olen], append, alenz);
1138
1139         _talloc_set_name_const(ret, ret);
1140
1141         return ret;
1142 }
1143
1144 /*
1145   strndup with a talloc 
1146 */
1147 char *talloc_strndup(const void *t, const char *p, size_t n)
1148 {
1149         size_t len;
1150         char *ret;
1151
1152         for (len=0; len<n && p[len]; len++) ;
1153
1154         ret = (char *)__talloc(t, len + 1);
1155         if (!ret) { return NULL; }
1156         memcpy(ret, p, len);
1157         ret[len] = 0;
1158         _talloc_set_name_const(ret, ret);
1159         return ret;
1160 }
1161
1162 #ifndef HAVE_VA_COPY
1163 #ifdef HAVE___VA_COPY
1164 #define va_copy(dest, src) __va_copy(dest, src)
1165 #else
1166 #define va_copy(dest, src) (dest) = (src)
1167 #endif
1168 #endif
1169
1170 char *talloc_vasprintf(const void *t, const char *fmt, va_list ap)
1171 {       
1172         int len;
1173         char *ret;
1174         va_list ap2;
1175         char c;
1176         
1177         /* this call looks strange, but it makes it work on older solaris boxes */
1178         va_copy(ap2, ap);
1179         len = vsnprintf(&c, 1, fmt, ap2);
1180         va_end(ap2);
1181         if (len < 0) {
1182                 return NULL;
1183         }
1184
1185         ret = (char *)__talloc(t, len+1);
1186         if (ret) {
1187                 va_copy(ap2, ap);
1188                 vsnprintf(ret, len+1, fmt, ap2);
1189                 va_end(ap2);
1190                 _talloc_set_name_const(ret, ret);
1191         }
1192
1193         return ret;
1194 }
1195
1196
1197 /*
1198   Perform string formatting, and return a pointer to newly allocated
1199   memory holding the result, inside a memory pool.
1200  */
1201 char *talloc_asprintf(const void *t, const char *fmt, ...)
1202 {
1203         va_list ap;
1204         char *ret;
1205
1206         va_start(ap, fmt);
1207         ret = talloc_vasprintf(t, fmt, ap);
1208         va_end(ap);
1209         return ret;
1210 }
1211
1212
1213 /**
1214  * Realloc @p s to append the formatted result of @p fmt and @p ap,
1215  * and return @p s, which may have moved.  Good for gradually
1216  * accumulating output into a string buffer.
1217  **/
1218 char *talloc_vasprintf_append(char *s, const char *fmt, va_list ap)
1219 {       
1220         struct talloc_chunk *tc;
1221         int len, s_len;
1222         va_list ap2;
1223         char c;
1224
1225         if (s == NULL) {
1226                 return talloc_vasprintf(NULL, fmt, ap);
1227         }
1228
1229         tc = talloc_chunk_from_ptr(s);
1230
1231         s_len = tc->size - 1;
1232
1233         va_copy(ap2, ap);
1234         len = vsnprintf(&c, 1, fmt, ap2);
1235         va_end(ap2);
1236
1237         if (len <= 0) {
1238                 /* Either the vsnprintf failed or the format resulted in
1239                  * no characters being formatted. In the former case, we
1240                  * ought to return NULL, in the latter we ought to return
1241                  * the original string. Most current callers of this 
1242                  * function expect it to never return NULL.
1243                  */
1244                 return s;
1245         }
1246
1247         s = talloc_realloc(NULL, s, char, s_len + len+1);
1248         if (!s) return NULL;
1249
1250         va_copy(ap2, ap);
1251         vsnprintf(s+s_len, len+1, fmt, ap2);
1252         va_end(ap2);
1253         _talloc_set_name_const(s, s);
1254
1255         return s;
1256 }
1257
1258 /*
1259   Realloc @p s to append the formatted result of @p fmt and return @p
1260   s, which may have moved.  Good for gradually accumulating output
1261   into a string buffer.
1262  */
1263 char *talloc_asprintf_append(char *s, const char *fmt, ...)
1264 {
1265         va_list ap;
1266
1267         va_start(ap, fmt);
1268         s = talloc_vasprintf_append(s, fmt, ap);
1269         va_end(ap);
1270         return s;
1271 }
1272
1273 /*
1274   alloc an array, checking for integer overflow in the array size
1275 */
1276 void *_talloc_array(const void *ctx, size_t el_size, unsigned count, const char *name)
1277 {
1278         if (count >= MAX_TALLOC_SIZE/el_size) {
1279                 return NULL;
1280         }
1281         return _talloc_named_const(ctx, el_size * count, name);
1282 }
1283
1284 /*
1285   alloc an zero array, checking for integer overflow in the array size
1286 */
1287 void *_talloc_zero_array(const void *ctx, size_t el_size, unsigned count, const char *name)
1288 {
1289         if (count >= MAX_TALLOC_SIZE/el_size) {
1290                 return NULL;
1291         }
1292         return _talloc_zero(ctx, el_size * count, name);
1293 }
1294
1295 /*
1296   realloc an array, checking for integer overflow in the array size
1297 */
1298 void *_talloc_realloc_array(const void *ctx, void *ptr, size_t el_size, unsigned count, const char *name)
1299 {
1300         if (count >= MAX_TALLOC_SIZE/el_size) {
1301                 return NULL;
1302         }
1303         return _talloc_realloc(ctx, ptr, el_size * count, name);
1304 }
1305
1306 /*
1307   a function version of talloc_realloc(), so it can be passed as a function pointer
1308   to libraries that want a realloc function (a realloc function encapsulates
1309   all the basic capabilities of an allocation library, which is why this is useful)
1310 */
1311 void *talloc_realloc_fn(const void *context, void *ptr, size_t size)
1312 {
1313         return _talloc_realloc(context, ptr, size, NULL);
1314 }
1315
1316
1317 static int talloc_autofree_destructor(void *ptr)
1318 {
1319         autofree_context = NULL;
1320         return 0;
1321 }
1322
1323 static void talloc_autofree(void)
1324 {
1325         _talloc_free(autofree_context);
1326 }
1327
1328 /*
1329   return a context which will be auto-freed on exit
1330   this is useful for reducing the noise in leak reports
1331 */
1332 void *talloc_autofree_context(void)
1333 {
1334         if (autofree_context == NULL) {
1335                 autofree_context = _talloc_named_const(NULL, 0, "autofree_context");
1336                 talloc_set_destructor(autofree_context, talloc_autofree_destructor);
1337                 atexit(talloc_autofree);
1338         }
1339         return autofree_context;
1340 }
1341
1342 size_t talloc_get_size(const void *context)
1343 {
1344         struct talloc_chunk *tc;
1345
1346         if (context == NULL)
1347                 return 0;
1348
1349         tc = talloc_chunk_from_ptr(context);
1350
1351         return tc->size;
1352 }
1353
1354 /*
1355   find a parent of this context that has the given name, if any
1356 */
1357 void *talloc_find_parent_byname(const void *context, const char *name)
1358 {
1359         struct talloc_chunk *tc;
1360
1361         if (context == NULL) {
1362                 return NULL;
1363         }
1364
1365         tc = talloc_chunk_from_ptr(context);
1366         while (tc) {
1367                 if (tc->name && strcmp(tc->name, name) == 0) {
1368                         return TC_PTR_FROM_CHUNK(tc);
1369                 }
1370                 while (tc && tc->prev) tc = tc->prev;
1371                 if (tc) {
1372                         tc = tc->parent;
1373                 }
1374         }
1375         return NULL;
1376 }
1377
1378 /*
1379   show the parentage of a context
1380 */
1381 void talloc_show_parents(const void *context, FILE *file)
1382 {
1383         struct talloc_chunk *tc;
1384
1385         if (context == NULL) {
1386                 fprintf(file, "talloc no parents for NULL\n");
1387                 return;
1388         }
1389
1390         tc = talloc_chunk_from_ptr(context);
1391         fprintf(file, "talloc parents of '%s'\n", talloc_get_name(context));
1392         while (tc) {
1393                 fprintf(file, "\t'%s'\n", talloc_get_name(TC_PTR_FROM_CHUNK(tc)));
1394                 while (tc && tc->prev) tc = tc->prev;
1395                 if (tc) {
1396                         tc = tc->parent;
1397                 }
1398         }
1399         fflush(file);
1400 }
1401
1402 /*
1403   return 1 if ptr is a parent of context
1404 */
1405 int talloc_is_parent(const void *context, const void *ptr)
1406 {
1407         struct talloc_chunk *tc;
1408
1409         if (context == NULL) {
1410                 return 0;
1411         }
1412
1413         tc = talloc_chunk_from_ptr(context);
1414         while (tc) {
1415                 if (TC_PTR_FROM_CHUNK(tc) == ptr) return 1;
1416                 while (tc && tc->prev) tc = tc->prev;
1417                 if (tc) {
1418                         tc = tc->parent;
1419                 }
1420         }
1421         return 0;
1422 }