blob: 66505bf7365214514777a62f248094ee2d64387e [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
Christopher Ferrisa4037802014-06-09 19:14:11 -070029// Contains definition of structures, global variables, and implementation of
30// routines that are used by malloc leak detection code and other components in
31// the system. The trick is that some components expect these data and
Christopher Ferris6fe376d2014-09-19 12:26:09 -070032// routines to be defined / implemented in libc.so, regardless whether or not
33// malloc leak detection code is going to run. To make things even more tricky,
34// malloc leak detection code, implemented in libc_malloc_debug.so also
35// requires access to these variables and routines (to fill allocation entry
36// hash table, for example). So, all relevant variables and routines are
37// defined / implemented here and exported to all, leak detection code and
38// other components via dynamic (libc.so), or static (libc.a) linking.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080039
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080040#include "malloc_debug_common.h"
41
Elliott Hughes3b297c42012-10-11 16:08:51 -070042#include <pthread.h>
43#include <stdlib.h>
Elliott Hughes05fc1d72015-01-28 18:02:33 -080044#include <string.h>
Elliott Hughes3b297c42012-10-11 16:08:51 -070045#include <unistd.h>
46
Josh Gao3c8fc2f2015-10-08 14:49:26 -070047#include "private/bionic_globals.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070048#include "private/ScopedPthreadMutexLocker.h"
Elliott Hughes3b297c42012-10-11 16:08:51 -070049
Christopher Ferrisdda1c6c2014-07-09 17:16:07 -070050#include "jemalloc.h"
51#define Malloc(function) je_ ## function
Christopher Ferrisdda1c6c2014-07-09 17:16:07 -070052
Josh Gao3c8fc2f2015-10-08 14:49:26 -070053static constexpr MallocDebug __libc_malloc_default_dispatch
54 __attribute__((unused)) = {
55 Malloc(calloc),
56 Malloc(free),
57 Malloc(mallinfo),
58 Malloc(malloc),
59 Malloc(malloc_usable_size),
60 Malloc(memalign),
61 Malloc(posix_memalign),
62#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
63 Malloc(pvalloc),
64#endif
65 Malloc(realloc),
66#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
67 Malloc(valloc),
68#endif
69 };
70
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070071// In a VM process, this is set to 1 after fork()ing out of zygote.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080072int gMallocLeakZygoteChild = 0;
73
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070074static HashTable g_hash_table;
75
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070076// Handle to shared library where actual memory allocation is implemented.
77// This library is loaded and memory allocation calls are redirected there
78// when libc.debug.malloc environment variable contains value other than
79// zero:
80// 1 - For memory leak detections.
81// 5 - For filling allocated / freed memory with patterns defined by
82// CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
83// 10 - For adding pre-, and post- allocation stubs in order to detect
84// buffer overruns.
85// Note that emulator's memory allocation instrumentation is not controlled by
86// libc.debug.malloc value, but rather by emulator, started with -memcheck
87// option. Note also, that if emulator has started with -memcheck option,
88// emulator's instrumented memory allocation will take over value saved in
89// libc.debug.malloc. In other words, if emulator has started with -memcheck
90// option, libc.debug.malloc value is ignored.
91// Actual functionality for debug levels 1-10 is implemented in
92// libc_malloc_debug_leak.so, while functionality for emulator's instrumented
93// allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
94// the emulator only.
95#if !defined(LIBC_STATIC)
96static void* libc_malloc_impl_handle = NULL;
97#endif
98
99
100// The value of libc.debug.malloc.
101#if !defined(LIBC_STATIC)
102static int g_malloc_debug_level = 0;
103#endif
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800104
105// =============================================================================
106// output functions
107// =============================================================================
108
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700109static int hash_entry_compare(const void* arg1, const void* arg2) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700110 int result;
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700111
Christopher Ferrisa4037802014-06-09 19:14:11 -0700112 const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
113 const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800114
Christopher Ferrisa4037802014-06-09 19:14:11 -0700115 // if one or both arg pointers are null, deal gracefully
116 if (e1 == NULL) {
117 result = (e2 == NULL) ? 0 : 1;
118 } else if (e2 == NULL) {
119 result = -1;
120 } else {
121 size_t nbAlloc1 = e1->allocations;
122 size_t nbAlloc2 = e2->allocations;
123 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
124 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
125 size_t alloc1 = nbAlloc1 * size1;
126 size_t alloc2 = nbAlloc2 * size2;
127
128 // sort in descending order by:
129 // 1) total size
130 // 2) number of allocations
131 //
132 // This is used for sorting, not determination of equality, so we don't
133 // need to compare the bit flags.
134 if (alloc1 > alloc2) {
135 result = -1;
136 } else if (alloc1 < alloc2) {
137 result = 1;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800138 } else {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700139 if (nbAlloc1 > nbAlloc2) {
140 result = -1;
141 } else if (nbAlloc1 < nbAlloc2) {
142 result = 1;
143 } else {
144 result = 0;
145 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800146 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700147 }
148 return result;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800149}
150
Christopher Ferrisa4037802014-06-09 19:14:11 -0700151// Retrieve native heap information.
152//
153// "*info" is set to a buffer we allocate
154// "*overallSize" is set to the size of the "info" buffer
155// "*infoSize" is set to the size of a single entry
156// "*totalMemory" is set to the sum of all allocations we're tracking; does
157// not include heap overhead
158// "*backtraceSize" is set to the maximum number of entries in the back trace
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700159
Christopher Ferrisa4037802014-06-09 19:14:11 -0700160// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700161// Exported for use by ddms.
Christopher Ferrisa4037802014-06-09 19:14:11 -0700162// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700163extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
Christopher Ferrisa4037802014-06-09 19:14:11 -0700164 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
165 // Don't do anything if we have invalid arguments.
166 if (info == NULL || overallSize == NULL || infoSize == NULL ||
167 totalMemory == NULL || backtraceSize == NULL) {
168 return;
169 }
170 *totalMemory = 0;
171
172 ScopedPthreadMutexLocker locker(&g_hash_table.lock);
173 if (g_hash_table.count == 0) {
174 *info = NULL;
175 *overallSize = 0;
176 *infoSize = 0;
177 *backtraceSize = 0;
178 return;
179 }
180
181 HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
182
183 // Get the entries into an array to be sorted.
184 size_t index = 0;
185 for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
186 HashEntry* entry = g_hash_table.slots[i];
187 while (entry != NULL) {
188 list[index] = entry;
189 *totalMemory = *totalMemory + ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
190 index++;
191 entry = entry->next;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800192 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700193 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800194
Christopher Ferrisa4037802014-06-09 19:14:11 -0700195 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
196 *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
197 *overallSize = *infoSize * g_hash_table.count;
198 *backtraceSize = BACKTRACE_SIZE;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800199
Christopher Ferrisa4037802014-06-09 19:14:11 -0700200 // now get a byte array big enough for this
201 *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
202 if (*info == NULL) {
203 *overallSize = 0;
Christopher Ferris72bbd422014-05-08 11:14:03 -0700204 Malloc(free)(list);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700205 return;
206 }
207
208 qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
209
210 uint8_t* head = *info;
211 const size_t count = g_hash_table.count;
212 for (size_t i = 0 ; i < count ; ++i) {
213 HashEntry* entry = list[i];
214 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
215 if (entrySize < *infoSize) {
216 // We're writing less than a full entry, clear out the rest.
217 memset(head + entrySize, 0, *infoSize - entrySize);
218 } else {
219 // Make sure the amount we're copying doesn't exceed the limit.
220 entrySize = *infoSize;
221 }
222 memcpy(head, &(entry->size), entrySize);
223 head += *infoSize;
224 }
225
226 Malloc(free)(list);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800227}
228
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700229extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700230 Malloc(free)(info);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800231}
232
Christopher Ferrisa4037802014-06-09 19:14:11 -0700233// =============================================================================
234// Allocation functions
235// =============================================================================
236extern "C" void* calloc(size_t n_elements, size_t elem_size) {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700237 auto _calloc = __libc_globals->malloc_dispatch.calloc;
238 if (__predict_false(_calloc != nullptr)) {
239 return _calloc(n_elements, elem_size);
240 }
241 return Malloc(calloc)(n_elements, elem_size);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800242}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700243
244extern "C" void free(void* mem) {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700245 auto _free = __libc_globals->malloc_dispatch.free;
246 if (__predict_false(_free != nullptr)) {
247 _free(mem);
248 } else {
249 Malloc(free)(mem);
250 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800251}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700252
Christopher Ferrisa4037802014-06-09 19:14:11 -0700253extern "C" struct mallinfo mallinfo() {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700254 auto _mallinfo = __libc_globals->malloc_dispatch.mallinfo;
255 if (__predict_false(_mallinfo != nullptr)) {
256 return _mallinfo();
257 }
258 return Malloc(mallinfo)();
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800259}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700260
Christopher Ferrisa4037802014-06-09 19:14:11 -0700261extern "C" void* malloc(size_t bytes) {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700262 auto _malloc = __libc_globals->malloc_dispatch.malloc;
263 if (__predict_false(_malloc != nullptr)) {
264 return _malloc(bytes);
265 }
266 return Malloc(malloc)(bytes);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800267}
268
Christopher Ferris885f3b92013-05-21 17:48:01 -0700269extern "C" size_t malloc_usable_size(const void* mem) {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700270 auto _malloc_usable_size = __libc_globals->malloc_dispatch.malloc_usable_size;
271 if (__predict_false(_malloc_usable_size != nullptr)) {
272 return _malloc_usable_size(mem);
273 }
274 return Malloc(malloc_usable_size)(mem);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700275}
276
Christopher Ferrisa4037802014-06-09 19:14:11 -0700277extern "C" void* memalign(size_t alignment, size_t bytes) {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700278 auto _memalign = __libc_globals->malloc_dispatch.memalign;
279 if (__predict_false(_memalign != nullptr)) {
280 return _memalign(alignment, bytes);
281 }
282 return Malloc(memalign)(alignment, bytes);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700283}
284
285extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700286 auto _posix_memalign = __libc_globals->malloc_dispatch.posix_memalign;
287 if (__predict_false(_posix_memalign != nullptr)) {
288 return _posix_memalign(memptr, alignment, size);
289 }
290 return Malloc(posix_memalign)(memptr, alignment, size);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700291}
292
Dan Alberte5fdaa42014-06-14 01:04:31 +0000293#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700294extern "C" void* pvalloc(size_t bytes) {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700295 auto _pvalloc = __libc_globals->malloc_dispatch.pvalloc;
296 if (__predict_false(_pvalloc != nullptr)) {
297 return _pvalloc(bytes);
298 }
299 return Malloc(pvalloc)(bytes);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700300}
Dan Alberte5fdaa42014-06-14 01:04:31 +0000301#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700302
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700303extern "C" void* realloc(void* old_mem, size_t bytes) {
304 auto _realloc = __libc_globals->malloc_dispatch.realloc;
305 if (__predict_false(_realloc != nullptr)) {
306 return _realloc(old_mem, bytes);
307 }
308 return Malloc(realloc)(old_mem, bytes);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700309}
310
Dan Alberte5fdaa42014-06-14 01:04:31 +0000311#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700312extern "C" void* valloc(size_t bytes) {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700313 auto _valloc = __libc_globals->malloc_dispatch.valloc;
314 if (__predict_false(_valloc != nullptr)) {
315 return _valloc(bytes);
316 }
317 return Malloc(valloc)(bytes);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700318}
Dan Alberte5fdaa42014-06-14 01:04:31 +0000319#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700320
321// We implement malloc debugging only in libc.so, so the code below
322// must be excluded if we compile this file for static libc.a
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800323#ifndef LIBC_STATIC
324#include <sys/system_properties.h>
325#include <dlfcn.h>
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700326#include <stdio.h>
Elliott Hugheseb847bc2013-10-09 15:50:50 -0700327#include "private/libc_logging.h"
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800328
Christopher Ferris885f3b92013-05-21 17:48:01 -0700329template<typename FunctionType>
Nick Kralevich35c18622013-10-03 14:59:05 -0700330static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700331 char symbol[128];
332 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
333 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
334 if (*func == NULL) {
335 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
336 }
Christopher Ferris885f3b92013-05-21 17:48:01 -0700337}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700338
Christopher Ferris885f3b92013-05-21 17:48:01 -0700339static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700340 __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
341 getprogname(), g_malloc_debug_level, prefix);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700342
Christopher Ferrisa4037802014-06-09 19:14:11 -0700343 InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
344 InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
345 InitMallocFunction<MallocDebugMallinfo>(malloc_impl_handler, &table->mallinfo, prefix, "mallinfo");
346 InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
347 InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
348 InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
349 InitMallocFunction<MallocDebugPosixMemalign>(malloc_impl_handler, &table->posix_memalign, prefix, "posix_memalign");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000350#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700351 InitMallocFunction<MallocDebugPvalloc>(malloc_impl_handler, &table->pvalloc, prefix, "pvalloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000352#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700353 InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000354#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700355 InitMallocFunction<MallocDebugValloc>(malloc_impl_handler, &table->valloc, prefix, "valloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000356#endif
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700357}
358
Christopher Ferrisa4037802014-06-09 19:14:11 -0700359// Initializes memory allocation framework once per process.
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700360static void malloc_init_impl(libc_globals* globals) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700361 const char* so_name = NULL;
362 MallocDebugInit malloc_debug_initialize = NULL;
363 unsigned int qemu_running = 0;
364 unsigned int memcheck_enabled = 0;
365 char env[PROP_VALUE_MAX];
366 char memcheck_tracing[PROP_VALUE_MAX];
367 char debug_program[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800368
Christopher Ferrisa4037802014-06-09 19:14:11 -0700369 // Get custom malloc debug level. Note that emulator started with
370 // memory checking option will have priority over debug level set in
371 // libc.debug.malloc system property.
372 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
373 qemu_running = 1;
374 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
375 if (memcheck_tracing[0] != '0') {
376 // Emulator has started with memory tracing enabled. Enforce it.
377 g_malloc_debug_level = 20;
378 memcheck_enabled = 1;
379 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800380 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700381 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800382
Christopher Ferrisa4037802014-06-09 19:14:11 -0700383 // If debug level has not been set by memcheck option in the emulator,
384 // lets grab it from libc.debug.malloc system property.
385 if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
386 g_malloc_debug_level = atoi(env);
387 }
388
389 // Debug level 0 means that we should use default allocation routines.
390 if (g_malloc_debug_level == 0) {
391 return;
392 }
393
394 // If libc.debug.malloc.program is set and is not a substring of progname,
395 // then exit.
396 if (__system_property_get("libc.debug.malloc.program", debug_program)) {
397 if (!strstr(getprogname(), debug_program)) {
398 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800399 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700400 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800401
Christopher Ferrisa4037802014-06-09 19:14:11 -0700402 // mksh is way too leaky. http://b/7291287.
403 if (g_malloc_debug_level >= 10) {
404 if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
405 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800406 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700407 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800408
Christopher Ferrisa4037802014-06-09 19:14:11 -0700409 // Choose the appropriate .so for the requested debug level.
410 switch (g_malloc_debug_level) {
411 case 1:
412 case 5:
413 case 10:
414 so_name = "libc_malloc_debug_leak.so";
415 break;
416 case 20:
417 // Quick check: debug level 20 can only be handled in emulator.
418 if (!qemu_running) {
419 error_log("%s: Debug level %d can only be set in emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700420 getprogname(), g_malloc_debug_level);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700421 return;
422 }
423 // Make sure that memory checking has been enabled in emulator.
424 if (!memcheck_enabled) {
425 error_log("%s: Memory checking is not enabled in the emulator\n", getprogname());
426 return;
427 }
428 so_name = "libc_malloc_debug_qemu.so";
429 break;
430 default:
431 error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
432 return;
433 }
434
435 // Load .so that implements the required malloc debugging functionality.
Dmitriy Ivanov84c10c22015-03-23 14:58:45 -0700436 void* malloc_impl_handle = dlopen(so_name, RTLD_NOW);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700437 if (malloc_impl_handle == NULL) {
438 error_log("%s: Missing module %s required for malloc debug level %d: %s",
439 getprogname(), so_name, g_malloc_debug_level, dlerror());
440 return;
441 }
442
443 // Initialize malloc debugging in the loaded module.
444 malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
445 "malloc_debug_initialize"));
446 if (malloc_debug_initialize == NULL) {
447 error_log("%s: Initialization routine is not found in %s\n", getprogname(), so_name);
448 dlclose(malloc_impl_handle);
449 return;
450 }
Christopher Ferrisdda1c6c2014-07-09 17:16:07 -0700451 if (!malloc_debug_initialize(&g_hash_table, &__libc_malloc_default_dispatch)) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700452 dlclose(malloc_impl_handle);
453 return;
454 }
455
456 if (g_malloc_debug_level == 20) {
457 // For memory checker we need to do extra initialization.
458 typedef int (*MemCheckInit)(int, const char*);
459 MemCheckInit memcheck_initialize =
460 reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle, "memcheck_initialize"));
461 if (memcheck_initialize == NULL) {
462 error_log("%s: memcheck_initialize routine is not found in %s\n",
463 getprogname(), so_name);
464 dlclose(malloc_impl_handle);
465 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800466 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700467
468 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
469 dlclose(malloc_impl_handle);
470 return;
471 }
472 }
473
474 // No need to init the dispatch table because we can only get
475 // here if debug level is 1, 5, 10, or 20.
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700476 MallocDebug malloc_dispatch_table;
Christopher Ferrisa4037802014-06-09 19:14:11 -0700477 switch (g_malloc_debug_level) {
478 case 1:
479 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
480 break;
481 case 5:
482 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
483 break;
484 case 10:
485 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
486 break;
487 case 20:
488 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
489 break;
490 default:
491 break;
492 }
493
494 // Make sure dispatch table is initialized
495 if ((malloc_dispatch_table.calloc == NULL) ||
496 (malloc_dispatch_table.free == NULL) ||
497 (malloc_dispatch_table.mallinfo == NULL) ||
498 (malloc_dispatch_table.malloc == NULL) ||
499 (malloc_dispatch_table.malloc_usable_size == NULL) ||
500 (malloc_dispatch_table.memalign == NULL) ||
501 (malloc_dispatch_table.posix_memalign == NULL) ||
Dan Alberte5fdaa42014-06-14 01:04:31 +0000502#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700503 (malloc_dispatch_table.pvalloc == NULL) ||
Dan Alberte5fdaa42014-06-14 01:04:31 +0000504#endif
505 (malloc_dispatch_table.realloc == NULL)
506#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
507 || (malloc_dispatch_table.valloc == NULL)
508#endif
509 ) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700510 error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
511 getprogname(), g_malloc_debug_level);
512 dlclose(malloc_impl_handle);
513 } else {
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700514 globals->malloc_dispatch = malloc_dispatch_table;
Christopher Ferrisa4037802014-06-09 19:14:11 -0700515 libc_malloc_impl_handle = malloc_impl_handle;
516 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800517}
518
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700519static void malloc_fini_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700520 if (libc_malloc_impl_handle != NULL) {
521 MallocDebugFini malloc_debug_finalize =
522 reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle, "malloc_debug_finalize"));
523 if (malloc_debug_finalize != NULL) {
Christopher Ferrisefc134d2015-09-03 15:01:59 -0700524 // Our BSD stdio implementation doesn't close the standard streams,
525 // it only flushes them. And it doesn't do that until its atexit
526 // handler is run, and we run first! It's great that other unclosed
527 // FILE*s show up as malloc leaks, but we need to manually clean up
528 // the standard streams ourselves.
529 fclose(stdin);
530 fclose(stdout);
531 fclose(stderr);
532
Christopher Ferrisa4037802014-06-09 19:14:11 -0700533 malloc_debug_finalize(g_malloc_debug_level);
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700534 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700535 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700536}
537
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800538#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800539
Christopher Ferrisa4037802014-06-09 19:14:11 -0700540// Initializes memory allocation framework.
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700541// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
542__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
543 (void)globals;
Christopher Ferrisa4037802014-06-09 19:14:11 -0700544#if !defined(LIBC_STATIC)
Josh Gao3c8fc2f2015-10-08 14:49:26 -0700545 malloc_init_impl(globals);
546#endif
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800547}
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700548
Kito Chengea489742013-04-12 16:13:34 +0800549extern "C" __LIBC_HIDDEN__ void malloc_debug_fini() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700550#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700551 static pthread_once_t malloc_fini_once_ctl = PTHREAD_ONCE_INIT;
552 if (pthread_once(&malloc_fini_once_ctl, malloc_fini_impl)) {
553 error_log("Unable to finalize malloc_debug component.");
554 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700555#endif // !LIBC_STATIC
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700556}