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