blob: a86255a0abb524dee554d2a0cb9c3f48f28d2562 [file] [log] [blame]
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29/*
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -080030 * Contains definition of structures, global variables, and implementation of
31 * routines that are used by malloc leak detection code and other components in
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080032 * the system. The trick is that some components expect these data and
33 * routines to be defined / implemented in libc.so library, regardless
34 * whether or not MALLOC_LEAK_CHECK macro is defined. To make things even
35 * more tricky, malloc leak detection code, implemented in
36 * libc_malloc_debug.so also requires access to these variables and routines
37 * (to fill allocation entry hash table, for example). So, all relevant
38 * variables and routines are defined / implemented here and exported
39 * to all, leak detection code and other components via dynamic (libc.so),
40 * or static (libc.a) linking.
41 */
42
43#include <stdlib.h>
44#include <pthread.h>
45#include <unistd.h>
46#include "dlmalloc.h"
47#include "malloc_debug_common.h"
48
49/*
50 * In a VM process, this is set to 1 after fork()ing out of zygote.
51 */
52int gMallocLeakZygoteChild = 0;
53
54pthread_mutex_t gAllocationsMutex = PTHREAD_MUTEX_INITIALIZER;
55HashTable gHashTable;
56
57// =============================================================================
58// output functions
59// =============================================================================
60
61static int hash_entry_compare(const void* arg1, const void* arg2)
62{
63 HashEntry* e1 = *(HashEntry**)arg1;
64 HashEntry* e2 = *(HashEntry**)arg2;
65
66 size_t nbAlloc1 = e1->allocations;
67 size_t nbAlloc2 = e2->allocations;
68 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
69 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
70 size_t alloc1 = nbAlloc1 * size1;
71 size_t alloc2 = nbAlloc2 * size2;
72
73 // sort in descending order by:
74 // 1) total size
75 // 2) number of allocations
76 //
77 // This is used for sorting, not determination of equality, so we don't
78 // need to compare the bit flags.
79 int result;
80 if (alloc1 > alloc2) {
81 result = -1;
82 } else if (alloc1 < alloc2) {
83 result = 1;
84 } else {
85 if (nbAlloc1 > nbAlloc2) {
86 result = -1;
87 } else if (nbAlloc1 < nbAlloc2) {
88 result = 1;
89 } else {
90 result = 0;
91 }
92 }
93 return result;
94}
95
96/*
97 * Retrieve native heap information.
98 *
99 * "*info" is set to a buffer we allocate
100 * "*overallSize" is set to the size of the "info" buffer
101 * "*infoSize" is set to the size of a single entry
102 * "*totalMemory" is set to the sum of all allocations we're tracking; does
103 * not include heap overhead
104 * "*backtraceSize" is set to the maximum number of entries in the back trace
105 */
106void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
107 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize)
108{
109 // don't do anything if we have invalid arguments
110 if (info == NULL || overallSize == NULL || infoSize == NULL ||
111 totalMemory == NULL || backtraceSize == NULL) {
112 return;
113 }
114
115 pthread_mutex_lock(&gAllocationsMutex);
116
117 if (gHashTable.count == 0) {
118 *info = NULL;
119 *overallSize = 0;
120 *infoSize = 0;
121 *totalMemory = 0;
122 *backtraceSize = 0;
123 goto done;
124 }
125
126 void** list = (void**)dlmalloc(sizeof(void*) * gHashTable.count);
127
128 // get the entries into an array to be sorted
129 int index = 0;
130 int i;
131 for (i = 0 ; i < HASHTABLE_SIZE ; i++) {
132 HashEntry* entry = gHashTable.slots[i];
133 while (entry != NULL) {
134 list[index] = entry;
135 *totalMemory = *totalMemory +
136 ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
137 index++;
138 entry = entry->next;
139 }
140 }
141
142 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
143 *infoSize = (sizeof(size_t) * 2) + (sizeof(intptr_t) * BACKTRACE_SIZE);
144 *overallSize = *infoSize * gHashTable.count;
145 *backtraceSize = BACKTRACE_SIZE;
146
147 // now get A byte array big enough for this
148 *info = (uint8_t*)dlmalloc(*overallSize);
149
150 if (*info == NULL) {
151 *overallSize = 0;
152 goto done;
153 }
154
155 qsort((void*)list, gHashTable.count, sizeof(void*), hash_entry_compare);
156
157 uint8_t* head = *info;
158 const int count = gHashTable.count;
159 for (i = 0 ; i < count ; i++) {
160 HashEntry* entry = list[i];
161 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(intptr_t) * entry->numEntries);
162 if (entrySize < *infoSize) {
163 /* we're writing less than a full entry, clear out the rest */
164 /* TODO: only clear out the part we're not overwriting? */
165 memset(head, 0, *infoSize);
166 } else {
167 /* make sure the amount we're copying doesn't exceed the limit */
168 entrySize = *infoSize;
169 }
170 memcpy(head, &(entry->size), entrySize);
171 head += *infoSize;
172 }
173
174 dlfree(list);
175
176done:
177 pthread_mutex_unlock(&gAllocationsMutex);
178}
179
180void free_malloc_leak_info(uint8_t* info)
181{
182 dlfree(info);
183}
184
185struct mallinfo mallinfo()
186{
187 return dlmallinfo();
188}
189
190void* valloc(size_t bytes) {
191 /* assume page size of 4096 bytes */
192 return memalign( getpagesize(), bytes );
193}
194
195/* Support for malloc debugging.
196 * Note that if USE_DL_PREFIX is not defined, it's assumed that memory
197 * allocation routines are implemented somewhere else, so all our custom
198 * malloc routines should not be compiled at all.
199 */
200#ifdef USE_DL_PREFIX
201
202/* Table for dispatching malloc calls, initialized with default dispatchers. */
203const MallocDebug __libc_malloc_default_dispatch __attribute__((aligned(32))) =
204{
205 dlmalloc, dlfree, dlcalloc, dlrealloc, dlmemalign
206};
207
208/* Selector of dispatch table to use for dispatching malloc calls. */
209const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch;
210
211void* malloc(size_t bytes) {
212 return __libc_malloc_dispatch->malloc(bytes);
213}
214void free(void* mem) {
215 __libc_malloc_dispatch->free(mem);
216}
217void* calloc(size_t n_elements, size_t elem_size) {
218 return __libc_malloc_dispatch->calloc(n_elements, elem_size);
219}
220void* realloc(void* oldMem, size_t bytes) {
221 return __libc_malloc_dispatch->realloc(oldMem, bytes);
222}
223void* memalign(size_t alignment, size_t bytes) {
224 return __libc_malloc_dispatch->memalign(alignment, bytes);
225}
226
227/* We implement malloc debugging only in libc.so, so code bellow
228 * must be excluded if we compile this file for static libc.a
229 */
230#ifndef LIBC_STATIC
231#include <sys/system_properties.h>
232#include <dlfcn.h>
233#include "logd.h"
234
235// =============================================================================
236// log functions
237// =============================================================================
238
239#define debug_log(format, ...) \
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800240 __libc_android_log_print(ANDROID_LOG_DEBUG, "libc", (format), ##__VA_ARGS__ )
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800241#define error_log(format, ...) \
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800242 __libc_android_log_print(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800243#define info_log(format, ...) \
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800244 __libc_android_log_print(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800245
246/* Table for dispatching malloc calls, depending on environment. */
247static MallocDebug gMallocUse __attribute__((aligned(32))) = {
248 dlmalloc, dlfree, dlcalloc, dlrealloc, dlmemalign
249};
250
251extern char* __progname;
252
253/* Handle to shared library where actual memory allocation is implemented.
254 * This library is loaded and memory allocation calls are redirected there
255 * when libc.debug.malloc environment variable contains value other than
256 * zero:
257 * 1 - For memory leak detections.
258 * 5 - For filling allocated / freed memory with patterns defined by
259 * CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
260 * 10 - For adding pre-, and post- allocation stubs in order to detect
261 * buffer overruns.
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800262 * Note that emulator's memory allocation instrumentation is not controlled by
263 * libc.debug.malloc value, but rather by emulator, started with -memcheck
264 * option. Note also, that if emulator has started with -memcheck option,
265 * emulator's instrumented memory allocation will take over value saved in
266 * libc.debug.malloc. In other words, if emulator has started with -memcheck
267 * option, libc.debug.malloc value is ignored.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800268 * Actual functionality for debug levels 1-10 is implemented in
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800269 * libc_malloc_debug_leak.so, while functionality for emultor's instrumented
270 * allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
271 * the emulator only.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800272 */
273static void* libc_malloc_impl_handle = NULL;
274
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800275/* Make sure we have MALLOC_ALIGNMENT that matches the one that is
276 * used in dlmalloc. Emulator's memchecker needs this value to properly
277 * align its guarding zones.
278 */
279#ifndef MALLOC_ALIGNMENT
280#define MALLOC_ALIGNMENT ((size_t)8U)
281#endif /* MALLOC_ALIGNMENT */
282
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800283/* Initializes memory allocation framework once per process. */
284static void malloc_init_impl(void)
285{
286 const char* so_name = NULL;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800287 MallocDebugInit malloc_debug_initialize = NULL;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800288 unsigned int qemu_running = 0;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800289 unsigned int debug_level = 0;
290 unsigned int memcheck_enabled = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800291 char env[PROP_VALUE_MAX];
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800292 char memcheck_tracing[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800293
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800294 /* Get custom malloc debug level. Note that emulator started with
295 * memory checking option will have priority over debug level set in
296 * libc.debug.malloc system property. */
297 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
298 qemu_running = 1;
299 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
300 if (memcheck_tracing[0] != '0') {
301 // Emulator has started with memory tracing enabled. Enforce it.
302 debug_level = 20;
303 memcheck_enabled = 1;
304 }
305 }
306 }
307
308 /* If debug level has not been set by memcheck option in the emulator,
309 * lets grab it from libc.debug.malloc system property. */
310 if (!debug_level && __system_property_get("libc.debug.malloc", env)) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800311 debug_level = atoi(env);
312 }
313
314 /* Debug level 0 means that we should use dlxxx allocation
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800315 * routines (default). */
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800316 if (!debug_level) {
317 return;
318 }
319
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800320 // Lets see which .so must be loaded for the requested debug level
321 switch (debug_level) {
322 case 1:
323 case 5:
324 case 10:
325 so_name = "/system/lib/libc_malloc_debug_leak.so";
326 break;
327 case 20:
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800328 // Quick check: debug level 20 can only be handled in emulator.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800329 if (!qemu_running) {
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800330 error_log("%s: Debug level %d can only be set in emulator\n",
331 __progname, debug_level);
332 return;
333 }
334 // Make sure that memory checking has been enabled in emulator.
335 if (!memcheck_enabled) {
336 error_log("%s: Memory checking is not enabled in the emulator\n",
337 __progname);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800338 return;
339 }
340 so_name = "/system/lib/libc_malloc_debug_qemu.so";
341 break;
342 default:
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800343 error_log("%s: Debug level %d is unknown\n",
344 __progname, debug_level);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800345 return;
346 }
347
348 // Load .so that implements the required malloc debugging functionality.
349 libc_malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
350 if (libc_malloc_impl_handle == NULL) {
351 error_log("%s: Missing module %s required for malloc debug level %d\n",
352 __progname, so_name, debug_level);
353 return;
354 }
355
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800356 // Initialize malloc debugging in the loaded module.
357 malloc_debug_initialize =
358 dlsym(libc_malloc_impl_handle, "malloc_debug_initialize");
359 if (malloc_debug_initialize == NULL) {
360 error_log("%s: Initialization routine is not found in %s\n",
361 __progname, so_name);
362 dlclose(libc_malloc_impl_handle);
363 return;
364 }
365 if (malloc_debug_initialize()) {
366 dlclose(libc_malloc_impl_handle);
367 return;
368 }
369
370 if (debug_level == 20) {
371 // For memory checker we need to do extra initialization.
372 int (*memcheck_initialize)(int, const char*) =
373 dlsym(libc_malloc_impl_handle, "memcheck_initialize");
374 if (memcheck_initialize == NULL) {
375 error_log("%s: memcheck_initialize routine is not found in %s\n",
376 __progname, so_name);
377 dlclose(libc_malloc_impl_handle);
378 return;
379 }
380 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
381 dlclose(libc_malloc_impl_handle);
382 return;
383 }
384 }
385
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800386 // Initialize malloc dispatch table with appropriate routines.
387 switch (debug_level) {
388 case 1:
389 __libc_android_log_print(ANDROID_LOG_INFO, "libc",
390 "%s using MALLOC_DEBUG = %d (leak checker)\n",
391 __progname, debug_level);
392 gMallocUse.malloc =
393 dlsym(libc_malloc_impl_handle, "leak_malloc");
394 gMallocUse.free =
395 dlsym(libc_malloc_impl_handle, "leak_free");
396 gMallocUse.calloc =
397 dlsym(libc_malloc_impl_handle, "leak_calloc");
398 gMallocUse.realloc =
399 dlsym(libc_malloc_impl_handle, "leak_realloc");
400 gMallocUse.memalign =
401 dlsym(libc_malloc_impl_handle, "leak_memalign");
402 break;
403 case 5:
404 __libc_android_log_print(ANDROID_LOG_INFO, "libc",
405 "%s using MALLOC_DEBUG = %d (fill)\n",
406 __progname, debug_level);
407 gMallocUse.malloc =
408 dlsym(libc_malloc_impl_handle, "fill_malloc");
409 gMallocUse.free =
410 dlsym(libc_malloc_impl_handle, "fill_free");
411 gMallocUse.calloc = dlcalloc;
412 gMallocUse.realloc =
413 dlsym(libc_malloc_impl_handle, "fill_realloc");
414 gMallocUse.memalign =
415 dlsym(libc_malloc_impl_handle, "fill_memalign");
416 break;
417 case 10:
418 __libc_android_log_print(ANDROID_LOG_INFO, "libc",
419 "%s using MALLOC_DEBUG = %d (sentinels, fill)\n",
420 __progname, debug_level);
421 gMallocUse.malloc =
422 dlsym(libc_malloc_impl_handle, "chk_malloc");
423 gMallocUse.free =
424 dlsym(libc_malloc_impl_handle, "chk_free");
425 gMallocUse.calloc =
426 dlsym(libc_malloc_impl_handle, "chk_calloc");
427 gMallocUse.realloc =
428 dlsym(libc_malloc_impl_handle, "chk_realloc");
429 gMallocUse.memalign =
430 dlsym(libc_malloc_impl_handle, "chk_memalign");
431 break;
432 case 20:
433 __libc_android_log_print(ANDROID_LOG_INFO, "libc",
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800434 "%s[%u] using MALLOC_DEBUG = %d (instrumented for emulator)\n",
435 __progname, getpid(), debug_level);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800436 gMallocUse.malloc =
437 dlsym(libc_malloc_impl_handle, "qemu_instrumented_malloc");
438 gMallocUse.free =
439 dlsym(libc_malloc_impl_handle, "qemu_instrumented_free");
440 gMallocUse.calloc =
441 dlsym(libc_malloc_impl_handle, "qemu_instrumented_calloc");
442 gMallocUse.realloc =
443 dlsym(libc_malloc_impl_handle, "qemu_instrumented_realloc");
444 gMallocUse.memalign =
445 dlsym(libc_malloc_impl_handle, "qemu_instrumented_memalign");
446 break;
447 default:
448 break;
449 }
450
451 // Make sure dispatch table is initialized
452 if ((gMallocUse.malloc == NULL) ||
453 (gMallocUse.free == NULL) ||
454 (gMallocUse.calloc == NULL) ||
455 (gMallocUse.realloc == NULL) ||
456 (gMallocUse.memalign == NULL)) {
457 error_log("%s: Cannot initialize malloc dispatch table for debug level"
458 " %d: %p, %p, %p, %p, %p\n",
459 __progname, debug_level,
460 gMallocUse.malloc, gMallocUse.free,
461 gMallocUse.calloc, gMallocUse.realloc,
462 gMallocUse.memalign);
463 dlclose(libc_malloc_impl_handle);
464 libc_malloc_impl_handle = NULL;
465 } else {
466 __libc_malloc_dispatch = &gMallocUse;
467 }
468}
469
470static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
471
472#endif // !LIBC_STATIC
473#endif // USE_DL_PREFIX
474
475/* Initializes memory allocation framework.
476 * This routine is called from __libc_init routines implemented
477 * in libc_init_static.c and libc_init_dynamic.c files.
478 */
479void malloc_debug_init(void)
480{
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800481 /* We need to initialize malloc iff we implement here custom
482 * malloc routines (i.e. USE_DL_PREFIX is defined) for libc.so */
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800483#if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC)
484 if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
485 error_log("Unable to initialize malloc_debug component.");
486 }
487#endif // USE_DL_PREFIX && !LIBC_STATIC
488}