talloc: use the system pytalloc-util for python3 as well
[sfrench/samba-autobuild/.git] / lib / talloc / talloc.c
index fcd86d754a99990146d2aa3851c634e54fa5facf..7721fa4a9c6d7d59c3f85b82eaeeae2b3f09d4b7 100644 (file)
@@ -1,4 +1,4 @@
-/* 
+/*
    Samba Unix SMB/CIFS implementation.
 
    Samba trivial allocation library - new interface
@@ -7,11 +7,11 @@
 
    Copyright (C) Andrew Tridgell 2004
    Copyright (C) Stefan Metzmacher 2006
-   
+
      ** NOTE! The following LGPL license applies to the talloc
      ** library. This does NOT imply that all of Samba is released
      ** under the LGPL
-   
+
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
 #include "replace.h"
 #include "talloc.h"
 
-#ifdef TALLOC_BUILD_VERSION_MAJOR
+#ifdef HAVE_SYS_AUXV_H
+#include <sys/auxv.h>
+#endif
+
 #if (TALLOC_VERSION_MAJOR != TALLOC_BUILD_VERSION_MAJOR)
 #error "TALLOC_VERSION_MAJOR != TALLOC_BUILD_VERSION_MAJOR"
 #endif
-#endif
 
-#ifdef TALLOC_BUILD_VERSION_MINOR
 #if (TALLOC_VERSION_MINOR != TALLOC_BUILD_VERSION_MINOR)
 #error "TALLOC_VERSION_MINOR != TALLOC_BUILD_VERSION_MINOR"
 #endif
-#endif
 
 /* Special macros that are no-ops except when run under Valgrind on
  * x86.  They've moved a little bit from valgrind 1.0.4 to 1.9.4 */
 
 
 #define MAX_TALLOC_SIZE 0x10000000
-#define TALLOC_MAGIC_BASE 0xe814ec70
-#define TALLOC_MAGIC ( \
-       TALLOC_MAGIC_BASE + \
-       (TALLOC_VERSION_MAJOR << 12) + \
-       (TALLOC_VERSION_MINOR << 4) \
-)
 
 #define TALLOC_FLAG_FREE 0x01
 #define TALLOC_FLAG_LOOP 0x02
 #define TALLOC_FLAG_POOL 0x04          /* This is a talloc pool */
 #define TALLOC_FLAG_POOLMEM 0x08       /* This is allocated in a pool */
+
+/*
+ * Bits above this are random, used to make it harder to fake talloc
+ * headers during an attack.  Try not to change this without good reason.
+ */
+#define TALLOC_FLAG_MASK 0x0F
+
 #define TALLOC_MAGIC_REFERENCE ((const char *)1)
 
-/* by default we abort when given a bad pointer (such as when talloc_free() is called 
+#define TALLOC_MAGIC_BASE 0xe814ec70
+static unsigned int talloc_magic = (
+       ~TALLOC_FLAG_MASK & (
+               TALLOC_MAGIC_BASE +
+               (TALLOC_BUILD_VERSION_MAJOR << 24) +
+               (TALLOC_BUILD_VERSION_MINOR << 16) +
+               (TALLOC_BUILD_VERSION_RELEASE << 8)));
+
+/* by default we abort when given a bad pointer (such as when talloc_free() is called
    on a pointer that came from malloc() */
 #ifndef TALLOC_ABORT
 #define TALLOC_ABORT(reason) abort()
@@ -227,29 +236,80 @@ struct talloc_reference_handle {
        const char *location;
 };
 
+struct talloc_memlimit {
+       struct talloc_chunk *parent;
+       struct talloc_memlimit *upper;
+       size_t max_size;
+       size_t cur_size;
+};
+
+static inline bool talloc_memlimit_check(struct talloc_memlimit *limit, size_t size);
+static inline void talloc_memlimit_grow(struct talloc_memlimit *limit,
+                               size_t size);
+static inline void talloc_memlimit_shrink(struct talloc_memlimit *limit,
+                               size_t size);
+static inline void tc_memlimit_update_on_free(struct talloc_chunk *tc);
+
+static inline void _tc_set_name_const(struct talloc_chunk *tc,
+                               const char *name);
+static struct talloc_chunk *_vasprintf_tc(const void *t,
+                               const char *fmt,
+                               va_list ap);
+
 typedef int (*talloc_destructor_t)(void *);
 
+struct talloc_pool_hdr;
+
 struct talloc_chunk {
+       /*
+        * flags includes the talloc magic, which is randomised to
+        * make overwrite attacks harder
+        */
+       unsigned flags;
+
+       /*
+        * If you have a logical tree like:
+        *
+        *           <parent>
+        *           /   |   \
+        *          /    |    \
+        *         /     |     \
+        * <child 1> <child 2> <child 3>
+        *
+        * The actual talloc tree is:
+        *
+        *  <parent>
+        *     |
+        *  <child 1> - <child 2> - <child 3>
+        *
+        * The children are linked with next/prev pointers, and
+        * child 1 is linked to the parent with parent/child
+        * pointers.
+        */
+
        struct talloc_chunk *next, *prev;
        struct talloc_chunk *parent, *child;
        struct talloc_reference_handle *refs;
        talloc_destructor_t destructor;
        const char *name;
        size_t size;
-       unsigned flags;
 
        /*
-        * "pool" has dual use:
-        *
-        * For the talloc pool itself (i.e. TALLOC_FLAG_POOL is set), "pool"
-        * marks the end of the currently allocated area.
-        *
-        * For members of the pool (i.e. TALLOC_FLAG_POOLMEM is set), "pool"
+        * limit semantics:
+        * if 'limit' is set it means all *new* children of the context will
+        * be limited to a total aggregate size ox max_size for memory
+        * allocations.
+        * cur_size is used to keep track of the current use
+        */
+       struct talloc_memlimit *limit;
+
+       /*
+        * For members of a pool (i.e. TALLOC_FLAG_POOLMEM is set), "pool"
         * is a pointer to the struct talloc_chunk of the pool that it was
         * allocated from. This way children can quickly find the pool to chew
         * from.
         */
-       void *pool;
+       struct talloc_pool_hdr *pool;
 };
 
 /* 16 byte alignment seems to keep everyone happy */
@@ -267,6 +327,11 @@ _PUBLIC_ int talloc_version_minor(void)
        return TALLOC_VERSION_MINOR;
 }
 
+_PUBLIC_ int talloc_test_get_magic(void)
+{
+       return talloc_magic;
+}
+
 static void (*talloc_log_fn)(const char *message);
 
 _PUBLIC_ void talloc_set_log_fn(void (*log_fn)(const char *message))
@@ -274,6 +339,50 @@ _PUBLIC_ void talloc_set_log_fn(void (*log_fn)(const char *message))
        talloc_log_fn = log_fn;
 }
 
+#ifdef HAVE_CONSTRUCTOR_ATTRIBUTE
+void talloc_lib_init(void) __attribute__((constructor));
+void talloc_lib_init(void)
+{
+       uint32_t random_value;
+#if defined(HAVE_GETAUXVAL) && defined(AT_RANDOM)
+       uint8_t *p;
+       /*
+        * Use the kernel-provided random values used for
+        * ASLR.  This won't change per-exec, which is ideal for us
+        */
+       p = (uint8_t *) getauxval(AT_RANDOM);
+       if (p) {
+               /*
+                * We get 16 bytes from getauxval.  By calling rand(),
+                * a totally insecure PRNG, but one that will
+                * deterministically have a different value when called
+                * twice, we ensure that if two talloc-like libraries
+                * are somehow loaded in the same address space, that
+                * because we choose different bytes, we will keep the
+                * protection against collision of multiple talloc
+                * libs.
+                *
+                * This protection is important because the effects of
+                * passing a talloc pointer from one to the other may
+                * be very hard to determine.
+                */
+               int offset = rand() % (16 - sizeof(random_value));
+               memcpy(&random_value, p + offset, sizeof(random_value));
+       } else
+#endif
+       {
+               /*
+                * Otherwise, hope the location we are loaded in
+                * memory is randomised by someone else
+                */
+               random_value = ((uintptr_t)talloc_lib_init & 0xFFFFFFFF);
+       }
+       talloc_magic = random_value & ~TALLOC_FLAG_MASK;
+}
+#else
+#warning "No __attribute__((constructor)) support found on this platform, additional talloc security measures not available"
+#endif
+
 static void talloc_log(const char *fmt, ...) PRINTF_ATTRIBUTE(1,2);
 static void talloc_log(const char *fmt, ...)
 {
@@ -322,12 +431,6 @@ static void talloc_abort(const char *reason)
 
 static void talloc_abort_magic(unsigned magic)
 {
-       unsigned striped = magic - TALLOC_MAGIC_BASE;
-       unsigned major = (striped & 0xFFFFF000) >> 12;
-       unsigned minor = (striped & 0x00000FF0) >> 4;
-       talloc_log("Bad talloc magic[0x%08X/%u/%u] expected[0x%08X/%u/%u]\n",
-                  magic, major, minor,
-                  TALLOC_MAGIC, TALLOC_VERSION_MAJOR, TALLOC_VERSION_MINOR);
        talloc_abort("Bad talloc magic value - wrong talloc version used/mixed");
 }
 
@@ -346,9 +449,9 @@ static inline struct talloc_chunk *talloc_chunk_from_ptr(const void *ptr)
 {
        const char *pp = (const char *)ptr;
        struct talloc_chunk *tc = discard_const_p(struct talloc_chunk, pp - TC_HDR_SIZE);
-       if (unlikely((tc->flags & (TALLOC_FLAG_FREE | ~0xF)) != TALLOC_MAGIC)) { 
-               if ((tc->flags & (~0xFFF)) == TALLOC_MAGIC_BASE) {
-                       talloc_abort_magic(tc->flags & (~0xF));
+       if (unlikely((tc->flags & (TALLOC_FLAG_FREE | ~TALLOC_FLAG_MASK)) != talloc_magic)) {
+               if ((tc->flags & (~TALLOC_FLAG_MASK)) == talloc_magic) {
+                       talloc_abort_magic(tc->flags & (~TALLOC_FLAG_MASK));
                        return NULL;
                }
 
@@ -437,59 +540,69 @@ _PUBLIC_ const char *talloc_parent_name(const void *ptr)
   memory footprint of each talloc chunk by those 16 bytes.
 */
 
-#define TALLOC_POOL_HDR_SIZE 16
+struct talloc_pool_hdr {
+       void *end;
+       unsigned int object_count;
+       size_t poolsize;
+};
 
-#define TC_POOL_SPACE_LEFT(_pool_tc) \
-       PTR_DIFF(TC_HDR_SIZE + (_pool_tc)->size + (char *)(_pool_tc), \
-                (_pool_tc)->pool)
+#define TP_HDR_SIZE TC_ALIGN16(sizeof(struct talloc_pool_hdr))
 
-#define TC_POOL_FIRST_CHUNK(_pool_tc) \
-       ((void *)(TC_HDR_SIZE + TALLOC_POOL_HDR_SIZE + (char *)(_pool_tc)))
+static inline struct talloc_pool_hdr *talloc_pool_from_chunk(struct talloc_chunk *c)
+{
+       return (struct talloc_pool_hdr *)((char *)c - TP_HDR_SIZE);
+}
 
-#define TC_POOLMEM_CHUNK_SIZE(_tc) \
-       TC_ALIGN16(TC_HDR_SIZE + (_tc)->size)
+static inline struct talloc_chunk *talloc_chunk_from_pool(struct talloc_pool_hdr *h)
+{
+       return (struct talloc_chunk *)((char *)h + TP_HDR_SIZE);
+}
 
-#define TC_POOLMEM_NEXT_CHUNK(_tc) \
-       ((void *)(TC_POOLMEM_CHUNK_SIZE(tc) + (char*)(_tc)))
+static inline void *tc_pool_end(struct talloc_pool_hdr *pool_hdr)
+{
+       struct talloc_chunk *tc = talloc_chunk_from_pool(pool_hdr);
+       return (char *)tc + TC_HDR_SIZE + pool_hdr->poolsize;
+}
 
-/* Mark the whole remaining pool as not accessable */
-#define TC_INVALIDATE_FILL_POOL(_pool_tc) do { \
-       if (unlikely(talloc_fill.enabled)) { \
-               size_t _flen = TC_POOL_SPACE_LEFT(_pool_tc); \
-               char *_fptr = (char *)(_pool_tc)->pool; \
-               memset(_fptr, talloc_fill.fill_value, _flen); \
-       } \
-} while(0)
+static inline size_t tc_pool_space_left(struct talloc_pool_hdr *pool_hdr)
+{
+       return (char *)tc_pool_end(pool_hdr) - (char *)pool_hdr->end;
+}
 
-#if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_NOACCESS)
-/* Mark the whole remaining pool as not accessable */
-#define TC_INVALIDATE_VALGRIND_POOL(_pool_tc) do { \
-       size_t _flen = TC_POOL_SPACE_LEFT(_pool_tc); \
-       char *_fptr = (char *)(_pool_tc)->pool; \
-       VALGRIND_MAKE_MEM_NOACCESS(_fptr, _flen); \
-} while(0)
-#else
-#define TC_INVALIDATE_VALGRIND_POOL(_pool_tc) do { } while (0)
-#endif
+/* If tc is inside a pool, this gives the next neighbour. */
+static inline void *tc_next_chunk(struct talloc_chunk *tc)
+{
+       return (char *)tc + TC_ALIGN16(TC_HDR_SIZE + tc->size);
+}
 
-#define TC_INVALIDATE_POOL(_pool_tc) do { \
-       TC_INVALIDATE_FILL_POOL(_pool_tc); \
-       TC_INVALIDATE_VALGRIND_POOL(_pool_tc); \
-} while (0)
+static inline void *tc_pool_first_chunk(struct talloc_pool_hdr *pool_hdr)
+{
+       struct talloc_chunk *tc = talloc_chunk_from_pool(pool_hdr);
+       return tc_next_chunk(tc);
+}
 
-static unsigned int *talloc_pool_objectcount(struct talloc_chunk *tc)
+/* Mark the whole remaining pool as not accessable */
+static inline void tc_invalidate_pool(struct talloc_pool_hdr *pool_hdr)
 {
-       return (unsigned int *)((char *)tc + TC_HDR_SIZE);
+       size_t flen = tc_pool_space_left(pool_hdr);
+
+       if (unlikely(talloc_fill.enabled)) {
+               memset(pool_hdr->end, talloc_fill.fill_value, flen);
+       }
+
+#if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_NOACCESS)
+       VALGRIND_MAKE_MEM_NOACCESS(pool_hdr->end, flen);
+#endif
 }
 
 /*
   Allocate from a pool
 */
 
-static struct talloc_chunk *talloc_alloc_pool(struct talloc_chunk *parent,
-                                             size_t size)
+static inline struct talloc_chunk *tc_alloc_pool(struct talloc_chunk *parent,
+                                                    size_t size, size_t prefix_len)
 {
-       struct talloc_chunk *pool_ctx = NULL;
+       struct talloc_pool_hdr *pool_hdr = NULL;
        size_t space_left;
        struct talloc_chunk *result;
        size_t chunk_size;
@@ -499,49 +612,55 @@ static struct talloc_chunk *talloc_alloc_pool(struct talloc_chunk *parent,
        }
 
        if (parent->flags & TALLOC_FLAG_POOL) {
-               pool_ctx = parent;
+               pool_hdr = talloc_pool_from_chunk(parent);
        }
        else if (parent->flags & TALLOC_FLAG_POOLMEM) {
-               pool_ctx = (struct talloc_chunk *)parent->pool;
+               pool_hdr = parent->pool;
        }
 
-       if (pool_ctx == NULL) {
+       if (pool_hdr == NULL) {
                return NULL;
        }
 
-       space_left = TC_POOL_SPACE_LEFT(pool_ctx);
+       space_left = tc_pool_space_left(pool_hdr);
 
        /*
         * Align size to 16 bytes
         */
-       chunk_size = TC_ALIGN16(size);
+       chunk_size = TC_ALIGN16(size + prefix_len);
 
        if (space_left < chunk_size) {
                return NULL;
        }
 
-       result = (struct talloc_chunk *)pool_ctx->pool;
+       result = (struct talloc_chunk *)((char *)pool_hdr->end + prefix_len);
 
 #if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_UNDEFINED)
-       VALGRIND_MAKE_MEM_UNDEFINED(result, size);
+       VALGRIND_MAKE_MEM_UNDEFINED(pool_hdr->end, chunk_size);
 #endif
 
-       pool_ctx->pool = (void *)((char *)result + chunk_size);
+       pool_hdr->end = (void *)((char *)pool_hdr->end + chunk_size);
 
-       result->flags = TALLOC_MAGIC | TALLOC_FLAG_POOLMEM;
-       result->pool = pool_ctx;
+       result->flags = talloc_magic | TALLOC_FLAG_POOLMEM;
+       result->pool = pool_hdr;
 
-       *talloc_pool_objectcount(pool_ctx) += 1;
+       pool_hdr->object_count++;
 
        return result;
 }
 
-/* 
+/*
    Allocate a bit of memory as a child of an existing pointer
 */
-static inline void *__talloc(const void *context, size_t size)
+static inline void *__talloc_with_prefix(const void *context,
+                                       size_t size,
+                                       size_t prefix_len,
+                                       struct talloc_chunk **tc_ret)
 {
        struct talloc_chunk *tc = NULL;
+       struct talloc_memlimit *limit = NULL;
+       size_t total_len = TC_HDR_SIZE + size + prefix_len;
+       struct talloc_chunk *parent = NULL;
 
        if (unlikely(context == NULL)) {
                context = null_context;
@@ -551,27 +670,50 @@ static inline void *__talloc(const void *context, size_t size)
                return NULL;
        }
 
-       if (context != NULL) {
-               tc = talloc_alloc_pool(talloc_chunk_from_ptr(context),
-                                      TC_HDR_SIZE+size);
+       if (unlikely(total_len < TC_HDR_SIZE)) {
+               return NULL;
+       }
+
+       if (likely(context != NULL)) {
+               parent = talloc_chunk_from_ptr(context);
+
+               if (parent->limit != NULL) {
+                       limit = parent->limit;
+               }
+
+               tc = tc_alloc_pool(parent, TC_HDR_SIZE+size, prefix_len);
        }
 
        if (tc == NULL) {
-               tc = (struct talloc_chunk *)malloc(TC_HDR_SIZE+size);
-               if (unlikely(tc == NULL)) return NULL;
-               tc->flags = TALLOC_MAGIC;
+               char *ptr;
+
+               /*
+                * Only do the memlimit check/update on actual allocation.
+                */
+               if (!talloc_memlimit_check(limit, total_len)) {
+                       errno = ENOMEM;
+                       return NULL;
+               }
+
+               ptr = malloc(total_len);
+               if (unlikely(ptr == NULL)) {
+                       return NULL;
+               }
+               tc = (struct talloc_chunk *)(ptr + prefix_len);
+               tc->flags = talloc_magic;
                tc->pool  = NULL;
+
+               talloc_memlimit_grow(limit, total_len);
        }
 
+       tc->limit = limit;
        tc->size = size;
        tc->destructor = NULL;
        tc->child = NULL;
        tc->name = NULL;
        tc->refs = NULL;
 
-       if (likely(context)) {
-               struct talloc_chunk *parent = talloc_chunk_from_ptr(context);
-
+       if (likely(context != NULL)) {
                if (parent->child) {
                        parent->child->parent = NULL;
                        tc->next = parent->child;
@@ -586,34 +728,118 @@ static inline void *__talloc(const void *context, size_t size)
                tc->next = tc->prev = tc->parent = NULL;
        }
 
+       *tc_ret = tc;
        return TC_PTR_FROM_CHUNK(tc);
 }
 
+static inline void *__talloc(const void *context,
+                       size_t size,
+                       struct talloc_chunk **tc)
+{
+       return __talloc_with_prefix(context, size, 0, tc);
+}
+
 /*
  * Create a talloc pool
  */
 
-_PUBLIC_ void *talloc_pool(const void *context, size_t size)
+static inline void *_talloc_pool(const void *context, size_t size)
 {
-       void *result = __talloc(context, size + TALLOC_POOL_HDR_SIZE);
        struct talloc_chunk *tc;
+       struct talloc_pool_hdr *pool_hdr;
+       void *result;
+
+       result = __talloc_with_prefix(context, size, TP_HDR_SIZE, &tc);
 
        if (unlikely(result == NULL)) {
                return NULL;
        }
 
-       tc = talloc_chunk_from_ptr(result);
+       pool_hdr = talloc_pool_from_chunk(tc);
 
        tc->flags |= TALLOC_FLAG_POOL;
-       tc->pool = TC_POOL_FIRST_CHUNK(tc);
+       tc->size = 0;
 
-       *talloc_pool_objectcount(tc) = 1;
+       pool_hdr->object_count = 1;
+       pool_hdr->end = result;
+       pool_hdr->poolsize = size;
 
-       TC_INVALIDATE_POOL(tc);
+       tc_invalidate_pool(pool_hdr);
 
        return result;
 }
 
+_PUBLIC_ void *talloc_pool(const void *context, size_t size)
+{
+       return _talloc_pool(context, size);
+}
+
+/*
+ * Create a talloc pool correctly sized for a basic size plus
+ * a number of subobjects whose total size is given. Essentially
+ * a custom allocator for talloc to reduce fragmentation.
+ */
+
+_PUBLIC_ void *_talloc_pooled_object(const void *ctx,
+                                    size_t type_size,
+                                    const char *type_name,
+                                    unsigned num_subobjects,
+                                    size_t total_subobjects_size)
+{
+       size_t poolsize, subobjects_slack, tmp;
+       struct talloc_chunk *tc;
+       struct talloc_pool_hdr *pool_hdr;
+       void *ret;
+
+       poolsize = type_size + total_subobjects_size;
+
+       if ((poolsize < type_size) || (poolsize < total_subobjects_size)) {
+               goto overflow;
+       }
+
+       if (num_subobjects == UINT_MAX) {
+               goto overflow;
+       }
+       num_subobjects += 1;       /* the object body itself */
+
+       /*
+        * Alignment can increase the pool size by at most 15 bytes per object
+        * plus alignment for the object itself
+        */
+       subobjects_slack = (TC_HDR_SIZE + TP_HDR_SIZE + 15) * num_subobjects;
+       if (subobjects_slack < num_subobjects) {
+               goto overflow;
+       }
+
+       tmp = poolsize + subobjects_slack;
+       if ((tmp < poolsize) || (tmp < subobjects_slack)) {
+               goto overflow;
+       }
+       poolsize = tmp;
+
+       ret = _talloc_pool(ctx, poolsize);
+       if (ret == NULL) {
+               return NULL;
+       }
+
+       tc = talloc_chunk_from_ptr(ret);
+       tc->size = type_size;
+
+       pool_hdr = talloc_pool_from_chunk(tc);
+
+#if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_UNDEFINED)
+       VALGRIND_MAKE_MEM_UNDEFINED(pool_hdr->end, type_size);
+#endif
+
+       pool_hdr->end = ((char *)pool_hdr->end + TC_ALIGN16(type_size));
+
+       _tc_set_name_const(tc, type_name);
+       return ret;
+
+overflow:
+       return NULL;
+}
+
 /*
   setup a destructor to be called on free of a pointer
   the destructor should return 0 on success, or -1 on failure.
@@ -627,7 +853,7 @@ _PUBLIC_ void _talloc_set_destructor(const void *ptr, int (*destructor)(void *))
 }
 
 /*
-  increase the reference count on a piece of memory. 
+  increase the reference count on a piece of memory.
 */
 _PUBLIC_ int talloc_increase_ref_count(const void *ptr)
 {
@@ -650,12 +876,12 @@ static int talloc_reference_destructor(struct talloc_reference_handle *handle)
 }
 
 /*
-   more efficient way to add a name to a pointer - the name must point to a 
+   more efficient way to add a name to a pointer - the name must point to a
    true string constant
 */
-static inline void _talloc_set_name_const(const void *ptr, const char *name)
+static inline void _tc_set_name_const(struct talloc_chunk *tc,
+                                       const char *name)
 {
-       struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
        tc->name = name;
 }
 
@@ -665,13 +891,14 @@ static inline void _talloc_set_name_const(const void *ptr, const char *name)
 static inline void *_talloc_named_const(const void *context, size_t size, const char *name)
 {
        void *ptr;
+       struct talloc_chunk *tc;
 
-       ptr = __talloc(context, size);
+       ptr = __talloc(context, size, &tc);
        if (unlikely(ptr == NULL)) {
                return NULL;
        }
 
-       _talloc_set_name_const(ptr, name);
+       _tc_set_name_const(tc, name);
 
        return ptr;
 }
@@ -680,8 +907,8 @@ static inline void *_talloc_named_const(const void *context, size_t size, const
   make a secondary reference to a pointer, hanging off the given context.
   the pointer remains valid until both the original caller and this given
   context are freed.
-  
-  the major use for this is when two different structures need to reference the 
+
+  the major use for this is when two different structures need to reference the
   same underlying data, and you want to be able to free the two instances separately,
   and in either order
 */
@@ -709,15 +936,16 @@ _PUBLIC_ void *_talloc_reference_loc(const void *context, const void *ptr, const
 
 static void *_talloc_steal_internal(const void *new_ctx, const void *ptr);
 
-static inline void _talloc_free_poolmem(struct talloc_chunk *tc,
+static inline void _tc_free_poolmem(struct talloc_chunk *tc,
                                        const char *location)
 {
-       struct talloc_chunk *pool;
+       struct talloc_pool_hdr *pool;
+       struct talloc_chunk *pool_tc;
        void *next_tc;
-       unsigned int *pool_object_count;
 
-       pool = (struct talloc_chunk *)tc->pool;
-       next_tc = TC_POOLMEM_NEXT_CHUNK(tc);
+       pool = tc->pool;
+       pool_tc = talloc_chunk_from_pool(pool);
+       next_tc = tc_next_chunk(tc);
 
        tc->flags |= TALLOC_FLAG_FREE;
 
@@ -729,16 +957,15 @@ static inline void _talloc_free_poolmem(struct talloc_chunk *tc,
 
        TC_INVALIDATE_FULL_CHUNK(tc);
 
-       pool_object_count = talloc_pool_objectcount(pool);
-
-       if (unlikely(*pool_object_count == 0)) {
+       if (unlikely(pool->object_count == 0)) {
                talloc_abort("Pool object count zero!");
                return;
        }
 
-       *pool_object_count -= 1;
+       pool->object_count--;
 
-       if (unlikely(*pool_object_count == 1 && !(pool->flags & TALLOC_FLAG_FREE))) {
+       if (unlikely(pool->object_count == 1
+                    && !(pool_tc->flags & TALLOC_FLAG_FREE))) {
                /*
                 * if there is just one object left in the pool
                 * and pool->flags does not have TALLOC_FLAG_FREE,
@@ -746,50 +973,65 @@ static inline void _talloc_free_poolmem(struct talloc_chunk *tc,
                 * the rest is available for new objects
                 * again.
                 */
-               pool->pool = TC_POOL_FIRST_CHUNK(pool);
-               TC_INVALIDATE_POOL(pool);
-       } else if (unlikely(*pool_object_count == 0)) {
+               pool->end = tc_pool_first_chunk(pool);
+               tc_invalidate_pool(pool);
+               return;
+       }
+
+       if (unlikely(pool->object_count == 0)) {
                /*
                 * we mark the freed memory with where we called the free
                 * from. This means on a double free error we can report where
                 * the first free came from
                 */
-               pool->name = location;
+               pool_tc->name = location;
+
+               if (pool_tc->flags & TALLOC_FLAG_POOLMEM) {
+                       _tc_free_poolmem(pool_tc, location);
+               } else {
+                       /*
+                        * The tc_memlimit_update_on_free()
+                        * call takes into account the
+                        * prefix TP_HDR_SIZE allocated before
+                        * the pool talloc_chunk.
+                        */
+                       tc_memlimit_update_on_free(pool_tc);
+                       TC_INVALIDATE_FULL_CHUNK(pool_tc);
+                       free(pool);
+               }
+               return;
+       }
 
-               TC_INVALIDATE_FULL_CHUNK(pool);
-               free(pool);
-       } else if (pool->pool == next_tc) {
+       if (pool->end == next_tc) {
                /*
                 * if pool->pool still points to end of
                 * 'tc' (which is stored in the 'next_tc' variable),
                 * we can reclaim the memory of 'tc'.
                 */
-               pool->pool = tc;
+               pool->end = tc;
+               return;
        }
-}
 
-/* 
-   internal talloc_free call
-*/
-static inline int _talloc_free_internal(void *ptr, const char *location)
-{
-       struct talloc_chunk *tc;
+       /*
+        * Do nothing. The memory is just "wasted", waiting for the pool
+        * itself to be freed.
+        */
+}
 
-       if (unlikely(ptr == NULL)) {
-               return -1;
-       }
+static inline void _tc_free_children_internal(struct talloc_chunk *tc,
+                                                 void *ptr,
+                                                 const char *location);
 
-       /* possibly initialised the talloc fill value */
-       if (unlikely(!talloc_fill.initialised)) {
-               const char *fill = getenv(TALLOC_FILL_ENV);
-               if (fill != NULL) {
-                       talloc_fill.enabled = true;
-                       talloc_fill.fill_value = strtoul(fill, NULL, 0);
-               }
-               talloc_fill.initialised = true;
-       }
+static inline int _talloc_free_internal(void *ptr, const char *location);
 
-       tc = talloc_chunk_from_ptr(ptr);
+/*
+   internal free call that takes a struct talloc_chunk *.
+*/
+static inline int _tc_free_internal(struct talloc_chunk *tc,
+                               const char *location)
+{
+       void *ptr_to_free;
+       void *ptr = TC_PTR_FROM_CHUNK(tc);
 
        if (unlikely(tc->refs)) {
                int is_child;
@@ -815,12 +1057,32 @@ static inline int _talloc_free_internal(void *ptr, const char *location)
 
        if (unlikely(tc->destructor)) {
                talloc_destructor_t d = tc->destructor;
+
+               /*
+                * Protect the destructor against some overwrite
+                * attacks, by explicitly checking it has the right
+                * magic here.
+                */
+               if (talloc_chunk_from_ptr(ptr) != tc) {
+                       /*
+                        * This can't actually happen, the
+                        * call itself will panic.
+                        */
+                       TALLOC_ABORT("talloc_chunk_from_ptr failed!");
+               }
+
                if (d == (talloc_destructor_t)-1) {
                        return -1;
                }
                tc->destructor = (talloc_destructor_t)-1;
                if (d(ptr) == -1) {
-                       tc->destructor = d;
+                       /*
+                        * Only replace the destructor pointer if
+                        * calling the destructor didn't modify it.
+                        */
+                       if (tc->destructor == (talloc_destructor_t)-1) {
+                               tc->destructor = d;
+                       }
                        return -1;
                }
                tc->destructor = NULL;
@@ -834,80 +1096,89 @@ static inline int _talloc_free_internal(void *ptr, const char *location)
        } else {
                if (tc->prev) tc->prev->next = tc->next;
                if (tc->next) tc->next->prev = tc->prev;
+               tc->prev = tc->next = NULL;
        }
 
        tc->flags |= TALLOC_FLAG_LOOP;
 
-       while (tc->child) {
-               /* we need to work out who will own an abandoned child
-                  if it cannot be freed. In priority order, the first
-                  choice is owner of any remaining reference to this
-                  pointer, the second choice is our parent, and the
-                  final choice is the null context. */
-               void *child = TC_PTR_FROM_CHUNK(tc->child);
-               const void *new_parent = null_context;
-               struct talloc_chunk *old_parent = NULL;
-               if (unlikely(tc->child->refs)) {
-                       struct talloc_chunk *p = talloc_parent_chunk(tc->child->refs);
-                       if (p) new_parent = TC_PTR_FROM_CHUNK(p);
-               }
-               /* finding the parent here is potentially quite
-                  expensive, but the alternative, which is to change
-                  talloc to always have a valid tc->parent pointer,
-                  makes realloc more expensive where there are a
-                  large number of children.
-
-                  The reason we need the parent pointer here is that
-                  if _talloc_free_internal() fails due to references
-                  or a failing destructor we need to re-parent, but
-                  the free call can invalidate the prev pointer.
-               */
-               if (new_parent == null_context && (tc->child->refs || tc->child->destructor)) {
-                       old_parent = talloc_parent_chunk(ptr);
-               }
-               if (unlikely(_talloc_free_internal(child, location) == -1)) {
-                       if (new_parent == null_context) {
-                               struct talloc_chunk *p = old_parent;
-                               if (p) new_parent = TC_PTR_FROM_CHUNK(p);
-                       }
-                       _talloc_steal_internal(new_parent, child);
-               }
-       }
+       _tc_free_children_internal(tc, ptr, location);
 
        tc->flags |= TALLOC_FLAG_FREE;
 
        /* we mark the freed memory with where we called the free
         * from. This means on a double free error we can report where
-        * the first free came from 
-        */      
+        * the first free came from
+        */
        tc->name = location;
 
        if (tc->flags & TALLOC_FLAG_POOL) {
-               unsigned int *pool_object_count;
+               struct talloc_pool_hdr *pool;
 
-               pool_object_count = talloc_pool_objectcount(tc);
+               pool = talloc_pool_from_chunk(tc);
 
-               if (unlikely(*pool_object_count == 0)) {
+               if (unlikely(pool->object_count == 0)) {
                        talloc_abort("Pool object count zero!");
                        return 0;
                }
 
-               *pool_object_count -= 1;
+               pool->object_count--;
 
-               if (unlikely(*pool_object_count == 0)) {
-                       TC_INVALIDATE_FULL_CHUNK(tc);
-                       free(tc);
+               if (likely(pool->object_count != 0)) {
+                       return 0;
                }
-       } else if (tc->flags & TALLOC_FLAG_POOLMEM) {
-               _talloc_free_poolmem(tc, location);
+
+               /*
+                * With object_count==0, a pool becomes a normal piece of
+                * memory to free. If it's allocated inside a pool, it needs
+                * to be freed as poolmem, else it needs to be just freed.
+               */
+               ptr_to_free = pool;
        } else {
-               TC_INVALIDATE_FULL_CHUNK(tc);
-               free(tc);
+               ptr_to_free = tc;
        }
+
+       if (tc->flags & TALLOC_FLAG_POOLMEM) {
+               _tc_free_poolmem(tc, location);
+               return 0;
+       }
+
+       tc_memlimit_update_on_free(tc);
+
+       TC_INVALIDATE_FULL_CHUNK(tc);
+       free(ptr_to_free);
        return 0;
 }
 
-/* 
+/*
+   internal talloc_free call
+*/
+static inline int _talloc_free_internal(void *ptr, const char *location)
+{
+       struct talloc_chunk *tc;
+
+       if (unlikely(ptr == NULL)) {
+               return -1;
+       }
+
+       /* possibly initialised the talloc fill value */
+       if (unlikely(!talloc_fill.initialised)) {
+               const char *fill = getenv(TALLOC_FILL_ENV);
+               if (fill != NULL) {
+                       talloc_fill.enabled = true;
+                       talloc_fill.fill_value = strtoul(fill, NULL, 0);
+               }
+               talloc_fill.initialised = true;
+       }
+
+       tc = talloc_chunk_from_ptr(ptr);
+       return _tc_free_internal(tc, location);
+}
+
+static inline size_t _talloc_total_limit_size(const void *ptr,
+                                       struct talloc_memlimit *old_limit,
+                                       struct talloc_memlimit *new_limit);
+
+/*
    move a lump of memory from one talloc context to another return the
    ptr on success, or NULL if it could not be transferred.
    passing NULL as ptr will always return NULL with no side effects.
@@ -915,6 +1186,7 @@ static inline int _talloc_free_internal(void *ptr, const char *location)
 static void *_talloc_steal_internal(const void *new_ctx, const void *ptr)
 {
        struct talloc_chunk *tc, *new_tc;
+       size_t ctx_size = 0;
 
        if (unlikely(!ptr)) {
                return NULL;
@@ -926,6 +1198,20 @@ static void *_talloc_steal_internal(const void *new_ctx, const void *ptr)
 
        tc = talloc_chunk_from_ptr(ptr);
 
+       if (tc->limit != NULL) {
+
+               ctx_size = _talloc_total_limit_size(ptr, NULL, NULL);
+
+               /* Decrement the memory limit from the source .. */
+               talloc_memlimit_shrink(tc->limit->upper, ctx_size);
+
+               if (tc->limit->parent == tc) {
+                       tc->limit->upper = NULL;
+               } else {
+                       tc->limit = NULL;
+               }
+       }
+
        if (unlikely(new_ctx == NULL)) {
                if (tc->parent) {
                        _TLIST_REMOVE(tc->parent->child, tc);
@@ -936,7 +1222,7 @@ static void *_talloc_steal_internal(const void *new_ctx, const void *ptr)
                        if (tc->prev) tc->prev->next = tc->next;
                        if (tc->next) tc->next->prev = tc->prev;
                }
-               
+
                tc->parent = tc->next = tc->prev = NULL;
                return discard_const_p(void, ptr);
        }
@@ -955,16 +1241,26 @@ static void *_talloc_steal_internal(const void *new_ctx, const void *ptr)
        } else {
                if (tc->prev) tc->prev->next = tc->next;
                if (tc->next) tc->next->prev = tc->prev;
+               tc->prev = tc->next = NULL;
        }
 
        tc->parent = new_tc;
        if (new_tc->child) new_tc->child->parent = NULL;
        _TLIST_ADD(new_tc->child, tc);
 
+       if (tc->limit || new_tc->limit) {
+               ctx_size = _talloc_total_limit_size(ptr, tc->limit,
+                                                   new_tc->limit);
+               /* .. and increment it in the destination. */
+               if (new_tc->limit) {
+                       talloc_memlimit_grow(new_tc->limit, ctx_size);
+               }
+       }
+
        return discard_const_p(void, ptr);
 }
 
-/* 
+/*
    move a lump of memory from one talloc context to another return the
    ptr on success, or NULL if it could not be transferred.
    passing NULL as ptr will always return NULL with no side effects.
@@ -976,9 +1272,9 @@ _PUBLIC_ void *_talloc_steal_loc(const void *new_ctx, const void *ptr, const cha
        if (unlikely(ptr == NULL)) {
                return NULL;
        }
-       
+
        tc = talloc_chunk_from_ptr(ptr);
-       
+
        if (unlikely(tc->refs != NULL) && talloc_parent(ptr) != new_ctx) {
                struct talloc_reference_handle *h;
 
@@ -998,11 +1294,11 @@ _PUBLIC_ void *_talloc_steal_loc(const void *new_ctx, const void *ptr, const cha
                talloc_log("WARNING: stealing into talloc child at %s\n", location);
        }
 #endif
-       
+
        return _talloc_steal_internal(new_ctx, ptr);
 }
 
-/* 
+/*
    this is like a talloc_steal(), but you must supply the old
    parent. This resolves the ambiguity in a talloc_steal() which is
    called on a context that has more than one parent (via references)
@@ -1030,7 +1326,7 @@ _PUBLIC_ void *talloc_reparent(const void *old_parent, const void *new_parent, c
                        }
                        return discard_const_p(void, ptr);
                }
-       }       
+       }
 
        /* it wasn't a parent */
        return NULL;
@@ -1067,11 +1363,11 @@ static inline int talloc_unreference(const void *context, const void *ptr)
 
 /*
   remove a specific parent context from a pointer. This is a more
-  controlled varient of talloc_free()
+  controlled variant of talloc_free()
 */
 _PUBLIC_ int talloc_unlink(const void *context, void *ptr)
 {
-       struct talloc_chunk *tc_p, *new_p;
+       struct talloc_chunk *tc_p, *new_p, *tc_c;
        void *new_parent;
 
        if (ptr == NULL) {
@@ -1086,16 +1382,15 @@ _PUBLIC_ int talloc_unlink(const void *context, void *ptr)
                return 0;
        }
 
-       if (context == NULL) {
-               if (talloc_parent_chunk(ptr) != NULL) {
-                       return -1;
-               }
+       if (context != NULL) {
+               tc_c = talloc_chunk_from_ptr(context);
        } else {
-               if (talloc_chunk_from_ptr(context) != talloc_parent_chunk(ptr)) {
-                       return -1;
-               }
+               tc_c = NULL;
+       }
+       if (tc_c != talloc_parent_chunk(ptr)) {
+               return -1;
        }
-       
+
        tc_p = talloc_chunk_from_ptr(ptr);
 
        if (tc_p->refs == NULL) {
@@ -1121,14 +1416,22 @@ _PUBLIC_ int talloc_unlink(const void *context, void *ptr)
 /*
   add a name to an existing pointer - va_list version
 */
-static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(2,0);
-
-static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va_list ap)
-{
-       struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
-       tc->name = talloc_vasprintf(ptr, fmt, ap);
-       if (likely(tc->name)) {
-               _talloc_set_name_const(tc->name, ".name");
+static inline const char *tc_set_name_v(struct talloc_chunk *tc,
+                               const char *fmt,
+                               va_list ap) PRINTF_ATTRIBUTE(2,0);
+
+static inline const char *tc_set_name_v(struct talloc_chunk *tc,
+                               const char *fmt,
+                               va_list ap)
+{
+       struct talloc_chunk *name_tc = _vasprintf_tc(TC_PTR_FROM_CHUNK(tc),
+                                                       fmt,
+                                                       ap);
+       if (likely(name_tc)) {
+               tc->name = TC_PTR_FROM_CHUNK(name_tc);
+               _tc_set_name_const(name_tc, ".name");
+       } else {
+               tc->name = NULL;
        }
        return tc->name;
 }
@@ -1138,10 +1441,11 @@ static inline const char *talloc_set_name_v(const void *ptr, const char *fmt, va
 */
 _PUBLIC_ const char *talloc_set_name(const void *ptr, const char *fmt, ...)
 {
+       struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
        const char *name;
        va_list ap;
        va_start(ap, fmt);
-       name = talloc_set_name_v(ptr, fmt, ap);
+       name = tc_set_name_v(tc, fmt, ap);
        va_end(ap);
        return name;
 }
@@ -1157,12 +1461,13 @@ _PUBLIC_ void *talloc_named(const void *context, size_t size, const char *fmt, .
        va_list ap;
        void *ptr;
        const char *name;
+       struct talloc_chunk *tc;
 
-       ptr = __talloc(context, size);
+       ptr = __talloc(context, size, &tc);
        if (unlikely(ptr == NULL)) return NULL;
 
        va_start(ap, fmt);
-       name = talloc_set_name_v(ptr, fmt, ap);
+       name = tc_set_name_v(tc, fmt, ap);
        va_end(ap);
 
        if (unlikely(name == NULL)) {
@@ -1176,7 +1481,7 @@ _PUBLIC_ void *talloc_named(const void *context, size_t size, const char *fmt, .
 /*
   return the name of a talloc ptr, or "UNNAMED"
 */
-_PUBLIC_ const char *talloc_get_name(const void *ptr)
+static inline const char *__talloc_get_name(const void *ptr)
 {
        struct talloc_chunk *tc = talloc_chunk_from_ptr(ptr);
        if (unlikely(tc->name == TALLOC_MAGIC_REFERENCE)) {
@@ -1188,6 +1493,10 @@ _PUBLIC_ const char *talloc_get_name(const void *ptr)
        return "UNNAMED";
 }
 
+_PUBLIC_ const char *talloc_get_name(const void *ptr)
+{
+       return __talloc_get_name(ptr);
+}
 
 /*
   check if a pointer has the given name. If it does, return the pointer,
@@ -1197,14 +1506,14 @@ _PUBLIC_ void *talloc_check_name(const void *ptr, const char *name)
 {
        const char *pname;
        if (unlikely(ptr == NULL)) return NULL;
-       pname = talloc_get_name(ptr);
+       pname = __talloc_get_name(ptr);
        if (likely(pname == name || strcmp(pname, name) == 0)) {
                return discard_const_p(void, ptr);
        }
        return NULL;
 }
 
-static void talloc_abort_type_missmatch(const char *location,
+static void talloc_abort_type_mismatch(const char *location,
                                        const char *name,
                                        const char *expected)
 {
@@ -1227,16 +1536,16 @@ _PUBLIC_ void *_talloc_get_type_abort(const void *ptr, const char *name, const c
        const char *pname;
 
        if (unlikely(ptr == NULL)) {
-               talloc_abort_type_missmatch(location, NULL, name);
+               talloc_abort_type_mismatch(location, NULL, name);
                return NULL;
        }
 
-       pname = talloc_get_name(ptr);
+       pname = __talloc_get_name(ptr);
        if (likely(pname == name || strcmp(pname, name) == 0)) {
                return discard_const_p(void, ptr);
        }
 
-       talloc_abort_type_missmatch(location, pname, name);
+       talloc_abort_type_mismatch(location, pname, name);
        return NULL;
 }
 
@@ -1248,12 +1557,13 @@ _PUBLIC_ void *talloc_init(const char *fmt, ...)
        va_list ap;
        void *ptr;
        const char *name;
+       struct talloc_chunk *tc;
 
-       ptr = __talloc(NULL, 0);
+       ptr = __talloc(NULL, 0, &tc);
        if (unlikely(ptr == NULL)) return NULL;
 
        va_start(ap, fmt);
-       name = talloc_set_name_v(ptr, fmt, ap);
+       name = tc_set_name_v(tc, fmt, ap);
        va_end(ap);
 
        if (unlikely(name == NULL)) {
@@ -1264,21 +1574,10 @@ _PUBLIC_ void *talloc_init(const char *fmt, ...)
        return ptr;
 }
 
-/*
-  this is a replacement for the Samba3 talloc_destroy_pool functionality. It
-  should probably not be used in new code. It's in here to keep the talloc
-  code consistent across Samba 3 and 4.
-*/
-_PUBLIC_ void talloc_free_children(void *ptr)
+static inline void _tc_free_children_internal(struct talloc_chunk *tc,
+                                                 void *ptr,
+                                                 const char *location)
 {
-       struct talloc_chunk *tc;
-
-       if (unlikely(ptr == NULL)) {
-               return;
-       }
-
-       tc = talloc_chunk_from_ptr(ptr);
-
        while (tc->child) {
                /* we need to work out who will own an abandoned child
                   if it cannot be freed. In priority order, the first
@@ -1291,7 +1590,14 @@ _PUBLIC_ void talloc_free_children(void *ptr)
                        struct talloc_chunk *p = talloc_parent_chunk(tc->child->refs);
                        if (p) new_parent = TC_PTR_FROM_CHUNK(p);
                }
-               if (unlikely(talloc_free(child) == -1)) {
+               if (unlikely(_tc_free_internal(tc->child, location) == -1)) {
+                       if (talloc_parent_chunk(child) != tc) {
+                               /*
+                                * Destructor already reparented this child.
+                                * No further reparenting needed.
+                                */
+                               continue;
+                       }
                        if (new_parent == null_context) {
                                struct talloc_chunk *p = talloc_parent_chunk(ptr);
                                if (p) new_parent = TC_PTR_FROM_CHUNK(p);
@@ -1301,12 +1607,54 @@ _PUBLIC_ void talloc_free_children(void *ptr)
        }
 }
 
-/* 
+/*
+  this is a replacement for the Samba3 talloc_destroy_pool functionality. It
+  should probably not be used in new code. It's in here to keep the talloc
+  code consistent across Samba 3 and 4.
+*/
+_PUBLIC_ void talloc_free_children(void *ptr)
+{
+       struct talloc_chunk *tc_name = NULL;
+       struct talloc_chunk *tc;
+
+       if (unlikely(ptr == NULL)) {
+               return;
+       }
+
+       tc = talloc_chunk_from_ptr(ptr);
+
+       /* we do not want to free the context name if it is a child .. */
+       if (likely(tc->child)) {
+               for (tc_name = tc->child; tc_name; tc_name = tc_name->next) {
+                       if (tc->name == TC_PTR_FROM_CHUNK(tc_name)) break;
+               }
+               if (tc_name) {
+                       _TLIST_REMOVE(tc->child, tc_name);
+                       if (tc->child) {
+                               tc->child->parent = tc;
+                       }
+               }
+       }
+
+       _tc_free_children_internal(tc, ptr, __location__);
+
+       /* .. so we put it back after all other children have been freed */
+       if (tc_name) {
+               if (tc->child) {
+                       tc->child->parent = NULL;
+               }
+               tc_name->parent = tc;
+               _TLIST_ADD(tc->child, tc_name);
+       }
+}
+
+/*
    Allocate a bit of memory as a child of an existing pointer
 */
 _PUBLIC_ void *_talloc(const void *context, size_t size)
 {
-       return __talloc(context, size);
+       struct talloc_chunk *tc;
+       return __talloc(context, size, &tc);
 }
 
 /*
@@ -1314,7 +1662,7 @@ _PUBLIC_ void *_talloc(const void *context, size_t size)
 */
 _PUBLIC_ void talloc_set_name_const(const void *ptr, const char *name)
 {
-       _talloc_set_name_const(ptr, name);
+       _tc_set_name_const(talloc_chunk_from_ptr(ptr), name);
 }
 
 /*
@@ -1327,8 +1675,8 @@ _PUBLIC_ void *talloc_named_const(const void *context, size_t size, const char *
        return _talloc_named_const(context, size, name);
 }
 
-/* 
-   free a talloc pointer. This also frees all child pointers of this 
+/*
+   free a talloc pointer. This also frees all child pointers of this
    pointer recursively
 
    return 0 if the memory is actually freed, otherwise -1. The memory
@@ -1342,9 +1690,9 @@ _PUBLIC_ int _talloc_free(void *ptr, const char *location)
        if (unlikely(ptr == NULL)) {
                return -1;
        }
-       
+
        tc = talloc_chunk_from_ptr(ptr);
-       
+
        if (unlikely(tc->refs != NULL)) {
                struct talloc_reference_handle *h;
 
@@ -1364,7 +1712,7 @@ _PUBLIC_ int _talloc_free(void *ptr, const char *location)
                }
                return -1;
        }
-       
+
        return _talloc_free_internal(ptr, location);
 }
 
@@ -1379,7 +1727,9 @@ _PUBLIC_ void *_talloc_realloc(const void *context, void *ptr, size_t size, cons
        struct talloc_chunk *tc;
        void *new_ptr;
        bool malloced = false;
-       struct talloc_chunk *pool_tc = NULL;
+       struct talloc_pool_hdr *pool_hdr = NULL;
+       size_t old_size = 0;
+       size_t new_size = 0;
 
        /* size zero is equivalent to free() */
        if (unlikely(size == 0)) {
@@ -1408,20 +1758,28 @@ _PUBLIC_ void *_talloc_realloc(const void *context, void *ptr, size_t size, cons
                return NULL;
        }
 
-       /* don't let anybody try to realloc a talloc_pool */
+       if (tc->limit && (size > tc->size)) {
+               if (!talloc_memlimit_check(tc->limit, (size - tc->size))) {
+                       errno = ENOMEM;
+                       return NULL;
+               }
+       }
+
+       /* handle realloc inside a talloc_pool */
        if (unlikely(tc->flags & TALLOC_FLAG_POOLMEM)) {
-               pool_tc = (struct talloc_chunk *)tc->pool;
+               pool_hdr = tc->pool;
        }
 
 #if (ALWAYS_REALLOC == 0)
        /* don't shrink if we have less than 1k to gain */
-       if (size < tc->size) {
-               if (pool_tc) {
-                       void *next_tc = TC_POOLMEM_NEXT_CHUNK(tc);
+       if (size < tc->size && tc->limit == NULL) {
+               if (pool_hdr) {
+                       void *next_tc = tc_next_chunk(tc);
                        TC_INVALIDATE_SHRINK_CHUNK(tc, size);
                        tc->size = size;
-                       if (next_tc == pool_tc->pool) {
-                               pool_tc->pool = TC_POOLMEM_NEXT_CHUNK(tc);
+                       if (next_tc == pool_hdr->end) {
+                               /* note: tc->size has changed, so this works */
+                               pool_hdr->end = tc_next_chunk(tc);
                        }
                        return ptr;
                } else if ((tc->size - size) < 1024) {
@@ -1452,13 +1810,14 @@ _PUBLIC_ void *_talloc_realloc(const void *context, void *ptr, size_t size, cons
        tc->flags |= TALLOC_FLAG_FREE;
 
 #if ALWAYS_REALLOC
-       if (pool_tc) {
-               new_ptr = talloc_alloc_pool(tc, size + TC_HDR_SIZE);
-               *talloc_pool_objectcount(pool_tc) -= 1;
+       if (pool_hdr) {
+               new_ptr = tc_alloc_pool(tc, size + TC_HDR_SIZE, 0);
+               pool_hdr->object_count--;
 
                if (new_ptr == NULL) {
                        new_ptr = malloc(TC_HDR_SIZE+size);
                        malloced = true;
+                       new_size = size;
                }
 
                if (new_ptr) {
@@ -1466,6 +1825,9 @@ _PUBLIC_ void *_talloc_realloc(const void *context, void *ptr, size_t size, cons
                        TC_INVALIDATE_FULL_CHUNK(tc);
                }
        } else {
+               /* We're doing malloc then free here, so record the difference. */
+               old_size = tc->size;
+               new_size = size;
                new_ptr = malloc(size + TC_HDR_SIZE);
                if (new_ptr) {
                        memcpy(new_ptr, tc, MIN(tc->size, size) + TC_HDR_SIZE);
@@ -1473,40 +1835,57 @@ _PUBLIC_ void *_talloc_realloc(const void *context, void *ptr, size_t size, cons
                }
        }
 #else
-       if (pool_tc) {
-               void *next_tc = TC_POOLMEM_NEXT_CHUNK(tc);
-               size_t old_chunk_size = TC_POOLMEM_CHUNK_SIZE(tc);
+       if (pool_hdr) {
+               struct talloc_chunk *pool_tc;
+               void *next_tc = tc_next_chunk(tc);
+               size_t old_chunk_size = TC_ALIGN16(TC_HDR_SIZE + tc->size);
                size_t new_chunk_size = TC_ALIGN16(TC_HDR_SIZE + size);
                size_t space_needed;
                size_t space_left;
+               unsigned int chunk_count = pool_hdr->object_count;
 
-               if (*talloc_pool_objectcount(pool_tc) == 2) {
+               pool_tc = talloc_chunk_from_pool(pool_hdr);
+               if (!(pool_tc->flags & TALLOC_FLAG_FREE)) {
+                       chunk_count -= 1;
+               }
+
+               if (chunk_count == 1) {
                        /*
                         * optimize for the case where 'tc' is the only
                         * chunk in the pool.
                         */
+                       char *start = tc_pool_first_chunk(pool_hdr);
                        space_needed = new_chunk_size;
-                       space_left = pool_tc->size - TALLOC_POOL_HDR_SIZE;
+                       space_left = (char *)tc_pool_end(pool_hdr) - start;
 
                        if (space_left >= space_needed) {
                                size_t old_used = TC_HDR_SIZE + tc->size;
                                size_t new_used = TC_HDR_SIZE + size;
-                               pool_tc->pool = TC_POOL_FIRST_CHUNK(pool_tc);
+                               new_ptr = start;
+
 #if defined(DEVELOPER) && defined(VALGRIND_MAKE_MEM_UNDEFINED)
-                               /*
-                                * we need to prepare the memmove into
-                                * the unaccessable area.
-                                */
                                {
-                                       size_t diff = PTR_DIFF(tc, pool_tc->pool);
-                                       size_t flen = MIN(diff, old_used);
-                                       char *fptr = (char *)pool_tc->pool;
-                                       VALGRIND_MAKE_MEM_UNDEFINED(fptr, flen);
+                                       /*
+                                        * The area from
+                                        * start -> tc may have
+                                        * been freed and thus been marked as
+                                        * VALGRIND_MEM_NOACCESS. Set it to
+                                        * VALGRIND_MEM_UNDEFINED so we can
+                                        * copy into it without valgrind errors.
+                                        * We can't just mark
+                                        * new_ptr -> new_ptr + old_used
+                                        * as this may overlap on top of tc,
+                                        * (which is why we use memmove, not
+                                        * memcpy below) hence the MIN.
+                                        */
+                                       size_t undef_len = MIN((((char *)tc) - ((char *)new_ptr)),old_used);
+                                       VALGRIND_MAKE_MEM_UNDEFINED(new_ptr, undef_len);
                                }
 #endif
-                               memmove(pool_tc->pool, tc, old_used);
-                               new_ptr = pool_tc->pool;
 
+                               memmove(new_ptr, tc, old_used);
+
+                               tc = (struct talloc_chunk *)new_ptr;
                                TC_UNDEFINE_GROW_CHUNK(tc, size);
 
                                /*
@@ -1514,11 +1893,11 @@ _PUBLIC_ void *_talloc_realloc(const void *context, void *ptr, size_t size, cons
                                 * because we want to invalidate the padding
                                 * too.
                                 */
-                               pool_tc->pool = new_used + (char *)new_ptr;
-                               TC_INVALIDATE_POOL(pool_tc);
+                               pool_hdr->end = new_used + (char *)new_ptr;
+                               tc_invalidate_pool(pool_hdr);
 
                                /* now the aligned pointer */
-                               pool_tc->pool = new_chunk_size + (char *)new_ptr;
+                               pool_hdr->end = new_chunk_size + (char *)new_ptr;
                                goto got_new_ptr;
                        }
 
@@ -1532,44 +1911,48 @@ _PUBLIC_ void *_talloc_realloc(const void *context, void *ptr, size_t size, cons
                        return ptr;
                }
 
-               if (next_tc == pool_tc->pool) {
+               if (next_tc == pool_hdr->end) {
                        /*
                         * optimize for the case where 'tc' is the last
                         * chunk in the pool.
                         */
                        space_needed = new_chunk_size - old_chunk_size;
-                       space_left = TC_POOL_SPACE_LEFT(pool_tc);
+                       space_left = tc_pool_space_left(pool_hdr);
 
                        if (space_left >= space_needed) {
                                TC_UNDEFINE_GROW_CHUNK(tc, size);
                                tc->flags &= ~TALLOC_FLAG_FREE;
                                tc->size = size;
-                               pool_tc->pool = TC_POOLMEM_NEXT_CHUNK(tc);
+                               pool_hdr->end = tc_next_chunk(tc);
                                return ptr;
                        }
                }
 
-               new_ptr = talloc_alloc_pool(tc, size + TC_HDR_SIZE);
+               new_ptr = tc_alloc_pool(tc, size + TC_HDR_SIZE, 0);
 
                if (new_ptr == NULL) {
                        new_ptr = malloc(TC_HDR_SIZE+size);
                        malloced = true;
+                       new_size = size;
                }
 
                if (new_ptr) {
                        memcpy(new_ptr, tc, MIN(tc->size,size) + TC_HDR_SIZE);
 
-                       _talloc_free_poolmem(tc, __location__ "_talloc_realloc");
+                       _tc_free_poolmem(tc, __location__ "_talloc_realloc");
                }
        }
        else {
+               /* We're doing realloc here, so record the difference. */
+               old_size = tc->size;
+               new_size = size;
                new_ptr = realloc(tc, size + TC_HDR_SIZE);
        }
 got_new_ptr:
 #endif
-       if (unlikely(!new_ptr)) {       
-               tc->flags &= ~TALLOC_FLAG_FREE; 
-               return NULL; 
+       if (unlikely(!new_ptr)) {
+               tc->flags &= ~TALLOC_FLAG_FREE;
+               return NULL;
        }
 
        tc = (struct talloc_chunk *)new_ptr;
@@ -1591,8 +1974,14 @@ got_new_ptr:
                tc->next->prev = tc;
        }
 
+       if (new_size > old_size) {
+               talloc_memlimit_grow(tc->limit, new_size - old_size);
+       } else if (new_size < old_size) {
+               talloc_memlimit_shrink(tc->limit, old_size - new_size);
+       }
+
        tc->size = size;
-       _talloc_set_name_const(TC_PTR_FROM_CHUNK(tc), name);
+       _tc_set_name_const(tc, name);
 
        return TC_PTR_FROM_CHUNK(tc);
 }
@@ -1609,10 +1998,16 @@ _PUBLIC_ void *_talloc_move(const void *new_ctx, const void *_pptr)
        return ret;
 }
 
-/*
-  return the total size of a talloc pool (subtree)
-*/
-_PUBLIC_ size_t talloc_total_size(const void *ptr)
+enum talloc_mem_count_type {
+       TOTAL_MEM_SIZE,
+       TOTAL_MEM_BLOCKS,
+       TOTAL_MEM_LIMIT,
+};
+
+static inline size_t _talloc_total_mem_internal(const void *ptr,
+                                        enum talloc_mem_count_type type,
+                                        struct talloc_memlimit *old_limit,
+                                        struct talloc_memlimit *new_limit)
 {
        size_t total = 0;
        struct talloc_chunk *c, *tc;
@@ -1626,17 +2021,71 @@ _PUBLIC_ size_t talloc_total_size(const void *ptr)
 
        tc = talloc_chunk_from_ptr(ptr);
 
+       if (old_limit || new_limit) {
+               if (tc->limit && tc->limit->upper == old_limit) {
+                       tc->limit->upper = new_limit;
+               }
+       }
+
+       /* optimize in the memlimits case */
+       if (type == TOTAL_MEM_LIMIT &&
+           tc->limit != NULL &&
+           tc->limit != old_limit &&
+           tc->limit->parent == tc) {
+               return tc->limit->cur_size;
+       }
+
        if (tc->flags & TALLOC_FLAG_LOOP) {
                return 0;
        }
 
        tc->flags |= TALLOC_FLAG_LOOP;
 
-       if (likely(tc->name != TALLOC_MAGIC_REFERENCE)) {
-               total = tc->size;
+       if (old_limit || new_limit) {
+               if (old_limit == tc->limit) {
+                       tc->limit = new_limit;
+               }
        }
-       for (c=tc->child;c;c=c->next) {
-               total += talloc_total_size(TC_PTR_FROM_CHUNK(c));
+
+       switch (type) {
+       case TOTAL_MEM_SIZE:
+               if (likely(tc->name != TALLOC_MAGIC_REFERENCE)) {
+                       total = tc->size;
+               }
+               break;
+       case TOTAL_MEM_BLOCKS:
+               total++;
+               break;
+       case TOTAL_MEM_LIMIT:
+               if (likely(tc->name != TALLOC_MAGIC_REFERENCE)) {
+                       /*
+                        * Don't count memory allocated from a pool
+                        * when calculating limits. Only count the
+                        * pool itself.
+                        */
+                       if (!(tc->flags & TALLOC_FLAG_POOLMEM)) {
+                               if (tc->flags & TALLOC_FLAG_POOL) {
+                                       /*
+                                        * If this is a pool, the allocated
+                                        * size is in the pool header, and
+                                        * remember to add in the prefix
+                                        * length.
+                                        */
+                                       struct talloc_pool_hdr *pool_hdr
+                                                       = talloc_pool_from_chunk(tc);
+                                       total = pool_hdr->poolsize +
+                                                       TC_HDR_SIZE +
+                                                       TP_HDR_SIZE;
+                               } else {
+                                       total = tc->size + TC_HDR_SIZE;
+                               }
+                       }
+               }
+               break;
+       }
+       for (c = tc->child; c; c = c->next) {
+               total += _talloc_total_mem_internal(TC_PTR_FROM_CHUNK(c), type,
+                                                   old_limit, new_limit);
        }
 
        tc->flags &= ~TALLOC_FLAG_LOOP;
@@ -1644,37 +2093,20 @@ _PUBLIC_ size_t talloc_total_size(const void *ptr)
        return total;
 }
 
+/*
+  return the total size of a talloc pool (subtree)
+*/
+_PUBLIC_ size_t talloc_total_size(const void *ptr)
+{
+       return _talloc_total_mem_internal(ptr, TOTAL_MEM_SIZE, NULL, NULL);
+}
+
 /*
   return the total number of blocks in a talloc pool (subtree)
 */
 _PUBLIC_ size_t talloc_total_blocks(const void *ptr)
 {
-       size_t total = 0;
-       struct talloc_chunk *c, *tc;
-
-       if (ptr == NULL) {
-               ptr = null_context;
-       }
-       if (ptr == NULL) {
-               return 0;
-       }
-
-       tc = talloc_chunk_from_ptr(ptr);
-
-       if (tc->flags & TALLOC_FLAG_LOOP) {
-               return 0;
-       }
-
-       tc->flags |= TALLOC_FLAG_LOOP;
-
-       total++;
-       for (c=tc->child;c;c=c->next) {
-               total += talloc_total_blocks(TC_PTR_FROM_CHUNK(c));
-       }
-
-       tc->flags &= ~TALLOC_FLAG_LOOP;
-
-       return total;
+       return _talloc_total_mem_internal(ptr, TOTAL_MEM_BLOCKS, NULL, NULL);
 }
 
 /*
@@ -1735,7 +2167,8 @@ _PUBLIC_ void talloc_report_depth_cb(const void *ptr, int depth, int max_depth,
 
 static void talloc_report_depth_FILE_helper(const void *ptr, int depth, int max_depth, int is_ref, void *_f)
 {
-       const char *name = talloc_get_name(ptr);
+       const char *name = __talloc_get_name(ptr);
+       struct talloc_chunk *tc;
        FILE *f = (FILE *)_f;
 
        if (is_ref) {
@@ -1743,15 +2176,25 @@ static void talloc_report_depth_FILE_helper(const void *ptr, int depth, int max_
                return;
        }
 
+       tc = talloc_chunk_from_ptr(ptr);
+       if (tc->limit && tc->limit->parent == tc) {
+               fprintf(f, "%*s%-30s is a memlimit context"
+                       " (max_size = %lu bytes, cur_size = %lu bytes)\n",
+                       depth*4, "",
+                       name,
+                       (unsigned long)tc->limit->max_size,
+                       (unsigned long)tc->limit->cur_size);
+       }
+
        if (depth == 0) {
-               fprintf(f,"%stalloc report on '%s' (total %6lu bytes in %3lu blocks)\n", 
+               fprintf(f,"%stalloc report on '%s' (total %6lu bytes in %3lu blocks)\n",
                        (max_depth < 0 ? "full " :""), name,
                        (unsigned long)talloc_total_size(ptr),
                        (unsigned long)talloc_total_blocks(ptr));
                return;
        }
 
-       fprintf(f, "%*s%-30s contains %6lu bytes in %3lu blocks (ref %d) %p\n", 
+       fprintf(f, "%*s%-30s contains %6lu bytes in %3lu blocks (ref %d) %p\n",
                depth*4, "",
                name,
                (unsigned long)talloc_total_size(ptr),
@@ -1890,8 +2333,8 @@ _PUBLIC_ void talloc_enable_leak_report_full(void)
        atexit(talloc_report_null_full);
 }
 
-/* 
-   talloc and zero memory. 
+/*
+   talloc and zero memory.
 */
 _PUBLIC_ void *_talloc_zero(const void *ctx, size_t size, const char *name)
 {
@@ -1905,7 +2348,7 @@ _PUBLIC_ void *_talloc_zero(const void *ctx, size_t size, const char *name)
 }
 
 /*
-  memdup with a talloc. 
+  memdup with a talloc.
 */
 _PUBLIC_ void *_talloc_memdup(const void *t, const void *p, size_t size, const char *name)
 {
@@ -1921,14 +2364,15 @@ _PUBLIC_ void *_talloc_memdup(const void *t, const void *p, size_t size, const c
 static inline char *__talloc_strlendup(const void *t, const char *p, size_t len)
 {
        char *ret;
+       struct talloc_chunk *tc;
 
-       ret = (char *)__talloc(t, len + 1);
+       ret = (char *)__talloc(t, len + 1, &tc);
        if (unlikely(!ret)) return NULL;
 
        memcpy(ret, p, len);
        ret[len] = 0;
 
-       _talloc_set_name_const(ret, ret);
+       _tc_set_name_const(tc, ret);
        return ret;
 }
 
@@ -1962,7 +2406,7 @@ static inline char *__talloc_strlendup_append(char *s, size_t slen,
        memcpy(&ret[slen], a, alen);
        ret[slen+alen] = 0;
 
-       _talloc_set_name_const(ret, ret);
+       _tc_set_name_const(talloc_chunk_from_ptr(ret), ret);
        return ret;
 }
 
@@ -2012,7 +2456,7 @@ _PUBLIC_ char *talloc_strdup_append_buffer(char *s, const char *a)
 _PUBLIC_ char *talloc_strndup_append(char *s, const char *a, size_t n)
 {
        if (unlikely(!s)) {
-               return talloc_strdup(NULL, a);
+               return talloc_strndup(NULL, a, n);
        }
 
        if (unlikely(!a)) {
@@ -2031,7 +2475,7 @@ _PUBLIC_ char *talloc_strndup_append_buffer(char *s, const char *a, size_t n)
        size_t slen;
 
        if (unlikely(!s)) {
-               return talloc_strdup(NULL, a);
+               return talloc_strndup(NULL, a, n);
        }
 
        if (unlikely(!a)) {
@@ -2054,30 +2498,50 @@ _PUBLIC_ char *talloc_strndup_append_buffer(char *s, const char *a, size_t n)
 #endif
 #endif
 
-_PUBLIC_ char *talloc_vasprintf(const void *t, const char *fmt, va_list ap)
+static struct talloc_chunk *_vasprintf_tc(const void *t,
+                                         const char *fmt,
+                                         va_list ap) PRINTF_ATTRIBUTE(2,0);
+
+static struct talloc_chunk *_vasprintf_tc(const void *t,
+                                         const char *fmt,
+                                         va_list ap)
 {
        int len;
        char *ret;
        va_list ap2;
-       char c;
+       struct talloc_chunk *tc;
+       char buf[1024];
 
        /* this call looks strange, but it makes it work on older solaris boxes */
        va_copy(ap2, ap);
-       len = vsnprintf(&c, 1, fmt, ap2);
+       len = vsnprintf(buf, sizeof(buf), fmt, ap2);
        va_end(ap2);
        if (unlikely(len < 0)) {
                return NULL;
        }
 
-       ret = (char *)__talloc(t, len+1);
+       ret = (char *)__talloc(t, len+1, &tc);
        if (unlikely(!ret)) return NULL;
 
-       va_copy(ap2, ap);
-       vsnprintf(ret, len+1, fmt, ap2);
-       va_end(ap2);
+       if (len < sizeof(buf)) {
+               memcpy(ret, buf, len+1);
+       } else {
+               va_copy(ap2, ap);
+               vsnprintf(ret, len+1, fmt, ap2);
+               va_end(ap2);
+       }
 
-       _talloc_set_name_const(ret, ret);
-       return ret;
+       _tc_set_name_const(tc, ret);
+       return tc;
+}
+
+_PUBLIC_ char *talloc_vasprintf(const void *t, const char *fmt, va_list ap)
+{
+       struct talloc_chunk *tc = _vasprintf_tc(t, fmt, ap);
+       if (tc == NULL) {
+               return NULL;
+       }
+       return TC_PTR_FROM_CHUNK(tc);
 }
 
 
@@ -2128,7 +2592,7 @@ static inline char *__talloc_vaslenprintf_append(char *s, size_t slen,
        vsnprintf(s + slen, alen + 1, fmt, ap2);
        va_end(ap2);
 
-       _talloc_set_name_const(s, s);
+       _tc_set_name_const(talloc_chunk_from_ptr(s), s);
        return s;
 }
 
@@ -2271,9 +2735,6 @@ _PUBLIC_ size_t talloc_get_size(const void *context)
 {
        struct talloc_chunk *tc;
 
-       if (context == NULL) {
-               context = null_context;
-       }
        if (context == NULL) {
                return 0;
        }
@@ -2320,9 +2781,9 @@ _PUBLIC_ void talloc_show_parents(const void *context, FILE *file)
        }
 
        tc = talloc_chunk_from_ptr(context);
-       fprintf(file, "talloc parents of '%s'\n", talloc_get_name(context));
+       fprintf(file, "talloc parents of '%s'\n", __talloc_get_name(context));
        while (tc) {
-               fprintf(file, "\t'%s'\n", talloc_get_name(TC_PTR_FROM_CHUNK(tc)));
+               fprintf(file, "\t'%s'\n", __talloc_get_name(TC_PTR_FROM_CHUNK(tc)));
                while (tc && tc->prev) tc = tc->prev;
                if (tc) {
                        tc = tc->parent;
@@ -2343,7 +2804,10 @@ static int _talloc_is_parent(const void *context, const void *ptr, int depth)
        }
 
        tc = talloc_chunk_from_ptr(context);
-       while (tc && depth > 0) {
+       while (tc) {
+               if (depth <= 0) {
+                       return 0;
+               }
                if (TC_PTR_FROM_CHUNK(tc) == ptr) return 1;
                while (tc && tc->prev) tc = tc->prev;
                if (tc) {
@@ -2361,3 +2825,140 @@ _PUBLIC_ int talloc_is_parent(const void *context, const void *ptr)
 {
        return _talloc_is_parent(context, ptr, TALLOC_MAX_DEPTH);
 }
+
+/*
+  return the total size of memory used by this context and all children
+*/
+static inline size_t _talloc_total_limit_size(const void *ptr,
+                                       struct talloc_memlimit *old_limit,
+                                       struct talloc_memlimit *new_limit)
+{
+       return _talloc_total_mem_internal(ptr, TOTAL_MEM_LIMIT,
+                                         old_limit, new_limit);
+}
+
+static inline bool talloc_memlimit_check(struct talloc_memlimit *limit, size_t size)
+{
+       struct talloc_memlimit *l;
+
+       for (l = limit; l != NULL; l = l->upper) {
+               if (l->max_size != 0 &&
+                   ((l->max_size <= l->cur_size) ||
+                    (l->max_size - l->cur_size < size))) {
+                       return false;
+               }
+       }
+
+       return true;
+}
+
+/*
+  Update memory limits when freeing a talloc_chunk.
+*/
+static void tc_memlimit_update_on_free(struct talloc_chunk *tc)
+{
+       size_t limit_shrink_size;
+
+       if (!tc->limit) {
+               return;
+       }
+
+       /*
+        * Pool entries don't count. Only the pools
+        * themselves are counted as part of the memory
+        * limits. Note that this also takes care of
+        * nested pools which have both flags
+        * TALLOC_FLAG_POOLMEM|TALLOC_FLAG_POOL set.
+        */
+       if (tc->flags & TALLOC_FLAG_POOLMEM) {
+               return;
+       }
+
+       /*
+        * If we are part of a memory limited context hierarchy
+        * we need to subtract the memory used from the counters
+        */
+
+       limit_shrink_size = tc->size+TC_HDR_SIZE;
+
+       /*
+        * If we're deallocating a pool, take into
+        * account the prefix size added for the pool.
+        */
+
+       if (tc->flags & TALLOC_FLAG_POOL) {
+               limit_shrink_size += TP_HDR_SIZE;
+       }
+
+       talloc_memlimit_shrink(tc->limit, limit_shrink_size);
+
+       if (tc->limit->parent == tc) {
+               free(tc->limit);
+       }
+
+       tc->limit = NULL;
+}
+
+/*
+  Increase memory limit accounting after a malloc/realloc.
+*/
+static void talloc_memlimit_grow(struct talloc_memlimit *limit,
+                               size_t size)
+{
+       struct talloc_memlimit *l;
+
+       for (l = limit; l != NULL; l = l->upper) {
+               size_t new_cur_size = l->cur_size + size;
+               if (new_cur_size < l->cur_size) {
+                       talloc_abort("logic error in talloc_memlimit_grow\n");
+                       return;
+               }
+               l->cur_size = new_cur_size;
+       }
+}
+
+/*
+  Decrease memory limit accounting after a free/realloc.
+*/
+static void talloc_memlimit_shrink(struct talloc_memlimit *limit,
+                               size_t size)
+{
+       struct talloc_memlimit *l;
+
+       for (l = limit; l != NULL; l = l->upper) {
+               if (l->cur_size < size) {
+                       talloc_abort("logic error in talloc_memlimit_shrink\n");
+                       return;
+               }
+               l->cur_size = l->cur_size - size;
+       }
+}
+
+_PUBLIC_ int talloc_set_memlimit(const void *ctx, size_t max_size)
+{
+       struct talloc_chunk *tc = talloc_chunk_from_ptr(ctx);
+       struct talloc_memlimit *orig_limit;
+       struct talloc_memlimit *limit = NULL;
+
+       if (tc->limit && tc->limit->parent == tc) {
+               tc->limit->max_size = max_size;
+               return 0;
+       }
+       orig_limit = tc->limit;
+
+       limit = malloc(sizeof(struct talloc_memlimit));
+       if (limit == NULL) {
+               return 1;
+       }
+       limit->parent = tc;
+       limit->max_size = max_size;
+       limit->cur_size = _talloc_total_limit_size(ctx, tc->limit, limit);
+
+       if (orig_limit) {
+               limit->upper = orig_limit;
+       } else {
+               limit->upper = NULL;
+       }
+
+       return 0;
+}