fixed typo
[strongswan.git] / src / libstrongswan / utils / leak_detective.c
1 /**
2 * @file leak_detective.c
3 *
4 * @brief Allocation hooks to find memory leaks.
5 */
6
7 /*
8 * Copyright (C) 2006 Martin Willi
9 * Hochschule fuer Technik Rapperswil
10 *
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the
13 * Free Software Foundation; either version 2 of the License, or (at your
14 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 * for more details.
20 */
21
22 #include <stddef.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <malloc.h>
26 #include <signal.h>
27 #include <sys/socket.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 #include <dlfcn.h>
31 #include <unistd.h>
32 #include <syslog.h>
33 #include <pthread.h>
34 #include <netdb.h>
35 #include <printf.h>
36 #ifdef HAVE_BACKTRACE
37 # include <execinfo.h>
38 #endif /* HAVE_BACKTRACE */
39
40 #include "leak_detective.h"
41
42 #include <library.h>
43 #include <debug.h>
44
45 #ifdef LEAK_DETECTIVE
46
47 /**
48 * Magic value which helps to detect memory corruption. Yummy!
49 */
50 #define MEMORY_HEADER_MAGIC 0x7ac0be11
51
52 /**
53 * Pattern which is filled in memory before freeing it
54 */
55 #define MEMORY_FREE_PATTERN 0xFF
56
57 /**
58 * Pattern which is filled in newly allocated memory
59 */
60 #define MEMORY_ALLOC_PATTERN 0xEE
61
62
63 static void install_hooks(void);
64 static void uninstall_hooks(void);
65 static void *malloc_hook(size_t, const void *);
66 static void *realloc_hook(void *, size_t, const void *);
67 static void free_hook(void*, const void *);
68
69 static u_int count_malloc = 0;
70 static u_int count_free = 0;
71 static u_int count_realloc = 0;
72
73 typedef struct memory_header_t memory_header_t;
74
75 /**
76 * Header which is prepended to each allocated memory block
77 */
78 struct memory_header_t {
79 /**
80 * Magci byte which must(!) hold MEMORY_HEADER_MAGIC
81 */
82 u_int32_t magic;
83
84 /**
85 * Number of bytes following after the header
86 */
87 size_t bytes;
88
89 /**
90 * Stack frames at the time of allocation
91 */
92 void *stack_frames[STACK_FRAMES_COUNT];
93
94 /**
95 * Number of stacks frames obtained in stack_frames
96 */
97 int stack_frame_count;
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 /**
111 * first mem header is just a dummy to chain
112 * the others on it...
113 */
114 static memory_header_t first_header = {
115 magic: MEMORY_HEADER_MAGIC,
116 bytes: 0,
117 stack_frame_count: 0,
118 previous: NULL,
119 next: NULL
120 };
121
122 /**
123 * standard hooks, used to temparily remove hooking
124 */
125 static void *old_malloc_hook, *old_realloc_hook, *old_free_hook;
126
127 /**
128 * are the hooks currently installed?
129 */
130 static bool installed = FALSE;
131
132 /**
133 * Mutex to exclusivly uninstall hooks, access heap list
134 */
135 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
136
137
138 /**
139 * log stack frames queried by backtrace()
140 * TODO: Dump symbols of static functions. This could be done with
141 * the addr2line utility or the GNU BFD Library...
142 */
143 static void log_stack_frames(void **stack_frames, int stack_frame_count)
144 {
145 #ifdef HAVE_BACKTRACE
146 char **strings;
147 size_t i;
148
149 strings = backtrace_symbols (stack_frames, stack_frame_count);
150
151 DBG1(" dumping %d stack frame addresses", stack_frame_count);
152
153 for (i = 0; i < stack_frame_count; i++)
154 {
155 DBG1(" %s", strings[i]);
156 }
157 free (strings);
158 #endif /* HAVE_BACKTRACE */
159 }
160
161 /**
162 * Whitelist, which contains address ranges in stack frames ignored when leaking.
163 *
164 * This is necessary, as some function use allocation hacks (static buffers)
165 * and so on, which we want to suppress on leak reports.
166 *
167 * The range_size is calculated using the readelf utility, e.g.:
168 * readelf -s /lib/glibc.so.6
169 * The values are for glibc-2.4 and may or may not be correct on other systems.
170 */
171 typedef struct whitelist_t whitelist_t;
172
173 struct whitelist_t {
174 void* range_start;
175 size_t range_size;
176 };
177
178 whitelist_t whitelist[] = {
179 {pthread_create, 2542},
180 {pthread_setspecific, 217},
181 {mktime, 60},
182 {tzset, 123},
183 {inet_ntoa, 249},
184 {strerror, 180},
185 {getprotobynumber, 291},
186 {getservbyport, 311},
187 {register_printf_function, 159},
188 {syslog, 45},
189 {dlopen, 109},
190 };
191
192 /**
193 * Check if this stack frame is whitelisted.
194 */
195 static bool is_whitelisted(void **stack_frames, int stack_frame_count)
196 {
197 int i, j;
198
199 for (i=0; i< stack_frame_count; i++)
200 {
201 for (j=0; j<sizeof(whitelist)/sizeof(whitelist_t); j++)
202 {
203 if (stack_frames[i] >= whitelist[j].range_start &&
204 stack_frames[i] <= (whitelist[j].range_start + whitelist[j].range_size))
205 {
206 return TRUE;
207 }
208 }
209 }
210 return FALSE;
211 }
212
213 /**
214 * Report leaks at library destruction
215 */
216 void report_leaks()
217 {
218 memory_header_t *hdr;
219 int leaks = 0;
220
221 for (hdr = first_header.next; hdr != NULL; hdr = hdr->next)
222 {
223 if (!is_whitelisted(hdr->stack_frames, hdr->stack_frame_count))
224 {
225 DBG1("Leak (%d bytes at %p):", hdr->bytes, hdr + 1);
226 log_stack_frames(hdr->stack_frames, hdr->stack_frame_count);
227 leaks++;
228 }
229 }
230
231 switch (leaks)
232 {
233 case 0:
234 DBG1("No leaks detected");
235 break;
236 case 1:
237 DBG1("One leak detected");
238 break;
239 default:
240 DBG1("%d leaks detected", leaks);
241 break;
242 }
243 }
244
245 /**
246 * Installs the malloc hooks, enables leak detection
247 */
248 static void install_hooks()
249 {
250 if (!installed)
251 {
252 old_malloc_hook = __malloc_hook;
253 old_realloc_hook = __realloc_hook;
254 old_free_hook = __free_hook;
255 __malloc_hook = malloc_hook;
256 __realloc_hook = realloc_hook;
257 __free_hook = free_hook;
258 installed = TRUE;
259 }
260 }
261
262 /**
263 * Uninstalls the malloc hooks, disables leak detection
264 */
265 static void uninstall_hooks()
266 {
267 if (installed)
268 {
269 __malloc_hook = old_malloc_hook;
270 __free_hook = old_free_hook;
271 __realloc_hook = old_realloc_hook;
272 installed = FALSE;
273 }
274 }
275
276 /**
277 * Hook function for malloc()
278 */
279 void *malloc_hook(size_t bytes, const void *caller)
280 {
281 memory_header_t *hdr;
282
283 pthread_mutex_lock(&mutex);
284 count_malloc++;
285 uninstall_hooks();
286 hdr = malloc(bytes + sizeof(memory_header_t));
287 /* set to something which causes crashes */
288 memset(hdr, MEMORY_ALLOC_PATTERN, bytes + sizeof(memory_header_t));
289
290 hdr->magic = MEMORY_HEADER_MAGIC;
291 hdr->bytes = bytes;
292 hdr->stack_frame_count = backtrace(hdr->stack_frames, STACK_FRAMES_COUNT);
293 install_hooks();
294
295 /* insert at the beginning of the list */
296 hdr->next = first_header.next;
297 if (hdr->next)
298 {
299 hdr->next->previous = hdr;
300 }
301 hdr->previous = &first_header;
302 first_header.next = hdr;
303 pthread_mutex_unlock(&mutex);
304 return hdr + 1;
305 }
306
307 /**
308 * Hook function for free()
309 */
310 void free_hook(void *ptr, const void *caller)
311 {
312 void *stack_frames[STACK_FRAMES_COUNT];
313 int stack_frame_count;
314 memory_header_t *hdr = ptr - sizeof(memory_header_t);
315
316 /* allow freeing of NULL */
317 if (ptr == NULL)
318 {
319 return;
320 }
321
322 pthread_mutex_lock(&mutex);
323 count_free++;
324 uninstall_hooks();
325 if (hdr->magic != MEMORY_HEADER_MAGIC)
326 {
327 DBG1("freeing of invalid memory (%p, MAGIC 0x%x != 0x%x):",
328 ptr, hdr->magic, MEMORY_HEADER_MAGIC);
329 stack_frame_count = backtrace(stack_frames, STACK_FRAMES_COUNT);
330 log_stack_frames(stack_frames, stack_frame_count);
331 install_hooks();
332 pthread_mutex_unlock(&mutex);
333 return;
334 }
335
336 /* remove item from list */
337 if (hdr->next)
338 {
339 hdr->next->previous = hdr->previous;
340 }
341 hdr->previous->next = hdr->next;
342
343 /* clear MAGIC, set mem to something remarkable */
344 memset(hdr, MEMORY_FREE_PATTERN, hdr->bytes + sizeof(memory_header_t));
345
346 free(hdr);
347 install_hooks();
348 pthread_mutex_unlock(&mutex);
349 }
350
351 /**
352 * Hook function for realloc()
353 */
354 void *realloc_hook(void *old, size_t bytes, const void *caller)
355 {
356 memory_header_t *hdr;
357 void *stack_frames[STACK_FRAMES_COUNT];
358 int stack_frame_count;
359
360 /* allow reallocation of NULL */
361 if (old == NULL)
362 {
363 return malloc_hook(bytes, caller);
364 }
365
366 hdr = old - sizeof(memory_header_t);
367
368 pthread_mutex_lock(&mutex);
369 count_realloc++;
370 uninstall_hooks();
371 if (hdr->magic != MEMORY_HEADER_MAGIC)
372 {
373 DBG1("reallocation of invalid memory (%p):", old);
374 stack_frame_count = backtrace(stack_frames, STACK_FRAMES_COUNT);
375 log_stack_frames(stack_frames, stack_frame_count);
376 install_hooks();
377 pthread_mutex_unlock(&mutex);
378 raise(SIGKILL);
379 return NULL;
380 }
381
382 hdr = realloc(hdr, bytes + sizeof(memory_header_t));
383
384 /* update statistics */
385 hdr->bytes = bytes;
386 hdr->stack_frame_count = backtrace(hdr->stack_frames, STACK_FRAMES_COUNT);
387
388 /* update header of linked list neighbours */
389 if (hdr->next)
390 {
391 hdr->next->previous = hdr;
392 }
393 hdr->previous->next = hdr;
394 install_hooks();
395 pthread_mutex_unlock(&mutex);
396 return hdr + 1;
397 }
398
399 /**
400 * Setup leak detective
401 */
402 void __attribute__ ((constructor)) leak_detective_init()
403 {
404 install_hooks();
405 }
406
407 /**
408 * Clean up leak detective
409 */
410 void __attribute__ ((destructor)) leak_detective_cleanup()
411 {
412 uninstall_hooks();
413 report_leaks();
414 }
415
416 /**
417 * Log memory allocation statistics
418 */
419 void leak_detective_status(FILE *stream)
420 {
421 u_int blocks = 0;
422 size_t bytes = 0;
423 memory_header_t *hdr = &first_header;
424
425 pthread_mutex_lock(&mutex);
426 while ((hdr = hdr->next))
427 {
428 blocks++;
429 bytes += hdr->bytes;
430 }
431 pthread_mutex_unlock(&mutex);
432
433 fprintf(stream, "allocation statistics:\n");
434 fprintf(stream, " call stats: malloc: %d, free: %d, realloc: %d\n",
435 count_malloc, count_free, count_realloc);
436 fprintf(stream, " allocated %d blocks, total size %d bytes (avg. %d bytes)\n",
437 blocks, bytes, bytes/blocks);
438 }
439
440 #else /* !LEAK_DETECTION */
441
442 /**
443 * Dummy when !using LEAK_DETECTIVE
444 */
445 void leak_detective_status(FILE *stream)
446 {
447
448 }
449
450 #endif /* LEAK_DETECTION */