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