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