talloc accounting now includes number of chunks and bytes allocated.
[ira/wip.git] / source3 / lib / talloc.c
1 /* 
2    Samba Unix SMB/Netbios implementation.
3    Samba temporary memory allocation functions
4    Copyright (C) Andrew Tridgell 2000
5    Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 /**
23    @defgroup talloc Simple memory allocator
24    @{
25    
26    This is a very simple temporary memory allocator. To use it do the following:
27
28    1) when you first want to allocate a pool of meomry use
29    talloc_init() and save the resulting context pointer somewhere
30
31    2) to allocate memory use talloc()
32
33    3) when _all_ of the memory allocated using this context is no longer needed
34    use talloc_destroy()
35
36    talloc does not zero the memory. It guarantees memory of a
37    TALLOC_ALIGN alignment
38
39    @sa talloc.h
40 */
41
42 /**
43  * @todo We could allocate both the talloc_chunk structure, and the
44  * memory it contains all in one allocation, which might be a bit
45  * faster and perhaps use less memory overhead.
46  *
47  * That smells like a premature optimization, though.  -- mbp
48  **/
49
50 /**
51  * If you want testing for memory corruption, link with dmalloc or use
52  * Insure++.  It doesn't seem useful to duplicate them here.
53  **/
54
55 #include "includes.h"
56
57 struct talloc_chunk {
58         struct talloc_chunk *next;
59         size_t size;
60         void *ptr;
61 };
62
63
64 struct talloc_ctx {
65         struct talloc_chunk *list;
66         size_t total_alloc_size;
67
68         /** The name recorded for this pool, if any.  Should describe
69          * the purpose for which it was allocated.  The string is
70          * allocated within the pool. **/
71         char *name;
72
73         /** Pointer to the next allocate talloc pool, so that we can
74          * summarize all talloc memory usage. **/
75         struct talloc_ctx *next_ctx;
76 };
77
78
79 /**
80  * Start of linked list of all talloc pools.
81  **/
82 TALLOC_CTX *list_head = NULL;
83
84
85 /**
86  * Add to the global list
87  **/
88 static void talloc_enroll(TALLOC_CTX *t)
89 {
90         t->next_ctx = list_head;
91         list_head = t;
92 }
93
94
95 static void talloc_disenroll(TALLOC_CTX *t)
96 {
97         TALLOC_CTX **ttmp;
98
99         /* Use a double-* so that no special case is required for the
100          * list head. */
101         for (ttmp = &list_head; *ttmp; ttmp = &((*ttmp)->next_ctx))
102                 if (*ttmp == t) {
103                         /* ttmp is the link that points to t, either
104                          * list_head or the next_ctx link in its
105                          * predecessor */
106                         *ttmp = t->next_ctx;
107                         t->next_ctx = NULL;     /* clobber */
108                         return;
109                 }
110         abort();                /* oops, this talloc was already
111                                  * clobbered or something else went
112                                  * wrong. */
113 }
114
115
116 /** Create a new talloc context. **/
117 TALLOC_CTX *talloc_init(void)
118 {
119         TALLOC_CTX *t;
120
121         t = (TALLOC_CTX *)malloc(sizeof(*t));
122         if (!t) return NULL;
123
124         t->list = NULL;
125         t->total_alloc_size = 0;
126         t->name = NULL;
127         talloc_enroll(t);
128
129         return t;
130 }
131
132
133
134 /**
135  * Create a new talloc context, with a name specifying its purpose.
136  * Please call this in preference to talloc_init().
137  **/
138  TALLOC_CTX *talloc_init_named(char const *fmt, ...) 
139 {
140         TALLOC_CTX *t;
141         va_list ap;
142
143         t = talloc_init();
144         if (fmt) {
145                 va_start(ap, fmt);
146                 t->name = talloc_vasprintf(t, fmt, ap);
147                 va_end(ap);
148         }
149         
150         return t;
151 }
152
153
154 /** Allocate a bit of memory from the specified pool **/
155 void *talloc(TALLOC_CTX *t, size_t size)
156 {
157         void *p;
158         struct talloc_chunk *tc;
159
160         if (size == 0) return NULL;
161
162         p = malloc(size);
163         if (!p) return p;
164
165         tc = malloc(sizeof(*tc));
166         if (!tc) {
167                 SAFE_FREE(p);
168                 return NULL;
169         }
170
171         tc->ptr = p;
172         tc->size = size;
173         tc->next = t->list;
174         t->list = tc;
175         t->total_alloc_size += size;
176
177         return p;
178 }
179
180 /** A talloc version of realloc */
181 void *talloc_realloc(TALLOC_CTX *t, void *ptr, size_t size)
182 {
183         struct talloc_chunk *tc;
184
185         /* size zero is equivalent to free() */
186         if (size == 0)
187                 return NULL;
188
189         /* realloc(NULL) is equavalent to malloc() */
190         if (ptr == NULL)
191                 return talloc(t, size);
192
193         for (tc=t->list; tc; tc=tc->next) {
194                 if (tc->ptr == ptr) {
195                         ptr = Realloc(ptr, size);
196                         if (ptr) {
197                                 t->total_alloc_size += (size - tc->size);
198                                 tc->size = size;
199                                 tc->ptr = ptr;
200                         }
201                         return ptr;
202                 }
203         }
204         return NULL;
205 }
206
207 /** Destroy all the memory allocated inside @p t, but not @p t
208  * itself. */
209 void talloc_destroy_pool(TALLOC_CTX *t)
210 {
211         struct talloc_chunk *c;
212         
213         if (!t)
214                 return;
215
216         while (t->list) {
217                 c = t->list->next;
218                 SAFE_FREE(t->list->ptr);
219                 SAFE_FREE(t->list);
220                 t->list = c;
221         }
222
223         t->total_alloc_size = 0;
224 }
225
226 /** Destroy a whole pool including the context */
227 void talloc_destroy(TALLOC_CTX *t)
228 {
229         if (!t)
230                 return;
231         talloc_destroy_pool(t);
232         talloc_disenroll(t);
233         memset(t, 0, sizeof(*t));
234         SAFE_FREE(t);
235 }
236
237 /** Return the current total size of the pool. */
238 size_t talloc_pool_size(TALLOC_CTX *t)
239 {
240         return t->total_alloc_size;
241 }
242
243 const char * talloc_pool_name(TALLOC_CTX const *t)
244 {
245         return t->name;
246 }
247
248
249 /** talloc and zero memory. */
250 void *talloc_zero(TALLOC_CTX *t, size_t size)
251 {
252         void *p = talloc(t, size);
253
254         if (p)
255                 memset(p, '\0', size);
256
257         return p;
258 }
259
260 /** memdup with a talloc. */
261 void *talloc_memdup(TALLOC_CTX *t, const void *p, size_t size)
262 {
263         void *newp = talloc(t,size);
264
265         if (!newp)
266                 return 0;
267
268         memcpy(newp, p, size);
269
270         return newp;
271 }
272
273 /** strdup with a talloc */
274 char *talloc_strdup(TALLOC_CTX *t, const char *p)
275 {
276         return talloc_memdup(t, p, strlen(p) + 1);
277 }
278
279 /**
280  * Perform string formatting, and return a pointer to newly allocated
281  * memory holding the result, inside a memory pool.
282  **/
283  char *talloc_asprintf(TALLOC_CTX *t, const char *fmt, ...)
284 {
285         va_list ap;
286         char *ret;
287
288         va_start(ap, fmt);
289         ret = talloc_vasprintf(t, fmt, ap);
290         va_end(ap);
291         return ret;
292 }
293
294
295  char *talloc_vasprintf(TALLOC_CTX *t, const char *fmt, va_list ap)
296 {       
297         int len;
298         char *ret;
299         
300         len = vsnprintf(NULL, 0, fmt, ap);
301
302         ret = talloc(t, len+1);
303         if (!ret) return NULL;
304
305         vsnprintf(ret, len+1, fmt, ap);
306
307         return ret;
308 }
309
310
311 /**
312  * Realloc @p s to append the formatted result of @p fmt and return @p
313  * s, which may have moved.  Good for gradually accumulating output
314  * into a string buffer.
315  **/
316  char *talloc_asprintf_append(TALLOC_CTX *t, char *s,
317                               const char *fmt, ...)
318 {
319         va_list ap;
320
321         va_start(ap, fmt);
322         s = talloc_vasprintf_append(t, s, fmt, ap);
323         va_end(ap);
324         return s;
325 }
326
327
328
329 /**
330  * Realloc @p s to append the formatted result of @p fmt and @p ap,
331  * and return @p s, which may have moved.  Good for gradually
332  * accumulating output into a string buffer.
333  **/
334  char *talloc_vasprintf_append(TALLOC_CTX *t, char *s,
335                                const char *fmt, va_list ap)
336 {       
337         int len, s_len;
338
339         s_len = strlen(s);
340         len = vsnprintf(NULL, 0, fmt, ap);
341
342         s = talloc_realloc(t, s, s_len + len+1);
343         if (!s) return NULL;
344
345         vsnprintf(s+s_len, len+1, fmt, ap);
346
347         return s;
348 }
349
350
351 /**
352  * Return a human-readable description of all talloc memory usage.
353  * The result is allocated from @p t.
354  **/
355 char *talloc_describe_all(TALLOC_CTX *rt)
356 {
357         int n_pools = 0, total_chunks = 0;
358         size_t total_bytes = 0;
359         TALLOC_CTX *it;
360         char *s;
361
362         s = talloc_asprintf(rt, "global talloc allocations in pid%u:\n",
363                             (unsigned) getpid());
364         s = talloc_asprintf_append(rt, s, "%-40s %8s %8s\n",
365                                    "name", "chunks", "bytes");
366         s = talloc_asprintf_append(rt, s, "%-40s %8s %8s\n",
367                                    "----------------------------------------",
368                                    "--------",
369                                    "--------"); 
370         
371         for (it = list_head; it; it = it->next_ctx) {
372                 size_t bytes;
373                 int n_chunks;
374                 n_pools++;
375                 talloc_get_allocation(it, &bytes, &n_chunks);
376                 s = talloc_asprintf_append(rt, s, "%-40s %8u %8u\n",
377                                            it->name,
378                                            (unsigned) n_chunks,
379                                            (unsigned) bytes);
380                 total_bytes += bytes;
381                 total_chunks += n_chunks;
382         }
383
384         s = talloc_asprintf_append(rt, s, "%-40s %8s %8s\n",
385                                    "----------------------------------------",
386                                    "--------",
387                                    "--------"); 
388
389         s = talloc_asprintf_append(rt, s, "%-40s %8u %8u\n",
390                                    "TOTAL",
391                                    (unsigned) total_chunks, (unsigned) total_bytes);
392
393         return s;
394 }
395
396
397
398 /**
399  * Return an estimated memory usage for the specified pool.  This does
400  * not include memory used by the underlying malloc implementation.
401  **/
402 void talloc_get_allocation(TALLOC_CTX *t,
403                            size_t *total_bytes,
404                            int *n_chunks)
405 {
406         struct talloc_chunk *chunk;
407
408         *total_bytes = 0;
409         *n_chunks = 0;
410
411         for (chunk = t->list; chunk; chunk = chunk->next) {
412                 n_chunks[0]++;
413                 *total_bytes += chunk->size;
414         }
415 }
416
417
418 /** @} */