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