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