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