f132c51208b652d6115d4f0174244e6cac3e8ce5
[strongswan.git] / src / libstrongswan / utils / leak_detective.c
1 /**
2 * @file leak_detective.c
3 *
4 * @brief Allocation hooks to find memory leaks.
5 */
6
7 /*
8 * Copyright (C) 2006 Martin Willi
9 * Hochschule fuer Technik Rapperswil
10 *
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the
13 * Free Software Foundation; either version 2 of the License, or (at your
14 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 * for more details.
20 */
21
22 #include <stddef.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <malloc.h>
26 #include <execinfo.h>
27 #include <signal.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <dlfcn.h>
32 #include <unistd.h>
33 #include <syslog.h>
34 #include <pthread.h>
35 #include <netdb.h>
36 #include <printf.h>
37
38 #include "leak_detective.h"
39
40 #include <library.h>
41 #include <debug.h>
42
43 #ifdef LEAK_DETECTIVE
44
45 /**
46 * Magic value which helps to detect memory corruption. Yummy!
47 */
48 #define MEMORY_HEADER_MAGIC 0x7ac0be11
49
50 /**
51 * Pattern which is filled in memory before freeing it
52 */
53 #define MEMORY_FREE_PATTERN 0xFF
54
55 /**
56 * Pattern which is filled in newly allocated memory
57 */
58 #define MEMORY_ALLOC_PATTERN 0xEE
59
60
61 static void install_hooks(void);
62 static void uninstall_hooks(void);
63 static void *malloc_hook(size_t, const void *);
64 static void *realloc_hook(void *, size_t, const void *);
65 static void free_hook(void*, const void *);
66
67 static u_int count_malloc = 0;
68 static u_int count_free = 0;
69 static u_int count_realloc = 0;
70
71 typedef struct memory_header_t memory_header_t;
72
73 /**
74 * Header which is prepended to each allocated memory block
75 */
76 struct memory_header_t {
77 /**
78 * Magci byte which must(!) hold MEMORY_HEADER_MAGIC
79 */
80 u_int32_t magic;
81
82 /**
83 * Number of bytes following after the header
84 */
85 size_t bytes;
86
87 /**
88 * Stack frames at the time of allocation
89 */
90 void *stack_frames[STACK_FRAMES_COUNT];
91
92 /**
93 * Number of stacks frames obtained in stack_frames
94 */
95 int stack_frame_count;
96
97 /**
98 * Pointer to previous entry in linked list
99 */
100 memory_header_t *previous;
101
102 /**
103 * Pointer to next entry in linked list
104 */
105 memory_header_t *next;
106 };
107
108 /**
109 * first mem header is just a dummy to chain
110 * the others on it...
111 */
112 static memory_header_t first_header = {
113 magic: MEMORY_HEADER_MAGIC,
114 bytes: 0,
115 stack_frame_count: 0,
116 previous: NULL,
117 next: NULL
118 };
119
120 /**
121 * standard hooks, used to temparily remove hooking
122 */
123 static void *old_malloc_hook, *old_realloc_hook, *old_free_hook;
124
125 /**
126 * are the hooks currently installed?
127 */
128 static bool installed = FALSE;
129
130 /**
131 * Mutex to exclusivly uninstall hooks, access heap list
132 */
133 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
134
135
136 /**
137 * log stack frames queried by backtrace()
138 * TODO: Dump symbols of static functions. This could be done with
139 * the addr2line utility or the GNU BFD Library...
140 */
141 static void log_stack_frames(void **stack_frames, int stack_frame_count)
142 {
143 char **strings;
144 size_t i;
145
146 strings = backtrace_symbols (stack_frames, stack_frame_count);
147
148 DBG1(" dumping %d stack frame addresses", stack_frame_count);
149
150 for (i = 0; i < stack_frame_count; i++)
151 {
152 DBG1(" %s", strings[i]);
153 }
154 free (strings);
155 }
156
157 /**
158 * Whitelist, which contains address ranges in stack frames ignored when leaking.
159 *
160 * This is necessary, as some function use allocation hacks (static buffers)
161 * and so on, which we want to suppress on leak reports.
162 *
163 * The range_size is calculated using the readelf utility, e.g.:
164 * readelf -s /lib/glibc.so.6
165 * The values are for glibc-2.4 and may or may not be correct on other systems.
166 */
167 typedef struct whitelist_t whitelist_t;
168
169 struct whitelist_t {
170 void* range_start;
171 size_t range_size;
172 };
173
174 whitelist_t whitelist[] = {
175 {pthread_create, 2542},
176 {pthread_setspecific, 217},
177 {mktime, 60},
178 {tzset, 123},
179 {inet_ntoa, 249},
180 {strerror, 180},
181 {getprotobynumber, 291},
182 {getservbyport, 311},
183 {register_printf_function, 159},
184 {syslog, 45},
185 };
186
187 /**
188 * Check if this stack frame is whitelisted.
189 */
190 static bool is_whitelisted(void **stack_frames, int stack_frame_count)
191 {
192 int i, j;
193
194 for (i=0; i< stack_frame_count; i++)
195 {
196 for (j=0; j<sizeof(whitelist)/sizeof(whitelist_t); j++)
197 {
198 if (stack_frames[i] >= whitelist[j].range_start &&
199 stack_frames[i] <= (whitelist[j].range_start + whitelist[j].range_size))
200 {
201 return TRUE;
202 }
203 }
204 }
205 return FALSE;
206 }
207
208 /**
209 * Report leaks at library destruction
210 */
211 void report_leaks()
212 {
213 memory_header_t *hdr;
214 int leaks = 0;
215
216 for (hdr = first_header.next; hdr != NULL; hdr = hdr->next)
217 {
218 if (!is_whitelisted(hdr->stack_frames, hdr->stack_frame_count))
219 {
220 DBG1("Leak (%d bytes at %p):", hdr->bytes, hdr + 1);
221 log_stack_frames(hdr->stack_frames, hdr->stack_frame_count);
222 leaks++;
223 }
224 }
225
226 switch (leaks)
227 {
228 case 0:
229 DBG1("No leaks detected");
230 break;
231 case 1:
232 DBG1("One leak detected");
233 break;
234 default:
235 DBG1("%d leaks detected", leaks);
236 break;
237 }
238 }
239
240 /**
241 * Installs the malloc hooks, enables leak detection
242 */
243 static void install_hooks()
244 {
245 if (!installed)
246 {
247 old_malloc_hook = __malloc_hook;
248 old_realloc_hook = __realloc_hook;
249 old_free_hook = __free_hook;
250 __malloc_hook = malloc_hook;
251 __realloc_hook = realloc_hook;
252 __free_hook = free_hook;
253 installed = TRUE;
254 }
255 }
256
257 /**
258 * Uninstalls the malloc hooks, disables leak detection
259 */
260 static void uninstall_hooks()
261 {
262 if (installed)
263 {
264 __malloc_hook = old_malloc_hook;
265 __free_hook = old_free_hook;
266 __realloc_hook = old_realloc_hook;
267 installed = FALSE;
268 }
269 }
270
271 /**
272 * Hook function for malloc()
273 */
274 void *malloc_hook(size_t bytes, const void *caller)
275 {
276 memory_header_t *hdr;
277
278 pthread_mutex_lock(&mutex);
279 count_malloc++;
280 uninstall_hooks();
281 hdr = malloc(bytes + sizeof(memory_header_t));
282 /* set to something which causes crashes */
283 memset(hdr, MEMORY_ALLOC_PATTERN, bytes + sizeof(memory_header_t));
284
285 hdr->magic = MEMORY_HEADER_MAGIC;
286 hdr->bytes = bytes;
287 hdr->stack_frame_count = backtrace(hdr->stack_frames, STACK_FRAMES_COUNT);
288 install_hooks();
289
290 /* insert at the beginning of the list */
291 hdr->next = first_header.next;
292 if (hdr->next)
293 {
294 hdr->next->previous = hdr;
295 }
296 hdr->previous = &first_header;
297 first_header.next = hdr;
298 pthread_mutex_unlock(&mutex);
299 return hdr + 1;
300 }
301
302 /**
303 * Hook function for free()
304 */
305 void free_hook(void *ptr, const void *caller)
306 {
307 void *stack_frames[STACK_FRAMES_COUNT];
308 int stack_frame_count;
309 memory_header_t *hdr = ptr - sizeof(memory_header_t);
310
311 /* allow freeing of NULL */
312 if (ptr == NULL)
313 {
314 return;
315 }
316
317 pthread_mutex_lock(&mutex);
318 count_free++;
319 uninstall_hooks();
320 if (hdr->magic != MEMORY_HEADER_MAGIC)
321 {
322 DBG1("freeing of invalid memory (%p, MAGIC 0x%x != 0x%x):",
323 ptr, hdr->magic, MEMORY_HEADER_MAGIC);
324 stack_frame_count = backtrace(stack_frames, STACK_FRAMES_COUNT);
325 log_stack_frames(stack_frames, stack_frame_count);
326 install_hooks();
327 pthread_mutex_unlock(&mutex);
328 return;
329 }
330
331 /* remove item from list */
332 if (hdr->next)
333 {
334 hdr->next->previous = hdr->previous;
335 }
336 hdr->previous->next = hdr->next;
337
338 /* clear MAGIC, set mem to something remarkable */
339 memset(hdr, MEMORY_FREE_PATTERN, hdr->bytes + sizeof(memory_header_t));
340
341 free(hdr);
342 install_hooks();
343 pthread_mutex_unlock(&mutex);
344 }
345
346 /**
347 * Hook function for realloc()
348 */
349 void *realloc_hook(void *old, size_t bytes, const void *caller)
350 {
351 memory_header_t *hdr;
352 void *stack_frames[STACK_FRAMES_COUNT];
353 int stack_frame_count;
354
355 /* allow reallocation of NULL */
356 if (old == NULL)
357 {
358 return malloc_hook(bytes, caller);
359 }
360
361 hdr = old - sizeof(memory_header_t);
362
363 pthread_mutex_lock(&mutex);
364 count_realloc++;
365 uninstall_hooks();
366 if (hdr->magic != MEMORY_HEADER_MAGIC)
367 {
368 DBG1("reallocation of invalid memory (%p):", old);
369 stack_frame_count = backtrace(stack_frames, STACK_FRAMES_COUNT);
370 log_stack_frames(stack_frames, stack_frame_count);
371 install_hooks();
372 pthread_mutex_unlock(&mutex);
373 raise(SIGKILL);
374 return NULL;
375 }
376
377 hdr = realloc(hdr, bytes + sizeof(memory_header_t));
378
379 /* update statistics */
380 hdr->bytes = bytes;
381 hdr->stack_frame_count = backtrace(hdr->stack_frames, STACK_FRAMES_COUNT);
382
383 /* update header of linked list neighbours */
384 if (hdr->next)
385 {
386 hdr->next->previous = hdr;
387 }
388 hdr->previous->next = hdr;
389 install_hooks();
390 pthread_mutex_unlock(&mutex);
391 return hdr + 1;
392 }
393
394 /**
395 * Setup leak detective
396 */
397 void __attribute__ ((constructor)) leak_detective_init()
398 {
399 install_hooks();
400 }
401
402 /**
403 * Clean up leak detective
404 */
405 void __attribute__ ((destructor)) leak_detective_cleanup()
406 {
407 uninstall_hooks();
408 report_leaks();
409 }
410
411 /**
412 * Log memory allocation statistics
413 */
414 void leak_detective_status(FILE *stream)
415 {
416 u_int blocks = 0;
417 size_t bytes = 0;
418 memory_header_t *hdr = &first_header;
419
420 pthread_mutex_lock(&mutex);
421 while ((hdr = hdr->next))
422 {
423 blocks++;
424 bytes += hdr->bytes;
425 }
426 pthread_mutex_unlock(&mutex);
427
428 fprintf(stream, "allocation statistics:\n");
429 fprintf(stream, " call stats: malloc: %d, free: %d, realloc: %d\n",
430 count_malloc, count_free, count_realloc);
431 fprintf(stream, " allocated %d blocks, total size %d bytes (avg. %d bytes)\n",
432 blocks, bytes, bytes/blocks);
433 }
434
435 #else /* !LEAK_DETECTION */
436
437 /**
438 * Dummy when !using LEAK_DETECTIVE
439 */
440 void leak_detective_status(FILE *stream)
441 {
442
443 }
444
445 #endif /* LEAK_DETECTION */