451408a8f70bc4466c6174f27aa35f4cedc67fc1
[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 };
270
271
272 /**
273 * Hashtable hash function
274 */
275 static u_int hash(backtrace_t *key)
276 {
277 enumerator_t *enumerator;
278 void *addr;
279 u_int hash = 0;
280
281 enumerator = key->create_frame_enumerator(key);
282 while (enumerator->enumerate(enumerator, &addr))
283 {
284 hash = chunk_hash_inc(chunk_from_thing(addr), hash);
285 }
286 enumerator->destroy(enumerator);
287
288 return hash;
289 }
290
291 /**
292 * Hashtable equals function
293 */
294 static bool equals(backtrace_t *a, backtrace_t *b)
295 {
296 return a->equals(a, b);
297 }
298
299 /**
300 * Summarize and print backtraces
301 */
302 static int print_traces(private_leak_detective_t *this,
303 FILE *out, int thresh, bool detailed, int *whitelisted)
304 {
305 int leaks = 0;
306 memory_header_t *hdr;
307 enumerator_t *enumerator;
308 hashtable_t *entries;
309 struct {
310 /** associated backtrace */
311 backtrace_t *backtrace;
312 /** total size of all allocations */
313 size_t bytes;
314 /** number of allocations */
315 u_int count;
316 } *entry;
317
318 uninstall_hooks();
319
320 entries = hashtable_create((hashtable_hash_t)hash,
321 (hashtable_equals_t)equals, 1024);
322 for (hdr = first_header.next; hdr != NULL; hdr = hdr->next)
323 {
324 if (whitelisted &&
325 hdr->backtrace->contains_function(hdr->backtrace,
326 whitelist, countof(whitelist)))
327 {
328 (*whitelisted)++;
329 continue;
330 }
331 entry = entries->get(entries, hdr->backtrace);
332 if (entry)
333 {
334 entry->bytes += hdr->bytes;
335 entry->count++;
336 }
337 else
338 {
339 INIT(entry,
340 .backtrace = hdr->backtrace,
341 .bytes = hdr->bytes,
342 .count = 1,
343 );
344 entries->put(entries, hdr->backtrace, entry);
345 }
346 leaks++;
347 }
348 enumerator = entries->create_enumerator(entries);
349 while (enumerator->enumerate(enumerator, NULL, &entry))
350 {
351 if (!thresh || entry->bytes >= thresh)
352 {
353 fprintf(out, "%d bytes total, %d allocations, %d bytes average:\n",
354 entry->bytes, entry->count, entry->bytes / entry->count);
355 entry->backtrace->log(entry->backtrace, out, detailed);
356 }
357 free(entry);
358 }
359 enumerator->destroy(enumerator);
360 entries->destroy(entries);
361
362 install_hooks();
363 return leaks;
364 }
365
366 METHOD(leak_detective_t, report, void,
367 private_leak_detective_t *this, bool detailed)
368 {
369 if (lib->leak_detective)
370 {
371 int leaks = 0, whitelisted = 0;
372
373 leaks = print_traces(this, stderr, 0, detailed, &whitelisted);
374 switch (leaks)
375 {
376 case 0:
377 fprintf(stderr, "No leaks detected");
378 break;
379 case 1:
380 fprintf(stderr, "One leak detected");
381 break;
382 default:
383 fprintf(stderr, "%d leaks detected", leaks);
384 break;
385 }
386 fprintf(stderr, ", %d suppressed by whitelist\n", whitelisted);
387 }
388 else
389 {
390 fprintf(stderr, "Leak detective disabled\n");
391 }
392 }
393
394 METHOD(leak_detective_t, usage, void,
395 private_leak_detective_t *this, FILE *out)
396 {
397 int oldpolicy, thresh;
398 bool detailed;
399 pthread_t thread_id = pthread_self();
400 struct sched_param oldparams, params;
401
402 thresh = lib->settings->get_int(lib->settings,
403 "libstrongswan.leak_detective.usage_threshold", 10240);
404 detailed = lib->settings->get_bool(lib->settings,
405 "libstrongswan.leak_detective.detailed", TRUE);
406
407 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
408 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
409 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
410
411 print_traces(this, out, thresh, detailed, NULL);
412
413 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
414 }
415
416 /**
417 * Hook function for malloc()
418 */
419 void *malloc_hook(size_t bytes, const void *caller)
420 {
421 memory_header_t *hdr;
422 memory_tail_t *tail;
423 pthread_t thread_id = pthread_self();
424 int oldpolicy;
425 struct sched_param oldparams, params;
426
427 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
428
429 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
430 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
431
432 count_malloc++;
433 uninstall_hooks();
434 hdr = malloc(sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
435 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
436 /* set to something which causes crashes */
437 memset(hdr, MEMORY_ALLOC_PATTERN,
438 sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
439
440 hdr->magic = MEMORY_HEADER_MAGIC;
441 hdr->bytes = bytes;
442 hdr->backtrace = backtrace_create(3);
443 tail->magic = MEMORY_TAIL_MAGIC;
444 install_hooks();
445
446 /* insert at the beginning of the list */
447 hdr->next = first_header.next;
448 if (hdr->next)
449 {
450 hdr->next->previous = hdr;
451 }
452 hdr->previous = &first_header;
453 first_header.next = hdr;
454
455 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
456
457 return hdr + 1;
458 }
459
460 /**
461 * Hook function for free()
462 */
463 void free_hook(void *ptr, const void *caller)
464 {
465 memory_header_t *hdr, *current;
466 memory_tail_t *tail;
467 backtrace_t *backtrace;
468 pthread_t thread_id = pthread_self();
469 int oldpolicy;
470 struct sched_param oldparams, params;
471 bool found = FALSE;
472
473 /* allow freeing of NULL */
474 if (ptr == NULL)
475 {
476 return;
477 }
478 hdr = ptr - sizeof(memory_header_t);
479 tail = ptr + hdr->bytes;
480
481 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
482
483 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
484 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
485
486 count_free++;
487 uninstall_hooks();
488 if (hdr->magic != MEMORY_HEADER_MAGIC ||
489 tail->magic != MEMORY_TAIL_MAGIC)
490 {
491 for (current = &first_header; current != NULL; current = current->next)
492 {
493 if (current == hdr)
494 {
495 found = TRUE;
496 break;
497 }
498 }
499 if (found)
500 {
501 /* memory was allocated by our hooks but is corrupted */
502 fprintf(stderr, "freeing corrupted memory (%p): "
503 "header magic 0x%x, tail magic 0x%x:\n",
504 ptr, hdr->magic, tail->magic);
505 }
506 else
507 {
508 /* memory was not allocated by our hooks */
509 fprintf(stderr, "freeing invalid memory (%p)", ptr);
510 }
511 backtrace = backtrace_create(3);
512 backtrace->log(backtrace, stderr, TRUE);
513 backtrace->destroy(backtrace);
514 }
515 else
516 {
517 /* remove item from list */
518 if (hdr->next)
519 {
520 hdr->next->previous = hdr->previous;
521 }
522 hdr->previous->next = hdr->next;
523 hdr->backtrace->destroy(hdr->backtrace);
524
525 /* clear MAGIC, set mem to something remarkable */
526 memset(hdr, MEMORY_FREE_PATTERN,
527 sizeof(memory_header_t) + hdr->bytes + sizeof(memory_tail_t));
528
529 free(hdr);
530 }
531
532 install_hooks();
533 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
534 }
535
536 /**
537 * Hook function for realloc()
538 */
539 void *realloc_hook(void *old, size_t bytes, const void *caller)
540 {
541 memory_header_t *hdr;
542 memory_tail_t *tail;
543 backtrace_t *backtrace;
544 pthread_t thread_id = pthread_self();
545 int oldpolicy;
546 struct sched_param oldparams, params;
547
548 /* allow reallocation of NULL */
549 if (old == NULL)
550 {
551 return malloc_hook(bytes, caller);
552 }
553
554 hdr = old - sizeof(memory_header_t);
555 tail = old + hdr->bytes;
556
557 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
558
559 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
560 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
561
562 count_realloc++;
563 uninstall_hooks();
564 if (hdr->magic != MEMORY_HEADER_MAGIC ||
565 tail->magic != MEMORY_TAIL_MAGIC)
566 {
567 fprintf(stderr, "reallocating invalid memory (%p): "
568 "header magic 0x%x, tail magic 0x%x:\n",
569 old, hdr->magic, tail->magic);
570 backtrace = backtrace_create(3);
571 backtrace->log(backtrace, stderr, TRUE);
572 backtrace->destroy(backtrace);
573 }
574 /* clear tail magic, allocate, set tail magic */
575 memset(&tail->magic, MEMORY_ALLOC_PATTERN, sizeof(tail->magic));
576 hdr = realloc(hdr, sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
577 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
578 tail->magic = MEMORY_TAIL_MAGIC;
579
580 /* update statistics */
581 hdr->bytes = bytes;
582 hdr->backtrace->destroy(hdr->backtrace);
583 hdr->backtrace = backtrace_create(3);
584
585 /* update header of linked list neighbours */
586 if (hdr->next)
587 {
588 hdr->next->previous = hdr;
589 }
590 hdr->previous->next = hdr;
591 install_hooks();
592 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
593 return hdr + 1;
594 }
595
596 METHOD(leak_detective_t, destroy, void,
597 private_leak_detective_t *this)
598 {
599 if (installed)
600 {
601 uninstall_hooks();
602 }
603 free(this);
604 }
605
606 /*
607 * see header file
608 */
609 leak_detective_t *leak_detective_create()
610 {
611 private_leak_detective_t *this;
612
613 INIT(this,
614 .public = {
615 .report = _report,
616 .usage = _usage,
617 .destroy = _destroy,
618 },
619 );
620
621 if (getenv("LEAK_DETECTIVE_DISABLE") == NULL)
622 {
623 cpu_set_t mask;
624
625 CPU_ZERO(&mask);
626 CPU_SET(0, &mask);
627
628 if (sched_setaffinity(0, sizeof(cpu_set_t), &mask) != 0)
629 {
630 fprintf(stderr, "setting CPU affinity failed: %m");
631 }
632
633 install_hooks();
634 }
635 return &this->public;
636 }
637