blob: cbca160eb3240ae8e79b09b929fff70849a81d7e [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
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070049// In a VM process, this is set to 1 after fork()ing out of zygote.
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -080050int gMallocLeakZygoteChild = 0;
51
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070052static HashTable g_hash_table;
53
54// Support for malloc debugging.
55// Table for dispatching malloc calls, initialized with default dispatchers.
56static const MallocDebug __libc_malloc_default_dispatch __attribute__((aligned(32))) = {
Christopher Ferrisa4037802014-06-09 19:14:11 -070057 Malloc(calloc),
58 Malloc(free),
59 Malloc(mallinfo),
60 Malloc(malloc),
61 Malloc(malloc_usable_size),
62 Malloc(memalign),
63 Malloc(posix_memalign),
Dan Alberte5fdaa42014-06-14 01:04:31 +000064#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -070065 Malloc(pvalloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000066#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -070067 Malloc(realloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000068#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -070069 Malloc(valloc),
Dan Alberte5fdaa42014-06-14 01:04:31 +000070#endif
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070071};
72
73// Selector of dispatch table to use for dispatching malloc calls.
Elliott Hughes14442bb2014-06-04 15:18:36 -070074// TODO: fix http://b/15432753 and make this static again.
75const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch;
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070076
77// Handle to shared library where actual memory allocation is implemented.
78// This library is loaded and memory allocation calls are redirected there
79// when libc.debug.malloc environment variable contains value other than
80// zero:
81// 1 - For memory leak detections.
82// 5 - For filling allocated / freed memory with patterns defined by
83// CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
84// 10 - For adding pre-, and post- allocation stubs in order to detect
85// buffer overruns.
86// Note that emulator's memory allocation instrumentation is not controlled by
87// libc.debug.malloc value, but rather by emulator, started with -memcheck
88// option. Note also, that if emulator has started with -memcheck option,
89// emulator's instrumented memory allocation will take over value saved in
90// libc.debug.malloc. In other words, if emulator has started with -memcheck
91// option, libc.debug.malloc value is ignored.
92// Actual functionality for debug levels 1-10 is implemented in
93// libc_malloc_debug_leak.so, while functionality for emulator's instrumented
94// allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
95// the emulator only.
96#if !defined(LIBC_STATIC)
97static void* libc_malloc_impl_handle = NULL;
98#endif
99
100
101// The value of libc.debug.malloc.
102#if !defined(LIBC_STATIC)
103static int g_malloc_debug_level = 0;
104#endif
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800105
106// =============================================================================
107// output functions
108// =============================================================================
109
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700110static int hash_entry_compare(const void* arg1, const void* arg2) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700111 int result;
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700112
Christopher Ferrisa4037802014-06-09 19:14:11 -0700113 const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
114 const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800115
Christopher Ferrisa4037802014-06-09 19:14:11 -0700116 // if one or both arg pointers are null, deal gracefully
117 if (e1 == NULL) {
118 result = (e2 == NULL) ? 0 : 1;
119 } else if (e2 == NULL) {
120 result = -1;
121 } else {
122 size_t nbAlloc1 = e1->allocations;
123 size_t nbAlloc2 = e2->allocations;
124 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
125 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
126 size_t alloc1 = nbAlloc1 * size1;
127 size_t alloc2 = nbAlloc2 * size2;
128
129 // sort in descending order by:
130 // 1) total size
131 // 2) number of allocations
132 //
133 // This is used for sorting, not determination of equality, so we don't
134 // need to compare the bit flags.
135 if (alloc1 > alloc2) {
136 result = -1;
137 } else if (alloc1 < alloc2) {
138 result = 1;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800139 } else {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700140 if (nbAlloc1 > nbAlloc2) {
141 result = -1;
142 } else if (nbAlloc1 < nbAlloc2) {
143 result = 1;
144 } else {
145 result = 0;
146 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800147 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700148 }
149 return result;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800150}
151
Christopher Ferrisa4037802014-06-09 19:14:11 -0700152// Retrieve native heap information.
153//
154// "*info" is set to a buffer we allocate
155// "*overallSize" is set to the size of the "info" buffer
156// "*infoSize" is set to the size of a single entry
157// "*totalMemory" is set to the sum of all allocations we're tracking; does
158// not include heap overhead
159// "*backtraceSize" is set to the maximum number of entries in the back trace
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700160
Christopher Ferrisa4037802014-06-09 19:14:11 -0700161// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700162// Exported for use by ddms.
Christopher Ferrisa4037802014-06-09 19:14:11 -0700163// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700164extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
Christopher Ferrisa4037802014-06-09 19:14:11 -0700165 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
166 // Don't do anything if we have invalid arguments.
167 if (info == NULL || overallSize == NULL || infoSize == NULL ||
168 totalMemory == NULL || backtraceSize == NULL) {
169 return;
170 }
171 *totalMemory = 0;
172
173 ScopedPthreadMutexLocker locker(&g_hash_table.lock);
174 if (g_hash_table.count == 0) {
175 *info = NULL;
176 *overallSize = 0;
177 *infoSize = 0;
178 *backtraceSize = 0;
179 return;
180 }
181
182 HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
183
184 // Get the entries into an array to be sorted.
185 size_t index = 0;
186 for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
187 HashEntry* entry = g_hash_table.slots[i];
188 while (entry != NULL) {
189 list[index] = entry;
190 *totalMemory = *totalMemory + ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
191 index++;
192 entry = entry->next;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800193 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700194 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800195
Christopher Ferrisa4037802014-06-09 19:14:11 -0700196 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
197 *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
198 *overallSize = *infoSize * g_hash_table.count;
199 *backtraceSize = BACKTRACE_SIZE;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800200
Christopher Ferrisa4037802014-06-09 19:14:11 -0700201 // now get a byte array big enough for this
202 *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
203 if (*info == NULL) {
204 *overallSize = 0;
Christopher Ferris72bbd422014-05-08 11:14:03 -0700205 Malloc(free)(list);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700206 return;
207 }
208
209 qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
210
211 uint8_t* head = *info;
212 const size_t count = g_hash_table.count;
213 for (size_t i = 0 ; i < count ; ++i) {
214 HashEntry* entry = list[i];
215 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
216 if (entrySize < *infoSize) {
217 // We're writing less than a full entry, clear out the rest.
218 memset(head + entrySize, 0, *infoSize - entrySize);
219 } else {
220 // Make sure the amount we're copying doesn't exceed the limit.
221 entrySize = *infoSize;
222 }
223 memcpy(head, &(entry->size), entrySize);
224 head += *infoSize;
225 }
226
227 Malloc(free)(list);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800228}
229
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700230extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700231 Malloc(free)(info);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800232}
233
Christopher Ferrisa4037802014-06-09 19:14:11 -0700234// =============================================================================
235// Allocation functions
236// =============================================================================
237extern "C" void* calloc(size_t n_elements, size_t elem_size) {
238 return __libc_malloc_dispatch->calloc(n_elements, elem_size);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800239}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700240
241extern "C" void free(void* mem) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700242 __libc_malloc_dispatch->free(mem);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800243}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700244
Christopher Ferrisa4037802014-06-09 19:14:11 -0700245extern "C" struct mallinfo mallinfo() {
246 return __libc_malloc_dispatch->mallinfo();
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800247}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700248
Christopher Ferrisa4037802014-06-09 19:14:11 -0700249extern "C" void* malloc(size_t bytes) {
250 return __libc_malloc_dispatch->malloc(bytes);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800251}
252
Christopher Ferris885f3b92013-05-21 17:48:01 -0700253extern "C" size_t malloc_usable_size(const void* mem) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700254 return __libc_malloc_dispatch->malloc_usable_size(mem);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700255}
256
Christopher Ferrisa4037802014-06-09 19:14:11 -0700257extern "C" void* memalign(size_t alignment, size_t bytes) {
258 return __libc_malloc_dispatch->memalign(alignment, bytes);
259}
260
261extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
262 return __libc_malloc_dispatch->posix_memalign(memptr, alignment, size);
263}
264
Dan Alberte5fdaa42014-06-14 01:04:31 +0000265#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700266extern "C" void* pvalloc(size_t bytes) {
267 return __libc_malloc_dispatch->pvalloc(bytes);
268}
Dan Alberte5fdaa42014-06-14 01:04:31 +0000269#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700270
271extern "C" void* realloc(void* oldMem, size_t bytes) {
272 return __libc_malloc_dispatch->realloc(oldMem, bytes);
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* valloc(size_t bytes) {
277 return __libc_malloc_dispatch->valloc(bytes);
278}
Dan Alberte5fdaa42014-06-14 01:04:31 +0000279#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700280
281// We implement malloc debugging only in libc.so, so the code below
282// must be excluded if we compile this file for static libc.a
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800283#ifndef LIBC_STATIC
284#include <sys/system_properties.h>
285#include <dlfcn.h>
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700286#include <stdio.h>
Elliott Hugheseb847bc2013-10-09 15:50:50 -0700287#include "private/libc_logging.h"
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800288
Christopher Ferris885f3b92013-05-21 17:48:01 -0700289template<typename FunctionType>
Nick Kralevich35c18622013-10-03 14:59:05 -0700290static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700291 char symbol[128];
292 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
293 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
294 if (*func == NULL) {
295 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
296 }
Christopher Ferris885f3b92013-05-21 17:48:01 -0700297}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700298
Christopher Ferris885f3b92013-05-21 17:48:01 -0700299static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700300 __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
301 getprogname(), g_malloc_debug_level, prefix);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700302
Christopher Ferrisa4037802014-06-09 19:14:11 -0700303 InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
304 InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
305 InitMallocFunction<MallocDebugMallinfo>(malloc_impl_handler, &table->mallinfo, prefix, "mallinfo");
306 InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
307 InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
308 InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
309 InitMallocFunction<MallocDebugPosixMemalign>(malloc_impl_handler, &table->posix_memalign, prefix, "posix_memalign");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000310#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700311 InitMallocFunction<MallocDebugPvalloc>(malloc_impl_handler, &table->pvalloc, prefix, "pvalloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000312#endif
Christopher Ferrisa4037802014-06-09 19:14:11 -0700313 InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000314#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700315 InitMallocFunction<MallocDebugValloc>(malloc_impl_handler, &table->valloc, prefix, "valloc");
Dan Alberte5fdaa42014-06-14 01:04:31 +0000316#endif
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700317}
318
Christopher Ferrisa4037802014-06-09 19:14:11 -0700319// Initializes memory allocation framework once per process.
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700320static void malloc_init_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700321 const char* so_name = NULL;
322 MallocDebugInit malloc_debug_initialize = NULL;
323 unsigned int qemu_running = 0;
324 unsigned int memcheck_enabled = 0;
325 char env[PROP_VALUE_MAX];
326 char memcheck_tracing[PROP_VALUE_MAX];
327 char debug_program[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800328
Christopher Ferrisa4037802014-06-09 19:14:11 -0700329 // Get custom malloc debug level. Note that emulator started with
330 // memory checking option will have priority over debug level set in
331 // libc.debug.malloc system property.
332 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
333 qemu_running = 1;
334 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
335 if (memcheck_tracing[0] != '0') {
336 // Emulator has started with memory tracing enabled. Enforce it.
337 g_malloc_debug_level = 20;
338 memcheck_enabled = 1;
339 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800340 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700341 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800342
Christopher Ferrisa4037802014-06-09 19:14:11 -0700343 // If debug level has not been set by memcheck option in the emulator,
344 // lets grab it from libc.debug.malloc system property.
345 if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
346 g_malloc_debug_level = atoi(env);
347 }
348
349 // Debug level 0 means that we should use default allocation routines.
350 if (g_malloc_debug_level == 0) {
351 return;
352 }
353
354 // If libc.debug.malloc.program is set and is not a substring of progname,
355 // then exit.
356 if (__system_property_get("libc.debug.malloc.program", debug_program)) {
357 if (!strstr(getprogname(), debug_program)) {
358 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800359 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700360 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800361
Christopher Ferrisa4037802014-06-09 19:14:11 -0700362 // mksh is way too leaky. http://b/7291287.
363 if (g_malloc_debug_level >= 10) {
364 if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
365 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800366 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700367 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800368
Christopher Ferrisa4037802014-06-09 19:14:11 -0700369 // Choose the appropriate .so for the requested debug level.
370 switch (g_malloc_debug_level) {
371 case 1:
372 case 5:
373 case 10:
374 so_name = "libc_malloc_debug_leak.so";
375 break;
376 case 20:
377 // Quick check: debug level 20 can only be handled in emulator.
378 if (!qemu_running) {
379 error_log("%s: Debug level %d can only be set in emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700380 getprogname(), g_malloc_debug_level);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700381 return;
382 }
383 // Make sure that memory checking has been enabled in emulator.
384 if (!memcheck_enabled) {
385 error_log("%s: Memory checking is not enabled in the emulator\n", getprogname());
386 return;
387 }
388 so_name = "libc_malloc_debug_qemu.so";
389 break;
390 default:
391 error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
392 return;
393 }
394
395 // Load .so that implements the required malloc debugging functionality.
396 void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
397 if (malloc_impl_handle == NULL) {
398 error_log("%s: Missing module %s required for malloc debug level %d: %s",
399 getprogname(), so_name, g_malloc_debug_level, dlerror());
400 return;
401 }
402
403 // Initialize malloc debugging in the loaded module.
404 malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
405 "malloc_debug_initialize"));
406 if (malloc_debug_initialize == NULL) {
407 error_log("%s: Initialization routine is not found in %s\n", getprogname(), so_name);
408 dlclose(malloc_impl_handle);
409 return;
410 }
411 if (malloc_debug_initialize(&g_hash_table) == -1) {
412 dlclose(malloc_impl_handle);
413 return;
414 }
415
416 if (g_malloc_debug_level == 20) {
417 // For memory checker we need to do extra initialization.
418 typedef int (*MemCheckInit)(int, const char*);
419 MemCheckInit memcheck_initialize =
420 reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle, "memcheck_initialize"));
421 if (memcheck_initialize == NULL) {
422 error_log("%s: memcheck_initialize routine is not found in %s\n",
423 getprogname(), so_name);
424 dlclose(malloc_impl_handle);
425 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800426 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700427
428 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
429 dlclose(malloc_impl_handle);
430 return;
431 }
432 }
433
434 // No need to init the dispatch table because we can only get
435 // here if debug level is 1, 5, 10, or 20.
436 static MallocDebug malloc_dispatch_table __attribute__((aligned(32)));
437 switch (g_malloc_debug_level) {
438 case 1:
439 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
440 break;
441 case 5:
442 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
443 break;
444 case 10:
445 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
446 break;
447 case 20:
448 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
449 break;
450 default:
451 break;
452 }
453
454 // Make sure dispatch table is initialized
455 if ((malloc_dispatch_table.calloc == NULL) ||
456 (malloc_dispatch_table.free == NULL) ||
457 (malloc_dispatch_table.mallinfo == NULL) ||
458 (malloc_dispatch_table.malloc == NULL) ||
459 (malloc_dispatch_table.malloc_usable_size == NULL) ||
460 (malloc_dispatch_table.memalign == NULL) ||
461 (malloc_dispatch_table.posix_memalign == NULL) ||
Dan Alberte5fdaa42014-06-14 01:04:31 +0000462#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisa4037802014-06-09 19:14:11 -0700463 (malloc_dispatch_table.pvalloc == NULL) ||
Dan Alberte5fdaa42014-06-14 01:04:31 +0000464#endif
465 (malloc_dispatch_table.realloc == NULL)
466#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
467 || (malloc_dispatch_table.valloc == NULL)
468#endif
469 ) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700470 error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
471 getprogname(), g_malloc_debug_level);
472 dlclose(malloc_impl_handle);
473 } else {
474 __libc_malloc_dispatch = &malloc_dispatch_table;
475 libc_malloc_impl_handle = malloc_impl_handle;
476 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800477}
478
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700479static void malloc_fini_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700480 // Our BSD stdio implementation doesn't close the standard streams, it only flushes them.
481 // And it doesn't do that until its atexit handler is run, and we run first!
482 // It's great that other unclosed FILE*s show up as malloc leaks, but we need to manually
483 // clean up the standard streams ourselves.
484 fclose(stdin);
485 fclose(stdout);
486 fclose(stderr);
Elliott Hughes1e980b62013-01-17 18:36:06 -0800487
Christopher Ferrisa4037802014-06-09 19:14:11 -0700488 if (libc_malloc_impl_handle != NULL) {
489 MallocDebugFini malloc_debug_finalize =
490 reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle, "malloc_debug_finalize"));
491 if (malloc_debug_finalize != NULL) {
492 malloc_debug_finalize(g_malloc_debug_level);
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700493 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700494 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700495}
496
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800497#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800498
Christopher Ferrisa4037802014-06-09 19:14:11 -0700499// Initializes memory allocation framework.
500// This routine is called from __libc_init routines implemented
501// in libc_init_static.c and libc_init_dynamic.c files.
Kito Chengea489742013-04-12 16:13:34 +0800502extern "C" __LIBC_HIDDEN__ void malloc_debug_init() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700503#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700504 static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
505 if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
506 error_log("Unable to initialize malloc_debug component.");
507 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700508#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800509}
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700510
Kito Chengea489742013-04-12 16:13:34 +0800511extern "C" __LIBC_HIDDEN__ void malloc_debug_fini() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700512#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700513 static pthread_once_t malloc_fini_once_ctl = PTHREAD_ONCE_INIT;
514 if (pthread_once(&malloc_fini_once_ctl, malloc_fini_impl)) {
515 error_log("Unable to finalize malloc_debug component.");
516 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700517#endif // !LIBC_STATIC
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700518}