bb33259ff6a9c6e64f80730f1a1dcafa15e1847d
[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 #include <stddef.h>
19 #include <string.h>
20 #include <stdio.h>
21 #include <malloc.h>
22 #include <signal.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <unistd.h>
27 #include <syslog.h>
28 #include <pthread.h>
29 #include <netdb.h>
30 #include <printf.h>
31 #include <locale.h>
32
33 #include "leak_detective.h"
34
35 #include <library.h>
36 #include <debug.h>
37 #include <utils/backtrace.h>
38
39 typedef struct private_leak_detective_t private_leak_detective_t;
40
41 /**
42 * private data of leak_detective
43 */
44 struct private_leak_detective_t {
45
46 /**
47 * public functions
48 */
49 leak_detective_t public;
50 };
51
52 /**
53 * Magic value which helps to detect memory corruption. Yummy!
54 */
55 #define MEMORY_HEADER_MAGIC 0x7ac0be11
56
57 /**
58 * Magic written to tail of allocation
59 */
60 #define MEMORY_TAIL_MAGIC 0xcafebabe
61
62 /**
63 * Pattern which is filled in memory before freeing it
64 */
65 #define MEMORY_FREE_PATTERN 0xFF
66
67 /**
68 * Pattern which is filled in newly allocated memory
69 */
70 #define MEMORY_ALLOC_PATTERN 0xEE
71
72
73 static void install_hooks(void);
74 static void uninstall_hooks(void);
75 static void *malloc_hook(size_t, const void *);
76 static void *realloc_hook(void *, size_t, const void *);
77 static void free_hook(void*, const void *);
78
79 void *(*old_malloc_hook)(size_t, const void *);
80 void *(*old_realloc_hook)(void *, size_t, const void *);
81 void (*old_free_hook)(void*, const void *);
82
83 static u_int count_malloc = 0;
84 static u_int count_free = 0;
85 static u_int count_realloc = 0;
86
87 typedef struct memory_header_t memory_header_t;
88 typedef struct memory_tail_t memory_tail_t;
89
90 /**
91 * Header which is prepended to each allocated memory block
92 */
93 struct memory_header_t {
94
95 /**
96 * Number of bytes following after the header
97 */
98 u_int bytes;
99
100 /**
101 * Pointer to previous entry in linked list
102 */
103 memory_header_t *previous;
104
105 /**
106 * Pointer to next entry in linked list
107 */
108 memory_header_t *next;
109
110 /**
111 * backtrace taken during (re-)allocation
112 */
113 backtrace_t *backtrace;
114
115 /**
116 * magic bytes to detect bad free or heap underflow, MEMORY_HEADER_MAGIC
117 */
118 u_int32_t magic;
119
120 }__attribute__((__packed__));
121
122 /**
123 * tail appended to each allocated memory block
124 */
125 struct memory_tail_t {
126
127 /**
128 * Magic bytes to detect heap overflow, MEMORY_TAIL_MAGIC
129 */
130 u_int32_t magic;
131
132 }__attribute__((__packed__));
133
134 /**
135 * first mem header is just a dummy to chain
136 * the others on it...
137 */
138 static memory_header_t first_header = {
139 magic: MEMORY_HEADER_MAGIC,
140 bytes: 0,
141 backtrace: NULL,
142 previous: NULL,
143 next: NULL
144 };
145
146 /**
147 * are the hooks currently installed?
148 */
149 static bool installed = FALSE;
150
151 /**
152 * Leak report white list
153 *
154 * List of functions using static allocation buffers or should be suppressed
155 * otherwise on leak report.
156 */
157 char *whitelist[] = {
158 /* backtraces, including own */
159 "backtrace_create",
160 /* pthread stuff */
161 "pthread_create",
162 "pthread_setspecific",
163 /* glibc functions */
164 "mktime",
165 "__gmtime_r",
166 "tzset",
167 "inet_ntoa",
168 "strerror",
169 "getprotobynumber",
170 "getservbyport",
171 "getservbyname",
172 "gethostbyname_r",
173 "gethostbyname2_r",
174 "getpwnam_r",
175 "getgrnam_r",
176 "register_printf_function",
177 "syslog",
178 "vsyslog",
179 "getaddrinfo",
180 "setlocale",
181 /* ignore dlopen, as we do not dlclose to get proper leak reports */
182 "dlopen",
183 "dlerror",
184 "dlclose",
185 /* mysql functions */
186 "mysql_init_character_set",
187 "init_client_errs",
188 "my_thread_init",
189 /* fastcgi library */
190 "FCGX_Init",
191 /* libxml */
192 "xmlInitCharEncodingHandlers",
193 "xmlInitParser",
194 "xmlInitParserCtxt",
195 /* ClearSilver */
196 "nerr_init",
197 /* OpenSSL */
198 "RSA_new_method",
199 "DH_new_method",
200 "ENGINE_load_builtin_engines",
201 };
202
203 /**
204 * check if a stack frame contains functions listed above
205 */
206 static bool is_whitelisted(backtrace_t *backtrace)
207 {
208 int i;
209 for (i = 0; i < sizeof(whitelist)/sizeof(char*); i++)
210 {
211 if (backtrace->contains_function(backtrace, whitelist[i]))
212 {
213 return TRUE;
214 }
215 }
216 return FALSE;
217 }
218
219 /**
220 * Report leaks at library destruction
221 */
222 void report_leaks()
223 {
224 memory_header_t *hdr;
225 int leaks = 0, whitelisted = 0;
226
227 for (hdr = first_header.next; hdr != NULL; hdr = hdr->next)
228 {
229 if (is_whitelisted(hdr->backtrace))
230 {
231 whitelisted++;
232 }
233 else
234 {
235 fprintf(stderr, "Leak (%d bytes at %p):\n", hdr->bytes, hdr + 1);
236 /* skip the first frame, contains leak detective logic */
237 hdr->backtrace->log(hdr->backtrace, stderr);
238 leaks++;
239 }
240 }
241
242 switch (leaks)
243 {
244 case 0:
245 fprintf(stderr, "No leaks detected");
246 break;
247 case 1:
248 fprintf(stderr, "One leak detected");
249 break;
250 default:
251 fprintf(stderr, "%d leaks detected", leaks);
252 break;
253 }
254 fprintf(stderr, ", %d suppressed by whitelist\n", whitelisted);
255 }
256
257 /**
258 * Installs the malloc hooks, enables leak detection
259 */
260 static void install_hooks()
261 {
262 if (!installed)
263 {
264 old_malloc_hook = __malloc_hook;
265 old_realloc_hook = __realloc_hook;
266 old_free_hook = __free_hook;
267 __malloc_hook = malloc_hook;
268 __realloc_hook = realloc_hook;
269 __free_hook = free_hook;
270 installed = TRUE;
271 }
272 }
273
274 /**
275 * Uninstalls the malloc hooks, disables leak detection
276 */
277 static void uninstall_hooks()
278 {
279 if (installed)
280 {
281 __malloc_hook = old_malloc_hook;
282 __free_hook = old_free_hook;
283 __realloc_hook = old_realloc_hook;
284 installed = FALSE;
285 }
286 }
287
288 /**
289 * Hook function for malloc()
290 */
291 void *malloc_hook(size_t bytes, const void *caller)
292 {
293 memory_header_t *hdr;
294 memory_tail_t *tail;
295 pthread_t thread_id = pthread_self();
296 int oldpolicy;
297 struct sched_param oldparams, params;
298
299 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
300
301 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
302 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
303
304 count_malloc++;
305 uninstall_hooks();
306 hdr = malloc(sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
307 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
308 /* set to something which causes crashes */
309 memset(hdr, MEMORY_ALLOC_PATTERN,
310 sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
311
312 hdr->magic = MEMORY_HEADER_MAGIC;
313 hdr->bytes = bytes;
314 hdr->backtrace = backtrace_create(3);
315 tail->magic = MEMORY_TAIL_MAGIC;
316 install_hooks();
317
318 /* insert at the beginning of the list */
319 hdr->next = first_header.next;
320 if (hdr->next)
321 {
322 hdr->next->previous = hdr;
323 }
324 hdr->previous = &first_header;
325 first_header.next = hdr;
326
327 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
328
329 return hdr + 1;
330 }
331
332 /**
333 * Hook function for free()
334 */
335 void free_hook(void *ptr, const void *caller)
336 {
337 memory_header_t *hdr;
338 memory_tail_t *tail;
339 backtrace_t *backtrace;
340 pthread_t thread_id = pthread_self();
341 int oldpolicy;
342 struct sched_param oldparams, params;
343
344 /* allow freeing of NULL */
345 if (ptr == NULL)
346 {
347 return;
348 }
349 hdr = ptr - sizeof(memory_header_t);
350 tail = ptr + hdr->bytes;
351
352 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
353
354 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
355 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
356
357 count_free++;
358 uninstall_hooks();
359 if (hdr->magic != MEMORY_HEADER_MAGIC ||
360 tail->magic != MEMORY_TAIL_MAGIC)
361 {
362 fprintf(stderr, "freeing invalid memory (%p): "
363 "header magic 0x%x, tail magic 0x%x:\n",
364 ptr, hdr->magic, tail->magic);
365 backtrace = backtrace_create(3);
366 backtrace->log(backtrace, stderr);
367 backtrace->destroy(backtrace);
368 }
369 else
370 {
371 /* remove item from list */
372 if (hdr->next)
373 {
374 hdr->next->previous = hdr->previous;
375 }
376 hdr->previous->next = hdr->next;
377 hdr->backtrace->destroy(hdr->backtrace);
378
379 /* clear MAGIC, set mem to something remarkable */
380 memset(hdr, MEMORY_FREE_PATTERN, hdr->bytes + sizeof(memory_header_t));
381
382 free(hdr);
383 }
384
385 install_hooks();
386 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
387 }
388
389 /**
390 * Hook function for realloc()
391 */
392 void *realloc_hook(void *old, size_t bytes, const void *caller)
393 {
394 memory_header_t *hdr;
395 memory_tail_t *tail;
396 backtrace_t *backtrace;
397 pthread_t thread_id = pthread_self();
398 int oldpolicy;
399 struct sched_param oldparams, params;
400
401 /* allow reallocation of NULL */
402 if (old == NULL)
403 {
404 return malloc_hook(bytes, caller);
405 }
406
407 hdr = old - sizeof(memory_header_t);
408 tail = old + hdr->bytes;
409
410 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
411
412 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
413 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
414
415 count_realloc++;
416 uninstall_hooks();
417 if (hdr->magic != MEMORY_HEADER_MAGIC ||
418 tail->magic != MEMORY_TAIL_MAGIC)
419 {
420 fprintf(stderr, "reallocating invalid memory (%p): "
421 "header magic 0x%x, tail magic 0x%x:\n",
422 old, hdr->magic, tail->magic);
423 backtrace = backtrace_create(3);
424 backtrace->log(backtrace, stderr);
425 backtrace->destroy(backtrace);
426 }
427 /* clear tail magic, allocate, set tail magic */
428 memset(&tail->magic, MEMORY_ALLOC_PATTERN, sizeof(tail->magic));
429 hdr = realloc(hdr, sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
430 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
431 tail->magic = MEMORY_TAIL_MAGIC;
432
433 /* update statistics */
434 hdr->bytes = bytes;
435 hdr->backtrace->destroy(hdr->backtrace);
436 hdr->backtrace = backtrace_create(3);
437
438 /* update header of linked list neighbours */
439 if (hdr->next)
440 {
441 hdr->next->previous = hdr;
442 }
443 hdr->previous->next = hdr;
444 install_hooks();
445 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
446 return hdr + 1;
447 }
448
449 /**
450 * Implementation of leak_detective_t.destroy
451 */
452 static void destroy(private_leak_detective_t *this)
453 {
454 if (installed)
455 {
456 uninstall_hooks();
457 report_leaks();
458 }
459 free(this);
460 }
461
462 /*
463 * see header file
464 */
465 leak_detective_t *leak_detective_create()
466 {
467 private_leak_detective_t *this = malloc_thing(private_leak_detective_t);
468
469 this->public.destroy = (void(*)(leak_detective_t*))destroy;
470
471 if (getenv("LEAK_DETECTIVE_DISABLE") == NULL)
472 {
473 lib->leak_detective = TRUE;
474 install_hooks();
475 }
476 return &this->public;
477 }
478