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