blob: ebf0006a55654d6081532d445d5bdcc651722182 [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{
Christopher Tate52e7d3d2010-08-09 13:43:46 -070063 int result;
64
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080065 HashEntry* e1 = *(HashEntry**)arg1;
66 HashEntry* e2 = *(HashEntry**)arg2;
67
Christopher Tate52e7d3d2010-08-09 13:43:46 -070068 // if one or both arg pointers are null, deal gracefully
69 if (e1 == NULL) {
70 result = (e2 == NULL) ? 0 : 1;
71 } else if (e2 == NULL) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080072 result = -1;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080073 } else {
Christopher Tate52e7d3d2010-08-09 13:43:46 -070074 size_t nbAlloc1 = e1->allocations;
75 size_t nbAlloc2 = e2->allocations;
76 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
77 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
78 size_t alloc1 = nbAlloc1 * size1;
79 size_t alloc2 = nbAlloc2 * size2;
80
81 // sort in descending order by:
82 // 1) total size
83 // 2) number of allocations
84 //
85 // This is used for sorting, not determination of equality, so we don't
86 // need to compare the bit flags.
87 int result;
88 if (alloc1 > alloc2) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080089 result = -1;
Christopher Tate52e7d3d2010-08-09 13:43:46 -070090 } else if (alloc1 < alloc2) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080091 result = 1;
92 } else {
Christopher Tate52e7d3d2010-08-09 13:43:46 -070093 if (nbAlloc1 > nbAlloc2) {
94 result = -1;
95 } else if (nbAlloc1 < nbAlloc2) {
96 result = 1;
97 } else {
98 result = 0;
99 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800100 }
101 }
102 return result;
103}
104
105/*
106 * Retrieve native heap information.
107 *
108 * "*info" is set to a buffer we allocate
109 * "*overallSize" is set to the size of the "info" buffer
110 * "*infoSize" is set to the size of a single entry
111 * "*totalMemory" is set to the sum of all allocations we're tracking; does
112 * not include heap overhead
113 * "*backtraceSize" is set to the maximum number of entries in the back trace
114 */
115void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
116 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize)
117{
118 // don't do anything if we have invalid arguments
119 if (info == NULL || overallSize == NULL || infoSize == NULL ||
120 totalMemory == NULL || backtraceSize == NULL) {
121 return;
122 }
tedbo9d8be542010-10-05 13:06:06 -0700123 *totalMemory = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800124
125 pthread_mutex_lock(&gAllocationsMutex);
126
127 if (gHashTable.count == 0) {
128 *info = NULL;
129 *overallSize = 0;
130 *infoSize = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800131 *backtraceSize = 0;
132 goto done;
133 }
134
135 void** list = (void**)dlmalloc(sizeof(void*) * gHashTable.count);
136
137 // get the entries into an array to be sorted
138 int index = 0;
139 int i;
140 for (i = 0 ; i < HASHTABLE_SIZE ; i++) {
141 HashEntry* entry = gHashTable.slots[i];
142 while (entry != NULL) {
143 list[index] = entry;
144 *totalMemory = *totalMemory +
145 ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
146 index++;
147 entry = entry->next;
148 }
149 }
150
151 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
152 *infoSize = (sizeof(size_t) * 2) + (sizeof(intptr_t) * BACKTRACE_SIZE);
153 *overallSize = *infoSize * gHashTable.count;
154 *backtraceSize = BACKTRACE_SIZE;
155
156 // now get A byte array big enough for this
157 *info = (uint8_t*)dlmalloc(*overallSize);
158
159 if (*info == NULL) {
160 *overallSize = 0;
The Android Open Source Project95faece2010-04-08 11:11:53 -0700161 goto out_nomem_info;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800162 }
163
164 qsort((void*)list, gHashTable.count, sizeof(void*), hash_entry_compare);
165
166 uint8_t* head = *info;
167 const int count = gHashTable.count;
168 for (i = 0 ; i < count ; i++) {
169 HashEntry* entry = list[i];
170 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(intptr_t) * entry->numEntries);
171 if (entrySize < *infoSize) {
172 /* we're writing less than a full entry, clear out the rest */
The Android Open Source Project95faece2010-04-08 11:11:53 -0700173 memset(head + entrySize, 0, *infoSize - entrySize);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800174 } else {
175 /* make sure the amount we're copying doesn't exceed the limit */
176 entrySize = *infoSize;
177 }
178 memcpy(head, &(entry->size), entrySize);
179 head += *infoSize;
180 }
181
The Android Open Source Project95faece2010-04-08 11:11:53 -0700182out_nomem_info:
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800183 dlfree(list);
184
185done:
186 pthread_mutex_unlock(&gAllocationsMutex);
187}
188
189void free_malloc_leak_info(uint8_t* info)
190{
191 dlfree(info);
192}
193
194struct mallinfo mallinfo()
195{
196 return dlmallinfo();
197}
198
199void* valloc(size_t bytes) {
200 /* assume page size of 4096 bytes */
201 return memalign( getpagesize(), bytes );
202}
203
204/* Support for malloc debugging.
205 * Note that if USE_DL_PREFIX is not defined, it's assumed that memory
206 * allocation routines are implemented somewhere else, so all our custom
207 * malloc routines should not be compiled at all.
208 */
209#ifdef USE_DL_PREFIX
210
211/* Table for dispatching malloc calls, initialized with default dispatchers. */
212const MallocDebug __libc_malloc_default_dispatch __attribute__((aligned(32))) =
213{
214 dlmalloc, dlfree, dlcalloc, dlrealloc, dlmemalign
215};
216
217/* Selector of dispatch table to use for dispatching malloc calls. */
218const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch;
219
220void* malloc(size_t bytes) {
221 return __libc_malloc_dispatch->malloc(bytes);
222}
223void free(void* mem) {
224 __libc_malloc_dispatch->free(mem);
225}
226void* calloc(size_t n_elements, size_t elem_size) {
227 return __libc_malloc_dispatch->calloc(n_elements, elem_size);
228}
229void* realloc(void* oldMem, size_t bytes) {
230 return __libc_malloc_dispatch->realloc(oldMem, bytes);
231}
232void* memalign(size_t alignment, size_t bytes) {
233 return __libc_malloc_dispatch->memalign(alignment, bytes);
234}
235
236/* We implement malloc debugging only in libc.so, so code bellow
237 * must be excluded if we compile this file for static libc.a
238 */
239#ifndef LIBC_STATIC
240#include <sys/system_properties.h>
241#include <dlfcn.h>
242#include "logd.h"
243
244// =============================================================================
245// log functions
246// =============================================================================
247
248#define debug_log(format, ...) \
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800249 __libc_android_log_print(ANDROID_LOG_DEBUG, "libc", (format), ##__VA_ARGS__ )
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800250#define error_log(format, ...) \
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800251 __libc_android_log_print(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800252#define info_log(format, ...) \
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800253 __libc_android_log_print(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800254
255/* Table for dispatching malloc calls, depending on environment. */
256static MallocDebug gMallocUse __attribute__((aligned(32))) = {
257 dlmalloc, dlfree, dlcalloc, dlrealloc, dlmemalign
258};
259
260extern char* __progname;
261
262/* Handle to shared library where actual memory allocation is implemented.
263 * This library is loaded and memory allocation calls are redirected there
264 * when libc.debug.malloc environment variable contains value other than
265 * zero:
266 * 1 - For memory leak detections.
267 * 5 - For filling allocated / freed memory with patterns defined by
268 * CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
269 * 10 - For adding pre-, and post- allocation stubs in order to detect
270 * buffer overruns.
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800271 * Note that emulator's memory allocation instrumentation is not controlled by
272 * libc.debug.malloc value, but rather by emulator, started with -memcheck
273 * option. Note also, that if emulator has started with -memcheck option,
274 * emulator's instrumented memory allocation will take over value saved in
275 * libc.debug.malloc. In other words, if emulator has started with -memcheck
276 * option, libc.debug.malloc value is ignored.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800277 * Actual functionality for debug levels 1-10 is implemented in
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800278 * libc_malloc_debug_leak.so, while functionality for emultor's instrumented
279 * allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
280 * the emulator only.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800281 */
282static void* libc_malloc_impl_handle = NULL;
283
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800284/* Make sure we have MALLOC_ALIGNMENT that matches the one that is
285 * used in dlmalloc. Emulator's memchecker needs this value to properly
286 * align its guarding zones.
287 */
288#ifndef MALLOC_ALIGNMENT
289#define MALLOC_ALIGNMENT ((size_t)8U)
290#endif /* MALLOC_ALIGNMENT */
291
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800292/* Initializes memory allocation framework once per process. */
293static void malloc_init_impl(void)
294{
295 const char* so_name = NULL;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800296 MallocDebugInit malloc_debug_initialize = NULL;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800297 unsigned int qemu_running = 0;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800298 unsigned int debug_level = 0;
299 unsigned int memcheck_enabled = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800300 char env[PROP_VALUE_MAX];
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800301 char memcheck_tracing[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800302
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800303 /* Get custom malloc debug level. Note that emulator started with
304 * memory checking option will have priority over debug level set in
305 * libc.debug.malloc system property. */
306 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
307 qemu_running = 1;
308 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
309 if (memcheck_tracing[0] != '0') {
310 // Emulator has started with memory tracing enabled. Enforce it.
311 debug_level = 20;
312 memcheck_enabled = 1;
313 }
314 }
315 }
316
317 /* If debug level has not been set by memcheck option in the emulator,
318 * lets grab it from libc.debug.malloc system property. */
319 if (!debug_level && __system_property_get("libc.debug.malloc", env)) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800320 debug_level = atoi(env);
321 }
322
323 /* Debug level 0 means that we should use dlxxx allocation
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800324 * routines (default). */
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800325 if (!debug_level) {
326 return;
327 }
328
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800329 // Lets see which .so must be loaded for the requested debug level
330 switch (debug_level) {
331 case 1:
332 case 5:
333 case 10:
334 so_name = "/system/lib/libc_malloc_debug_leak.so";
335 break;
336 case 20:
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800337 // Quick check: debug level 20 can only be handled in emulator.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800338 if (!qemu_running) {
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800339 error_log("%s: Debug level %d can only be set in emulator\n",
340 __progname, debug_level);
341 return;
342 }
343 // Make sure that memory checking has been enabled in emulator.
344 if (!memcheck_enabled) {
345 error_log("%s: Memory checking is not enabled in the emulator\n",
346 __progname);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800347 return;
348 }
349 so_name = "/system/lib/libc_malloc_debug_qemu.so";
350 break;
351 default:
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800352 error_log("%s: Debug level %d is unknown\n",
353 __progname, debug_level);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800354 return;
355 }
356
357 // Load .so that implements the required malloc debugging functionality.
358 libc_malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
359 if (libc_malloc_impl_handle == NULL) {
360 error_log("%s: Missing module %s required for malloc debug level %d\n",
361 __progname, so_name, debug_level);
362 return;
363 }
364
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800365 // Initialize malloc debugging in the loaded module.
366 malloc_debug_initialize =
367 dlsym(libc_malloc_impl_handle, "malloc_debug_initialize");
368 if (malloc_debug_initialize == NULL) {
369 error_log("%s: Initialization routine is not found in %s\n",
370 __progname, so_name);
371 dlclose(libc_malloc_impl_handle);
372 return;
373 }
374 if (malloc_debug_initialize()) {
375 dlclose(libc_malloc_impl_handle);
376 return;
377 }
378
379 if (debug_level == 20) {
380 // For memory checker we need to do extra initialization.
381 int (*memcheck_initialize)(int, const char*) =
382 dlsym(libc_malloc_impl_handle, "memcheck_initialize");
383 if (memcheck_initialize == NULL) {
384 error_log("%s: memcheck_initialize routine is not found in %s\n",
385 __progname, so_name);
386 dlclose(libc_malloc_impl_handle);
387 return;
388 }
389 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
390 dlclose(libc_malloc_impl_handle);
391 return;
392 }
393 }
394
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800395 // Initialize malloc dispatch table with appropriate routines.
396 switch (debug_level) {
397 case 1:
398 __libc_android_log_print(ANDROID_LOG_INFO, "libc",
399 "%s using MALLOC_DEBUG = %d (leak checker)\n",
400 __progname, debug_level);
401 gMallocUse.malloc =
402 dlsym(libc_malloc_impl_handle, "leak_malloc");
403 gMallocUse.free =
404 dlsym(libc_malloc_impl_handle, "leak_free");
405 gMallocUse.calloc =
406 dlsym(libc_malloc_impl_handle, "leak_calloc");
407 gMallocUse.realloc =
408 dlsym(libc_malloc_impl_handle, "leak_realloc");
409 gMallocUse.memalign =
410 dlsym(libc_malloc_impl_handle, "leak_memalign");
411 break;
412 case 5:
413 __libc_android_log_print(ANDROID_LOG_INFO, "libc",
414 "%s using MALLOC_DEBUG = %d (fill)\n",
415 __progname, debug_level);
416 gMallocUse.malloc =
417 dlsym(libc_malloc_impl_handle, "fill_malloc");
418 gMallocUse.free =
419 dlsym(libc_malloc_impl_handle, "fill_free");
420 gMallocUse.calloc = dlcalloc;
421 gMallocUse.realloc =
422 dlsym(libc_malloc_impl_handle, "fill_realloc");
423 gMallocUse.memalign =
424 dlsym(libc_malloc_impl_handle, "fill_memalign");
425 break;
426 case 10:
427 __libc_android_log_print(ANDROID_LOG_INFO, "libc",
428 "%s using MALLOC_DEBUG = %d (sentinels, fill)\n",
429 __progname, debug_level);
430 gMallocUse.malloc =
431 dlsym(libc_malloc_impl_handle, "chk_malloc");
432 gMallocUse.free =
433 dlsym(libc_malloc_impl_handle, "chk_free");
434 gMallocUse.calloc =
435 dlsym(libc_malloc_impl_handle, "chk_calloc");
436 gMallocUse.realloc =
437 dlsym(libc_malloc_impl_handle, "chk_realloc");
438 gMallocUse.memalign =
439 dlsym(libc_malloc_impl_handle, "chk_memalign");
440 break;
441 case 20:
442 __libc_android_log_print(ANDROID_LOG_INFO, "libc",
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800443 "%s[%u] using MALLOC_DEBUG = %d (instrumented for emulator)\n",
444 __progname, getpid(), debug_level);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800445 gMallocUse.malloc =
446 dlsym(libc_malloc_impl_handle, "qemu_instrumented_malloc");
447 gMallocUse.free =
448 dlsym(libc_malloc_impl_handle, "qemu_instrumented_free");
449 gMallocUse.calloc =
450 dlsym(libc_malloc_impl_handle, "qemu_instrumented_calloc");
451 gMallocUse.realloc =
452 dlsym(libc_malloc_impl_handle, "qemu_instrumented_realloc");
453 gMallocUse.memalign =
454 dlsym(libc_malloc_impl_handle, "qemu_instrumented_memalign");
455 break;
456 default:
457 break;
458 }
459
460 // Make sure dispatch table is initialized
461 if ((gMallocUse.malloc == NULL) ||
462 (gMallocUse.free == NULL) ||
463 (gMallocUse.calloc == NULL) ||
464 (gMallocUse.realloc == NULL) ||
465 (gMallocUse.memalign == NULL)) {
466 error_log("%s: Cannot initialize malloc dispatch table for debug level"
467 " %d: %p, %p, %p, %p, %p\n",
468 __progname, debug_level,
469 gMallocUse.malloc, gMallocUse.free,
470 gMallocUse.calloc, gMallocUse.realloc,
471 gMallocUse.memalign);
472 dlclose(libc_malloc_impl_handle);
473 libc_malloc_impl_handle = NULL;
474 } else {
475 __libc_malloc_dispatch = &gMallocUse;
476 }
477}
478
479static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
480
481#endif // !LIBC_STATIC
482#endif // USE_DL_PREFIX
483
484/* Initializes memory allocation framework.
485 * This routine is called from __libc_init routines implemented
486 * in libc_init_static.c and libc_init_dynamic.c files.
487 */
488void malloc_debug_init(void)
489{
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800490 /* We need to initialize malloc iff we implement here custom
491 * malloc routines (i.e. USE_DL_PREFIX is defined) for libc.so */
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800492#if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC)
493 if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
494 error_log("Unable to initialize malloc_debug component.");
495 }
496#endif // USE_DL_PREFIX && !LIBC_STATIC
497}