Add an external method to disable leak detective temporarly
[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 #include <utils/hashtable.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 * Pointer to previous entry in linked list
97 */
98 memory_header_t *previous;
99
100 /**
101 * Pointer to next entry in linked list
102 */
103 memory_header_t *next;
104
105 /**
106 * backtrace taken during (re-)allocation
107 */
108 backtrace_t *backtrace;
109
110 /**
111 * Number of bytes following after the header
112 */
113 u_int32_t bytes;
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 * Installs the malloc hooks, enables leak detection
153 */
154 static void install_hooks()
155 {
156 if (!installed)
157 {
158 old_malloc_hook = __malloc_hook;
159 old_realloc_hook = __realloc_hook;
160 old_free_hook = __free_hook;
161 __malloc_hook = malloc_hook;
162 __realloc_hook = realloc_hook;
163 __free_hook = free_hook;
164 installed = TRUE;
165 }
166 }
167
168 /**
169 * Uninstalls the malloc hooks, disables leak detection
170 */
171 static void uninstall_hooks()
172 {
173 if (installed)
174 {
175 __malloc_hook = old_malloc_hook;
176 __free_hook = old_free_hook;
177 __realloc_hook = old_realloc_hook;
178 installed = FALSE;
179 }
180 }
181
182 /**
183 * Leak report white list
184 *
185 * List of functions using static allocation buffers or should be suppressed
186 * otherwise on leak report.
187 */
188 char *whitelist[] = {
189 /* backtraces, including own */
190 "backtrace_create",
191 "safe_strerror",
192 /* pthread stuff */
193 "pthread_create",
194 "pthread_setspecific",
195 "__pthread_setspecific",
196 /* glibc functions */
197 "mktime",
198 "ctime",
199 "__gmtime_r",
200 "localtime_r",
201 "tzset",
202 "time_printf_hook",
203 "inet_ntoa",
204 "strerror",
205 "getprotobyname",
206 "getprotobynumber",
207 "getservbyport",
208 "getservbyname",
209 "gethostbyname",
210 "gethostbyname2",
211 "gethostbyname_r",
212 "gethostbyname2_r",
213 "getnetbyname",
214 "getpwnam_r",
215 "getgrnam_r",
216 "register_printf_function",
217 "register_printf_specifier",
218 "syslog",
219 "vsyslog",
220 "__syslog_chk",
221 "__vsyslog_chk",
222 "getaddrinfo",
223 "setlocale",
224 "getpass",
225 "getpwent_r",
226 "setpwent",
227 "endpwent",
228 /* ignore dlopen, as we do not dlclose to get proper leak reports */
229 "dlopen",
230 "dlerror",
231 "dlclose",
232 "dlsym",
233 /* mysql functions */
234 "mysql_init_character_set",
235 "init_client_errs",
236 "my_thread_init",
237 /* fastcgi library */
238 "FCGX_Init",
239 /* libxml */
240 "xmlInitCharEncodingHandlers",
241 "xmlInitParser",
242 "xmlInitParserCtxt",
243 /* libcurl */
244 "Curl_client_write",
245 /* ClearSilver */
246 "nerr_init",
247 /* OpenSSL */
248 "RSA_new_method",
249 "DH_new_method",
250 "ENGINE_load_builtin_engines",
251 "OPENSSL_config",
252 "ecdsa_check",
253 "ERR_put_error",
254 /* libgcrypt */
255 "gcry_control",
256 "gcry_check_version",
257 "gcry_randomize",
258 "gcry_create_nonce",
259 /* NSPR */
260 "PR_CallOnce",
261 /* libapr */
262 "apr_pool_create_ex",
263 /* glib */
264 "g_type_init_with_debug_flags",
265 "g_type_register_static",
266 "g_type_class_ref",
267 "g_type_create_instance",
268 "g_type_add_interface_static",
269 "g_type_interface_add_prerequisite",
270 "g_socket_connection_factory_lookup_type",
271 /* libgpg */
272 "gpg_err_init",
273 /* gnutls */
274 "gnutls_global_init",
275 };
276
277
278 /**
279 * Hashtable hash function
280 */
281 static u_int hash(backtrace_t *key)
282 {
283 enumerator_t *enumerator;
284 void *addr;
285 u_int hash = 0;
286
287 enumerator = key->create_frame_enumerator(key);
288 while (enumerator->enumerate(enumerator, &addr))
289 {
290 hash = chunk_hash_inc(chunk_from_thing(addr), hash);
291 }
292 enumerator->destroy(enumerator);
293
294 return hash;
295 }
296
297 /**
298 * Hashtable equals function
299 */
300 static bool equals(backtrace_t *a, backtrace_t *b)
301 {
302 return a->equals(a, b);
303 }
304
305 /**
306 * Summarize and print backtraces
307 */
308 static int print_traces(private_leak_detective_t *this,
309 FILE *out, int thresh, bool detailed, int *whitelisted)
310 {
311 int leaks = 0;
312 memory_header_t *hdr;
313 enumerator_t *enumerator;
314 hashtable_t *entries;
315 struct {
316 /** associated backtrace */
317 backtrace_t *backtrace;
318 /** total size of all allocations */
319 size_t bytes;
320 /** number of allocations */
321 u_int count;
322 } *entry;
323
324 uninstall_hooks();
325
326 entries = hashtable_create((hashtable_hash_t)hash,
327 (hashtable_equals_t)equals, 1024);
328 for (hdr = first_header.next; hdr != NULL; hdr = hdr->next)
329 {
330 if (whitelisted &&
331 hdr->backtrace->contains_function(hdr->backtrace,
332 whitelist, countof(whitelist)))
333 {
334 (*whitelisted)++;
335 continue;
336 }
337 entry = entries->get(entries, hdr->backtrace);
338 if (entry)
339 {
340 entry->bytes += hdr->bytes;
341 entry->count++;
342 }
343 else
344 {
345 INIT(entry,
346 .backtrace = hdr->backtrace,
347 .bytes = hdr->bytes,
348 .count = 1,
349 );
350 entries->put(entries, hdr->backtrace, entry);
351 }
352 leaks++;
353 }
354 enumerator = entries->create_enumerator(entries);
355 while (enumerator->enumerate(enumerator, NULL, &entry))
356 {
357 if (!thresh || entry->bytes >= thresh)
358 {
359 fprintf(out, "%d bytes total, %d allocations, %d bytes average:\n",
360 entry->bytes, entry->count, entry->bytes / entry->count);
361 entry->backtrace->log(entry->backtrace, out, detailed);
362 }
363 free(entry);
364 }
365 enumerator->destroy(enumerator);
366 entries->destroy(entries);
367
368 install_hooks();
369 return leaks;
370 }
371
372 METHOD(leak_detective_t, report, void,
373 private_leak_detective_t *this, bool detailed)
374 {
375 if (lib->leak_detective)
376 {
377 int leaks = 0, whitelisted = 0;
378
379 leaks = print_traces(this, stderr, 0, detailed, &whitelisted);
380 switch (leaks)
381 {
382 case 0:
383 fprintf(stderr, "No leaks detected");
384 break;
385 case 1:
386 fprintf(stderr, "One leak detected");
387 break;
388 default:
389 fprintf(stderr, "%d leaks detected", leaks);
390 break;
391 }
392 fprintf(stderr, ", %d suppressed by whitelist\n", whitelisted);
393 }
394 else
395 {
396 fprintf(stderr, "Leak detective disabled\n");
397 }
398 }
399
400 METHOD(leak_detective_t, set_state, bool,
401 private_leak_detective_t *this, bool enable)
402 {
403 static struct sched_param oldparams;
404 static int oldpolicy;
405 struct sched_param params;
406 pthread_t thread_id;
407
408 if (enable == installed)
409 {
410 return installed;
411 }
412 thread_id = pthread_self();
413 if (enable)
414 {
415 install_hooks();
416 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
417 }
418 else
419 {
420 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
421 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
422 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
423 uninstall_hooks();
424 }
425 installed = enable;
426 return !installed;
427 }
428
429 METHOD(leak_detective_t, usage, void,
430 private_leak_detective_t *this, FILE *out)
431 {
432 int oldpolicy, thresh;
433 bool detailed;
434 pthread_t thread_id = pthread_self();
435 struct sched_param oldparams, params;
436
437 thresh = lib->settings->get_int(lib->settings,
438 "libstrongswan.leak_detective.usage_threshold", 10240);
439 detailed = lib->settings->get_bool(lib->settings,
440 "libstrongswan.leak_detective.detailed", TRUE);
441
442 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
443 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
444 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
445
446 print_traces(this, out, thresh, detailed, NULL);
447
448 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
449 }
450
451 /**
452 * Hook function for malloc()
453 */
454 void *malloc_hook(size_t bytes, const void *caller)
455 {
456 memory_header_t *hdr;
457 memory_tail_t *tail;
458 pthread_t thread_id = pthread_self();
459 int oldpolicy;
460 struct sched_param oldparams, params;
461
462 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
463
464 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
465 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
466
467 count_malloc++;
468 uninstall_hooks();
469 hdr = malloc(sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
470 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
471 /* set to something which causes crashes */
472 memset(hdr, MEMORY_ALLOC_PATTERN,
473 sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
474
475 hdr->magic = MEMORY_HEADER_MAGIC;
476 hdr->bytes = bytes;
477 hdr->backtrace = backtrace_create(3);
478 tail->magic = MEMORY_TAIL_MAGIC;
479 install_hooks();
480
481 /* insert at the beginning of the list */
482 hdr->next = first_header.next;
483 if (hdr->next)
484 {
485 hdr->next->previous = hdr;
486 }
487 hdr->previous = &first_header;
488 first_header.next = hdr;
489
490 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
491
492 return hdr + 1;
493 }
494
495 /**
496 * Hook function for free()
497 */
498 void free_hook(void *ptr, const void *caller)
499 {
500 memory_header_t *hdr, *current;
501 memory_tail_t *tail;
502 backtrace_t *backtrace;
503 pthread_t thread_id = pthread_self();
504 int oldpolicy;
505 struct sched_param oldparams, params;
506 bool found = FALSE;
507
508 /* allow freeing of NULL */
509 if (ptr == NULL)
510 {
511 return;
512 }
513 hdr = ptr - sizeof(memory_header_t);
514 tail = ptr + hdr->bytes;
515
516 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
517
518 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
519 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
520
521 count_free++;
522 uninstall_hooks();
523 if (hdr->magic != MEMORY_HEADER_MAGIC ||
524 tail->magic != MEMORY_TAIL_MAGIC)
525 {
526 for (current = &first_header; current != NULL; current = current->next)
527 {
528 if (current == hdr)
529 {
530 found = TRUE;
531 break;
532 }
533 }
534 if (found)
535 {
536 /* memory was allocated by our hooks but is corrupted */
537 fprintf(stderr, "freeing corrupted memory (%p): "
538 "header magic 0x%x, tail magic 0x%x:\n",
539 ptr, hdr->magic, tail->magic);
540 }
541 else
542 {
543 /* memory was not allocated by our hooks */
544 fprintf(stderr, "freeing invalid memory (%p)", ptr);
545 }
546 backtrace = backtrace_create(3);
547 backtrace->log(backtrace, stderr, TRUE);
548 backtrace->destroy(backtrace);
549 }
550 else
551 {
552 /* remove item from list */
553 if (hdr->next)
554 {
555 hdr->next->previous = hdr->previous;
556 }
557 hdr->previous->next = hdr->next;
558 hdr->backtrace->destroy(hdr->backtrace);
559
560 /* clear MAGIC, set mem to something remarkable */
561 memset(hdr, MEMORY_FREE_PATTERN,
562 sizeof(memory_header_t) + hdr->bytes + sizeof(memory_tail_t));
563
564 free(hdr);
565 }
566
567 install_hooks();
568 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
569 }
570
571 /**
572 * Hook function for realloc()
573 */
574 void *realloc_hook(void *old, size_t bytes, const void *caller)
575 {
576 memory_header_t *hdr;
577 memory_tail_t *tail;
578 backtrace_t *backtrace;
579 pthread_t thread_id = pthread_self();
580 int oldpolicy;
581 struct sched_param oldparams, params;
582
583 /* allow reallocation of NULL */
584 if (old == NULL)
585 {
586 return malloc_hook(bytes, caller);
587 }
588
589 hdr = old - sizeof(memory_header_t);
590 tail = old + hdr->bytes;
591
592 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
593
594 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
595 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
596
597 count_realloc++;
598 uninstall_hooks();
599 if (hdr->magic != MEMORY_HEADER_MAGIC ||
600 tail->magic != MEMORY_TAIL_MAGIC)
601 {
602 fprintf(stderr, "reallocating invalid memory (%p): "
603 "header magic 0x%x, tail magic 0x%x:\n",
604 old, hdr->magic, tail->magic);
605 backtrace = backtrace_create(3);
606 backtrace->log(backtrace, stderr, TRUE);
607 backtrace->destroy(backtrace);
608 }
609 /* clear tail magic, allocate, set tail magic */
610 memset(&tail->magic, MEMORY_ALLOC_PATTERN, sizeof(tail->magic));
611 hdr = realloc(hdr, sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
612 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
613 tail->magic = MEMORY_TAIL_MAGIC;
614
615 /* update statistics */
616 hdr->bytes = bytes;
617 hdr->backtrace->destroy(hdr->backtrace);
618 hdr->backtrace = backtrace_create(3);
619
620 /* update header of linked list neighbours */
621 if (hdr->next)
622 {
623 hdr->next->previous = hdr;
624 }
625 hdr->previous->next = hdr;
626 install_hooks();
627 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
628 return hdr + 1;
629 }
630
631 METHOD(leak_detective_t, destroy, void,
632 private_leak_detective_t *this)
633 {
634 if (installed)
635 {
636 uninstall_hooks();
637 }
638 free(this);
639 }
640
641 /*
642 * see header file
643 */
644 leak_detective_t *leak_detective_create()
645 {
646 private_leak_detective_t *this;
647
648 INIT(this,
649 .public = {
650 .report = _report,
651 .usage = _usage,
652 .set_state = _set_state,
653 .destroy = _destroy,
654 },
655 );
656
657 if (getenv("LEAK_DETECTIVE_DISABLE") == NULL)
658 {
659 cpu_set_t mask;
660
661 CPU_ZERO(&mask);
662 CPU_SET(0, &mask);
663
664 if (sched_setaffinity(0, sizeof(cpu_set_t), &mask) != 0)
665 {
666 fprintf(stderr, "setting CPU affinity failed: %m");
667 }
668
669 install_hooks();
670 }
671 return &this->public;
672 }
673