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