blob: 77ec080fe7ac2784de292a0fa80f61fbdd28f6a6 [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
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080043#include "malloc_debug_common.h"
44
Elliott Hughes3b297c42012-10-11 16:08:51 -070045#include <pthread.h>
46#include <stdlib.h>
47#include <unistd.h>
48
Elliott Hugheseb847bc2013-10-09 15:50:50 -070049#include "private/ScopedPthreadMutexLocker.h"
Elliott Hughes3b297c42012-10-11 16:08:51 -070050
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070051// In a VM process, this is set to 1 after fork()ing out of zygote.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080052int gMallocLeakZygoteChild = 0;
53
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070054static HashTable g_hash_table;
55
56// Support for malloc debugging.
57// Table for dispatching malloc calls, initialized with default dispatchers.
58static const MallocDebug __libc_malloc_default_dispatch __attribute__((aligned(32))) = {
59 Malloc(malloc), Malloc(free), Malloc(calloc), Malloc(realloc), Malloc(memalign), Malloc(malloc_usable_size),
60};
61
62// Selector of dispatch table to use for dispatching malloc calls.
Elliott Hughes14442bb2014-06-04 15:18:36 -070063// TODO: fix http://b/15432753 and make this static again.
64const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch;
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070065
66// Handle to shared library where actual memory allocation is implemented.
67// This library is loaded and memory allocation calls are redirected there
68// when libc.debug.malloc environment variable contains value other than
69// zero:
70// 1 - For memory leak detections.
71// 5 - For filling allocated / freed memory with patterns defined by
72// CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
73// 10 - For adding pre-, and post- allocation stubs in order to detect
74// buffer overruns.
75// Note that emulator's memory allocation instrumentation is not controlled by
76// libc.debug.malloc value, but rather by emulator, started with -memcheck
77// option. Note also, that if emulator has started with -memcheck option,
78// emulator's instrumented memory allocation will take over value saved in
79// libc.debug.malloc. In other words, if emulator has started with -memcheck
80// option, libc.debug.malloc value is ignored.
81// Actual functionality for debug levels 1-10 is implemented in
82// libc_malloc_debug_leak.so, while functionality for emulator's instrumented
83// allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
84// the emulator only.
85#if !defined(LIBC_STATIC)
86static void* libc_malloc_impl_handle = NULL;
87#endif
88
89
90// The value of libc.debug.malloc.
91#if !defined(LIBC_STATIC)
92static int g_malloc_debug_level = 0;
93#endif
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080094
95// =============================================================================
96// output functions
97// =============================================================================
98
Elliott Hughesc4d1fec2012-08-28 14:15:04 -070099static int hash_entry_compare(const void* arg1, const void* arg2) {
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700100 int result;
101
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700102 const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
103 const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800104
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700105 // if one or both arg pointers are null, deal gracefully
106 if (e1 == NULL) {
107 result = (e2 == NULL) ? 0 : 1;
108 } else if (e2 == NULL) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800109 result = -1;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800110 } else {
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700111 size_t nbAlloc1 = e1->allocations;
112 size_t nbAlloc2 = e2->allocations;
113 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
114 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
115 size_t alloc1 = nbAlloc1 * size1;
116 size_t alloc2 = nbAlloc2 * size2;
117
118 // sort in descending order by:
119 // 1) total size
120 // 2) number of allocations
121 //
122 // This is used for sorting, not determination of equality, so we don't
123 // need to compare the bit flags.
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700124 if (alloc1 > alloc2) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800125 result = -1;
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700126 } else if (alloc1 < alloc2) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800127 result = 1;
128 } else {
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700129 if (nbAlloc1 > nbAlloc2) {
130 result = -1;
131 } else if (nbAlloc1 < nbAlloc2) {
132 result = 1;
133 } else {
134 result = 0;
135 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800136 }
137 }
138 return result;
139}
140
141/*
142 * Retrieve native heap information.
143 *
144 * "*info" is set to a buffer we allocate
145 * "*overallSize" is set to the size of the "info" buffer
146 * "*infoSize" is set to the size of a single entry
147 * "*totalMemory" is set to the sum of all allocations we're tracking; does
148 * not include heap overhead
149 * "*backtraceSize" is set to the maximum number of entries in the back trace
150 */
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700151
152// Exported for use by ddms.
153extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700154 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800155 // don't do anything if we have invalid arguments
156 if (info == NULL || overallSize == NULL || infoSize == NULL ||
157 totalMemory == NULL || backtraceSize == NULL) {
158 return;
159 }
tedbo9d8be542010-10-05 13:06:06 -0700160 *totalMemory = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800161
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700162 ScopedPthreadMutexLocker locker(&g_hash_table.lock);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800163
Elliott Hughes1728b232014-05-14 10:02:03 -0700164 if (g_hash_table.count == 0) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800165 *info = NULL;
166 *overallSize = 0;
167 *infoSize = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800168 *backtraceSize = 0;
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700169 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800170 }
171
Christopher Ferris72bbd422014-05-08 11:14:03 -0700172 HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800173
174 // get the entries into an array to be sorted
175 int index = 0;
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700176 for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
Elliott Hughes1728b232014-05-14 10:02:03 -0700177 HashEntry* entry = g_hash_table.slots[i];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800178 while (entry != NULL) {
179 list[index] = entry;
180 *totalMemory = *totalMemory +
181 ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
182 index++;
183 entry = entry->next;
184 }
185 }
186
187 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
Elliott Hughes239e7a02013-01-25 17:13:45 -0800188 *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
Elliott Hughes1728b232014-05-14 10:02:03 -0700189 *overallSize = *infoSize * g_hash_table.count;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800190 *backtraceSize = BACKTRACE_SIZE;
191
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700192 // now get a byte array big enough for this
Christopher Ferris72bbd422014-05-08 11:14:03 -0700193 *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800194
195 if (*info == NULL) {
196 *overallSize = 0;
Christopher Ferris72bbd422014-05-08 11:14:03 -0700197 Malloc(free)(list);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700198 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800199 }
200
Elliott Hughes1728b232014-05-14 10:02:03 -0700201 qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800202
203 uint8_t* head = *info;
Elliott Hughes1728b232014-05-14 10:02:03 -0700204 const int count = g_hash_table.count;
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700205 for (int i = 0 ; i < count ; ++i) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800206 HashEntry* entry = list[i];
Elliott Hughes239e7a02013-01-25 17:13:45 -0800207 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800208 if (entrySize < *infoSize) {
209 /* we're writing less than a full entry, clear out the rest */
The Android Open Source Project95faece2010-04-08 11:11:53 -0700210 memset(head + entrySize, 0, *infoSize - entrySize);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800211 } else {
212 /* make sure the amount we're copying doesn't exceed the limit */
213 entrySize = *infoSize;
214 }
215 memcpy(head, &(entry->size), entrySize);
216 head += *infoSize;
217 }
218
Christopher Ferris72bbd422014-05-08 11:14:03 -0700219 Malloc(free)(list);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800220}
221
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700222// Exported for use by ddms.
223extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700224 Malloc(free)(info);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800225}
226
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700227extern "C" struct mallinfo mallinfo() {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700228 return Malloc(mallinfo)();
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800229}
230
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700231extern "C" void* valloc(size_t bytes) {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700232 return Malloc(valloc)(bytes);
Ian Rogers99908912012-08-17 17:28:15 -0700233}
234
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700235extern "C" void* pvalloc(size_t bytes) {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700236 return Malloc(pvalloc)(bytes);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800237}
238
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700239extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700240 return Malloc(posix_memalign)(memptr, alignment, size);
Brian Carlstrombfc1d972012-08-20 18:28:20 -0700241}
242
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700243extern "C" void* malloc(size_t bytes) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800244 return __libc_malloc_dispatch->malloc(bytes);
245}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700246
247extern "C" void free(void* mem) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800248 __libc_malloc_dispatch->free(mem);
249}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700250
251extern "C" void* calloc(size_t n_elements, size_t elem_size) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800252 return __libc_malloc_dispatch->calloc(n_elements, elem_size);
253}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700254
255extern "C" void* realloc(void* oldMem, size_t bytes) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800256 return __libc_malloc_dispatch->realloc(oldMem, bytes);
257}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700258
259extern "C" void* memalign(size_t alignment, size_t bytes) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800260 return __libc_malloc_dispatch->memalign(alignment, bytes);
261}
262
Christopher Ferris885f3b92013-05-21 17:48:01 -0700263extern "C" size_t malloc_usable_size(const void* mem) {
264 return __libc_malloc_dispatch->malloc_usable_size(mem);
265}
266
Elliott Hughesdb492b32013-01-03 15:44:03 -0800267/* We implement malloc debugging only in libc.so, so code below
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800268 * must be excluded if we compile this file for static libc.a
269 */
270#ifndef LIBC_STATIC
271#include <sys/system_properties.h>
272#include <dlfcn.h>
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700273#include <stdio.h>
Elliott Hugheseb847bc2013-10-09 15:50:50 -0700274#include "private/libc_logging.h"
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800275
Christopher Ferris885f3b92013-05-21 17:48:01 -0700276template<typename FunctionType>
Nick Kralevich35c18622013-10-03 14:59:05 -0700277static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
Christopher Ferris885f3b92013-05-21 17:48:01 -0700278 char symbol[128];
279 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
280 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
281 if (*func == NULL) {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700282 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700283 }
284}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700285
Christopher Ferris885f3b92013-05-21 17:48:01 -0700286static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
287 __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700288 getprogname(), g_malloc_debug_level, prefix);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700289
Christopher Ferris885f3b92013-05-21 17:48:01 -0700290 InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
291 InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
292 InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
293 InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
294 InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
295 InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700296}
297
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800298/* Initializes memory allocation framework once per process. */
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700299static void malloc_init_impl() {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800300 const char* so_name = NULL;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800301 MallocDebugInit malloc_debug_initialize = NULL;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800302 unsigned int qemu_running = 0;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800303 unsigned int memcheck_enabled = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800304 char env[PROP_VALUE_MAX];
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800305 char memcheck_tracing[PROP_VALUE_MAX];
Iliyan Malchev7d2e24e2012-05-29 16:46:17 -0700306 char debug_program[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800307
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800308 /* Get custom malloc debug level. Note that emulator started with
309 * memory checking option will have priority over debug level set in
310 * libc.debug.malloc system property. */
311 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
312 qemu_running = 1;
313 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
314 if (memcheck_tracing[0] != '0') {
315 // Emulator has started with memory tracing enabled. Enforce it.
Elliott Hughes1728b232014-05-14 10:02:03 -0700316 g_malloc_debug_level = 20;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800317 memcheck_enabled = 1;
318 }
319 }
320 }
321
322 /* If debug level has not been set by memcheck option in the emulator,
323 * lets grab it from libc.debug.malloc system property. */
Elliott Hughes1728b232014-05-14 10:02:03 -0700324 if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
325 g_malloc_debug_level = atoi(env);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800326 }
327
Christopher Ferris72bbd422014-05-08 11:14:03 -0700328 /* Debug level 0 means that we should use default allocation routines. */
Elliott Hughes1728b232014-05-14 10:02:03 -0700329 if (g_malloc_debug_level == 0) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800330 return;
331 }
332
Iliyan Malchev7d2e24e2012-05-29 16:46:17 -0700333 /* If libc.debug.malloc.program is set and is not a substring of progname,
334 * then exit.
335 */
336 if (__system_property_get("libc.debug.malloc.program", debug_program)) {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700337 if (!strstr(getprogname(), debug_program)) {
Iliyan Malchev7d2e24e2012-05-29 16:46:17 -0700338 return;
339 }
340 }
341
Elliott Hughes84f8b5f2013-01-22 18:35:14 -0800342 // mksh is way too leaky. http://b/7291287.
Elliott Hughes1728b232014-05-14 10:02:03 -0700343 if (g_malloc_debug_level >= 10) {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700344 if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
Elliott Hughes239e7a02013-01-25 17:13:45 -0800345 return;
346 }
Elliott Hughes84f8b5f2013-01-22 18:35:14 -0800347 }
348
Elliott Hughese5d5f7f2012-10-09 17:23:09 -0700349 // Choose the appropriate .so for the requested debug level.
Elliott Hughes1728b232014-05-14 10:02:03 -0700350 switch (g_malloc_debug_level) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800351 case 1:
352 case 5:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700353 case 10:
Elliott Hughes64b29632014-04-01 13:48:30 -0700354 so_name = "libc_malloc_debug_leak.so";
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800355 break;
356 case 20:
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800357 // Quick check: debug level 20 can only be handled in emulator.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800358 if (!qemu_running) {
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800359 error_log("%s: Debug level %d can only be set in emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700360 getprogname(), g_malloc_debug_level);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800361 return;
362 }
363 // Make sure that memory checking has been enabled in emulator.
364 if (!memcheck_enabled) {
365 error_log("%s: Memory checking is not enabled in the emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700366 getprogname());
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800367 return;
368 }
Elliott Hughes64b29632014-04-01 13:48:30 -0700369 so_name = "libc_malloc_debug_qemu.so";
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800370 break;
371 default:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700372 error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800373 return;
374 }
375
376 // Load .so that implements the required malloc debugging functionality.
Christopher Ferris885f3b92013-05-21 17:48:01 -0700377 void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
378 if (malloc_impl_handle == NULL) {
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700379 error_log("%s: Missing module %s required for malloc debug level %d: %s",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700380 getprogname(), so_name, g_malloc_debug_level, dlerror());
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800381 return;
382 }
383
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800384 // Initialize malloc debugging in the loaded module.
Christopher Ferris885f3b92013-05-21 17:48:01 -0700385 malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700386 "malloc_debug_initialize"));
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800387 if (malloc_debug_initialize == NULL) {
388 error_log("%s: Initialization routine is not found in %s\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700389 getprogname(), so_name);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700390 dlclose(malloc_impl_handle);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800391 return;
392 }
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700393 if (malloc_debug_initialize(&g_hash_table) == -1) {
Christopher Ferris885f3b92013-05-21 17:48:01 -0700394 dlclose(malloc_impl_handle);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800395 return;
396 }
397
Elliott Hughes1728b232014-05-14 10:02:03 -0700398 if (g_malloc_debug_level == 20) {
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800399 // For memory checker we need to do extra initialization.
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700400 typedef int (*MemCheckInit)(int, const char*);
401 MemCheckInit memcheck_initialize =
Christopher Ferris885f3b92013-05-21 17:48:01 -0700402 reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle,
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700403 "memcheck_initialize"));
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800404 if (memcheck_initialize == NULL) {
405 error_log("%s: memcheck_initialize routine is not found in %s\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700406 getprogname(), so_name);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700407 dlclose(malloc_impl_handle);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800408 return;
409 }
Elliott Hughesdb492b32013-01-03 15:44:03 -0800410
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800411 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
Christopher Ferris885f3b92013-05-21 17:48:01 -0700412 dlclose(malloc_impl_handle);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800413 return;
414 }
415 }
416
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800417 // Initialize malloc dispatch table with appropriate routines.
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700418 static MallocDebug malloc_dispatch_table __attribute__((aligned(32))) = {
419 Malloc(malloc),
420 Malloc(free),
421 Malloc(calloc),
422 Malloc(realloc),
423 Malloc(memalign),
424 Malloc(malloc_usable_size)
425 };
426
Elliott Hughes1728b232014-05-14 10:02:03 -0700427 switch (g_malloc_debug_level) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800428 case 1:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700429 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800430 break;
431 case 5:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700432 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800433 break;
434 case 10:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700435 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800436 break;
437 case 20:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700438 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800439 break;
440 default:
441 break;
442 }
443
444 // Make sure dispatch table is initialized
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700445 if ((malloc_dispatch_table.malloc == NULL) ||
446 (malloc_dispatch_table.free == NULL) ||
447 (malloc_dispatch_table.calloc == NULL) ||
448 (malloc_dispatch_table.realloc == NULL) ||
449 (malloc_dispatch_table.memalign == NULL) ||
450 (malloc_dispatch_table.malloc_usable_size == NULL)) {
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700451 error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700452 getprogname(), g_malloc_debug_level);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700453 dlclose(malloc_impl_handle);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800454 } else {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700455 __libc_malloc_dispatch = &malloc_dispatch_table;
Christopher Ferris885f3b92013-05-21 17:48:01 -0700456 libc_malloc_impl_handle = malloc_impl_handle;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800457 }
458}
459
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700460static void malloc_fini_impl() {
Elliott Hughes1e980b62013-01-17 18:36:06 -0800461 // Our BSD stdio implementation doesn't close the standard streams, it only flushes them.
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700462 // And it doesn't do that until its atexit handler is run, and we run first!
Elliott Hughes1e980b62013-01-17 18:36:06 -0800463 // It's great that other unclosed FILE*s show up as malloc leaks, but we need to manually
464 // clean up the standard streams ourselves.
465 fclose(stdin);
466 fclose(stdout);
467 fclose(stderr);
468
469 if (libc_malloc_impl_handle != NULL) {
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700470 MallocDebugFini malloc_debug_finalize =
471 reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle,
472 "malloc_debug_finalize"));
Elliott Hughes1e980b62013-01-17 18:36:06 -0800473 if (malloc_debug_finalize != NULL) {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700474 malloc_debug_finalize(g_malloc_debug_level);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700475 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700476 }
477}
478
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800479#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800480
481/* Initializes memory allocation framework.
482 * This routine is called from __libc_init routines implemented
483 * in libc_init_static.c and libc_init_dynamic.c files.
484 */
Kito Chengea489742013-04-12 16:13:34 +0800485extern "C" __LIBC_HIDDEN__ void malloc_debug_init() {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800486#if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700487 static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
488 if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
489 error_log("Unable to initialize malloc_debug component.");
490 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800491#endif // USE_DL_PREFIX && !LIBC_STATIC
492}
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700493
Kito Chengea489742013-04-12 16:13:34 +0800494extern "C" __LIBC_HIDDEN__ void malloc_debug_fini() {
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700495#if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700496 static pthread_once_t malloc_fini_once_ctl = PTHREAD_ONCE_INIT;
497 if (pthread_once(&malloc_fini_once_ctl, malloc_fini_impl)) {
498 error_log("Unable to finalize malloc_debug component.");
499 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700500#endif // USE_DL_PREFIX && !LIBC_STATIC
501}