Implemented an alternative HTTP fetcher based on libsoup
[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 /* glib */
224 "g_type_init_with_debug_flags",
225 "g_type_register_static",
226 "g_type_class_ref",
227 "g_type_create_instance",
228 "g_type_add_interface_static",
229 "g_type_interface_add_prerequisite",
230 "g_socket_connection_factory_lookup_type",
231 /* libgpg */
232 "gpg_err_init",
233 };
234
235 /**
236 * Report leaks at library destruction
237 */
238 static void report(private_leak_detective_t *this, bool detailed)
239 {
240 if (lib->leak_detective)
241 {
242 memory_header_t *hdr;
243 int leaks = 0, whitelisted = 0;
244
245 for (hdr = first_header.next; hdr != NULL; hdr = hdr->next)
246 {
247 if (hdr->backtrace->contains_function(hdr->backtrace,
248 whitelist, countof(whitelist)))
249 {
250 whitelisted++;
251 }
252 else
253 {
254 fprintf(stderr, "Leak (%d bytes at %p):\n", hdr->bytes, hdr + 1);
255 /* skip the first frame, contains leak detective logic */
256 hdr->backtrace->log(hdr->backtrace, stderr, detailed);
257 leaks++;
258 }
259 }
260 switch (leaks)
261 {
262 case 0:
263 fprintf(stderr, "No leaks detected");
264 break;
265 case 1:
266 fprintf(stderr, "One leak detected");
267 break;
268 default:
269 fprintf(stderr, "%d leaks detected", leaks);
270 break;
271 }
272 fprintf(stderr, ", %d suppressed by whitelist\n", whitelisted);
273 }
274 else
275 {
276 fprintf(stderr, "Leak detective disabled\n");
277 }
278 }
279
280 /**
281 * Installs the malloc hooks, enables leak detection
282 */
283 static void install_hooks()
284 {
285 if (!installed)
286 {
287 old_malloc_hook = __malloc_hook;
288 old_realloc_hook = __realloc_hook;
289 old_free_hook = __free_hook;
290 __malloc_hook = malloc_hook;
291 __realloc_hook = realloc_hook;
292 __free_hook = free_hook;
293 installed = TRUE;
294 }
295 }
296
297 /**
298 * Uninstalls the malloc hooks, disables leak detection
299 */
300 static void uninstall_hooks()
301 {
302 if (installed)
303 {
304 __malloc_hook = old_malloc_hook;
305 __free_hook = old_free_hook;
306 __realloc_hook = old_realloc_hook;
307 installed = FALSE;
308 }
309 }
310
311 /**
312 * Hook function for malloc()
313 */
314 void *malloc_hook(size_t bytes, const void *caller)
315 {
316 memory_header_t *hdr;
317 memory_tail_t *tail;
318 pthread_t thread_id = pthread_self();
319 int oldpolicy;
320 struct sched_param oldparams, params;
321
322 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
323
324 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
325 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
326
327 count_malloc++;
328 uninstall_hooks();
329 hdr = malloc(sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
330 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
331 /* set to something which causes crashes */
332 memset(hdr, MEMORY_ALLOC_PATTERN,
333 sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
334
335 hdr->magic = MEMORY_HEADER_MAGIC;
336 hdr->bytes = bytes;
337 hdr->backtrace = backtrace_create(3);
338 tail->magic = MEMORY_TAIL_MAGIC;
339 install_hooks();
340
341 /* insert at the beginning of the list */
342 hdr->next = first_header.next;
343 if (hdr->next)
344 {
345 hdr->next->previous = hdr;
346 }
347 hdr->previous = &first_header;
348 first_header.next = hdr;
349
350 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
351
352 return hdr + 1;
353 }
354
355 /**
356 * Hook function for free()
357 */
358 void free_hook(void *ptr, const void *caller)
359 {
360 memory_header_t *hdr, *current;
361 memory_tail_t *tail;
362 backtrace_t *backtrace;
363 pthread_t thread_id = pthread_self();
364 int oldpolicy;
365 struct sched_param oldparams, params;
366 bool found = FALSE;
367
368 /* allow freeing of NULL */
369 if (ptr == NULL)
370 {
371 return;
372 }
373 hdr = ptr - sizeof(memory_header_t);
374 tail = ptr + hdr->bytes;
375
376 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
377
378 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
379 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
380
381 count_free++;
382 uninstall_hooks();
383 if (hdr->magic != MEMORY_HEADER_MAGIC ||
384 tail->magic != MEMORY_TAIL_MAGIC)
385 {
386 for (current = &first_header; current != NULL; current = current->next)
387 {
388 if (current == hdr)
389 {
390 found = TRUE;
391 break;
392 }
393 }
394 if (found)
395 {
396 /* memory was allocated by our hooks but is corrupted */
397 fprintf(stderr, "freeing corrupted memory (%p): "
398 "header magic 0x%x, tail magic 0x%x:\n",
399 ptr, hdr->magic, tail->magic);
400 }
401 else
402 {
403 /* memory was not allocated by our hooks */
404 fprintf(stderr, "freeing invalid memory (%p)", ptr);
405 }
406 backtrace = backtrace_create(3);
407 backtrace->log(backtrace, stderr, TRUE);
408 backtrace->destroy(backtrace);
409 }
410 else
411 {
412 /* remove item from list */
413 if (hdr->next)
414 {
415 hdr->next->previous = hdr->previous;
416 }
417 hdr->previous->next = hdr->next;
418 hdr->backtrace->destroy(hdr->backtrace);
419
420 /* clear MAGIC, set mem to something remarkable */
421 memset(hdr, MEMORY_FREE_PATTERN,
422 sizeof(memory_header_t) + hdr->bytes + sizeof(memory_tail_t));
423
424 free(hdr);
425 }
426
427 install_hooks();
428 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
429 }
430
431 /**
432 * Hook function for realloc()
433 */
434 void *realloc_hook(void *old, size_t bytes, const void *caller)
435 {
436 memory_header_t *hdr;
437 memory_tail_t *tail;
438 backtrace_t *backtrace;
439 pthread_t thread_id = pthread_self();
440 int oldpolicy;
441 struct sched_param oldparams, params;
442
443 /* allow reallocation of NULL */
444 if (old == NULL)
445 {
446 return malloc_hook(bytes, caller);
447 }
448
449 hdr = old - sizeof(memory_header_t);
450 tail = old + hdr->bytes;
451
452 pthread_getschedparam(thread_id, &oldpolicy, &oldparams);
453
454 params.__sched_priority = sched_get_priority_max(SCHED_FIFO);
455 pthread_setschedparam(thread_id, SCHED_FIFO, &params);
456
457 count_realloc++;
458 uninstall_hooks();
459 if (hdr->magic != MEMORY_HEADER_MAGIC ||
460 tail->magic != MEMORY_TAIL_MAGIC)
461 {
462 fprintf(stderr, "reallocating invalid memory (%p): "
463 "header magic 0x%x, tail magic 0x%x:\n",
464 old, hdr->magic, tail->magic);
465 backtrace = backtrace_create(3);
466 backtrace->log(backtrace, stderr, TRUE);
467 backtrace->destroy(backtrace);
468 }
469 /* clear tail magic, allocate, set tail magic */
470 memset(&tail->magic, MEMORY_ALLOC_PATTERN, sizeof(tail->magic));
471 hdr = realloc(hdr, sizeof(memory_header_t) + bytes + sizeof(memory_tail_t));
472 tail = ((void*)hdr) + bytes + sizeof(memory_header_t);
473 tail->magic = MEMORY_TAIL_MAGIC;
474
475 /* update statistics */
476 hdr->bytes = bytes;
477 hdr->backtrace->destroy(hdr->backtrace);
478 hdr->backtrace = backtrace_create(3);
479
480 /* update header of linked list neighbours */
481 if (hdr->next)
482 {
483 hdr->next->previous = hdr;
484 }
485 hdr->previous->next = hdr;
486 install_hooks();
487 pthread_setschedparam(thread_id, oldpolicy, &oldparams);
488 return hdr + 1;
489 }
490
491 /**
492 * Implementation of leak_detective_t.destroy
493 */
494 static void destroy(private_leak_detective_t *this)
495 {
496 if (installed)
497 {
498 uninstall_hooks();
499 }
500 free(this);
501 }
502
503 /*
504 * see header file
505 */
506 leak_detective_t *leak_detective_create()
507 {
508 private_leak_detective_t *this = malloc_thing(private_leak_detective_t);
509
510 this->public.report = (void(*)(leak_detective_t*,bool))report;
511 this->public.destroy = (void(*)(leak_detective_t*))destroy;
512
513 if (getenv("LEAK_DETECTIVE_DISABLE") == NULL)
514 {
515 cpu_set_t mask;
516
517 CPU_ZERO(&mask);
518 CPU_SET(0, &mask);
519
520 if (sched_setaffinity(0, sizeof(cpu_set_t), &mask) != 0)
521 {
522 fprintf(stderr, "setting CPU affinity failed: %m");
523 }
524
525 lib->leak_detective = TRUE;
526 install_hooks();
527 }
528 return &this->public;
529 }
530