blob: 19524bb28f534e8ca1d5dc9c6ec1acbcdc0c0a7b [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.
63static const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch;
64
65// Handle to shared library where actual memory allocation is implemented.
66// This library is loaded and memory allocation calls are redirected there
67// when libc.debug.malloc environment variable contains value other than
68// zero:
69// 1 - For memory leak detections.
70// 5 - For filling allocated / freed memory with patterns defined by
71// CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
72// 10 - For adding pre-, and post- allocation stubs in order to detect
73// buffer overruns.
74// Note that emulator's memory allocation instrumentation is not controlled by
75// libc.debug.malloc value, but rather by emulator, started with -memcheck
76// option. Note also, that if emulator has started with -memcheck option,
77// emulator's instrumented memory allocation will take over value saved in
78// libc.debug.malloc. In other words, if emulator has started with -memcheck
79// option, libc.debug.malloc value is ignored.
80// Actual functionality for debug levels 1-10 is implemented in
81// libc_malloc_debug_leak.so, while functionality for emulator's instrumented
82// allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
83// the emulator only.
84#if !defined(LIBC_STATIC)
85static void* libc_malloc_impl_handle = NULL;
86#endif
87
88
89// The value of libc.debug.malloc.
90#if !defined(LIBC_STATIC)
91static int g_malloc_debug_level = 0;
92#endif
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080093
94// =============================================================================
95// output functions
96// =============================================================================
97
Elliott Hughesc4d1fec2012-08-28 14:15:04 -070098static int hash_entry_compare(const void* arg1, const void* arg2) {
Christopher Tate52e7d3d2010-08-09 13:43:46 -070099 int result;
100
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700101 const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
102 const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800103
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700104 // if one or both arg pointers are null, deal gracefully
105 if (e1 == NULL) {
106 result = (e2 == NULL) ? 0 : 1;
107 } else if (e2 == NULL) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800108 result = -1;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800109 } else {
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700110 size_t nbAlloc1 = e1->allocations;
111 size_t nbAlloc2 = e2->allocations;
112 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
113 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
114 size_t alloc1 = nbAlloc1 * size1;
115 size_t alloc2 = nbAlloc2 * size2;
116
117 // sort in descending order by:
118 // 1) total size
119 // 2) number of allocations
120 //
121 // This is used for sorting, not determination of equality, so we don't
122 // need to compare the bit flags.
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700123 if (alloc1 > alloc2) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800124 result = -1;
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700125 } else if (alloc1 < alloc2) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800126 result = 1;
127 } else {
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700128 if (nbAlloc1 > nbAlloc2) {
129 result = -1;
130 } else if (nbAlloc1 < nbAlloc2) {
131 result = 1;
132 } else {
133 result = 0;
134 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800135 }
136 }
137 return result;
138}
139
140/*
141 * Retrieve native heap information.
142 *
143 * "*info" is set to a buffer we allocate
144 * "*overallSize" is set to the size of the "info" buffer
145 * "*infoSize" is set to the size of a single entry
146 * "*totalMemory" is set to the sum of all allocations we're tracking; does
147 * not include heap overhead
148 * "*backtraceSize" is set to the maximum number of entries in the back trace
149 */
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700150
151// Exported for use by ddms.
152extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700153 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800154 // don't do anything if we have invalid arguments
155 if (info == NULL || overallSize == NULL || infoSize == NULL ||
156 totalMemory == NULL || backtraceSize == NULL) {
157 return;
158 }
tedbo9d8be542010-10-05 13:06:06 -0700159 *totalMemory = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800160
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700161 ScopedPthreadMutexLocker locker(&g_hash_table.lock);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800162
Elliott Hughes1728b232014-05-14 10:02:03 -0700163 if (g_hash_table.count == 0) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800164 *info = NULL;
165 *overallSize = 0;
166 *infoSize = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800167 *backtraceSize = 0;
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700168 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800169 }
170
Christopher Ferris72bbd422014-05-08 11:14:03 -0700171 HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800172
173 // get the entries into an array to be sorted
174 int index = 0;
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700175 for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
Elliott Hughes1728b232014-05-14 10:02:03 -0700176 HashEntry* entry = g_hash_table.slots[i];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800177 while (entry != NULL) {
178 list[index] = entry;
179 *totalMemory = *totalMemory +
180 ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
181 index++;
182 entry = entry->next;
183 }
184 }
185
186 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
Elliott Hughes239e7a02013-01-25 17:13:45 -0800187 *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
Elliott Hughes1728b232014-05-14 10:02:03 -0700188 *overallSize = *infoSize * g_hash_table.count;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800189 *backtraceSize = BACKTRACE_SIZE;
190
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700191 // now get a byte array big enough for this
Christopher Ferris72bbd422014-05-08 11:14:03 -0700192 *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800193
194 if (*info == NULL) {
195 *overallSize = 0;
Christopher Ferris72bbd422014-05-08 11:14:03 -0700196 Malloc(free)(list);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700197 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800198 }
199
Elliott Hughes1728b232014-05-14 10:02:03 -0700200 qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800201
202 uint8_t* head = *info;
Elliott Hughes1728b232014-05-14 10:02:03 -0700203 const int count = g_hash_table.count;
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700204 for (int i = 0 ; i < count ; ++i) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800205 HashEntry* entry = list[i];
Elliott Hughes239e7a02013-01-25 17:13:45 -0800206 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800207 if (entrySize < *infoSize) {
208 /* we're writing less than a full entry, clear out the rest */
The Android Open Source Project95faece2010-04-08 11:11:53 -0700209 memset(head + entrySize, 0, *infoSize - entrySize);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800210 } else {
211 /* make sure the amount we're copying doesn't exceed the limit */
212 entrySize = *infoSize;
213 }
214 memcpy(head, &(entry->size), entrySize);
215 head += *infoSize;
216 }
217
Christopher Ferris72bbd422014-05-08 11:14:03 -0700218 Malloc(free)(list);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800219}
220
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700221// Exported for use by ddms.
222extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700223 Malloc(free)(info);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800224}
225
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700226extern "C" struct mallinfo mallinfo() {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700227 return Malloc(mallinfo)();
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800228}
229
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700230extern "C" void* valloc(size_t bytes) {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700231 return Malloc(valloc)(bytes);
Ian Rogers99908912012-08-17 17:28:15 -0700232}
233
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700234extern "C" void* pvalloc(size_t bytes) {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700235 return Malloc(pvalloc)(bytes);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800236}
237
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700238extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
Christopher Ferris72bbd422014-05-08 11:14:03 -0700239 return Malloc(posix_memalign)(memptr, alignment, size);
Brian Carlstrombfc1d972012-08-20 18:28:20 -0700240}
241
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700242extern "C" void* malloc(size_t bytes) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800243 return __libc_malloc_dispatch->malloc(bytes);
244}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700245
246extern "C" void free(void* mem) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800247 __libc_malloc_dispatch->free(mem);
248}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700249
250extern "C" void* calloc(size_t n_elements, size_t elem_size) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800251 return __libc_malloc_dispatch->calloc(n_elements, elem_size);
252}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700253
254extern "C" void* realloc(void* oldMem, size_t bytes) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800255 return __libc_malloc_dispatch->realloc(oldMem, bytes);
256}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700257
258extern "C" void* memalign(size_t alignment, size_t bytes) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800259 return __libc_malloc_dispatch->memalign(alignment, bytes);
260}
261
Christopher Ferris885f3b92013-05-21 17:48:01 -0700262extern "C" size_t malloc_usable_size(const void* mem) {
263 return __libc_malloc_dispatch->malloc_usable_size(mem);
264}
265
Elliott Hughesdb492b32013-01-03 15:44:03 -0800266/* We implement malloc debugging only in libc.so, so code below
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800267 * must be excluded if we compile this file for static libc.a
268 */
269#ifndef LIBC_STATIC
270#include <sys/system_properties.h>
271#include <dlfcn.h>
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700272#include <stdio.h>
Elliott Hugheseb847bc2013-10-09 15:50:50 -0700273#include "private/libc_logging.h"
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800274
Christopher Ferris885f3b92013-05-21 17:48:01 -0700275template<typename FunctionType>
Nick Kralevich35c18622013-10-03 14:59:05 -0700276static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
Christopher Ferris885f3b92013-05-21 17:48:01 -0700277 char symbol[128];
278 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
279 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
280 if (*func == NULL) {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700281 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700282 }
283}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700284
Christopher Ferris885f3b92013-05-21 17:48:01 -0700285static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
286 __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700287 getprogname(), g_malloc_debug_level, prefix);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700288
Christopher Ferris885f3b92013-05-21 17:48:01 -0700289 InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
290 InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
291 InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
292 InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
293 InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
294 InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700295}
296
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800297/* Initializes memory allocation framework once per process. */
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700298static void malloc_init_impl() {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800299 const char* so_name = NULL;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800300 MallocDebugInit malloc_debug_initialize = NULL;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800301 unsigned int qemu_running = 0;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800302 unsigned int memcheck_enabled = 0;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800303 char env[PROP_VALUE_MAX];
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800304 char memcheck_tracing[PROP_VALUE_MAX];
Iliyan Malchev7d2e24e2012-05-29 16:46:17 -0700305 char debug_program[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800306
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800307 /* Get custom malloc debug level. Note that emulator started with
308 * memory checking option will have priority over debug level set in
309 * libc.debug.malloc system property. */
310 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
311 qemu_running = 1;
312 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
313 if (memcheck_tracing[0] != '0') {
314 // Emulator has started with memory tracing enabled. Enforce it.
Elliott Hughes1728b232014-05-14 10:02:03 -0700315 g_malloc_debug_level = 20;
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800316 memcheck_enabled = 1;
317 }
318 }
319 }
320
321 /* If debug level has not been set by memcheck option in the emulator,
322 * lets grab it from libc.debug.malloc system property. */
Elliott Hughes1728b232014-05-14 10:02:03 -0700323 if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
324 g_malloc_debug_level = atoi(env);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800325 }
326
Christopher Ferris72bbd422014-05-08 11:14:03 -0700327 /* Debug level 0 means that we should use default allocation routines. */
Elliott Hughes1728b232014-05-14 10:02:03 -0700328 if (g_malloc_debug_level == 0) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800329 return;
330 }
331
Iliyan Malchev7d2e24e2012-05-29 16:46:17 -0700332 /* If libc.debug.malloc.program is set and is not a substring of progname,
333 * then exit.
334 */
335 if (__system_property_get("libc.debug.malloc.program", debug_program)) {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700336 if (!strstr(getprogname(), debug_program)) {
Iliyan Malchev7d2e24e2012-05-29 16:46:17 -0700337 return;
338 }
339 }
340
Elliott Hughes84f8b5f2013-01-22 18:35:14 -0800341 // mksh is way too leaky. http://b/7291287.
Elliott Hughes1728b232014-05-14 10:02:03 -0700342 if (g_malloc_debug_level >= 10) {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700343 if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
Elliott Hughes239e7a02013-01-25 17:13:45 -0800344 return;
345 }
Elliott Hughes84f8b5f2013-01-22 18:35:14 -0800346 }
347
Elliott Hughese5d5f7f2012-10-09 17:23:09 -0700348 // Choose the appropriate .so for the requested debug level.
Elliott Hughes1728b232014-05-14 10:02:03 -0700349 switch (g_malloc_debug_level) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800350 case 1:
351 case 5:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700352 case 10:
Elliott Hughes64b29632014-04-01 13:48:30 -0700353 so_name = "libc_malloc_debug_leak.so";
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800354 break;
355 case 20:
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800356 // Quick check: debug level 20 can only be handled in emulator.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800357 if (!qemu_running) {
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800358 error_log("%s: Debug level %d can only be set in emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700359 getprogname(), g_malloc_debug_level);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800360 return;
361 }
362 // Make sure that memory checking has been enabled in emulator.
363 if (!memcheck_enabled) {
364 error_log("%s: Memory checking is not enabled in the emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700365 getprogname());
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800366 return;
367 }
Elliott Hughes64b29632014-04-01 13:48:30 -0700368 so_name = "libc_malloc_debug_qemu.so";
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800369 break;
370 default:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700371 error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800372 return;
373 }
374
375 // Load .so that implements the required malloc debugging functionality.
Christopher Ferris885f3b92013-05-21 17:48:01 -0700376 void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
377 if (malloc_impl_handle == NULL) {
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700378 error_log("%s: Missing module %s required for malloc debug level %d: %s",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700379 getprogname(), so_name, g_malloc_debug_level, dlerror());
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800380 return;
381 }
382
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800383 // Initialize malloc debugging in the loaded module.
Christopher Ferris885f3b92013-05-21 17:48:01 -0700384 malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700385 "malloc_debug_initialize"));
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800386 if (malloc_debug_initialize == NULL) {
387 error_log("%s: Initialization routine is not found in %s\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700388 getprogname(), so_name);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700389 dlclose(malloc_impl_handle);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800390 return;
391 }
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700392 if (malloc_debug_initialize(&g_hash_table) == -1) {
Christopher Ferris885f3b92013-05-21 17:48:01 -0700393 dlclose(malloc_impl_handle);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800394 return;
395 }
396
Elliott Hughes1728b232014-05-14 10:02:03 -0700397 if (g_malloc_debug_level == 20) {
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800398 // For memory checker we need to do extra initialization.
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700399 typedef int (*MemCheckInit)(int, const char*);
400 MemCheckInit memcheck_initialize =
Christopher Ferris885f3b92013-05-21 17:48:01 -0700401 reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle,
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700402 "memcheck_initialize"));
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800403 if (memcheck_initialize == NULL) {
404 error_log("%s: memcheck_initialize routine is not found in %s\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700405 getprogname(), so_name);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700406 dlclose(malloc_impl_handle);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800407 return;
408 }
Elliott Hughesdb492b32013-01-03 15:44:03 -0800409
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800410 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
Christopher Ferris885f3b92013-05-21 17:48:01 -0700411 dlclose(malloc_impl_handle);
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800412 return;
413 }
414 }
415
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800416 // Initialize malloc dispatch table with appropriate routines.
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700417 static MallocDebug malloc_dispatch_table __attribute__((aligned(32))) = {
418 Malloc(malloc),
419 Malloc(free),
420 Malloc(calloc),
421 Malloc(realloc),
422 Malloc(memalign),
423 Malloc(malloc_usable_size)
424 };
425
Elliott Hughes1728b232014-05-14 10:02:03 -0700426 switch (g_malloc_debug_level) {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800427 case 1:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700428 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800429 break;
430 case 5:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700431 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800432 break;
433 case 10:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700434 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800435 break;
436 case 20:
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700437 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800438 break;
439 default:
440 break;
441 }
442
443 // Make sure dispatch table is initialized
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700444 if ((malloc_dispatch_table.malloc == NULL) ||
445 (malloc_dispatch_table.free == NULL) ||
446 (malloc_dispatch_table.calloc == NULL) ||
447 (malloc_dispatch_table.realloc == NULL) ||
448 (malloc_dispatch_table.memalign == NULL) ||
449 (malloc_dispatch_table.malloc_usable_size == NULL)) {
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700450 error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700451 getprogname(), g_malloc_debug_level);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700452 dlclose(malloc_impl_handle);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800453 } else {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700454 __libc_malloc_dispatch = &malloc_dispatch_table;
Christopher Ferris885f3b92013-05-21 17:48:01 -0700455 libc_malloc_impl_handle = malloc_impl_handle;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800456 }
457}
458
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700459static void malloc_fini_impl() {
Elliott Hughes1e980b62013-01-17 18:36:06 -0800460 // Our BSD stdio implementation doesn't close the standard streams, it only flushes them.
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700461 // And it doesn't do that until its atexit handler is run, and we run first!
Elliott Hughes1e980b62013-01-17 18:36:06 -0800462 // It's great that other unclosed FILE*s show up as malloc leaks, but we need to manually
463 // clean up the standard streams ourselves.
464 fclose(stdin);
465 fclose(stdout);
466 fclose(stderr);
467
468 if (libc_malloc_impl_handle != NULL) {
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700469 MallocDebugFini malloc_debug_finalize =
470 reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle,
471 "malloc_debug_finalize"));
Elliott Hughes1e980b62013-01-17 18:36:06 -0800472 if (malloc_debug_finalize != NULL) {
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700473 malloc_debug_finalize(g_malloc_debug_level);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700474 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700475 }
476}
477
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800478#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800479
480/* Initializes memory allocation framework.
481 * This routine is called from __libc_init routines implemented
482 * in libc_init_static.c and libc_init_dynamic.c files.
483 */
Kito Chengea489742013-04-12 16:13:34 +0800484extern "C" __LIBC_HIDDEN__ void malloc_debug_init() {
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800485#if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700486 static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
487 if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
488 error_log("Unable to initialize malloc_debug component.");
489 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800490#endif // USE_DL_PREFIX && !LIBC_STATIC
491}
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700492
Kito Chengea489742013-04-12 16:13:34 +0800493extern "C" __LIBC_HIDDEN__ void malloc_debug_fini() {
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700494#if defined(USE_DL_PREFIX) && !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700495 static pthread_once_t malloc_fini_once_ctl = PTHREAD_ONCE_INIT;
496 if (pthread_once(&malloc_fini_once_ctl, malloc_fini_impl)) {
497 error_log("Unable to finalize malloc_debug component.");
498 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700499#endif // USE_DL_PREFIX && !LIBC_STATIC
500}