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