talloc: Fix a documentation typo
[obnox/samba/samba-obnox.git] / lib / talloc / talloc.h
1 #ifndef _TALLOC_H_
2 #define _TALLOC_H_
3 /*
4    Unix SMB/CIFS implementation.
5    Samba temporary memory allocation functions
6
7    Copyright (C) Andrew Tridgell 2004-2005
8    Copyright (C) Stefan Metzmacher 2006
9
10      ** NOTE! The following LGPL license applies to the talloc
11      ** library. This does NOT imply that all of Samba is released
12      ** under the LGPL
13
14    This library is free software; you can redistribute it and/or
15    modify it under the terms of the GNU Lesser General Public
16    License as published by the Free Software Foundation; either
17    version 3 of the License, or (at your option) any later version.
18
19    This library is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    Lesser General Public License for more details.
23
24    You should have received a copy of the GNU Lesser General Public
25    License along with this library; if not, see <http://www.gnu.org/licenses/>.
26 */
27
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <stdarg.h>
31
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35
36 /**
37  * @defgroup talloc The talloc API
38  *
39  * talloc is a hierarchical, reference counted memory pool system with
40  * destructors. It is the core memory allocator used in Samba.
41  *
42  * @{
43  */
44
45 #define TALLOC_VERSION_MAJOR 2
46 #define TALLOC_VERSION_MINOR 0
47
48 int talloc_version_major(void);
49 int talloc_version_minor(void);
50 /* This is mostly useful only for testing */
51 int talloc_test_get_magic(void);
52
53 /**
54  * @brief Define a talloc parent type
55  *
56  * As talloc is a hierarchial memory allocator, every talloc chunk is a
57  * potential parent to other talloc chunks. So defining a separate type for a
58  * talloc chunk is not strictly necessary. TALLOC_CTX is defined nevertheless,
59  * as it provides an indicator for function arguments. You will frequently
60  * write code like
61  *
62  * @code
63  *      struct foo *foo_create(TALLOC_CTX *mem_ctx)
64  *      {
65  *              struct foo *result;
66  *              result = talloc(mem_ctx, struct foo);
67  *              if (result == NULL) return NULL;
68  *                      ... initialize foo ...
69  *              return result;
70  *      }
71  * @endcode
72  *
73  * In this type of allocating functions it is handy to have a general
74  * TALLOC_CTX type to indicate which parent to put allocated structures on.
75  */
76 typedef void TALLOC_CTX;
77
78 /*
79   this uses a little trick to allow __LINE__ to be stringified
80 */
81 #ifndef __location__
82 #define __TALLOC_STRING_LINE1__(s)    #s
83 #define __TALLOC_STRING_LINE2__(s)   __TALLOC_STRING_LINE1__(s)
84 #define __TALLOC_STRING_LINE3__  __TALLOC_STRING_LINE2__(__LINE__)
85 #define __location__ __FILE__ ":" __TALLOC_STRING_LINE3__
86 #endif
87
88 #ifndef TALLOC_DEPRECATED
89 #define TALLOC_DEPRECATED 0
90 #endif
91
92 #ifndef PRINTF_ATTRIBUTE
93 #if (__GNUC__ >= 3)
94 /** Use gcc attribute to check printf fns.  a1 is the 1-based index of
95  * the parameter containing the format, and a2 the index of the first
96  * argument. Note that some gcc 2.x versions don't handle this
97  * properly **/
98 #define PRINTF_ATTRIBUTE(a1, a2) __attribute__ ((format (__printf__, a1, a2)))
99 #else
100 #define PRINTF_ATTRIBUTE(a1, a2)
101 #endif
102 #endif
103
104 #ifdef DOXYGEN
105 /**
106  * @brief Create a new talloc context.
107  *
108  * The talloc() macro is the core of the talloc library. It takes a memory
109  * context and a type, and returns a pointer to a new area of memory of the
110  * given type.
111  *
112  * The returned pointer is itself a talloc context, so you can use it as the
113  * context argument to more calls to talloc if you wish.
114  *
115  * The returned pointer is a "child" of the supplied context. This means that if
116  * you talloc_free() the context then the new child disappears as well.
117  * Alternatively you can free just the child.
118  *
119  * @param[in]  ctx      A talloc context to create a new reference on or NULL to
120  *                      create a new top level context.
121  *
122  * @param[in]  type     The type of memory to allocate.
123  *
124  * @return              A type casted talloc context or NULL on error.
125  *
126  * @code
127  *      unsigned int *a, *b;
128  *
129  *      a = talloc(NULL, unsigned int);
130  *      b = talloc(a, unsigned int);
131  * @endcode
132  *
133  * @see talloc_zero
134  * @see talloc_array
135  * @see talloc_steal
136  * @see talloc_free
137  */
138 void *talloc(const void *ctx, #type);
139 #else
140 #define talloc(ctx, type) (type *)talloc_named_const(ctx, sizeof(type), #type)
141 void *_talloc(const void *context, size_t size);
142 #endif
143
144 /**
145  * @brief Create a new top level talloc context.
146  *
147  * This function creates a zero length named talloc context as a top level
148  * context. It is equivalent to:
149  *
150  * @code
151  *      talloc_named(NULL, 0, fmt, ...);
152  * @endcode
153  * @param[in]  fmt      Format string for the name.
154  *
155  * @param[in]  ...      Additional printf-style arguments.
156  *
157  * @return              The allocated memory chunk, NULL on error.
158  *
159  * @see talloc_named()
160  */
161 void *talloc_init(const char *fmt, ...) PRINTF_ATTRIBUTE(1,2);
162
163 #ifdef DOXYGEN
164 /**
165  * @brief Free a chunk of talloc memory.
166  *
167  * The talloc_free() function frees a piece of talloc memory, and all its
168  * children. You can call talloc_free() on any pointer returned by
169  * talloc().
170  *
171  * The return value of talloc_free() indicates success or failure, with 0
172  * returned for success and -1 for failure. A possible failure condition
173  * is if the pointer had a destructor attached to it and the destructor
174  * returned -1. See talloc_set_destructor() for details on
175  * destructors. Likewise, if "ptr" is NULL, then the function will make
176  * no modifications and return -1.
177  *
178  * From version 2.0 and onwards, as a special case, talloc_free() is
179  * refused on pointers that have more than one parent associated, as talloc
180  * would have no way of knowing which parent should be removed. This is
181  * different from older versions in the sense that always the reference to
182  * the most recently established parent has been destroyed. Hence to free a
183  * pointer that has more than one parent please use talloc_unlink().
184  *
185  * To help you find problems in your code caused by this behaviour, if
186  * you do try and free a pointer with more than one parent then the
187  * talloc logging function will be called to give output like this:
188  *
189  * @code
190  *   ERROR: talloc_free with references at some_dir/source/foo.c:123
191  *     reference at some_dir/source/other.c:325
192  *     reference at some_dir/source/third.c:121
193  * @endcode
194  *
195  * Please see the documentation for talloc_set_log_fn() and
196  * talloc_set_log_stderr() for more information on talloc logging
197  * functions.
198  *
199  * If <code>TALLOC_FREE_FILL</code> environment variable is set,
200  * the memory occupied by the context is filled with the value of this variable.
201  * The value should be a numeric representation of the character you want to
202  * use.
203  *
204  * talloc_free() operates recursively on its children.
205  *
206  * @param[in]  ptr      The chunk to be freed.
207  *
208  * @return              Returns 0 on success and -1 on error. A possible
209  *                      failure condition is if the pointer had a destructor
210  *                      attached to it and the destructor returned -1. Likewise,
211  *                      if "ptr" is NULL, then the function will make no
212  *                      modifications and returns -1.
213  *
214  * Example:
215  * @code
216  *      unsigned int *a, *b;
217  *      a = talloc(NULL, unsigned int);
218  *      b = talloc(a, unsigned int);
219  *
220  *      talloc_free(a); // Frees a and b
221  * @endcode
222  *
223  * @see talloc_set_destructor()
224  * @see talloc_unlink()
225  */
226 int talloc_free(void *ptr);
227 #else
228 #define talloc_free(ctx) _talloc_free(ctx, __location__)
229 int _talloc_free(void *ptr, const char *location);
230 #endif
231
232 /**
233  * @brief Free a talloc chunk's children.
234  *
235  * The function walks along the list of all children of a talloc context and
236  * talloc_free()s only the children, not the context itself.
237  *
238  * A NULL argument is handled as no-op.
239  *
240  * @param[in]  ptr      The chunk that you want to free the children of
241  *                      (NULL is allowed too)
242  */
243 void talloc_free_children(void *ptr);
244
245 #ifdef DOXYGEN
246 /**
247  * @brief Assign a destructor function to be called when a chunk is freed.
248  *
249  * The function talloc_set_destructor() sets the "destructor" for the pointer
250  * "ptr". A destructor is a function that is called when the memory used by a
251  * pointer is about to be released. The destructor receives the pointer as an
252  * argument, and should return 0 for success and -1 for failure.
253  *
254  * The destructor can do anything it wants to, including freeing other pieces
255  * of memory. A common use for destructors is to clean up operating system
256  * resources (such as open file descriptors) contained in the structure the
257  * destructor is placed on.
258  *
259  * You can only place one destructor on a pointer. If you need more than one
260  * destructor then you can create a zero-length child of the pointer and place
261  * an additional destructor on that.
262  *
263  * To remove a destructor call talloc_set_destructor() with NULL for the
264  * destructor.
265  *
266  * If your destructor attempts to talloc_free() the pointer that it is the
267  * destructor for then talloc_free() will return -1 and the free will be
268  * ignored. This would be a pointless operation anyway, as the destructor is
269  * only called when the memory is just about to go away.
270  *
271  * @param[in]  ptr      The talloc chunk to add a destructor to.
272  *
273  * @param[in]  destructor  The destructor function to be called. NULL to remove
274  *                         it.
275  *
276  * Example:
277  * @code
278  *      static int destroy_fd(int *fd) {
279  *              close(*fd);
280  *              return 0;
281  *      }
282  *
283  *      int *open_file(const char *filename) {
284  *              int *fd = talloc(NULL, int);
285  *              *fd = open(filename, O_RDONLY);
286  *              if (*fd < 0) {
287  *                      talloc_free(fd);
288  *                      return NULL;
289  *              }
290  *              // Whenever they free this, we close the file.
291  *              talloc_set_destructor(fd, destroy_fd);
292  *              return fd;
293  *      }
294  * @endcode
295  *
296  * @see talloc()
297  * @see talloc_free()
298  */
299 void talloc_set_destructor(const void *ptr, int (*destructor)(void *));
300
301 /**
302  * @brief Change a talloc chunk's parent.
303  *
304  * The talloc_steal() function changes the parent context of a talloc
305  * pointer. It is typically used when the context that the pointer is
306  * currently a child of is going to be freed and you wish to keep the
307  * memory for a longer time.
308  *
309  * To make the changed hierarchy less error-prone, you might consider to use
310  * talloc_move().
311  *
312  * If you try and call talloc_steal() on a pointer that has more than one
313  * parent then the result is ambiguous. Talloc will choose to remove the
314  * parent that is currently indicated by talloc_parent() and replace it with
315  * the chosen parent. You will also get a message like this via the talloc
316  * logging functions:
317  *
318  * @code
319  *   WARNING: talloc_steal with references at some_dir/source/foo.c:123
320  *     reference at some_dir/source/other.c:325
321  *     reference at some_dir/source/third.c:121
322  * @endcode
323  *
324  * To unambiguously change the parent of a pointer please see the function
325  * talloc_reparent(). See the talloc_set_log_fn() documentation for more
326  * information on talloc logging.
327  *
328  * @param[in]  new_ctx  The new parent context.
329  *
330  * @param[in]  ptr      The talloc chunk to move.
331  *
332  * @return              Returns the pointer that you pass it. It does not have
333  *                      any failure modes.
334  *
335  * @note It is possible to produce loops in the parent/child relationship
336  * if you are not careful with talloc_steal(). No guarantees are provided
337  * as to your sanity or the safety of your data if you do this.
338  */
339 void *talloc_steal(const void *new_ctx, const void *ptr);
340 #else /* DOXYGEN */
341 /* try to make talloc_set_destructor() and talloc_steal() type safe,
342    if we have a recent gcc */
343 #if (__GNUC__ >= 3)
344 #define _TALLOC_TYPEOF(ptr) __typeof__(ptr)
345 #define talloc_set_destructor(ptr, function)                                  \
346         do {                                                                  \
347                 int (*_talloc_destructor_fn)(_TALLOC_TYPEOF(ptr)) = (function);       \
348                 _talloc_set_destructor((ptr), (int (*)(void *))_talloc_destructor_fn); \
349         } while(0)
350 /* this extremely strange macro is to avoid some braindamaged warning
351    stupidity in gcc 4.1.x */
352 #define talloc_steal(ctx, ptr) ({ _TALLOC_TYPEOF(ptr) __talloc_steal_ret = (_TALLOC_TYPEOF(ptr))_talloc_steal_loc((ctx),(ptr), __location__); __talloc_steal_ret; })
353 #else /* __GNUC__ >= 3 */
354 #define talloc_set_destructor(ptr, function) \
355         _talloc_set_destructor((ptr), (int (*)(void *))(function))
356 #define _TALLOC_TYPEOF(ptr) void *
357 #define talloc_steal(ctx, ptr) (_TALLOC_TYPEOF(ptr))_talloc_steal_loc((ctx),(ptr), __location__)
358 #endif /* __GNUC__ >= 3 */
359 void _talloc_set_destructor(const void *ptr, int (*_destructor)(void *));
360 void *_talloc_steal_loc(const void *new_ctx, const void *ptr, const char *location);
361 #endif /* DOXYGEN */
362
363 /**
364  * @brief Assign a name to a talloc chunk.
365  *
366  * Each talloc pointer has a "name". The name is used principally for
367  * debugging purposes, although it is also possible to set and get the name on
368  * a pointer in as a way of "marking" pointers in your code.
369  *
370  * The main use for names on pointer is for "talloc reports". See
371  * talloc_report() and talloc_report_full() for details. Also see
372  * talloc_enable_leak_report() and talloc_enable_leak_report_full().
373  *
374  * The talloc_set_name() function allocates memory as a child of the
375  * pointer. It is logically equivalent to:
376  *
377  * @code
378  *      talloc_set_name_const(ptr, talloc_asprintf(ptr, fmt, ...));
379  * @endcode
380  *
381  * @param[in]  ptr      The talloc chunk to assign a name to.
382  *
383  * @param[in]  fmt      Format string for the name.
384  *
385  * @param[in]  ...      Add printf-style additional arguments.
386  *
387  * @return              The assigned name, NULL on error.
388  *
389  * @note Multiple calls to talloc_set_name() will allocate more memory without
390  * releasing the name. All of the memory is released when the ptr is freed
391  * using talloc_free().
392  */
393 const char *talloc_set_name(const void *ptr, const char *fmt, ...) PRINTF_ATTRIBUTE(2,3);
394
395 #ifdef DOXYGEN
396 /**
397  * @brief Change a talloc chunk's parent.
398  *
399  * This function has the same effect as talloc_steal(), and additionally sets
400  * the source pointer to NULL. You would use it like this:
401  *
402  * @code
403  *      struct foo *X = talloc(tmp_ctx, struct foo);
404  *      struct foo *Y;
405  *      Y = talloc_move(new_ctx, &X);
406  * @endcode
407  *
408  * @param[in]  new_ctx  The new parent context.
409  *
410  * @param[in]  pptr     Pointer to the talloc chunk to move.
411  *
412  * @return              The pointer of the talloc chunk it has been moved to,
413  *                      NULL on error.
414  */
415 void *talloc_move(const void *new_ctx, void **pptr);
416 #else
417 #define talloc_move(ctx, pptr) (_TALLOC_TYPEOF(*(pptr)))_talloc_move((ctx),(void *)(pptr))
418 void *_talloc_move(const void *new_ctx, const void *pptr);
419 #endif
420
421 /**
422  * @brief Assign a name to a talloc chunk.
423  *
424  * The function is just like talloc_set_name(), but it takes a string constant,
425  * and is much faster. It is extensively used by the "auto naming" macros, such
426  * as talloc_p().
427  *
428  * This function does not allocate any memory. It just copies the supplied
429  * pointer into the internal representation of the talloc ptr. This means you
430  * must not pass a name pointer to memory that will disappear before the ptr
431  * is freed with talloc_free().
432  *
433  * @param[in]  ptr      The talloc chunk to assign a name to.
434  *
435  * @param[in]  name     Format string for the name.
436  */
437 void talloc_set_name_const(const void *ptr, const char *name);
438
439 /**
440  * @brief Create a named talloc chunk.
441  *
442  * The talloc_named() function creates a named talloc pointer. It is
443  * equivalent to:
444  *
445  * @code
446  *      ptr = talloc_size(context, size);
447  *      talloc_set_name(ptr, fmt, ....);
448  * @endcode
449  *
450  * @param[in]  context  The talloc context to hang the result off.
451  *
452  * @param[in]  size     Number of char's that you want to allocate.
453  *
454  * @param[in]  fmt      Format string for the name.
455  *
456  * @param[in]  ...      Additional printf-style arguments.
457  *
458  * @return              The allocated memory chunk, NULL on error.
459  *
460  * @see talloc_set_name()
461  */
462 void *talloc_named(const void *context, size_t size,
463                    const char *fmt, ...) PRINTF_ATTRIBUTE(3,4);
464
465 /**
466  * @brief Basic routine to allocate a chunk of memory.
467  *
468  * This is equivalent to:
469  *
470  * @code
471  *      ptr = talloc_size(context, size);
472  *      talloc_set_name_const(ptr, name);
473  * @endcode
474  *
475  * @param[in]  context  The parent context.
476  *
477  * @param[in]  size     The number of char's that we want to allocate.
478  *
479  * @param[in]  name     The name the talloc block has.
480  *
481  * @return             The allocated memory chunk, NULL on error.
482  */
483 void *talloc_named_const(const void *context, size_t size, const char *name);
484
485 #ifdef DOXYGEN
486 /**
487  * @brief Untyped allocation.
488  *
489  * The function should be used when you don't have a convenient type to pass to
490  * talloc(). Unlike talloc(), it is not type safe (as it returns a void *), so
491  * you are on your own for type checking.
492  *
493  * Best to use talloc() or talloc_array() instead.
494  *
495  * @param[in]  ctx     The talloc context to hang the result off.
496  *
497  * @param[in]  size    Number of char's that you want to allocate.
498  *
499  * @return             The allocated memory chunk, NULL on error.
500  *
501  * Example:
502  * @code
503  *      void *mem = talloc_size(NULL, 100);
504  * @endcode
505  */
506 void *talloc_size(const void *ctx, size_t size);
507 #else
508 #define talloc_size(ctx, size) talloc_named_const(ctx, size, __location__)
509 #endif
510
511 #ifdef DOXYGEN
512 /**
513  * @brief Allocate into a typed pointer.
514  *
515  * The talloc_ptrtype() macro should be used when you have a pointer and want
516  * to allocate memory to point at with this pointer. When compiling with
517  * gcc >= 3 it is typesafe. Note this is a wrapper of talloc_size() and
518  * talloc_get_name() will return the current location in the source file and
519  * not the type.
520  *
521  * @param[in]  ctx      The talloc context to hang the result off.
522  *
523  * @param[in]  type     The pointer you want to assign the result to.
524  *
525  * @return              The properly casted allocated memory chunk, NULL on
526  *                      error.
527  *
528  * Example:
529  * @code
530  *       unsigned int *a = talloc_ptrtype(NULL, a);
531  * @endcode
532  */
533 void *talloc_ptrtype(const void *ctx, #type);
534 #else
535 #define talloc_ptrtype(ctx, ptr) (_TALLOC_TYPEOF(ptr))talloc_size(ctx, sizeof(*(ptr)))
536 #endif
537
538 #ifdef DOXYGEN
539 /**
540  * @brief Allocate a new 0-sized talloc chunk.
541  *
542  * This is a utility macro that creates a new memory context hanging off an
543  * existing context, automatically naming it "talloc_new: __location__" where
544  * __location__ is the source line it is called from. It is particularly
545  * useful for creating a new temporary working context.
546  *
547  * @param[in]  ctx      The talloc parent context.
548  *
549  * @return              A new talloc chunk, NULL on error.
550  */
551 void *talloc_new(const void *ctx);
552 #else
553 #define talloc_new(ctx) talloc_named_const(ctx, 0, "talloc_new: " __location__)
554 #endif
555
556 #ifdef DOXYGEN
557 /**
558  * @brief Allocate a 0-initizialized structure.
559  *
560  * The macro is equivalent to:
561  *
562  * @code
563  *      ptr = talloc(ctx, type);
564  *      if (ptr) memset(ptr, 0, sizeof(type));
565  * @endcode
566  *
567  * @param[in]  ctx      The talloc context to hang the result off.
568  *
569  * @param[in]  type     The type that we want to allocate.
570  *
571  * @return              Pointer to a piece of memory, properly cast to 'type *',
572  *                      NULL on error.
573  *
574  * Example:
575  * @code
576  *      unsigned int *a, *b;
577  *      a = talloc_zero(NULL, unsigned int);
578  *      b = talloc_zero(a, unsigned int);
579  * @endcode
580  *
581  * @see talloc()
582  * @see talloc_zero_size()
583  * @see talloc_zero_array()
584  */
585 void *talloc_zero(const void *ctx, #type);
586
587 /**
588  * @brief Allocate untyped, 0-initialized memory.
589  *
590  * @param[in]  ctx      The talloc context to hang the result off.
591  *
592  * @param[in]  size     Number of char's that you want to allocate.
593  *
594  * @return              The allocated memory chunk.
595  */
596 void *talloc_zero_size(const void *ctx, size_t size);
597 #else
598 #define talloc_zero(ctx, type) (type *)_talloc_zero(ctx, sizeof(type), #type)
599 #define talloc_zero_size(ctx, size) _talloc_zero(ctx, size, __location__)
600 void *_talloc_zero(const void *ctx, size_t size, const char *name);
601 #endif
602
603 /**
604  * @brief Return the name of a talloc chunk.
605  *
606  * @param[in]  ptr      The talloc chunk.
607  *
608  * @return              The current name for the given talloc pointer.
609  *
610  * @see talloc_set_name()
611  */
612 const char *talloc_get_name(const void *ptr);
613
614 /**
615  * @brief Verify that a talloc chunk carries a specified name.
616  *
617  * This function checks if a pointer has the specified name. If it does
618  * then the pointer is returned.
619  *
620  * @param[in]  ptr       The talloc chunk to check.
621  *
622  * @param[in]  name      The name to check against.
623  *
624  * @return               The pointer if the name matches, NULL if it doesn't.
625  */
626 void *talloc_check_name(const void *ptr, const char *name);
627
628 /**
629  * @brief Get the parent chunk of a pointer.
630  *
631  * @param[in]  ptr      The talloc pointer to inspect.
632  *
633  * @return              The talloc parent of ptr, NULL on error.
634  */
635 void *talloc_parent(const void *ptr);
636
637 /**
638  * @brief Get a talloc chunk's parent name.
639  *
640  * @param[in]  ptr      The talloc pointer to inspect.
641  *
642  * @return              The name of ptr's parent chunk.
643  */
644 const char *talloc_parent_name(const void *ptr);
645
646 /**
647  * @brief Get the total size of a talloc chunk including its children.
648  *
649  * The function returns the total size in bytes used by this pointer and all
650  * child pointers. Mostly useful for debugging.
651  *
652  * Passing NULL is allowed, but it will only give a meaningful result if
653  * talloc_enable_leak_report() or talloc_enable_leak_report_full() has
654  * been called.
655  *
656  * @param[in]  ptr      The talloc chunk.
657  *
658  * @return              The total size.
659  */
660 size_t talloc_total_size(const void *ptr);
661
662 /**
663  * @brief Get the number of talloc chunks hanging off a chunk.
664  *
665  * The talloc_total_blocks() function returns the total memory block
666  * count used by this pointer and all child pointers. Mostly useful for
667  * debugging.
668  *
669  * Passing NULL is allowed, but it will only give a meaningful result if
670  * talloc_enable_leak_report() or talloc_enable_leak_report_full() has
671  * been called.
672  *
673  * @param[in]  ptr      The talloc chunk.
674  *
675  * @return              The total size.
676  */
677 size_t talloc_total_blocks(const void *ptr);
678
679 #ifdef DOXYGEN
680 /**
681  * @brief Duplicate a memory area into a talloc chunk.
682  *
683  * The function is equivalent to:
684  *
685  * @code
686  *      ptr = talloc_size(ctx, size);
687  *      if (ptr) memcpy(ptr, p, size);
688  * @endcode
689  *
690  * @param[in]  t        The talloc context to hang the result off.
691  *
692  * @param[in]  p        The memory chunk you want to duplicate.
693  *
694  * @param[in]  size     Number of char's that you want copy.
695  *
696  * @return              The allocated memory chunk.
697  *
698  * @see talloc_size()
699  */
700 void *talloc_memdup(const void *t, const void *p, size_t size);
701 #else
702 #define talloc_memdup(t, p, size) _talloc_memdup(t, p, size, __location__)
703 void *_talloc_memdup(const void *t, const void *p, size_t size, const char *name);
704 #endif
705
706 #ifdef DOXYGEN
707 /**
708  * @brief Assign a type to a talloc chunk.
709  *
710  * This macro allows you to force the name of a pointer to be of a particular
711  * type. This can be used in conjunction with talloc_get_type() to do type
712  * checking on void* pointers.
713  *
714  * It is equivalent to this:
715  *
716  * @code
717  *      talloc_set_name_const(ptr, #type)
718  * @endcode
719  *
720  * @param[in]  ptr      The talloc chunk to assign the type to.
721  *
722  * @param[in]  type     The type to assign.
723  */
724 void talloc_set_type(const char *ptr, #type);
725
726 /**
727  * @brief Get a typed pointer out of a talloc pointer.
728  *
729  * This macro allows you to do type checking on talloc pointers. It is
730  * particularly useful for void* private pointers. It is equivalent to
731  * this:
732  *
733  * @code
734  *      (type *)talloc_check_name(ptr, #type)
735  * @endcode
736  *
737  * @param[in]  ptr      The talloc pointer to check.
738  *
739  * @param[in]  type     The type to check against.
740  *
741  * @return              The properly casted pointer given by ptr, NULL on error.
742  */
743 type *talloc_get_type(const void *ptr, #type);
744 #else
745 #define talloc_set_type(ptr, type) talloc_set_name_const(ptr, #type)
746 #define talloc_get_type(ptr, type) (type *)talloc_check_name(ptr, #type)
747 #endif
748
749 #ifdef DOXYGEN
750 /**
751  * @brief Safely turn a void pointer into a typed pointer.
752  *
753  * This macro is used together with talloc(mem_ctx, struct foo). If you had to
754  * assign the talloc chunk pointer to some void pointer variable,
755  * talloc_get_type_abort() is the recommended way to get the convert the void
756  * pointer back to a typed pointer.
757  *
758  * @param[in]  ptr      The void pointer to convert.
759  *
760  * @param[in]  type     The type that this chunk contains
761  *
762  * @return              The same value as ptr, type-checked and properly cast.
763  */
764 void *talloc_get_type_abort(const void *ptr, #type);
765 #else
766 #ifdef TALLOC_GET_TYPE_ABORT_NOOP
767 #define talloc_get_type_abort(ptr, type) (type *)(ptr)
768 #else
769 #define talloc_get_type_abort(ptr, type) (type *)_talloc_get_type_abort(ptr, #type, __location__)
770 #endif
771 void *_talloc_get_type_abort(const void *ptr, const char *name, const char *location);
772 #endif
773
774 /**
775  * @brief Find a parent context by name.
776  *
777  * Find a parent memory context of the current context that has the given
778  * name. This can be very useful in complex programs where it may be
779  * difficult to pass all information down to the level you need, but you
780  * know the structure you want is a parent of another context.
781  *
782  * @param[in]  ctx      The talloc chunk to start from.
783  *
784  * @param[in]  name     The name of the parent we look for.
785  *
786  * @return              The memory context we are looking for, NULL if not
787  *                      found.
788  */
789 void *talloc_find_parent_byname(const void *ctx, const char *name);
790
791 #ifdef DOXYGEN
792 /**
793  * @brief Find a parent context by type.
794  *
795  * Find a parent memory context of the current context that has the given
796  * name. This can be very useful in complex programs where it may be
797  * difficult to pass all information down to the level you need, but you
798  * know the structure you want is a parent of another context.
799  *
800  * Like talloc_find_parent_byname() but takes a type, making it typesafe.
801  *
802  * @param[in]  ptr      The talloc chunk to start from.
803  *
804  * @param[in]  type     The type of the parent to look for.
805  *
806  * @return              The memory context we are looking for, NULL if not
807  *                      found.
808  */
809 void *talloc_find_parent_bytype(const void *ptr, #type);
810 #else
811 #define talloc_find_parent_bytype(ptr, type) (type *)talloc_find_parent_byname(ptr, #type)
812 #endif
813
814 /**
815  * @brief Allocate a talloc pool.
816  *
817  * A talloc pool is a pure optimization for specific situations. In the
818  * release process for Samba 3.2 we found out that we had become considerably
819  * slower than Samba 3.0 was. Profiling showed that malloc(3) was a large CPU
820  * consumer in benchmarks. For Samba 3.2 we have internally converted many
821  * static buffers to dynamically allocated ones, so malloc(3) being beaten
822  * more was no surprise. But it made us slower.
823  *
824  * talloc_pool() is an optimization to call malloc(3) a lot less for the use
825  * pattern Samba has: The SMB protocol is mainly a request/response protocol
826  * where we have to allocate a certain amount of memory per request and free
827  * that after the SMB reply is sent to the client.
828  *
829  * talloc_pool() creates a talloc chunk that you can use as a talloc parent
830  * exactly as you would use any other ::TALLOC_CTX. The difference is that
831  * when you talloc a child of this pool, no malloc(3) is done. Instead, talloc
832  * just increments a pointer inside the talloc_pool. This also works
833  * recursively. If you use the child of the talloc pool as a parent for
834  * grand-children, their memory is also taken from the talloc pool.
835  *
836  * If there is not enough memory in the pool to allocate the new child,
837  * it will create a new talloc chunk as if the parent was a normal talloc
838  * context.
839  *
840  * If you talloc_free() children of a talloc pool, the memory is not given
841  * back to the system. Instead, free(3) is only called if the talloc_pool()
842  * itself is released with talloc_free().
843  *
844  * The downside of a talloc pool is that if you talloc_move() a child of a
845  * talloc pool to a talloc parent outside the pool, the whole pool memory is
846  * not free(3)'ed until that moved chunk is also talloc_free()ed.
847  *
848  * @param[in]  context  The talloc context to hang the result off.
849  *
850  * @param[in]  size     Size of the talloc pool.
851  *
852  * @return              The allocated talloc pool, NULL on error.
853  */
854 void *talloc_pool(const void *context, size_t size);
855
856 #ifdef DOXYGEN
857 /**
858  * @brief Allocate a talloc object as/with an additional pool.
859  *
860  * This is like talloc_pool(), but's it's more flexible
861  * and allows an object to be a pool for its children.
862  *
863  * @param[in] ctx                   The talloc context to hang the result off.
864  *
865  * @param[in] type                  The type that we want to allocate.
866  *
867  * @param[in] num_subobjects        The expected number of subobjects, which will
868  *                                  be allocated within the pool. This allocates
869  *                                  space for talloc_chunk headers.
870  *
871  * @param[in] total_subobjects_size The size that all subobjects can use in total.
872  *
873  *
874  * @return              The allocated talloc object, NULL on error.
875  */
876 void *talloc_pooled_object(const void *ctx, #type,
877                            unsigned num_subobjects,
878                            size_t total_subobjects_size);
879 #else
880 #define talloc_pooled_object(_ctx, _type, \
881                              _num_subobjects, \
882                              _total_subobjects_size) \
883         (_type *)_talloc_pooled_object((_ctx), sizeof(_type), #_type, \
884                                         (_num_subobjects), \
885                                         (_total_subobjects_size))
886 void *_talloc_pooled_object(const void *ctx,
887                             size_t type_size,
888                             const char *type_name,
889                             unsigned num_subobjects,
890                             size_t total_subobjects_size);
891 #endif
892
893 /**
894  * @brief Free a talloc chunk and NULL out the pointer.
895  *
896  * TALLOC_FREE() frees a pointer and sets it to NULL. Use this if you want
897  * immediate feedback (i.e. crash) if you use a pointer after having free'ed
898  * it.
899  *
900  * @param[in]  ctx      The chunk to be freed.
901  */
902 #define TALLOC_FREE(ctx) do { if (ctx != NULL) { talloc_free(ctx); ctx=NULL; } } while(0)
903
904 /* @} ******************************************************************/
905
906 /**
907  * \defgroup talloc_ref The talloc reference function.
908  * @ingroup talloc
909  *
910  * This module contains the definitions around talloc references
911  *
912  * @{
913  */
914
915 /**
916  * @brief Increase the reference count of a talloc chunk.
917  *
918  * The talloc_increase_ref_count(ptr) function is exactly equivalent to:
919  *
920  * @code
921  *      talloc_reference(NULL, ptr);
922  * @endcode
923  *
924  * You can use either syntax, depending on which you think is clearer in
925  * your code.
926  *
927  * @param[in]  ptr      The pointer to increase the reference count.
928  *
929  * @return              0 on success, -1 on error.
930  */
931 int talloc_increase_ref_count(const void *ptr);
932
933 /**
934  * @brief Get the number of references to a talloc chunk.
935  *
936  * @param[in]  ptr      The pointer to retrieve the reference count from.
937  *
938  * @return              The number of references.
939  */
940 size_t talloc_reference_count(const void *ptr);
941
942 #ifdef DOXYGEN
943 /**
944  * @brief Create an additional talloc parent to a pointer.
945  *
946  * The talloc_reference() function makes "context" an additional parent of
947  * ptr. Each additional reference consumes around 48 bytes of memory on intel
948  * x86 platforms.
949  *
950  * If ptr is NULL, then the function is a no-op, and simply returns NULL.
951  *
952  * After creating a reference you can free it in one of the following ways:
953  *
954  * - you can talloc_free() any parent of the original pointer. That
955  *   will reduce the number of parents of this pointer by 1, and will
956  *   cause this pointer to be freed if it runs out of parents.
957  *
958  * - you can talloc_free() the pointer itself if it has at maximum one
959  *   parent. This behaviour has been changed since the release of version
960  *   2.0. Further informations in the description of "talloc_free".
961  *
962  * For more control on which parent to remove, see talloc_unlink()
963  * @param[in]  ctx      The additional parent.
964  *
965  * @param[in]  ptr      The pointer you want to create an additional parent for.
966  *
967  * @return              The original pointer 'ptr', NULL if talloc ran out of
968  *                      memory in creating the reference.
969  *
970  * @warning You should try to avoid using this interface. It turns a beautiful
971  *          talloc-tree into a graph. It is often really hard to debug if you
972  *          screw something up by accident.
973  *
974  * Example:
975  * @code
976  *      unsigned int *a, *b, *c;
977  *      a = talloc(NULL, unsigned int);
978  *      b = talloc(NULL, unsigned int);
979  *      c = talloc(a, unsigned int);
980  *      // b also serves as a parent of c.
981  *      talloc_reference(b, c);
982  * @endcode
983  *
984  * @see talloc_unlink()
985  */
986 void *talloc_reference(const void *ctx, const void *ptr);
987 #else
988 #define talloc_reference(ctx, ptr) (_TALLOC_TYPEOF(ptr))_talloc_reference_loc((ctx),(ptr), __location__)
989 void *_talloc_reference_loc(const void *context, const void *ptr, const char *location);
990 #endif
991
992 /**
993  * @brief Remove a specific parent from a talloc chunk.
994  *
995  * The function removes a specific parent from ptr. The context passed must
996  * either be a context used in talloc_reference() with this pointer, or must be
997  * a direct parent of ptr.
998  *
999  * You can just use talloc_free() instead of talloc_unlink() if there
1000  * is at maximum one parent. This behaviour has been changed since the
1001  * release of version 2.0. Further informations in the description of
1002  * "talloc_free".
1003  *
1004  * @param[in]  context  The talloc parent to remove.
1005  *
1006  * @param[in]  ptr      The talloc ptr you want to remove the parent from.
1007  *
1008  * @return              0 on success, -1 on error.
1009  *
1010  * @note If the parent has already been removed using talloc_free() then
1011  * this function will fail and will return -1.  Likewise, if ptr is NULL,
1012  * then the function will make no modifications and return -1.
1013  *
1014  * @warning You should try to avoid using this interface. It turns a beautiful
1015  *          talloc-tree into a graph. It is often really hard to debug if you
1016  *          screw something up by accident.
1017  *
1018  * Example:
1019  * @code
1020  *      unsigned int *a, *b, *c;
1021  *      a = talloc(NULL, unsigned int);
1022  *      b = talloc(NULL, unsigned int);
1023  *      c = talloc(a, unsigned int);
1024  *      // b also serves as a parent of c.
1025  *      talloc_reference(b, c);
1026  *      talloc_unlink(b, c);
1027  * @endcode
1028  */
1029 int talloc_unlink(const void *context, void *ptr);
1030
1031 /**
1032  * @brief Provide a talloc context that is freed at program exit.
1033  *
1034  * This is a handy utility function that returns a talloc context
1035  * which will be automatically freed on program exit. This can be used
1036  * to reduce the noise in memory leak reports.
1037  *
1038  * Never use this in code that might be used in objects loaded with
1039  * dlopen and unloaded with dlclose. talloc_autofree_context()
1040  * internally uses atexit(3). Some platforms like modern Linux handles
1041  * this fine, but for example FreeBSD does not deal well with dlopen()
1042  * and atexit() used simultaneously: dlclose() does not clean up the
1043  * list of atexit-handlers, so when the program exits the code that
1044  * was registered from within talloc_autofree_context() is gone, the
1045  * program crashes at exit.
1046  *
1047  * @return              A talloc context, NULL on error.
1048  */
1049 void *talloc_autofree_context(void);
1050
1051 /**
1052  * @brief Get the size of a talloc chunk.
1053  *
1054  * This function lets you know the amount of memory allocated so far by
1055  * this context. It does NOT account for subcontext memory.
1056  * This can be used to calculate the size of an array.
1057  *
1058  * @param[in]  ctx      The talloc chunk.
1059  *
1060  * @return              The size of the talloc chunk.
1061  */
1062 size_t talloc_get_size(const void *ctx);
1063
1064 /**
1065  * @brief Show the parentage of a context.
1066  *
1067  * @param[in]  context            The talloc context to look at.
1068  *
1069  * @param[in]  file               The output to use, a file, stdout or stderr.
1070  */
1071 void talloc_show_parents(const void *context, FILE *file);
1072
1073 /**
1074  * @brief Check if a context is parent of a talloc chunk.
1075  *
1076  * This checks if context is referenced in the talloc hierarchy above ptr.
1077  *
1078  * @param[in]  context  The assumed talloc context.
1079  *
1080  * @param[in]  ptr      The talloc chunk to check.
1081  *
1082  * @return              Return 1 if this is the case, 0 if not.
1083  */
1084 int talloc_is_parent(const void *context, const void *ptr);
1085
1086 /**
1087  * @brief Change the parent context of a talloc pointer.
1088  *
1089  * The function changes the parent context of a talloc pointer. It is typically
1090  * used when the context that the pointer is currently a child of is going to be
1091  * freed and you wish to keep the memory for a longer time.
1092  *
1093  * The difference between talloc_reparent() and talloc_steal() is that
1094  * talloc_reparent() can specify which parent you wish to change. This is
1095  * useful when a pointer has multiple parents via references.
1096  *
1097  * @param[in]  old_parent
1098  * @param[in]  new_parent
1099  * @param[in]  ptr
1100  *
1101  * @return              Return the pointer you passed. It does not have any
1102  *                      failure modes.
1103  */
1104 void *talloc_reparent(const void *old_parent, const void *new_parent, const void *ptr);
1105
1106 /* @} ******************************************************************/
1107
1108 /**
1109  * @defgroup talloc_array The talloc array functions
1110  * @ingroup talloc
1111  *
1112  * Talloc contains some handy helpers for handling Arrays conveniently
1113  *
1114  * @{
1115  */
1116
1117 #ifdef DOXYGEN
1118 /**
1119  * @brief Allocate an array.
1120  *
1121  * The macro is equivalent to:
1122  *
1123  * @code
1124  *      (type *)talloc_size(ctx, sizeof(type) * count);
1125  * @endcode
1126  *
1127  * except that it provides integer overflow protection for the multiply,
1128  * returning NULL if the multiply overflows.
1129  *
1130  * @param[in]  ctx      The talloc context to hang the result off.
1131  *
1132  * @param[in]  type     The type that we want to allocate.
1133  *
1134  * @param[in]  count    The number of 'type' elements you want to allocate.
1135  *
1136  * @return              The allocated result, properly cast to 'type *', NULL on
1137  *                      error.
1138  *
1139  * Example:
1140  * @code
1141  *      unsigned int *a, *b;
1142  *      a = talloc_zero(NULL, unsigned int);
1143  *      b = talloc_array(a, unsigned int, 100);
1144  * @endcode
1145  *
1146  * @see talloc()
1147  * @see talloc_zero_array()
1148  */
1149 void *talloc_array(const void *ctx, #type, unsigned count);
1150 #else
1151 #define talloc_array(ctx, type, count) (type *)_talloc_array(ctx, sizeof(type), count, #type)
1152 void *_talloc_array(const void *ctx, size_t el_size, unsigned count, const char *name);
1153 #endif
1154
1155 #ifdef DOXYGEN
1156 /**
1157  * @brief Allocate an array.
1158  *
1159  * @param[in]  ctx      The talloc context to hang the result off.
1160  *
1161  * @param[in]  size     The size of an array element.
1162  *
1163  * @param[in]  count    The number of elements you want to allocate.
1164  *
1165  * @return              The allocated result, NULL on error.
1166  */
1167 void *talloc_array_size(const void *ctx, size_t size, unsigned count);
1168 #else
1169 #define talloc_array_size(ctx, size, count) _talloc_array(ctx, size, count, __location__)
1170 #endif
1171
1172 #ifdef DOXYGEN
1173 /**
1174  * @brief Allocate an array into a typed pointer.
1175  *
1176  * The macro should be used when you have a pointer to an array and want to
1177  * allocate memory of an array to point at with this pointer. When compiling
1178  * with gcc >= 3 it is typesafe. Note this is a wrapper of talloc_array_size()
1179  * and talloc_get_name() will return the current location in the source file
1180  * and not the type.
1181  *
1182  * @param[in]  ctx      The talloc context to hang the result off.
1183  *
1184  * @param[in]  ptr      The pointer you want to assign the result to.
1185  *
1186  * @param[in]  count    The number of elements you want to allocate.
1187  *
1188  * @return              The allocated memory chunk, properly casted. NULL on
1189  *                      error.
1190  */
1191 void *talloc_array_ptrtype(const void *ctx, const void *ptr, unsigned count);
1192 #else
1193 #define talloc_array_ptrtype(ctx, ptr, count) (_TALLOC_TYPEOF(ptr))talloc_array_size(ctx, sizeof(*(ptr)), count)
1194 #endif
1195
1196 #ifdef DOXYGEN
1197 /**
1198  * @brief Get the number of elements in a talloc'ed array.
1199  *
1200  * A talloc chunk carries its own size, so for talloc'ed arrays it is not
1201  * necessary to store the number of elements explicitly.
1202  *
1203  * @param[in]  ctx      The allocated array.
1204  *
1205  * @return              The number of elements in ctx.
1206  */
1207 size_t talloc_array_length(const void *ctx);
1208 #else
1209 #define talloc_array_length(ctx) (talloc_get_size(ctx)/sizeof(*ctx))
1210 #endif
1211
1212 #ifdef DOXYGEN
1213 /**
1214  * @brief Allocate a zero-initialized array
1215  *
1216  * @param[in]  ctx      The talloc context to hang the result off.
1217  *
1218  * @param[in]  type     The type that we want to allocate.
1219  *
1220  * @param[in]  count    The number of "type" elements you want to allocate.
1221  *
1222  * @return              The allocated result casted to "type *", NULL on error.
1223  *
1224  * The talloc_zero_array() macro is equivalent to:
1225  *
1226  * @code
1227  *     ptr = talloc_array(ctx, type, count);
1228  *     if (ptr) memset(ptr, sizeof(type) * count);
1229  * @endcode
1230  */
1231 void *talloc_zero_array(const void *ctx, #type, unsigned count);
1232 #else
1233 #define talloc_zero_array(ctx, type, count) (type *)_talloc_zero_array(ctx, sizeof(type), count, #type)
1234 void *_talloc_zero_array(const void *ctx,
1235                          size_t el_size,
1236                          unsigned count,
1237                          const char *name);
1238 #endif
1239
1240 #ifdef DOXYGEN
1241 /**
1242  * @brief Change the size of a talloc array.
1243  *
1244  * The macro changes the size of a talloc pointer. The 'count' argument is the
1245  * number of elements of type 'type' that you want the resulting pointer to
1246  * hold.
1247  *
1248  * talloc_realloc() has the following equivalences:
1249  *
1250  * @code
1251  *      talloc_realloc(ctx, NULL, type, 1) ==> talloc(ctx, type);
1252  *      talloc_realloc(ctx, NULL, type, N) ==> talloc_array(ctx, type, N);
1253  *      talloc_realloc(ctx, ptr, type, 0)  ==> talloc_free(ptr);
1254  * @endcode
1255  *
1256  * The "context" argument is only used if "ptr" is NULL, otherwise it is
1257  * ignored.
1258  *
1259  * @param[in]  ctx      The parent context used if ptr is NULL.
1260  *
1261  * @param[in]  ptr      The chunk to be resized.
1262  *
1263  * @param[in]  type     The type of the array element inside ptr.
1264  *
1265  * @param[in]  count    The intended number of array elements.
1266  *
1267  * @return              The new array, NULL on error. The call will fail either
1268  *                      due to a lack of memory, or because the pointer has more
1269  *                      than one parent (see talloc_reference()).
1270  */
1271 void *talloc_realloc(const void *ctx, void *ptr, #type, size_t count);
1272 #else
1273 #define talloc_realloc(ctx, p, type, count) (type *)_talloc_realloc_array(ctx, p, sizeof(type), count, #type)
1274 void *_talloc_realloc_array(const void *ctx, void *ptr, size_t el_size, unsigned count, const char *name);
1275 #endif
1276
1277 #ifdef DOXYGEN
1278 /**
1279  * @brief Untyped realloc to change the size of a talloc array.
1280  *
1281  * The macro is useful when the type is not known so the typesafe
1282  * talloc_realloc() cannot be used.
1283  *
1284  * @param[in]  ctx      The parent context used if 'ptr' is NULL.
1285  *
1286  * @param[in]  ptr      The chunk to be resized.
1287  *
1288  * @param[in]  size     The new chunk size.
1289  *
1290  * @return              The new array, NULL on error.
1291  */
1292 void *talloc_realloc_size(const void *ctx, void *ptr, size_t size);
1293 #else
1294 #define talloc_realloc_size(ctx, ptr, size) _talloc_realloc(ctx, ptr, size, __location__)
1295 void *_talloc_realloc(const void *context, void *ptr, size_t size, const char *name);
1296 #endif
1297
1298 /**
1299  * @brief Provide a function version of talloc_realloc_size.
1300  *
1301  * This is a non-macro version of talloc_realloc(), which is useful as
1302  * libraries sometimes want a ralloc function pointer. A realloc()
1303  * implementation encapsulates the functionality of malloc(), free() and
1304  * realloc() in one call, which is why it is useful to be able to pass around
1305  * a single function pointer.
1306  *
1307  * @param[in]  context  The parent context used if ptr is NULL.
1308  *
1309  * @param[in]  ptr      The chunk to be resized.
1310  *
1311  * @param[in]  size     The new chunk size.
1312  *
1313  * @return              The new chunk, NULL on error.
1314  */
1315 void *talloc_realloc_fn(const void *context, void *ptr, size_t size);
1316
1317 /* @} ******************************************************************/
1318
1319 /**
1320  * @defgroup talloc_string The talloc string functions.
1321  * @ingroup talloc
1322  *
1323  * talloc string allocation and manipulation functions.
1324  * @{
1325  */
1326
1327 /**
1328  * @brief Duplicate a string into a talloc chunk.
1329  *
1330  * This function is equivalent to:
1331  *
1332  * @code
1333  *      ptr = talloc_size(ctx, strlen(p)+1);
1334  *      if (ptr) memcpy(ptr, p, strlen(p)+1);
1335  * @endcode
1336  *
1337  * This functions sets the name of the new pointer to the passed
1338  * string. This is equivalent to:
1339  *
1340  * @code
1341  *      talloc_set_name_const(ptr, ptr)
1342  * @endcode
1343  *
1344  * @param[in]  t        The talloc context to hang the result off.
1345  *
1346  * @param[in]  p        The string you want to duplicate.
1347  *
1348  * @return              The duplicated string, NULL on error.
1349  */
1350 char *talloc_strdup(const void *t, const char *p);
1351
1352 /**
1353  * @brief Append a string to given string.
1354  *
1355  * The destination string is reallocated to take
1356  * <code>strlen(s) + strlen(a) + 1</code> characters.
1357  *
1358  * This functions sets the name of the new pointer to the new
1359  * string. This is equivalent to:
1360  *
1361  * @code
1362  *      talloc_set_name_const(ptr, ptr)
1363  * @endcode
1364  *
1365  * If <code>s == NULL</code> then new context is created.
1366  *
1367  * @param[in]  s        The destination to append to.
1368  *
1369  * @param[in]  a        The string you want to append.
1370  *
1371  * @return              The concatenated strings, NULL on error.
1372  *
1373  * @see talloc_strdup()
1374  * @see talloc_strdup_append_buffer()
1375  */
1376 char *talloc_strdup_append(char *s, const char *a);
1377
1378 /**
1379  * @brief Append a string to a given buffer.
1380  *
1381  * This is a more efficient version of talloc_strdup_append(). It determines the
1382  * length of the destination string by the size of the talloc context.
1383  *
1384  * Use this very carefully as it produces a different result than
1385  * talloc_strdup_append() when a zero character is in the middle of the
1386  * destination string.
1387  *
1388  * @code
1389  *      char *str_a = talloc_strdup(NULL, "hello world");
1390  *      char *str_b = talloc_strdup(NULL, "hello world");
1391  *      str_a[5] = str_b[5] = '\0'
1392  *
1393  *      char *app = talloc_strdup_append(str_a, ", hello");
1394  *      char *buf = talloc_strdup_append_buffer(str_b, ", hello");
1395  *
1396  *      printf("%s\n", app); // hello, hello (app = "hello, hello")
1397  *      printf("%s\n", buf); // hello (buf = "hello\0world, hello")
1398  * @endcode
1399  *
1400  * If <code>s == NULL</code> then new context is created.
1401  *
1402  * @param[in]  s        The destination buffer to append to.
1403  *
1404  * @param[in]  a        The string you want to append.
1405  *
1406  * @return              The concatenated strings, NULL on error.
1407  *
1408  * @see talloc_strdup()
1409  * @see talloc_strdup_append()
1410  * @see talloc_array_length()
1411  */
1412 char *talloc_strdup_append_buffer(char *s, const char *a);
1413
1414 /**
1415  * @brief Duplicate a length-limited string into a talloc chunk.
1416  *
1417  * This function is the talloc equivalent of the C library function strndup(3).
1418  *
1419  * This functions sets the name of the new pointer to the passed string. This is
1420  * equivalent to:
1421  *
1422  * @code
1423  *      talloc_set_name_const(ptr, ptr)
1424  * @endcode
1425  *
1426  * @param[in]  t        The talloc context to hang the result off.
1427  *
1428  * @param[in]  p        The string you want to duplicate.
1429  *
1430  * @param[in]  n        The maximum string length to duplicate.
1431  *
1432  * @return              The duplicated string, NULL on error.
1433  */
1434 char *talloc_strndup(const void *t, const char *p, size_t n);
1435
1436 /**
1437  * @brief Append at most n characters of a string to given string.
1438  *
1439  * The destination string is reallocated to take
1440  * <code>strlen(s) + strnlen(a, n) + 1</code> characters.
1441  *
1442  * This functions sets the name of the new pointer to the new
1443  * string. This is equivalent to:
1444  *
1445  * @code
1446  *      talloc_set_name_const(ptr, ptr)
1447  * @endcode
1448  *
1449  * If <code>s == NULL</code> then new context is created.
1450  *
1451  * @param[in]  s        The destination string to append to.
1452  *
1453  * @param[in]  a        The source string you want to append.
1454  *
1455  * @param[in]  n        The number of characters you want to append from the
1456  *                      string.
1457  *
1458  * @return              The concatenated strings, NULL on error.
1459  *
1460  * @see talloc_strndup()
1461  * @see talloc_strndup_append_buffer()
1462  */
1463 char *talloc_strndup_append(char *s, const char *a, size_t n);
1464
1465 /**
1466  * @brief Append at most n characters of a string to given buffer
1467  *
1468  * This is a more efficient version of talloc_strndup_append(). It determines
1469  * the length of the destination string by the size of the talloc context.
1470  *
1471  * Use this very carefully as it produces a different result than
1472  * talloc_strndup_append() when a zero character is in the middle of the
1473  * destination string.
1474  *
1475  * @code
1476  *      char *str_a = talloc_strdup(NULL, "hello world");
1477  *      char *str_b = talloc_strdup(NULL, "hello world");
1478  *      str_a[5] = str_b[5] = '\0'
1479  *
1480  *      char *app = talloc_strndup_append(str_a, ", hello", 7);
1481  *      char *buf = talloc_strndup_append_buffer(str_b, ", hello", 7);
1482  *
1483  *      printf("%s\n", app); // hello, hello (app = "hello, hello")
1484  *      printf("%s\n", buf); // hello (buf = "hello\0world, hello")
1485  * @endcode
1486  *
1487  * If <code>s == NULL</code> then new context is created.
1488  *
1489  * @param[in]  s        The destination buffer to append to.
1490  *
1491  * @param[in]  a        The source string you want to append.
1492  *
1493  * @param[in]  n        The number of characters you want to append from the
1494  *                      string.
1495  *
1496  * @return              The concatenated strings, NULL on error.
1497  *
1498  * @see talloc_strndup()
1499  * @see talloc_strndup_append()
1500  * @see talloc_array_length()
1501  */
1502 char *talloc_strndup_append_buffer(char *s, const char *a, size_t n);
1503
1504 /**
1505  * @brief Format a string given a va_list.
1506  *
1507  * This function is the talloc equivalent of the C library function
1508  * vasprintf(3).
1509  *
1510  * This functions sets the name of the new pointer to the new string. This is
1511  * equivalent to:
1512  *
1513  * @code
1514  *      talloc_set_name_const(ptr, ptr)
1515  * @endcode
1516  *
1517  * @param[in]  t        The talloc context to hang the result off.
1518  *
1519  * @param[in]  fmt      The format string.
1520  *
1521  * @param[in]  ap       The parameters used to fill fmt.
1522  *
1523  * @return              The formatted string, NULL on error.
1524  */
1525 char *talloc_vasprintf(const void *t, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(2,0);
1526
1527 /**
1528  * @brief Format a string given a va_list and append it to the given destination
1529  *        string.
1530  *
1531  * @param[in]  s        The destination string to append to.
1532  *
1533  * @param[in]  fmt      The format string.
1534  *
1535  * @param[in]  ap       The parameters used to fill fmt.
1536  *
1537  * @return              The formatted string, NULL on error.
1538  *
1539  * @see talloc_vasprintf()
1540  */
1541 char *talloc_vasprintf_append(char *s, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(2,0);
1542
1543 /**
1544  * @brief Format a string given a va_list and append it to the given destination
1545  *        buffer.
1546  *
1547  * @param[in]  s        The destination buffer to append to.
1548  *
1549  * @param[in]  fmt      The format string.
1550  *
1551  * @param[in]  ap       The parameters used to fill fmt.
1552  *
1553  * @return              The formatted string, NULL on error.
1554  *
1555  * @see talloc_vasprintf()
1556  */
1557 char *talloc_vasprintf_append_buffer(char *s, const char *fmt, va_list ap) PRINTF_ATTRIBUTE(2,0);
1558
1559 /**
1560  * @brief Format a string.
1561  *
1562  * This function is the talloc equivalent of the C library function asprintf(3).
1563  *
1564  * This functions sets the name of the new pointer to the new string. This is
1565  * equivalent to:
1566  *
1567  * @code
1568  *      talloc_set_name_const(ptr, ptr)
1569  * @endcode
1570  *
1571  * @param[in]  t        The talloc context to hang the result off.
1572  *
1573  * @param[in]  fmt      The format string.
1574  *
1575  * @param[in]  ...      The parameters used to fill fmt.
1576  *
1577  * @return              The formatted string, NULL on error.
1578  */
1579 char *talloc_asprintf(const void *t, const char *fmt, ...) PRINTF_ATTRIBUTE(2,3);
1580
1581 /**
1582  * @brief Append a formatted string to another string.
1583  *
1584  * This function appends the given formatted string to the given string. Use
1585  * this variant when the string in the current talloc buffer may have been
1586  * truncated in length.
1587  *
1588  * This functions sets the name of the new pointer to the new
1589  * string. This is equivalent to:
1590  *
1591  * @code
1592  *      talloc_set_name_const(ptr, ptr)
1593  * @endcode
1594  *
1595  * If <code>s == NULL</code> then new context is created.
1596  *
1597  * @param[in]  s        The string to append to.
1598  *
1599  * @param[in]  fmt      The format string.
1600  *
1601  * @param[in]  ...      The parameters used to fill fmt.
1602  *
1603  * @return              The formatted string, NULL on error.
1604  */
1605 char *talloc_asprintf_append(char *s, const char *fmt, ...) PRINTF_ATTRIBUTE(2,3);
1606
1607 /**
1608  * @brief Append a formatted string to another string.
1609  *
1610  * This is a more efficient version of talloc_asprintf_append(). It determines
1611  * the length of the destination string by the size of the talloc context.
1612  *
1613  * Use this very carefully as it produces a different result than
1614  * talloc_asprintf_append() when a zero character is in the middle of the
1615  * destination string.
1616  *
1617  * @code
1618  *      char *str_a = talloc_strdup(NULL, "hello world");
1619  *      char *str_b = talloc_strdup(NULL, "hello world");
1620  *      str_a[5] = str_b[5] = '\0'
1621  *
1622  *      char *app = talloc_asprintf_append(str_a, "%s", ", hello");
1623  *      char *buf = talloc_strdup_append_buffer(str_b, "%s", ", hello");
1624  *
1625  *      printf("%s\n", app); // hello, hello (app = "hello, hello")
1626  *      printf("%s\n", buf); // hello (buf = "hello\0world, hello")
1627  * @endcode
1628  *
1629  * If <code>s == NULL</code> then new context is created.
1630  *
1631  * @param[in]  s        The string to append to
1632  *
1633  * @param[in]  fmt      The format string.
1634  *
1635  * @param[in]  ...      The parameters used to fill fmt.
1636  *
1637  * @return              The formatted string, NULL on error.
1638  *
1639  * @see talloc_asprintf()
1640  * @see talloc_asprintf_append()
1641  */
1642 char *talloc_asprintf_append_buffer(char *s, const char *fmt, ...) PRINTF_ATTRIBUTE(2,3);
1643
1644 /* @} ******************************************************************/
1645
1646 /**
1647  * @defgroup talloc_debug The talloc debugging support functions
1648  * @ingroup talloc
1649  *
1650  * To aid memory debugging, talloc contains routines to inspect the currently
1651  * allocated memory hierarchy.
1652  *
1653  * @{
1654  */
1655
1656 /**
1657  * @brief Walk a complete talloc hierarchy.
1658  *
1659  * This provides a more flexible reports than talloc_report(). It
1660  * will recursively call the callback for the entire tree of memory
1661  * referenced by the pointer. References in the tree are passed with
1662  * is_ref = 1 and the pointer that is referenced.
1663  *
1664  * You can pass NULL for the pointer, in which case a report is
1665  * printed for the top level memory context, but only if
1666  * talloc_enable_leak_report() or talloc_enable_leak_report_full()
1667  * has been called.
1668  *
1669  * The recursion is stopped when depth >= max_depth.
1670  * max_depth = -1 means only stop at leaf nodes.
1671  *
1672  * @param[in]  ptr      The talloc chunk.
1673  *
1674  * @param[in]  depth    Internal parameter to control recursion. Call with 0.
1675  *
1676  * @param[in]  max_depth  Maximum recursion level.
1677  *
1678  * @param[in]  callback  Function to be called on every chunk.
1679  *
1680  * @param[in]  private_data  Private pointer passed to callback.
1681  */
1682 void talloc_report_depth_cb(const void *ptr, int depth, int max_depth,
1683                             void (*callback)(const void *ptr,
1684                                              int depth, int max_depth,
1685                                              int is_ref,
1686                                              void *private_data),
1687                             void *private_data);
1688
1689 /**
1690  * @brief Print a talloc hierarchy.
1691  *
1692  * This provides a more flexible reports than talloc_report(). It
1693  * will let you specify the depth and max_depth.
1694  *
1695  * @param[in]  ptr      The talloc chunk.
1696  *
1697  * @param[in]  depth    Internal parameter to control recursion. Call with 0.
1698  *
1699  * @param[in]  max_depth  Maximum recursion level.
1700  *
1701  * @param[in]  f        The file handle to print to.
1702  */
1703 void talloc_report_depth_file(const void *ptr, int depth, int max_depth, FILE *f);
1704
1705 /**
1706  * @brief Print a summary report of all memory used by ptr.
1707  *
1708  * This provides a more detailed report than talloc_report(). It will
1709  * recursively print the entire tree of memory referenced by the
1710  * pointer. References in the tree are shown by giving the name of the
1711  * pointer that is referenced.
1712  *
1713  * You can pass NULL for the pointer, in which case a report is printed
1714  * for the top level memory context, but only if
1715  * talloc_enable_leak_report() or talloc_enable_leak_report_full() has
1716  * been called.
1717  *
1718  * @param[in]  ptr      The talloc chunk.
1719  *
1720  * @param[in]  f        The file handle to print to.
1721  *
1722  * Example:
1723  * @code
1724  *      unsigned int *a, *b;
1725  *      a = talloc(NULL, unsigned int);
1726  *      b = talloc(a, unsigned int);
1727  *      fprintf(stderr, "Dumping memory tree for a:\n");
1728  *      talloc_report_full(a, stderr);
1729  * @endcode
1730  *
1731  * @see talloc_report()
1732  */
1733 void talloc_report_full(const void *ptr, FILE *f);
1734
1735 /**
1736  * @brief Print a summary report of all memory used by ptr.
1737  *
1738  * This function prints a summary report of all memory used by ptr. One line of
1739  * report is printed for each immediate child of ptr, showing the total memory
1740  * and number of blocks used by that child.
1741  *
1742  * You can pass NULL for the pointer, in which case a report is printed
1743  * for the top level memory context, but only if talloc_enable_leak_report()
1744  * or talloc_enable_leak_report_full() has been called.
1745  *
1746  * @param[in]  ptr      The talloc chunk.
1747  *
1748  * @param[in]  f        The file handle to print to.
1749  *
1750  * Example:
1751  * @code
1752  *      unsigned int *a, *b;
1753  *      a = talloc(NULL, unsigned int);
1754  *      b = talloc(a, unsigned int);
1755  *      fprintf(stderr, "Summary of memory tree for a:\n");
1756  *      talloc_report(a, stderr);
1757  * @endcode
1758  *
1759  * @see talloc_report_full()
1760  */
1761 void talloc_report(const void *ptr, FILE *f);
1762
1763 /**
1764  * @brief Enable tracking the use of NULL memory contexts.
1765  *
1766  * This enables tracking of the NULL memory context without enabling leak
1767  * reporting on exit. Useful for when you want to do your own leak
1768  * reporting call via talloc_report_null_full();
1769  */
1770 void talloc_enable_null_tracking(void);
1771
1772 /**
1773  * @brief Enable tracking the use of NULL memory contexts.
1774  *
1775  * This enables tracking of the NULL memory context without enabling leak
1776  * reporting on exit. Useful for when you want to do your own leak
1777  * reporting call via talloc_report_null_full();
1778  */
1779 void talloc_enable_null_tracking_no_autofree(void);
1780
1781 /**
1782  * @brief Disable tracking of the NULL memory context.
1783  *
1784  * This disables tracking of the NULL memory context.
1785  */
1786 void talloc_disable_null_tracking(void);
1787
1788 /**
1789  * @brief Enable leak report when a program exits.
1790  *
1791  * This enables calling of talloc_report(NULL, stderr) when the program
1792  * exits. In Samba4 this is enabled by using the --leak-report command
1793  * line option.
1794  *
1795  * For it to be useful, this function must be called before any other
1796  * talloc function as it establishes a "null context" that acts as the
1797  * top of the tree. If you don't call this function first then passing
1798  * NULL to talloc_report() or talloc_report_full() won't give you the
1799  * full tree printout.
1800  *
1801  * Here is a typical talloc report:
1802  *
1803  * @code
1804  * talloc report on 'null_context' (total 267 bytes in 15 blocks)
1805  *      libcli/auth/spnego_parse.c:55  contains     31 bytes in   2 blocks
1806  *      libcli/auth/spnego_parse.c:55  contains     31 bytes in   2 blocks
1807  *      iconv(UTF8,CP850)              contains     42 bytes in   2 blocks
1808  *      libcli/auth/spnego_parse.c:55  contains     31 bytes in   2 blocks
1809  *      iconv(CP850,UTF8)              contains     42 bytes in   2 blocks
1810  *      iconv(UTF8,UTF-16LE)           contains     45 bytes in   2 blocks
1811  *      iconv(UTF-16LE,UTF8)           contains     45 bytes in   2 blocks
1812  * @endcode
1813  */
1814 void talloc_enable_leak_report(void);
1815
1816 /**
1817  * @brief Enable full leak report when a program exits.
1818  *
1819  * This enables calling of talloc_report_full(NULL, stderr) when the
1820  * program exits. In Samba4 this is enabled by using the
1821  * --leak-report-full command line option.
1822  *
1823  * For it to be useful, this function must be called before any other
1824  * talloc function as it establishes a "null context" that acts as the
1825  * top of the tree. If you don't call this function first then passing
1826  * NULL to talloc_report() or talloc_report_full() won't give you the
1827  * full tree printout.
1828  *
1829  * Here is a typical full report:
1830  *
1831  * @code
1832  * full talloc report on 'root' (total 18 bytes in 8 blocks)
1833  *      p1                             contains     18 bytes in   7 blocks (ref 0)
1834  *      r1                             contains     13 bytes in   2 blocks (ref 0)
1835  *      reference to: p2
1836  *      p2                             contains      1 bytes in   1 blocks (ref 1)
1837  *      x3                             contains      1 bytes in   1 blocks (ref 0)
1838  *      x2                             contains      1 bytes in   1 blocks (ref 0)
1839  *      x1                             contains      1 bytes in   1 blocks (ref 0)
1840  * @endcode
1841  */
1842 void talloc_enable_leak_report_full(void);
1843
1844 /**
1845  * @brief Set a custom "abort" function that is called on serious error.
1846  *
1847  * The default "abort" function is <code>abort()</code>.
1848  *
1849  * The "abort" function is called when:
1850  *
1851  * <ul>
1852  *  <li>talloc_get_type_abort() fails</li>
1853  *  <li>the provided pointer is not a valid talloc context</li>
1854  *  <li>when the context meta data are invalid</li>
1855  *  <li>when access after free is detected</li>
1856  * </ul>
1857  *
1858  * Example:
1859  *
1860  * @code
1861  * void my_abort(const char *reason)
1862  * {
1863  *      fprintf(stderr, "talloc abort: %s\n", reason);
1864  *      abort();
1865  * }
1866  *
1867  *      talloc_set_abort_fn(my_abort);
1868  * @endcode
1869  *
1870  * @param[in]  abort_fn      The new "abort" function.
1871  *
1872  * @see talloc_set_log_fn()
1873  * @see talloc_get_type()
1874  */
1875 void talloc_set_abort_fn(void (*abort_fn)(const char *reason));
1876
1877 /**
1878  * @brief Set a logging function.
1879  *
1880  * @param[in]  log_fn      The logging function.
1881  *
1882  * @see talloc_set_log_stderr()
1883  * @see talloc_set_abort_fn()
1884  */
1885 void talloc_set_log_fn(void (*log_fn)(const char *message));
1886
1887 /**
1888  * @brief Set stderr as the output for logs.
1889  *
1890  * @see talloc_set_log_fn()
1891  * @see talloc_set_abort_fn()
1892  */
1893 void talloc_set_log_stderr(void);
1894
1895 /**
1896  * @brief Set a max memory limit for the current context hierarchy
1897  *        This affects all children of this context and constrain any
1898  *        allocation in the hierarchy to never exceed the limit set.
1899  *        The limit can be removed by setting 0 (unlimited) as the
1900  *        max_size by calling the funciton again on the sam context.
1901  *        Memory limits can also be nested, meaning a hild can have
1902  *        a stricter memory limit than a parent.
1903  *        Memory limits are enforced only at memory allocation time.
1904  *        Stealing a context into a 'limited' hierarchy properly
1905  *        updates memory usage but does *not* cause failure if the
1906  *        move causes the new parent to exceed its limits. However
1907  *        any further allocation on that hierarchy will then fail.
1908  *
1909  * @param[in]   ctx             The talloc context to set the limit on
1910  * @param[in]   max_size        The (new) max_size
1911  */
1912 int talloc_set_memlimit(const void *ctx, size_t max_size);
1913
1914 /* @} ******************************************************************/
1915
1916 #if TALLOC_DEPRECATED
1917 #define talloc_zero_p(ctx, type) talloc_zero(ctx, type)
1918 #define talloc_p(ctx, type) talloc(ctx, type)
1919 #define talloc_array_p(ctx, type, count) talloc_array(ctx, type, count)
1920 #define talloc_realloc_p(ctx, p, type, count) talloc_realloc(ctx, p, type, count)
1921 #define talloc_destroy(ctx) talloc_free(ctx)
1922 #define talloc_append_string(c, s, a) (s?talloc_strdup_append(s,a):talloc_strdup(c, a))
1923 #endif
1924
1925 #ifndef TALLOC_MAX_DEPTH
1926 #define TALLOC_MAX_DEPTH 10000
1927 #endif
1928
1929 #ifdef __cplusplus
1930 } /* end of extern "C" */
1931 #endif
1932
1933 #endif