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