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