e2506e7e2324abb16795f579317044e6cf277029
[strongswan.git] / src / libstrongswan / utils / leak_detective.c
1 /*
2 * Copyright (C) 2006-2008 Martin Willi
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 *
15 * $Id$
16 */
17
18 #ifdef HAVE_DLADDR
19 # define _GNU_SOURCE
20 # include <dlfcn.h>
21 #endif /* HAVE_DLADDR */
22
23 #include <stddef.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <malloc.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 #include <locale.h>
38 #ifdef HAVE_BACKTRACE
39 # include <execinfo.h>
40 #endif /* HAVE_BACKTRACE */
41
42 #include "leak_detective.h"
43
44 #include <library.h>
45 #include <debug.h>
46
47 typedef struct private_leak_detective_t private_leak_detective_t;
48
49 /**
50 * private data of leak_detective
51 */
52 struct private_leak_detective_t {
53
54 /**
55 * public functions
56 */
57 leak_detective_t public;
58 };
59
60 /**
61 * Magic value which helps to detect memory corruption. Yummy!
62 */
63 #define MEMORY_HEADER_MAGIC 0x7ac0be11
64
65 /**
66 * Magic written to tail of allocation
67 */
68 #define MEMORY_TAIL_MAGIC 0xcafebabe
69
70 /**
71 * Pattern which is filled in memory before freeing it
72 */
73 #define MEMORY_FREE_PATTERN 0xFF
74
75 /**
76 * Pattern which is filled in newly allocated memory
77 */
78 #define MEMORY_ALLOC_PATTERN 0xEE
79
80
81 static void install_hooks(void);
82 static void uninstall_hooks(void);
83 static void *malloc_hook(size_t, const void *);
84 static void *realloc_hook(void *, size_t, const void *);
85 static void free_hook(void*, const void *);
86
87 static u_int count_malloc = 0;
88 static u_int count_free = 0;
89 static u_int count_realloc = 0;
90
91 typedef struct memory_header_t memory_header_t;
92 typedef struct memory_tail_t memory_tail_t;
93
94 /**
95 * Header which is prepended to each allocated memory block
96 */
97 struct memory_header_t {
98
99 /**
100 * Number of bytes following after the header
101 */
102 u_int bytes;
103
104 /**
105 * Stack frames at the time of allocation
106 */
107 void *stack_frames[STACK_FRAMES_COUNT];
108
109 /**
110 * Number of stacks frames obtained in stack_frames
111 */
112 int stack_frame_count;
113
114 /**
115 * Pointer to previous entry in linked list
116 */
117 memory_header_t *previous;
118
119 /**
120 * Pointer to next entry in linked list
121 */
122 memory_header_t *next;
123
124 /**
125 * magic bytes to detect bad free or heap underflow, MEMORY_HEADER_MAGIC
126 */
127 u_int32_t magic;
128
129 }__attribute__((__packed__));
130
131 /**
132 * tail appended to each allocated memory block
133 */
134 struct memory_tail_t {
135
136 /**
137 * Magic bytes to detect heap overflow, MEMORY_TAIL_MAGIC
138 */
139 u_int32_t magic;
140
141 }__attribute__((__packed__));
142
143 /**
144 * first mem header is just a dummy to chain
145 * the others on it...
146 */
147 static memory_header_t first_header = {
148 magic: MEMORY_HEADER_MAGIC,
149 bytes: 0,
150 stack_frame_count: 0,
151 previous: NULL,
152 next: NULL
153 };
154
155 /**
156 * standard hooks, used to temparily remove hooking
157 */
158 static void *old_malloc_hook, *old_realloc_hook, *old_free_hook;
159
160 /**
161 * are the hooks currently installed?
162 */
163 static bool installed = FALSE;
164
165 /**
166 * Mutex to exclusivly uninstall hooks, access heap list
167 */
168 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
169
170
171 /**
172 * log stack frames queried by backtrace()
173 * TODO: Dump symbols of static functions. This could be done with
174 * the addr2line utility or the GNU BFD Library...
175 */
176 static void log_stack_frames(void **stack_frames, int stack_frame_count)
177 {
178 #ifdef HAVE_BACKTRACE
179 char **strings;
180 size_t i;
181
182 strings = backtrace_symbols(stack_frames, stack_frame_count);
183
184 fprintf(stderr, " dumping %d stack frame addresses\n", stack_frame_count);
185
186 for (i = 0; i < stack_frame_count; i++)
187 {
188 #ifdef HAVE_DLADDR
189 Dl_info info;
190
191 /* TODO: this is quite hackish, but it works. A more proper solution
192 * would execve addr2strongline and pipe the output to DBG1() */
193 if (dladdr(stack_frames[i], &info))
194 {
195 char cmd[1024];
196 void *ptr = stack_frames[i];
197
198 if (strstr(info.dli_fname, ".so"))
199 {
200 ptr = (void*)(stack_frames[i] - info.dli_fbase);
201 }
202 snprintf(cmd, sizeof(cmd), "addr2line -e %s %p", info.dli_fname, ptr);
203 if (info.dli_sname)
204 {
205 fprintf(stderr, " \e[33m%s\e[0m @ %p (\e[31m%s+0x%x\e[0m) [%p]\n",
206 info.dli_fname, info.dli_fbase, info.dli_sname,
207 stack_frames[i] - info.dli_saddr, stack_frames[i]);
208 }
209 else
210 {
211 fprintf(stderr, " \e[33m%s\e[0m @ %p [%p]\n", info.dli_fname,
212 info.dli_fbase, stack_frames[i]);
213 }
214 fprintf(stderr, " -> \e[32m");
215 system(cmd);
216 fprintf(stderr, "\e[0m");
217 }
218 else
219 #endif /* HAVE_DLADDR */
220 {
221 fprintf(stderr, " %s\n", strings[i]);
222 }
223 }
224 free (strings);
225 #endif /* HAVE_BACKTRACE */
226 }
227
228 /**
229 * Leak report white list
230 *
231 * List of functions using static allocation buffers or should be suppressed
232 * otherwise on leak report.
233 */
234 char *whitelist[] = {
235 /* pthread stuff */
236 "pthread_create",
237 "pthread_setspecific",
238 /* glibc functions */
239 "mktime",
240 "tzset",
241 "inet_ntoa",
242 "strerror",
243 "getprotobynumber",
244 "getservbyport",
245 "getservbyname",
246 "register_printf_function",
247 "syslog",
248 "vsyslog",
249 "getaddrinfo",
250 "setlocale",
251 /* ignore dlopen, as we do not dlclose to get proper leak reports */
252 "dlopen",
253 /* mysql functions */
254 "mysql_init_character_set",
255 "init_client_errs",
256 "my_thread_init",
257 /* fastcgi library */
258 "FCGX_Init",
259 /* libxml */
260 "xmlInitCharEncodingHandlers",
261 "xmlInitParser",
262 "xmlInitParserCtxt",
263 /* ClearSilver */
264 "nerr_init",
265 };
266
267 /**
268 * check if a stack frame contains functions listed above
269 */
270 static bool is_whitelisted(void **stack_frames, int stack_frame_count)
271 {
272 int i, j;
273
274 #ifdef HAVE_DLADDR
275 for (i=0; i< stack_frame_count; i++)
276 {
277 Dl_info info;
278
279 if (dladdr(stack_frames[i], &info) && info.dli_sname)
280 {
281 for (j = 0; j < sizeof(whitelist)/sizeof(char*); j++)
282 {
283 if (streq(info.dli_sname, whitelist[j]))
284 {
285 return TRUE;
286 }
287 }
288 }
289 }
290 #endif /* HAVE_DLADDR */
291 return FALSE;
292 }
293
294 /**
295 * Report leaks at library destruction
296 */
297 void report_leaks()
298 {
299 memory_header_t *hdr;
300 int leaks = 0, whitelisted = 0;
301
302 for (hdr = first_header.next; hdr != NULL; hdr = hdr->next)
303 {
304 if (is_whitelisted(hdr->stack_frames, hdr->stack_frame_count))
305 {
306 whitelisted++;
307 }
308 else
309 {
310 fprintf(stderr, "Leak (%d bytes at %p):\n", hdr->bytes, hdr + 1);
311 /* skip the first frame, contains leak detective logic */
312 log_stack_frames(hdr->stack_frames + 1, hdr->stack_frame_count - 1);
313 leaks++;
314 }
315 }
316
317 switch (leaks)
318 {
319 case 0:
320 fprintf(stderr, "No leaks detected");
321 break;
322 case 1:
323 fprintf(stderr, "One leak detected");
324 break;
325 default:
326 fprintf(stderr, "%d leaks detected", leaks);
327 break;
328 }
329 fprintf(stderr, ", %d suppressed by whitelist\n", whitelisted);
330 }
331
332 /**
333 * Installs the malloc hooks, enables leak detection
334 */
335 static void install_hooks()
336 {
337 if (!installed)
338 {
339 old_malloc_hook = __malloc_hook;
340 old_realloc_hook = __realloc_hook;
341 old_free_hook = __free_hook;
342 __malloc_hook = malloc_hook;
343 __realloc_hook = realloc_hook;
344 __free_hook = free_hook;
345 installed = TRUE;
346 }
347 }
348
349 /**
350 * Uninstalls the malloc hooks, disables leak detection
351 */
352 static void uninstall_hooks()
353 {
354 if (installed)
355 {
356 __malloc_hook = old_malloc_hook;
357 __free_hook = old_free_hook;
358 __realloc_hook = old_realloc_hook;
359 installed = FALSE;
360 }
361 }
362
363 /**
364 * Hook function for malloc()
365 */
366 void *malloc_hook(size_t bytes, const void *caller)
367 {
368 memory_header_t *hdr;
369 memory_tail_t *tail;
370
371 pthread_mutex_lock(&mutex);
372 count_malloc++;
373 uninstall_hooks();
374 hdr = malloc(sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
375 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
376 /* set to something which causes crashes */
377 memset(hdr, MEMORY_ALLOC_PATTERN,
378 sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
379
380 hdr->magic = MEMORY_HEADER_MAGIC;
381 hdr->bytes = bytes;
382 hdr->stack_frame_count = backtrace(hdr->stack_frames, STACK_FRAMES_COUNT);
383 tail->magic = MEMORY_TAIL_MAGIC;
384 install_hooks();
385
386 /* insert at the beginning of the list */
387 hdr->next = first_header.next;
388 if (hdr->next)
389 {
390 hdr->next->previous = hdr;
391 }
392 hdr->previous = &first_header;
393 first_header.next = hdr;
394 pthread_mutex_unlock(&mutex);
395 return hdr + 1;
396 }
397
398 /**
399 * Hook function for free()
400 */
401 void free_hook(void *ptr, const void *caller)
402 {
403 void *stack_frames[STACK_FRAMES_COUNT];
404 int stack_frame_count;
405 memory_header_t *hdr;
406 memory_tail_t *tail;
407
408 /* allow freeing of NULL */
409 if (ptr == NULL)
410 {
411 return;
412 }
413 hdr = ptr - sizeof(memory_header_t);
414 tail = ptr + hdr->bytes;
415
416 pthread_mutex_lock(&mutex);
417 count_free++;
418 uninstall_hooks();
419 if (hdr->magic != MEMORY_HEADER_MAGIC)
420 {
421 fprintf(stderr, "freeing memory with corrupted header "
422 "(%p, MAGIC 0x%x != 0x%x):\n",
423 ptr, hdr->magic, MEMORY_HEADER_MAGIC);
424 stack_frame_count = backtrace(stack_frames, STACK_FRAMES_COUNT);
425 log_stack_frames(stack_frames, stack_frame_count);
426 install_hooks();
427 pthread_mutex_unlock(&mutex);
428 return;
429 }
430 if (tail->magic != MEMORY_TAIL_MAGIC)
431 {
432 fprintf(stderr, "freeing memory with corrupted tail "
433 "(%p, MAGIC 0x%x != 0x%x):\n",
434 ptr, tail->magic, MEMORY_TAIL_MAGIC);
435 stack_frame_count = backtrace(stack_frames, STACK_FRAMES_COUNT);
436 log_stack_frames(stack_frames, stack_frame_count);
437 install_hooks();
438 pthread_mutex_unlock(&mutex);
439 return;
440 }
441
442 /* remove item from list */
443 if (hdr->next)
444 {
445 hdr->next->previous = hdr->previous;
446 }
447 hdr->previous->next = hdr->next;
448
449 /* clear MAGIC, set mem to something remarkable */
450 memset(hdr, MEMORY_FREE_PATTERN, hdr->bytes + sizeof(memory_header_t));
451
452 free(hdr);
453 install_hooks();
454 pthread_mutex_unlock(&mutex);
455 }
456
457 /**
458 * Hook function for realloc()
459 */
460 void *realloc_hook(void *old, size_t bytes, const void *caller)
461 {
462 memory_header_t *hdr;
463 void *stack_frames[STACK_FRAMES_COUNT];
464 int stack_frame_count;
465 memory_tail_t *tail;
466
467 /* allow reallocation of NULL */
468 if (old == NULL)
469 {
470 return malloc_hook(bytes, caller);
471 }
472
473 hdr = old - sizeof(memory_header_t);
474 tail = old + hdr->bytes;
475
476 pthread_mutex_lock(&mutex);
477 count_realloc++;
478 uninstall_hooks();
479 if (hdr->magic != MEMORY_HEADER_MAGIC)
480 {
481 fprintf(stderr, "reallocating memory with corrupted header "
482 "(%p, MAGIC 0x%x != 0x%x):\n",
483 old, hdr->magic, MEMORY_HEADER_MAGIC);
484 stack_frame_count = backtrace(stack_frames, STACK_FRAMES_COUNT);
485 log_stack_frames(stack_frames, stack_frame_count);
486 install_hooks();
487 pthread_mutex_unlock(&mutex);
488 raise(SIGKILL);
489 return NULL;
490 }
491 if (tail->magic != MEMORY_TAIL_MAGIC)
492 {
493 fprintf(stderr, "reallocating memory with corrupted tail "
494 "(%p, MAGIC 0x%x != 0x%x):\n",
495 old, tail->magic, MEMORY_TAIL_MAGIC);
496 stack_frame_count = backtrace(stack_frames, STACK_FRAMES_COUNT);
497 log_stack_frames(stack_frames, stack_frame_count);
498 install_hooks();
499 pthread_mutex_unlock(&mutex);
500 raise(SIGKILL);
501 return NULL;
502 }
503 /* clear tail magic, allocate, set tail magic */
504 memset(&tail->magic, MEMORY_ALLOC_PATTERN, sizeof(tail->magic));
505 hdr = realloc(hdr, sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
506 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
507 tail->magic = MEMORY_TAIL_MAGIC;
508
509 /* update statistics */
510 hdr->bytes = bytes;
511 hdr->stack_frame_count = backtrace(hdr->stack_frames, STACK_FRAMES_COUNT);
512
513 /* update header of linked list neighbours */
514 if (hdr->next)
515 {
516 hdr->next->previous = hdr;
517 }
518 hdr->previous->next = hdr;
519 install_hooks();
520 pthread_mutex_unlock(&mutex);
521 return hdr + 1;
522 }
523
524 /**
525 * Implementation of leak_detective_t.destroy
526 */
527 static void destroy(private_leak_detective_t *this)
528 {
529 if (installed)
530 {
531 uninstall_hooks();
532 report_leaks();
533 }
534 free(this);
535 }
536
537 /*
538 * see header file
539 */
540 leak_detective_t *leak_detective_create()
541 {
542 private_leak_detective_t *this = malloc_thing(private_leak_detective_t);
543
544 this->public.destroy = (void(*)(leak_detective_t*))destroy;
545
546 if (getenv("LEAK_DETECTIVE_DISABLE") == NULL)
547 {
548 install_hooks();
549 }
550 return &this->public;
551 }
552