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