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