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