blob: 38c65830a63b91f266ade7fa7948b12e256c1cb1 [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>
44#include <unistd.h>
45
Elliott Hugheseb847bc2013-10-09 15:50:50 -070046#include "private/ScopedPthreadMutexLocker.h"
Elliott Hughes3b297c42012-10-11 16:08:51 -070047
Christopher Ferrisdda1c6c2014-07-09 17:16:07 -070048#if defined(USE_JEMALLOC)
49#include "jemalloc.h"
50#define Malloc(function) je_ ## function
51#elif defined(USE_DLMALLOC)
52#include "dlmalloc.h"
53#define Malloc(function) dl ## function
54#else
55#error "Either one of USE_DLMALLOC or USE_JEMALLOC must be defined."
56#endif
57
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070058// In a VM process, this is set to 1 after fork()ing out of zygote.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080059int gMallocLeakZygoteChild = 0;
60
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070061static HashTable g_hash_table;
62
63// Support for malloc debugging.
64// Table for dispatching malloc calls, initialized with default dispatchers.
65static const MallocDebug __libc_malloc_default_dispatch __attribute__((aligned(32))) = {
Christopher Ferrisa4037802014-06-09 19:14:11 -070066 Malloc(calloc),
67 Malloc(free),
68 Malloc(mallinfo),
69 Malloc(malloc),
70 Malloc(malloc_usable_size),
71 Malloc(memalign),
72 Malloc(posix_memalign),
Dan Alberte5fdaa42014-06-14 01:04:31 +000073#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -070074 Malloc(pvalloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000075#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -070076 Malloc(realloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000077#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -070078 Malloc(valloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000079#endif
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070080};
81
82// Selector of dispatch table to use for dispatching malloc calls.
Dan Albertedd81faf2014-08-12 16:21:26 -070083static const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch;
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070084
85// Handle to shared library where actual memory allocation is implemented.
86// This library is loaded and memory allocation calls are redirected there
87// when libc.debug.malloc environment variable contains value other than
88// zero:
89// 1 - For memory leak detections.
90// 5 - For filling allocated / freed memory with patterns defined by
91// CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
92// 10 - For adding pre-, and post- allocation stubs in order to detect
93// buffer overruns.
94// Note that emulator's memory allocation instrumentation is not controlled by
95// libc.debug.malloc value, but rather by emulator, started with -memcheck
96// option. Note also, that if emulator has started with -memcheck option,
97// emulator's instrumented memory allocation will take over value saved in
98// libc.debug.malloc. In other words, if emulator has started with -memcheck
99// option, libc.debug.malloc value is ignored.
100// Actual functionality for debug levels 1-10 is implemented in
101// libc_malloc_debug_leak.so, while functionality for emulator's instrumented
102// allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
103// the emulator only.
104#if !defined(LIBC_STATIC)
105static void* libc_malloc_impl_handle = NULL;
106#endif
107
108
109// The value of libc.debug.malloc.
110#if !defined(LIBC_STATIC)
111static int g_malloc_debug_level = 0;
112#endif
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800113
114// =============================================================================
115// output functions
116// =============================================================================
117
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700118static int hash_entry_compare(const void* arg1, const void* arg2) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700119 int result;
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700120
Christopher Ferrisa4037802014-06-09 19:14:11 -0700121 const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
122 const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800123
Christopher Ferrisa4037802014-06-09 19:14:11 -0700124 // if one or both arg pointers are null, deal gracefully
125 if (e1 == NULL) {
126 result = (e2 == NULL) ? 0 : 1;
127 } else if (e2 == NULL) {
128 result = -1;
129 } else {
130 size_t nbAlloc1 = e1->allocations;
131 size_t nbAlloc2 = e2->allocations;
132 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
133 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
134 size_t alloc1 = nbAlloc1 * size1;
135 size_t alloc2 = nbAlloc2 * size2;
136
137 // sort in descending order by:
138 // 1) total size
139 // 2) number of allocations
140 //
141 // This is used for sorting, not determination of equality, so we don't
142 // need to compare the bit flags.
143 if (alloc1 > alloc2) {
144 result = -1;
145 } else if (alloc1 < alloc2) {
146 result = 1;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800147 } else {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700148 if (nbAlloc1 > nbAlloc2) {
149 result = -1;
150 } else if (nbAlloc1 < nbAlloc2) {
151 result = 1;
152 } else {
153 result = 0;
154 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800155 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700156 }
157 return result;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800158}
159
Christopher Ferrisa4037802014-06-09 19:14:11 -0700160// Retrieve native heap information.
161//
162// "*info" is set to a buffer we allocate
163// "*overallSize" is set to the size of the "info" buffer
164// "*infoSize" is set to the size of a single entry
165// "*totalMemory" is set to the sum of all allocations we're tracking; does
166// not include heap overhead
167// "*backtraceSize" is set to the maximum number of entries in the back trace
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700168
Christopher Ferrisa4037802014-06-09 19:14:11 -0700169// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700170// Exported for use by ddms.
Christopher Ferrisa4037802014-06-09 19:14:11 -0700171// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700172extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
Christopher Ferrisa4037802014-06-09 19:14:11 -0700173 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
174 // Don't do anything if we have invalid arguments.
175 if (info == NULL || overallSize == NULL || infoSize == NULL ||
176 totalMemory == NULL || backtraceSize == NULL) {
177 return;
178 }
179 *totalMemory = 0;
180
181 ScopedPthreadMutexLocker locker(&g_hash_table.lock);
182 if (g_hash_table.count == 0) {
183 *info = NULL;
184 *overallSize = 0;
185 *infoSize = 0;
186 *backtraceSize = 0;
187 return;
188 }
189
190 HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
191
192 // Get the entries into an array to be sorted.
193 size_t index = 0;
194 for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
195 HashEntry* entry = g_hash_table.slots[i];
196 while (entry != NULL) {
197 list[index] = entry;
198 *totalMemory = *totalMemory + ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
199 index++;
200 entry = entry->next;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800201 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700202 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800203
Christopher Ferrisa4037802014-06-09 19:14:11 -0700204 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
205 *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
206 *overallSize = *infoSize * g_hash_table.count;
207 *backtraceSize = BACKTRACE_SIZE;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800208
Christopher Ferrisa4037802014-06-09 19:14:11 -0700209 // now get a byte array big enough for this
210 *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
211 if (*info == NULL) {
212 *overallSize = 0;
Christopher Ferris72bbd422014-05-08 11:14:03 -0700213 Malloc(free)(list);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700214 return;
215 }
216
217 qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
218
219 uint8_t* head = *info;
220 const size_t count = g_hash_table.count;
221 for (size_t i = 0 ; i < count ; ++i) {
222 HashEntry* entry = list[i];
223 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
224 if (entrySize < *infoSize) {
225 // We're writing less than a full entry, clear out the rest.
226 memset(head + entrySize, 0, *infoSize - entrySize);
227 } else {
228 // Make sure the amount we're copying doesn't exceed the limit.
229 entrySize = *infoSize;
230 }
231 memcpy(head, &(entry->size), entrySize);
232 head += *infoSize;
233 }
234
235 Malloc(free)(list);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800236}
237
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700238extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700239 Malloc(free)(info);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800240}
241
Christopher Ferrisa4037802014-06-09 19:14:11 -0700242// =============================================================================
243// Allocation functions
244// =============================================================================
245extern "C" void* calloc(size_t n_elements, size_t elem_size) {
246 return __libc_malloc_dispatch->calloc(n_elements, elem_size);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800247}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700248
249extern "C" void free(void* mem) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700250 __libc_malloc_dispatch->free(mem);
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() {
254 return __libc_malloc_dispatch->mallinfo();
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800255}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700256
Christopher Ferrisa4037802014-06-09 19:14:11 -0700257extern "C" void* malloc(size_t bytes) {
258 return __libc_malloc_dispatch->malloc(bytes);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800259}
260
Christopher Ferris885f3b92013-05-21 17:48:01 -0700261extern "C" size_t malloc_usable_size(const void* mem) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700262 return __libc_malloc_dispatch->malloc_usable_size(mem);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700263}
264
Christopher Ferrisa4037802014-06-09 19:14:11 -0700265extern "C" void* memalign(size_t alignment, size_t bytes) {
266 return __libc_malloc_dispatch->memalign(alignment, bytes);
267}
268
269extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
270 return __libc_malloc_dispatch->posix_memalign(memptr, alignment, size);
271}
272
Dan Alberte5fdaa42014-06-14 01:04:31 +0000273#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700274extern "C" void* pvalloc(size_t bytes) {
275 return __libc_malloc_dispatch->pvalloc(bytes);
276}
Dan Alberte5fdaa42014-06-14 01:04:31 +0000277#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700278
279extern "C" void* realloc(void* oldMem, size_t bytes) {
280 return __libc_malloc_dispatch->realloc(oldMem, bytes);
281}
282
Dan Alberte5fdaa42014-06-14 01:04:31 +0000283#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700284extern "C" void* valloc(size_t bytes) {
285 return __libc_malloc_dispatch->valloc(bytes);
286}
Dan Alberte5fdaa42014-06-14 01:04:31 +0000287#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700288
289// We implement malloc debugging only in libc.so, so the code below
290// must be excluded if we compile this file for static libc.a
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800291#ifndef LIBC_STATIC
292#include <sys/system_properties.h>
293#include <dlfcn.h>
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700294#include <stdio.h>
Elliott Hugheseb847bc2013-10-09 15:50:50 -0700295#include "private/libc_logging.h"
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800296
Christopher Ferris885f3b92013-05-21 17:48:01 -0700297template<typename FunctionType>
Nick Kralevich35c18622013-10-03 14:59:05 -0700298static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700299 char symbol[128];
300 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
301 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
302 if (*func == NULL) {
303 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
304 }
Christopher Ferris885f3b92013-05-21 17:48:01 -0700305}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700306
Christopher Ferris885f3b92013-05-21 17:48:01 -0700307static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700308 __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
309 getprogname(), g_malloc_debug_level, prefix);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700310
Christopher Ferrisa4037802014-06-09 19:14:11 -0700311 InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
312 InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
313 InitMallocFunction<MallocDebugMallinfo>(malloc_impl_handler, &table->mallinfo, prefix, "mallinfo");
314 InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
315 InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
316 InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
317 InitMallocFunction<MallocDebugPosixMemalign>(malloc_impl_handler, &table->posix_memalign, prefix, "posix_memalign");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000318#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700319 InitMallocFunction<MallocDebugPvalloc>(malloc_impl_handler, &table->pvalloc, prefix, "pvalloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000320#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700321 InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000322#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700323 InitMallocFunction<MallocDebugValloc>(malloc_impl_handler, &table->valloc, prefix, "valloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000324#endif
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700325}
326
Christopher Ferrisa4037802014-06-09 19:14:11 -0700327// Initializes memory allocation framework once per process.
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700328static void malloc_init_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700329 const char* so_name = NULL;
330 MallocDebugInit malloc_debug_initialize = NULL;
331 unsigned int qemu_running = 0;
332 unsigned int memcheck_enabled = 0;
333 char env[PROP_VALUE_MAX];
334 char memcheck_tracing[PROP_VALUE_MAX];
335 char debug_program[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800336
Christopher Ferrisa4037802014-06-09 19:14:11 -0700337 // Get custom malloc debug level. Note that emulator started with
338 // memory checking option will have priority over debug level set in
339 // libc.debug.malloc system property.
340 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
341 qemu_running = 1;
342 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
343 if (memcheck_tracing[0] != '0') {
344 // Emulator has started with memory tracing enabled. Enforce it.
345 g_malloc_debug_level = 20;
346 memcheck_enabled = 1;
347 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800348 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700349 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800350
Christopher Ferrisa4037802014-06-09 19:14:11 -0700351 // If debug level has not been set by memcheck option in the emulator,
352 // lets grab it from libc.debug.malloc system property.
353 if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
354 g_malloc_debug_level = atoi(env);
355 }
356
357 // Debug level 0 means that we should use default allocation routines.
358 if (g_malloc_debug_level == 0) {
359 return;
360 }
361
362 // If libc.debug.malloc.program is set and is not a substring of progname,
363 // then exit.
364 if (__system_property_get("libc.debug.malloc.program", debug_program)) {
365 if (!strstr(getprogname(), debug_program)) {
366 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800367 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700368 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800369
Christopher Ferrisa4037802014-06-09 19:14:11 -0700370 // mksh is way too leaky. http://b/7291287.
371 if (g_malloc_debug_level >= 10) {
372 if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
373 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800374 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700375 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800376
Christopher Ferrisa4037802014-06-09 19:14:11 -0700377 // Choose the appropriate .so for the requested debug level.
378 switch (g_malloc_debug_level) {
379 case 1:
380 case 5:
381 case 10:
382 so_name = "libc_malloc_debug_leak.so";
383 break;
384 case 20:
385 // Quick check: debug level 20 can only be handled in emulator.
386 if (!qemu_running) {
387 error_log("%s: Debug level %d can only be set in emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700388 getprogname(), g_malloc_debug_level);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700389 return;
390 }
391 // Make sure that memory checking has been enabled in emulator.
392 if (!memcheck_enabled) {
393 error_log("%s: Memory checking is not enabled in the emulator\n", getprogname());
394 return;
395 }
396 so_name = "libc_malloc_debug_qemu.so";
397 break;
398 default:
399 error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
400 return;
401 }
402
403 // Load .so that implements the required malloc debugging functionality.
404 void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
405 if (malloc_impl_handle == NULL) {
406 error_log("%s: Missing module %s required for malloc debug level %d: %s",
407 getprogname(), so_name, g_malloc_debug_level, dlerror());
408 return;
409 }
410
411 // Initialize malloc debugging in the loaded module.
412 malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
413 "malloc_debug_initialize"));
414 if (malloc_debug_initialize == NULL) {
415 error_log("%s: Initialization routine is not found in %s\n", getprogname(), so_name);
416 dlclose(malloc_impl_handle);
417 return;
418 }
Christopher Ferrisdda1c6c2014-07-09 17:16:07 -0700419 if (!malloc_debug_initialize(&g_hash_table, &__libc_malloc_default_dispatch)) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700420 dlclose(malloc_impl_handle);
421 return;
422 }
423
424 if (g_malloc_debug_level == 20) {
425 // For memory checker we need to do extra initialization.
426 typedef int (*MemCheckInit)(int, const char*);
427 MemCheckInit memcheck_initialize =
428 reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle, "memcheck_initialize"));
429 if (memcheck_initialize == NULL) {
430 error_log("%s: memcheck_initialize routine is not found in %s\n",
431 getprogname(), so_name);
432 dlclose(malloc_impl_handle);
433 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800434 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700435
436 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
437 dlclose(malloc_impl_handle);
438 return;
439 }
440 }
441
442 // No need to init the dispatch table because we can only get
443 // here if debug level is 1, 5, 10, or 20.
444 static MallocDebug malloc_dispatch_table __attribute__((aligned(32)));
445 switch (g_malloc_debug_level) {
446 case 1:
447 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
448 break;
449 case 5:
450 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
451 break;
452 case 10:
453 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
454 break;
455 case 20:
456 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
457 break;
458 default:
459 break;
460 }
461
462 // Make sure dispatch table is initialized
463 if ((malloc_dispatch_table.calloc == NULL) ||
464 (malloc_dispatch_table.free == NULL) ||
465 (malloc_dispatch_table.mallinfo == NULL) ||
466 (malloc_dispatch_table.malloc == NULL) ||
467 (malloc_dispatch_table.malloc_usable_size == NULL) ||
468 (malloc_dispatch_table.memalign == NULL) ||
469 (malloc_dispatch_table.posix_memalign == NULL) ||
Dan Alberte5fdaa42014-06-14 01:04:31 +0000470#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700471 (malloc_dispatch_table.pvalloc == NULL) ||
Dan Alberte5fdaa42014-06-14 01:04:31 +0000472#endif
473 (malloc_dispatch_table.realloc == NULL)
474#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
475 || (malloc_dispatch_table.valloc == NULL)
476#endif
477 ) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700478 error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
479 getprogname(), g_malloc_debug_level);
480 dlclose(malloc_impl_handle);
481 } else {
482 __libc_malloc_dispatch = &malloc_dispatch_table;
483 libc_malloc_impl_handle = malloc_impl_handle;
484 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800485}
486
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700487static void malloc_fini_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700488 // Our BSD stdio implementation doesn't close the standard streams, it only flushes them.
489 // And it doesn't do that until its atexit handler is run, and we run first!
490 // It's great that other unclosed FILE*s show up as malloc leaks, but we need to manually
491 // clean up the standard streams ourselves.
492 fclose(stdin);
493 fclose(stdout);
494 fclose(stderr);
Elliott Hughes1e980b62013-01-17 18:36:06 -0800495
Christopher Ferrisa4037802014-06-09 19:14:11 -0700496 if (libc_malloc_impl_handle != NULL) {
497 MallocDebugFini malloc_debug_finalize =
498 reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle, "malloc_debug_finalize"));
499 if (malloc_debug_finalize != NULL) {
500 malloc_debug_finalize(g_malloc_debug_level);
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700501 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700502 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700503}
504
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800505#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800506
Christopher Ferrisa4037802014-06-09 19:14:11 -0700507// Initializes memory allocation framework.
508// This routine is called from __libc_init routines implemented
509// in libc_init_static.c and libc_init_dynamic.c files.
Kito Chengea489742013-04-12 16:13:34 +0800510extern "C" __LIBC_HIDDEN__ void malloc_debug_init() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700511#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700512 static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
513 if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
514 error_log("Unable to initialize malloc_debug component.");
515 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700516#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800517}
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700518
Kito Chengea489742013-04-12 16:13:34 +0800519extern "C" __LIBC_HIDDEN__ void malloc_debug_fini() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700520#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700521 static pthread_once_t malloc_fini_once_ctl = PTHREAD_ONCE_INIT;
522 if (pthread_once(&malloc_fini_once_ctl, malloc_fini_impl)) {
523 error_log("Unable to finalize malloc_debug component.");
524 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700525#endif // !LIBC_STATIC
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700526}