This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[kai/samba-autobuild/.git] / source / lib / talloc.c
1 /* 
2    Samba Unix SMB/CIFS 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  * @todo We should turn the global list off when using Insure++,
83  * otherwise all the memory will be seen as still reachable.
84  **/
85 TALLOC_CTX *list_head = NULL;
86
87
88 /**
89  * Add to the global list
90  **/
91 static void talloc_enroll(TALLOC_CTX *t)
92 {
93         t->next_ctx = list_head;
94         list_head = t;
95 }
96
97
98 static void talloc_disenroll(TALLOC_CTX *t)
99 {
100         TALLOC_CTX **ttmp;
101
102         /* Use a double-* so that no special case is required for the
103          * list head. */
104         for (ttmp = &list_head; *ttmp; ttmp = &((*ttmp)->next_ctx))
105                 if (*ttmp == t) {
106                         /* ttmp is the link that points to t, either
107                          * list_head or the next_ctx link in its
108                          * predecessor */
109                         *ttmp = t->next_ctx;
110                         t->next_ctx = NULL;     /* clobber */
111                         return;
112                 }
113         abort();                /* oops, this talloc was already
114                                  * clobbered or something else went
115                                  * wrong. */
116 }
117
118
119 /** Create a new talloc context. **/
120 TALLOC_CTX *talloc_init(void)
121 {
122         TALLOC_CTX *t;
123
124         t = (TALLOC_CTX *)malloc(sizeof(TALLOC_CTX));
125         if (t) {
126                 t->list = NULL;
127                 t->total_alloc_size = 0;
128                 t->name = NULL;
129                 talloc_enroll(t);
130         }
131
132         return t;
133 }
134
135
136
137 /**
138  * Create a new talloc context, with a name specifying its purpose.
139  * Please call this in preference to talloc_init().
140  **/
141  TALLOC_CTX *talloc_init_named(char const *fmt, ...) 
142 {
143         TALLOC_CTX *t;
144         va_list ap;
145
146         t = talloc_init();
147         if (t && fmt) {
148                 va_start(ap, fmt);
149                 t->name = talloc_vasprintf(t, fmt, ap);
150                 va_end(ap);
151         }
152         
153         return t;
154 }
155
156
157 /** Allocate a bit of memory from the specified pool **/
158 void *talloc(TALLOC_CTX *t, size_t size)
159 {
160         void *p;
161         struct talloc_chunk *tc;
162
163         if (!t || size == 0) return NULL;
164
165         p = malloc(size);
166         if (p) {
167                 tc = malloc(sizeof(*tc));
168                 if (tc) {
169                         tc->ptr = p;
170                         tc->size = size;
171                         tc->next = t->list;
172                         t->list = tc;
173                         t->total_alloc_size += size;
174                 }
175                 else {
176                         SAFE_FREE(p);
177                 }
178         }
179         return p;
180 }
181
182 /** A talloc version of realloc */
183 void *talloc_realloc(TALLOC_CTX *t, void *ptr, size_t size)
184 {
185         struct talloc_chunk *tc;
186         void *new_ptr;
187
188         /* size zero is equivalent to free() */
189         if (!t || size == 0)
190                 return NULL;
191
192         /* realloc(NULL) is equavalent to malloc() */
193         if (ptr == NULL)
194                 return talloc(t, size);
195
196         for (tc=t->list; tc; tc=tc->next) {
197                 if (tc->ptr == ptr) {
198                         new_ptr = Realloc(ptr, size);
199                         if (new_ptr) {
200                                 t->total_alloc_size += (size - tc->size);
201                                 tc->size = size;
202                                 tc->ptr = new_ptr;
203                         }
204                         return new_ptr;
205                 }
206         }
207         return NULL;
208 }
209
210 /** Destroy all the memory allocated inside @p t, but not @p t
211  * itself. */
212 void talloc_destroy_pool(TALLOC_CTX *t)
213 {
214         struct talloc_chunk *c;
215         
216         if (!t)
217                 return;
218
219         while (t->list) {
220                 c = t->list->next;
221                 SAFE_FREE(t->list->ptr);
222                 SAFE_FREE(t->list);
223                 t->list = c;
224         }
225
226         t->total_alloc_size = 0;
227 }
228
229 /** Destroy a whole pool including the context */
230 void talloc_destroy(TALLOC_CTX *t)
231 {
232         if (!t)
233                 return;
234
235         talloc_destroy_pool(t);
236         talloc_disenroll(t);
237         memset(t, 0, sizeof(TALLOC_CTX));
238         SAFE_FREE(t);
239 }
240
241 /** Return the current total size of the pool. */
242 size_t talloc_pool_size(TALLOC_CTX *t)
243 {
244         if (t)
245                 return t->total_alloc_size;
246         else
247                 return 0;
248 }
249
250 const char * talloc_pool_name(TALLOC_CTX const *t)
251 {
252         if (t)
253                 return t->name;
254         else
255                 return NULL;
256 }
257
258
259 /** talloc and zero memory. */
260 void *talloc_zero(TALLOC_CTX *t, size_t size)
261 {
262         void *p = talloc(t, size);
263
264         if (p)
265                 memset(p, '\0', size);
266
267         return p;
268 }
269
270 /** memdup with a talloc. */
271 void *talloc_memdup(TALLOC_CTX *t, const void *p, size_t size)
272 {
273         void *newp = talloc(t,size);
274
275         if (newp)
276                 memcpy(newp, p, size);
277
278         return newp;
279 }
280
281 /** strdup with a talloc */
282 char *talloc_strdup(TALLOC_CTX *t, const char *p)
283 {
284         if (p)
285                 return talloc_memdup(t, p, strlen(p) + 1);
286         else
287                 return NULL;
288 }
289
290 /**
291  * Perform string formatting, and return a pointer to newly allocated
292  * memory holding the result, inside a memory pool.
293  **/
294  char *talloc_asprintf(TALLOC_CTX *t, const char *fmt, ...)
295 {
296         va_list ap;
297         char *ret;
298
299         va_start(ap, fmt);
300         ret = talloc_vasprintf(t, fmt, ap);
301         va_end(ap);
302         return ret;
303 }
304
305
306  char *talloc_vasprintf(TALLOC_CTX *t, const char *fmt, va_list ap)
307 {       
308         int len;
309         char *ret;
310         
311         len = vsnprintf(NULL, 0, fmt, ap);
312
313         ret = talloc(t, len+1);
314         if (ret)
315                 vsnprintf(ret, len+1, fmt, ap);
316
317         return ret;
318 }
319
320
321 /**
322  * Realloc @p s to append the formatted result of @p fmt and return @p
323  * s, which may have moved.  Good for gradually accumulating output
324  * into a string buffer.
325  **/
326  char *talloc_asprintf_append(TALLOC_CTX *t, char *s,
327                               const char *fmt, ...)
328 {
329         va_list ap;
330
331         va_start(ap, fmt);
332         s = talloc_vasprintf_append(t, s, fmt, ap);
333         va_end(ap);
334         return s;
335 }
336
337
338
339 /**
340  * Realloc @p s to append the formatted result of @p fmt and @p ap,
341  * and return @p s, which may have moved.  Good for gradually
342  * accumulating output into a string buffer.
343  **/
344  char *talloc_vasprintf_append(TALLOC_CTX *t, char *s,
345                                const char *fmt, va_list ap)
346 {       
347         int len, s_len;
348
349         s_len = strlen(s);
350         len = vsnprintf(NULL, 0, fmt, ap);
351
352         s = talloc_realloc(t, s, s_len + len+1);
353         if (!s) return NULL;
354
355         vsnprintf(s+s_len, len+1, fmt, ap);
356
357         return s;
358 }
359
360
361 /**
362  * Return a human-readable description of all talloc memory usage.
363  * The result is allocated from @p t.
364  **/
365 char *talloc_describe_all(TALLOC_CTX *rt)
366 {
367         int n_pools = 0, total_chunks = 0;
368         size_t total_bytes = 0;
369         TALLOC_CTX *it;
370         char *s;
371
372         if (!rt) return NULL;
373
374         s = talloc_asprintf(rt, "global talloc allocations in pid: %u\n",
375                             (unsigned) sys_getpid());
376         s = talloc_asprintf_append(rt, s, "%-40s %8s %8s\n",
377                                    "name", "chunks", "bytes");
378         s = talloc_asprintf_append(rt, s, "%-40s %8s %8s\n",
379                                    "----------------------------------------",
380                                    "--------",
381                                    "--------"); 
382         
383         for (it = list_head; it; it = it->next_ctx) {
384                 size_t bytes;
385                 int n_chunks;
386                 fstring what;
387                 
388                 n_pools++;
389                 
390                 talloc_get_allocation(it, &bytes, &n_chunks);
391
392                 if (it->name)
393                         fstrcpy(what, it->name);
394                 else
395                         slprintf(what, sizeof what, "@%p", it);
396                 
397                 s = talloc_asprintf_append(rt, s, "%-40s %8u %8u\n",
398                                            what,
399                                            (unsigned) n_chunks,
400                                            (unsigned) bytes);
401                 total_bytes += bytes;
402                 total_chunks += n_chunks;
403         }
404
405         s = talloc_asprintf_append(rt, s, "%-40s %8s %8s\n",
406                                    "----------------------------------------",
407                                    "--------",
408                                    "--------"); 
409
410         s = talloc_asprintf_append(rt, s, "%-40s %8u %8u\n",
411                                    "TOTAL",
412                                    (unsigned) total_chunks, (unsigned) total_bytes);
413
414         return s;
415 }
416
417
418
419 /**
420  * Return an estimated memory usage for the specified pool.  This does
421  * not include memory used by the underlying malloc implementation.
422  **/
423 void talloc_get_allocation(TALLOC_CTX *t,
424                            size_t *total_bytes,
425                            int *n_chunks)
426 {
427         struct talloc_chunk *chunk;
428
429         if (t) {
430                 *total_bytes = 0;
431                 *n_chunks = 0;
432
433                 for (chunk = t->list; chunk; chunk = chunk->next) {
434                         n_chunks[0]++;
435                         *total_bytes += chunk->size;
436                 }
437         }
438 }
439
440
441 /** @} */