blob: be16625b8807f0d19781a8165f01360c5f9a9c70 [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
32// routines to be defined / implemented in libc.so library, regardless
33// whether or not MALLOC_LEAK_CHECK macro is defined. To make things even
34// more tricky, malloc leak detection code, implemented in
35// libc_malloc_debug.so also requires access to these variables and routines
36// (to fill allocation entry hash table, for example). So, all relevant
37// variables and routines are defined / implemented here and exported
38// to all, leak detection code and other components via dynamic (libc.so),
39// or static (libc.a) linking.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080040
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080041#include "malloc_debug_common.h"
42
Elliott Hughes3b297c42012-10-11 16:08:51 -070043#include <pthread.h>
44#include <stdlib.h>
45#include <unistd.h>
46
Elliott Hugheseb847bc2013-10-09 15:50:50 -070047#include "private/ScopedPthreadMutexLocker.h"
Elliott Hughes3b297c42012-10-11 16:08:51 -070048
Christopher Ferrisdda1c6c2014-07-09 17:16:07 -070049#if defined(USE_JEMALLOC)
50#include "jemalloc.h"
51#define Malloc(function) je_ ## function
52#elif defined(USE_DLMALLOC)
53#include "dlmalloc.h"
54#define Malloc(function) dl ## function
55#else
56#error "Either one of USE_DLMALLOC or USE_JEMALLOC must be defined."
57#endif
58
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070059// In a VM process, this is set to 1 after fork()ing out of zygote.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080060int gMallocLeakZygoteChild = 0;
61
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070062static HashTable g_hash_table;
63
64// Support for malloc debugging.
65// Table for dispatching malloc calls, initialized with default dispatchers.
66static const MallocDebug __libc_malloc_default_dispatch __attribute__((aligned(32))) = {
Christopher Ferrisa4037802014-06-09 19:14:11 -070067 Malloc(calloc),
68 Malloc(free),
69 Malloc(mallinfo),
70 Malloc(malloc),
71 Malloc(malloc_usable_size),
72 Malloc(memalign),
73 Malloc(posix_memalign),
Dan Alberte5fdaa42014-06-14 01:04:31 +000074#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -070075 Malloc(pvalloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000076#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -070077 Malloc(realloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000078#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -070079 Malloc(valloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000080#endif
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070081};
82
83// Selector of dispatch table to use for dispatching malloc calls.
Elliott Hughes14442bb2014-06-04 15:18:36 -070084// TODO: fix http://b/15432753 and make this static again.
85const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch;
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070086
87// Handle to shared library where actual memory allocation is implemented.
88// This library is loaded and memory allocation calls are redirected there
89// when libc.debug.malloc environment variable contains value other than
90// zero:
91// 1 - For memory leak detections.
92// 5 - For filling allocated / freed memory with patterns defined by
93// CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
94// 10 - For adding pre-, and post- allocation stubs in order to detect
95// buffer overruns.
96// Note that emulator's memory allocation instrumentation is not controlled by
97// libc.debug.malloc value, but rather by emulator, started with -memcheck
98// option. Note also, that if emulator has started with -memcheck option,
99// emulator's instrumented memory allocation will take over value saved in
100// libc.debug.malloc. In other words, if emulator has started with -memcheck
101// option, libc.debug.malloc value is ignored.
102// Actual functionality for debug levels 1-10 is implemented in
103// libc_malloc_debug_leak.so, while functionality for emulator's instrumented
104// allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
105// the emulator only.
106#if !defined(LIBC_STATIC)
107static void* libc_malloc_impl_handle = NULL;
108#endif
109
110
111// The value of libc.debug.malloc.
112#if !defined(LIBC_STATIC)
113static int g_malloc_debug_level = 0;
114#endif
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800115
116// =============================================================================
117// output functions
118// =============================================================================
119
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700120static int hash_entry_compare(const void* arg1, const void* arg2) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700121 int result;
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700122
Christopher Ferrisa4037802014-06-09 19:14:11 -0700123 const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
124 const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800125
Christopher Ferrisa4037802014-06-09 19:14:11 -0700126 // if one or both arg pointers are null, deal gracefully
127 if (e1 == NULL) {
128 result = (e2 == NULL) ? 0 : 1;
129 } else if (e2 == NULL) {
130 result = -1;
131 } else {
132 size_t nbAlloc1 = e1->allocations;
133 size_t nbAlloc2 = e2->allocations;
134 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
135 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
136 size_t alloc1 = nbAlloc1 * size1;
137 size_t alloc2 = nbAlloc2 * size2;
138
139 // sort in descending order by:
140 // 1) total size
141 // 2) number of allocations
142 //
143 // This is used for sorting, not determination of equality, so we don't
144 // need to compare the bit flags.
145 if (alloc1 > alloc2) {
146 result = -1;
147 } else if (alloc1 < alloc2) {
148 result = 1;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800149 } else {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700150 if (nbAlloc1 > nbAlloc2) {
151 result = -1;
152 } else if (nbAlloc1 < nbAlloc2) {
153 result = 1;
154 } else {
155 result = 0;
156 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800157 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700158 }
159 return result;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800160}
161
Christopher Ferrisa4037802014-06-09 19:14:11 -0700162// Retrieve native heap information.
163//
164// "*info" is set to a buffer we allocate
165// "*overallSize" is set to the size of the "info" buffer
166// "*infoSize" is set to the size of a single entry
167// "*totalMemory" is set to the sum of all allocations we're tracking; does
168// not include heap overhead
169// "*backtraceSize" is set to the maximum number of entries in the back trace
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700170
Christopher Ferrisa4037802014-06-09 19:14:11 -0700171// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700172// Exported for use by ddms.
Christopher Ferrisa4037802014-06-09 19:14:11 -0700173// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700174extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
Christopher Ferrisa4037802014-06-09 19:14:11 -0700175 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
176 // Don't do anything if we have invalid arguments.
177 if (info == NULL || overallSize == NULL || infoSize == NULL ||
178 totalMemory == NULL || backtraceSize == NULL) {
179 return;
180 }
181 *totalMemory = 0;
182
183 ScopedPthreadMutexLocker locker(&g_hash_table.lock);
184 if (g_hash_table.count == 0) {
185 *info = NULL;
186 *overallSize = 0;
187 *infoSize = 0;
188 *backtraceSize = 0;
189 return;
190 }
191
192 HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
193
194 // Get the entries into an array to be sorted.
195 size_t index = 0;
196 for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
197 HashEntry* entry = g_hash_table.slots[i];
198 while (entry != NULL) {
199 list[index] = entry;
200 *totalMemory = *totalMemory + ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
201 index++;
202 entry = entry->next;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800203 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700204 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800205
Christopher Ferrisa4037802014-06-09 19:14:11 -0700206 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
207 *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
208 *overallSize = *infoSize * g_hash_table.count;
209 *backtraceSize = BACKTRACE_SIZE;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800210
Christopher Ferrisa4037802014-06-09 19:14:11 -0700211 // now get a byte array big enough for this
212 *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
213 if (*info == NULL) {
214 *overallSize = 0;
Christopher Ferris72bbd422014-05-08 11:14:03 -0700215 Malloc(free)(list);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700216 return;
217 }
218
219 qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
220
221 uint8_t* head = *info;
222 const size_t count = g_hash_table.count;
223 for (size_t i = 0 ; i < count ; ++i) {
224 HashEntry* entry = list[i];
225 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
226 if (entrySize < *infoSize) {
227 // We're writing less than a full entry, clear out the rest.
228 memset(head + entrySize, 0, *infoSize - entrySize);
229 } else {
230 // Make sure the amount we're copying doesn't exceed the limit.
231 entrySize = *infoSize;
232 }
233 memcpy(head, &(entry->size), entrySize);
234 head += *infoSize;
235 }
236
237 Malloc(free)(list);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800238}
239
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700240extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700241 Malloc(free)(info);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800242}
243
Christopher Ferrisa4037802014-06-09 19:14:11 -0700244// =============================================================================
245// Allocation functions
246// =============================================================================
247extern "C" void* calloc(size_t n_elements, size_t elem_size) {
248 return __libc_malloc_dispatch->calloc(n_elements, elem_size);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800249}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700250
251extern "C" void free(void* mem) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700252 __libc_malloc_dispatch->free(mem);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800253}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700254
Christopher Ferrisa4037802014-06-09 19:14:11 -0700255extern "C" struct mallinfo mallinfo() {
256 return __libc_malloc_dispatch->mallinfo();
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800257}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700258
Christopher Ferrisa4037802014-06-09 19:14:11 -0700259extern "C" void* malloc(size_t bytes) {
260 return __libc_malloc_dispatch->malloc(bytes);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800261}
262
Christopher Ferris885f3b92013-05-21 17:48:01 -0700263extern "C" size_t malloc_usable_size(const void* mem) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700264 return __libc_malloc_dispatch->malloc_usable_size(mem);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700265}
266
Christopher Ferrisa4037802014-06-09 19:14:11 -0700267extern "C" void* memalign(size_t alignment, size_t bytes) {
268 return __libc_malloc_dispatch->memalign(alignment, bytes);
269}
270
271extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
272 return __libc_malloc_dispatch->posix_memalign(memptr, alignment, size);
273}
274
Dan Alberte5fdaa42014-06-14 01:04:31 +0000275#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700276extern "C" void* pvalloc(size_t bytes) {
277 return __libc_malloc_dispatch->pvalloc(bytes);
278}
Dan Alberte5fdaa42014-06-14 01:04:31 +0000279#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700280
281extern "C" void* realloc(void* oldMem, size_t bytes) {
282 return __libc_malloc_dispatch->realloc(oldMem, bytes);
283}
284
Dan Alberte5fdaa42014-06-14 01:04:31 +0000285#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700286extern "C" void* valloc(size_t bytes) {
287 return __libc_malloc_dispatch->valloc(bytes);
288}
Dan Alberte5fdaa42014-06-14 01:04:31 +0000289#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700290
291// We implement malloc debugging only in libc.so, so the code below
292// must be excluded if we compile this file for static libc.a
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800293#ifndef LIBC_STATIC
294#include <sys/system_properties.h>
295#include <dlfcn.h>
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700296#include <stdio.h>
Elliott Hugheseb847bc2013-10-09 15:50:50 -0700297#include "private/libc_logging.h"
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800298
Christopher Ferris885f3b92013-05-21 17:48:01 -0700299template<typename FunctionType>
Nick Kralevich35c18622013-10-03 14:59:05 -0700300static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700301 char symbol[128];
302 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
303 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
304 if (*func == NULL) {
305 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
306 }
Christopher Ferris885f3b92013-05-21 17:48:01 -0700307}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700308
Christopher Ferris885f3b92013-05-21 17:48:01 -0700309static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700310 __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
311 getprogname(), g_malloc_debug_level, prefix);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700312
Christopher Ferrisa4037802014-06-09 19:14:11 -0700313 InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
314 InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
315 InitMallocFunction<MallocDebugMallinfo>(malloc_impl_handler, &table->mallinfo, prefix, "mallinfo");
316 InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
317 InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
318 InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
319 InitMallocFunction<MallocDebugPosixMemalign>(malloc_impl_handler, &table->posix_memalign, prefix, "posix_memalign");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000320#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700321 InitMallocFunction<MallocDebugPvalloc>(malloc_impl_handler, &table->pvalloc, prefix, "pvalloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000322#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700323 InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000324#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700325 InitMallocFunction<MallocDebugValloc>(malloc_impl_handler, &table->valloc, prefix, "valloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000326#endif
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700327}
328
Christopher Ferrisa4037802014-06-09 19:14:11 -0700329// Initializes memory allocation framework once per process.
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700330static void malloc_init_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700331 const char* so_name = NULL;
332 MallocDebugInit malloc_debug_initialize = NULL;
333 unsigned int qemu_running = 0;
334 unsigned int memcheck_enabled = 0;
335 char env[PROP_VALUE_MAX];
336 char memcheck_tracing[PROP_VALUE_MAX];
337 char debug_program[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800338
Christopher Ferrisa4037802014-06-09 19:14:11 -0700339 // Get custom malloc debug level. Note that emulator started with
340 // memory checking option will have priority over debug level set in
341 // libc.debug.malloc system property.
342 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
343 qemu_running = 1;
344 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
345 if (memcheck_tracing[0] != '0') {
346 // Emulator has started with memory tracing enabled. Enforce it.
347 g_malloc_debug_level = 20;
348 memcheck_enabled = 1;
349 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800350 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700351 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800352
Christopher Ferrisa4037802014-06-09 19:14:11 -0700353 // If debug level has not been set by memcheck option in the emulator,
354 // lets grab it from libc.debug.malloc system property.
355 if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
356 g_malloc_debug_level = atoi(env);
357 }
358
359 // Debug level 0 means that we should use default allocation routines.
360 if (g_malloc_debug_level == 0) {
361 return;
362 }
363
364 // If libc.debug.malloc.program is set and is not a substring of progname,
365 // then exit.
366 if (__system_property_get("libc.debug.malloc.program", debug_program)) {
367 if (!strstr(getprogname(), debug_program)) {
368 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800369 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700370 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800371
Christopher Ferrisa4037802014-06-09 19:14:11 -0700372 // mksh is way too leaky. http://b/7291287.
373 if (g_malloc_debug_level >= 10) {
374 if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
375 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800376 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700377 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800378
Christopher Ferrisa4037802014-06-09 19:14:11 -0700379 // Choose the appropriate .so for the requested debug level.
380 switch (g_malloc_debug_level) {
381 case 1:
382 case 5:
383 case 10:
384 so_name = "libc_malloc_debug_leak.so";
385 break;
386 case 20:
387 // Quick check: debug level 20 can only be handled in emulator.
388 if (!qemu_running) {
389 error_log("%s: Debug level %d can only be set in emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700390 getprogname(), g_malloc_debug_level);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700391 return;
392 }
393 // Make sure that memory checking has been enabled in emulator.
394 if (!memcheck_enabled) {
395 error_log("%s: Memory checking is not enabled in the emulator\n", getprogname());
396 return;
397 }
398 so_name = "libc_malloc_debug_qemu.so";
399 break;
400 default:
401 error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
402 return;
403 }
404
405 // Load .so that implements the required malloc debugging functionality.
406 void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
407 if (malloc_impl_handle == NULL) {
408 error_log("%s: Missing module %s required for malloc debug level %d: %s",
409 getprogname(), so_name, g_malloc_debug_level, dlerror());
410 return;
411 }
412
413 // Initialize malloc debugging in the loaded module.
414 malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
415 "malloc_debug_initialize"));
416 if (malloc_debug_initialize == NULL) {
417 error_log("%s: Initialization routine is not found in %s\n", getprogname(), so_name);
418 dlclose(malloc_impl_handle);
419 return;
420 }
Christopher Ferrisdda1c6c2014-07-09 17:16:07 -0700421 if (!malloc_debug_initialize(&g_hash_table, &__libc_malloc_default_dispatch)) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700422 dlclose(malloc_impl_handle);
423 return;
424 }
425
426 if (g_malloc_debug_level == 20) {
427 // For memory checker we need to do extra initialization.
428 typedef int (*MemCheckInit)(int, const char*);
429 MemCheckInit memcheck_initialize =
430 reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle, "memcheck_initialize"));
431 if (memcheck_initialize == NULL) {
432 error_log("%s: memcheck_initialize routine is not found in %s\n",
433 getprogname(), so_name);
434 dlclose(malloc_impl_handle);
435 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800436 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700437
438 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
439 dlclose(malloc_impl_handle);
440 return;
441 }
442 }
443
444 // No need to init the dispatch table because we can only get
445 // here if debug level is 1, 5, 10, or 20.
446 static MallocDebug malloc_dispatch_table __attribute__((aligned(32)));
447 switch (g_malloc_debug_level) {
448 case 1:
449 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
450 break;
451 case 5:
452 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
453 break;
454 case 10:
455 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
456 break;
457 case 20:
458 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
459 break;
460 default:
461 break;
462 }
463
464 // Make sure dispatch table is initialized
465 if ((malloc_dispatch_table.calloc == NULL) ||
466 (malloc_dispatch_table.free == NULL) ||
467 (malloc_dispatch_table.mallinfo == NULL) ||
468 (malloc_dispatch_table.malloc == NULL) ||
469 (malloc_dispatch_table.malloc_usable_size == NULL) ||
470 (malloc_dispatch_table.memalign == NULL) ||
471 (malloc_dispatch_table.posix_memalign == NULL) ||
Dan Alberte5fdaa42014-06-14 01:04:31 +0000472#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700473 (malloc_dispatch_table.pvalloc == NULL) ||
Dan Alberte5fdaa42014-06-14 01:04:31 +0000474#endif
475 (malloc_dispatch_table.realloc == NULL)
476#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
477 || (malloc_dispatch_table.valloc == NULL)
478#endif
479 ) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700480 error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
481 getprogname(), g_malloc_debug_level);
482 dlclose(malloc_impl_handle);
483 } else {
484 __libc_malloc_dispatch = &malloc_dispatch_table;
485 libc_malloc_impl_handle = malloc_impl_handle;
486 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800487}
488
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700489static void malloc_fini_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700490 // Our BSD stdio implementation doesn't close the standard streams, it only flushes them.
491 // And it doesn't do that until its atexit handler is run, and we run first!
492 // It's great that other unclosed FILE*s show up as malloc leaks, but we need to manually
493 // clean up the standard streams ourselves.
494 fclose(stdin);
495 fclose(stdout);
496 fclose(stderr);
Elliott Hughes1e980b62013-01-17 18:36:06 -0800497
Christopher Ferrisa4037802014-06-09 19:14:11 -0700498 if (libc_malloc_impl_handle != NULL) {
499 MallocDebugFini malloc_debug_finalize =
500 reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle, "malloc_debug_finalize"));
501 if (malloc_debug_finalize != NULL) {
502 malloc_debug_finalize(g_malloc_debug_level);
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700503 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700504 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700505}
506
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800507#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800508
Christopher Ferrisa4037802014-06-09 19:14:11 -0700509// Initializes memory allocation framework.
510// This routine is called from __libc_init routines implemented
511// in libc_init_static.c and libc_init_dynamic.c files.
Kito Chengea489742013-04-12 16:13:34 +0800512extern "C" __LIBC_HIDDEN__ void malloc_debug_init() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700513#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700514 static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
515 if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
516 error_log("Unable to initialize malloc_debug component.");
517 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700518#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800519}
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700520
Kito Chengea489742013-04-12 16:13:34 +0800521extern "C" __LIBC_HIDDEN__ void malloc_debug_fini() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700522#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700523 static pthread_once_t malloc_fini_once_ctl = PTHREAD_ONCE_INIT;
524 if (pthread_once(&malloc_fini_once_ctl, malloc_fini_impl)) {
525 error_log("Unable to finalize malloc_debug component.");
526 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700527#endif // !LIBC_STATIC
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700528}