blob: 6677c22e3f54b4491b190e92068def26115a8476 [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),
64 Malloc(pvalloc),
65 Malloc(realloc),
66 Malloc(valloc),
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070067};
68
69// Selector of dispatch table to use for dispatching malloc calls.
Elliott Hughes14442bb2014-06-04 15:18:36 -070070// TODO: fix http://b/15432753 and make this static again.
71const MallocDebug* __libc_malloc_dispatch = &__libc_malloc_default_dispatch;
Elliott Hughes8e52e8f2014-06-04 12:07:11 -070072
73// Handle to shared library where actual memory allocation is implemented.
74// This library is loaded and memory allocation calls are redirected there
75// when libc.debug.malloc environment variable contains value other than
76// zero:
77// 1 - For memory leak detections.
78// 5 - For filling allocated / freed memory with patterns defined by
79// CHK_SENTINEL_VALUE, and CHK_FILL_FREE macros.
80// 10 - For adding pre-, and post- allocation stubs in order to detect
81// buffer overruns.
82// Note that emulator's memory allocation instrumentation is not controlled by
83// libc.debug.malloc value, but rather by emulator, started with -memcheck
84// option. Note also, that if emulator has started with -memcheck option,
85// emulator's instrumented memory allocation will take over value saved in
86// libc.debug.malloc. In other words, if emulator has started with -memcheck
87// option, libc.debug.malloc value is ignored.
88// Actual functionality for debug levels 1-10 is implemented in
89// libc_malloc_debug_leak.so, while functionality for emulator's instrumented
90// allocations is implemented in libc_malloc_debug_qemu.so and can be run inside
91// the emulator only.
92#if !defined(LIBC_STATIC)
93static void* libc_malloc_impl_handle = NULL;
94#endif
95
96
97// The value of libc.debug.malloc.
98#if !defined(LIBC_STATIC)
99static int g_malloc_debug_level = 0;
100#endif
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800101
102// =============================================================================
103// output functions
104// =============================================================================
105
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700106static int hash_entry_compare(const void* arg1, const void* arg2) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700107 int result;
Christopher Tate52e7d3d2010-08-09 13:43:46 -0700108
Christopher Ferrisa4037802014-06-09 19:14:11 -0700109 const HashEntry* e1 = *static_cast<HashEntry* const*>(arg1);
110 const HashEntry* e2 = *static_cast<HashEntry* const*>(arg2);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800111
Christopher Ferrisa4037802014-06-09 19:14:11 -0700112 // if one or both arg pointers are null, deal gracefully
113 if (e1 == NULL) {
114 result = (e2 == NULL) ? 0 : 1;
115 } else if (e2 == NULL) {
116 result = -1;
117 } else {
118 size_t nbAlloc1 = e1->allocations;
119 size_t nbAlloc2 = e2->allocations;
120 size_t size1 = e1->size & ~SIZE_FLAG_MASK;
121 size_t size2 = e2->size & ~SIZE_FLAG_MASK;
122 size_t alloc1 = nbAlloc1 * size1;
123 size_t alloc2 = nbAlloc2 * size2;
124
125 // sort in descending order by:
126 // 1) total size
127 // 2) number of allocations
128 //
129 // This is used for sorting, not determination of equality, so we don't
130 // need to compare the bit flags.
131 if (alloc1 > alloc2) {
132 result = -1;
133 } else if (alloc1 < alloc2) {
134 result = 1;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800135 } else {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700136 if (nbAlloc1 > nbAlloc2) {
137 result = -1;
138 } else if (nbAlloc1 < nbAlloc2) {
139 result = 1;
140 } else {
141 result = 0;
142 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800143 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700144 }
145 return result;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800146}
147
Christopher Ferrisa4037802014-06-09 19:14:11 -0700148// Retrieve native heap information.
149//
150// "*info" is set to a buffer we allocate
151// "*overallSize" is set to the size of the "info" buffer
152// "*infoSize" is set to the size of a single entry
153// "*totalMemory" is set to the sum of all allocations we're tracking; does
154// not include heap overhead
155// "*backtraceSize" is set to the maximum number of entries in the back trace
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700156
Christopher Ferrisa4037802014-06-09 19:14:11 -0700157// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700158// Exported for use by ddms.
Christopher Ferrisa4037802014-06-09 19:14:11 -0700159// =============================================================================
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700160extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
Christopher Ferrisa4037802014-06-09 19:14:11 -0700161 size_t* infoSize, size_t* totalMemory, size_t* backtraceSize) {
162 // Don't do anything if we have invalid arguments.
163 if (info == NULL || overallSize == NULL || infoSize == NULL ||
164 totalMemory == NULL || backtraceSize == NULL) {
165 return;
166 }
167 *totalMemory = 0;
168
169 ScopedPthreadMutexLocker locker(&g_hash_table.lock);
170 if (g_hash_table.count == 0) {
171 *info = NULL;
172 *overallSize = 0;
173 *infoSize = 0;
174 *backtraceSize = 0;
175 return;
176 }
177
178 HashEntry** list = static_cast<HashEntry**>(Malloc(malloc)(sizeof(void*) * g_hash_table.count));
179
180 // Get the entries into an array to be sorted.
181 size_t index = 0;
182 for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
183 HashEntry* entry = g_hash_table.slots[i];
184 while (entry != NULL) {
185 list[index] = entry;
186 *totalMemory = *totalMemory + ((entry->size & ~SIZE_FLAG_MASK) * entry->allocations);
187 index++;
188 entry = entry->next;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800189 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700190 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800191
Christopher Ferrisa4037802014-06-09 19:14:11 -0700192 // XXX: the protocol doesn't allow variable size for the stack trace (yet)
193 *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
194 *overallSize = *infoSize * g_hash_table.count;
195 *backtraceSize = BACKTRACE_SIZE;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800196
Christopher Ferrisa4037802014-06-09 19:14:11 -0700197 // now get a byte array big enough for this
198 *info = static_cast<uint8_t*>(Malloc(malloc)(*overallSize));
199 if (*info == NULL) {
200 *overallSize = 0;
Christopher Ferris72bbd422014-05-08 11:14:03 -0700201 Malloc(free)(list);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700202 return;
203 }
204
205 qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
206
207 uint8_t* head = *info;
208 const size_t count = g_hash_table.count;
209 for (size_t i = 0 ; i < count ; ++i) {
210 HashEntry* entry = list[i];
211 size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
212 if (entrySize < *infoSize) {
213 // We're writing less than a full entry, clear out the rest.
214 memset(head + entrySize, 0, *infoSize - entrySize);
215 } else {
216 // Make sure the amount we're copying doesn't exceed the limit.
217 entrySize = *infoSize;
218 }
219 memcpy(head, &(entry->size), entrySize);
220 head += *infoSize;
221 }
222
223 Malloc(free)(list);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800224}
225
Elliott Hughes7c9923d2014-05-16 16:29:55 -0700226extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700227 Malloc(free)(info);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800228}
229
Christopher Ferrisa4037802014-06-09 19:14:11 -0700230// =============================================================================
231// Allocation functions
232// =============================================================================
233extern "C" void* calloc(size_t n_elements, size_t elem_size) {
234 return __libc_malloc_dispatch->calloc(n_elements, elem_size);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800235}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700236
237extern "C" void free(void* mem) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700238 __libc_malloc_dispatch->free(mem);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800239}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700240
Christopher Ferrisa4037802014-06-09 19:14:11 -0700241extern "C" struct mallinfo mallinfo() {
242 return __libc_malloc_dispatch->mallinfo();
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" void* malloc(size_t bytes) {
246 return __libc_malloc_dispatch->malloc(bytes);
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800247}
248
Christopher Ferris885f3b92013-05-21 17:48:01 -0700249extern "C" size_t malloc_usable_size(const void* mem) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700250 return __libc_malloc_dispatch->malloc_usable_size(mem);
Christopher Ferris885f3b92013-05-21 17:48:01 -0700251}
252
Christopher Ferrisa4037802014-06-09 19:14:11 -0700253extern "C" void* memalign(size_t alignment, size_t bytes) {
254 return __libc_malloc_dispatch->memalign(alignment, bytes);
255}
256
257extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
258 return __libc_malloc_dispatch->posix_memalign(memptr, alignment, size);
259}
260
261extern "C" void* pvalloc(size_t bytes) {
262 return __libc_malloc_dispatch->pvalloc(bytes);
263}
264
265extern "C" void* realloc(void* oldMem, size_t bytes) {
266 return __libc_malloc_dispatch->realloc(oldMem, bytes);
267}
268
269extern "C" void* valloc(size_t bytes) {
270 return __libc_malloc_dispatch->valloc(bytes);
271}
272
273// We implement malloc debugging only in libc.so, so the code below
274// must be excluded if we compile this file for static libc.a
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800275#ifndef LIBC_STATIC
276#include <sys/system_properties.h>
277#include <dlfcn.h>
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700278#include <stdio.h>
Elliott Hugheseb847bc2013-10-09 15:50:50 -0700279#include "private/libc_logging.h"
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800280
Christopher Ferris885f3b92013-05-21 17:48:01 -0700281template<typename FunctionType>
Nick Kralevich35c18622013-10-03 14:59:05 -0700282static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700283 char symbol[128];
284 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
285 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
286 if (*func == NULL) {
287 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
288 }
Christopher Ferris885f3b92013-05-21 17:48:01 -0700289}
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700290
Christopher Ferris885f3b92013-05-21 17:48:01 -0700291static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700292 __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
293 getprogname(), g_malloc_debug_level, prefix);
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700294
Christopher Ferrisa4037802014-06-09 19:14:11 -0700295 InitMallocFunction<MallocDebugCalloc>(malloc_impl_handler, &table->calloc, prefix, "calloc");
296 InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
297 InitMallocFunction<MallocDebugMallinfo>(malloc_impl_handler, &table->mallinfo, prefix, "mallinfo");
298 InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
299 InitMallocFunction<MallocDebugMallocUsableSize>(malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size");
300 InitMallocFunction<MallocDebugMemalign>(malloc_impl_handler, &table->memalign, prefix, "memalign");
301 InitMallocFunction<MallocDebugPosixMemalign>(malloc_impl_handler, &table->posix_memalign, prefix, "posix_memalign");
302 InitMallocFunction<MallocDebugPvalloc>(malloc_impl_handler, &table->pvalloc, prefix, "pvalloc");
303 InitMallocFunction<MallocDebugRealloc>(malloc_impl_handler, &table->realloc, prefix, "realloc");
304 InitMallocFunction<MallocDebugValloc>(malloc_impl_handler, &table->valloc, prefix, "valloc");
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700305}
306
Christopher Ferrisa4037802014-06-09 19:14:11 -0700307// Initializes memory allocation framework once per process.
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700308static void malloc_init_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700309 const char* so_name = NULL;
310 MallocDebugInit malloc_debug_initialize = NULL;
311 unsigned int qemu_running = 0;
312 unsigned int memcheck_enabled = 0;
313 char env[PROP_VALUE_MAX];
314 char memcheck_tracing[PROP_VALUE_MAX];
315 char debug_program[PROP_VALUE_MAX];
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800316
Christopher Ferrisa4037802014-06-09 19:14:11 -0700317 // Get custom malloc debug level. Note that emulator started with
318 // memory checking option will have priority over debug level set in
319 // libc.debug.malloc system property.
320 if (__system_property_get("ro.kernel.qemu", env) && atoi(env)) {
321 qemu_running = 1;
322 if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
323 if (memcheck_tracing[0] != '0') {
324 // Emulator has started with memory tracing enabled. Enforce it.
325 g_malloc_debug_level = 20;
326 memcheck_enabled = 1;
327 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800328 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700329 }
Vladimir Chtchetkine75fba682010-02-12 08:59:58 -0800330
Christopher Ferrisa4037802014-06-09 19:14:11 -0700331 // If debug level has not been set by memcheck option in the emulator,
332 // lets grab it from libc.debug.malloc system property.
333 if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
334 g_malloc_debug_level = atoi(env);
335 }
336
337 // Debug level 0 means that we should use default allocation routines.
338 if (g_malloc_debug_level == 0) {
339 return;
340 }
341
342 // If libc.debug.malloc.program is set and is not a substring of progname,
343 // then exit.
344 if (__system_property_get("libc.debug.malloc.program", debug_program)) {
345 if (!strstr(getprogname(), debug_program)) {
346 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800347 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700348 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800349
Christopher Ferrisa4037802014-06-09 19:14:11 -0700350 // mksh is way too leaky. http://b/7291287.
351 if (g_malloc_debug_level >= 10) {
352 if (strcmp(getprogname(), "sh") == 0 || strcmp(getprogname(), "/system/bin/sh") == 0) {
353 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800354 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700355 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800356
Christopher Ferrisa4037802014-06-09 19:14:11 -0700357 // Choose the appropriate .so for the requested debug level.
358 switch (g_malloc_debug_level) {
359 case 1:
360 case 5:
361 case 10:
362 so_name = "libc_malloc_debug_leak.so";
363 break;
364 case 20:
365 // Quick check: debug level 20 can only be handled in emulator.
366 if (!qemu_running) {
367 error_log("%s: Debug level %d can only be set in emulator\n",
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700368 getprogname(), g_malloc_debug_level);
Christopher Ferrisa4037802014-06-09 19:14:11 -0700369 return;
370 }
371 // Make sure that memory checking has been enabled in emulator.
372 if (!memcheck_enabled) {
373 error_log("%s: Memory checking is not enabled in the emulator\n", getprogname());
374 return;
375 }
376 so_name = "libc_malloc_debug_qemu.so";
377 break;
378 default:
379 error_log("%s: Debug level %d is unknown\n", getprogname(), g_malloc_debug_level);
380 return;
381 }
382
383 // Load .so that implements the required malloc debugging functionality.
384 void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
385 if (malloc_impl_handle == NULL) {
386 error_log("%s: Missing module %s required for malloc debug level %d: %s",
387 getprogname(), so_name, g_malloc_debug_level, dlerror());
388 return;
389 }
390
391 // Initialize malloc debugging in the loaded module.
392 malloc_debug_initialize = reinterpret_cast<MallocDebugInit>(dlsym(malloc_impl_handle,
393 "malloc_debug_initialize"));
394 if (malloc_debug_initialize == NULL) {
395 error_log("%s: Initialization routine is not found in %s\n", getprogname(), so_name);
396 dlclose(malloc_impl_handle);
397 return;
398 }
399 if (malloc_debug_initialize(&g_hash_table) == -1) {
400 dlclose(malloc_impl_handle);
401 return;
402 }
403
404 if (g_malloc_debug_level == 20) {
405 // For memory checker we need to do extra initialization.
406 typedef int (*MemCheckInit)(int, const char*);
407 MemCheckInit memcheck_initialize =
408 reinterpret_cast<MemCheckInit>(dlsym(malloc_impl_handle, "memcheck_initialize"));
409 if (memcheck_initialize == NULL) {
410 error_log("%s: memcheck_initialize routine is not found in %s\n",
411 getprogname(), so_name);
412 dlclose(malloc_impl_handle);
413 return;
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800414 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700415
416 if (memcheck_initialize(MALLOC_ALIGNMENT, memcheck_tracing)) {
417 dlclose(malloc_impl_handle);
418 return;
419 }
420 }
421
422 // No need to init the dispatch table because we can only get
423 // here if debug level is 1, 5, 10, or 20.
424 static MallocDebug malloc_dispatch_table __attribute__((aligned(32)));
425 switch (g_malloc_debug_level) {
426 case 1:
427 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "leak");
428 break;
429 case 5:
430 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "fill");
431 break;
432 case 10:
433 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "chk");
434 break;
435 case 20:
436 InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "qemu_instrumented");
437 break;
438 default:
439 break;
440 }
441
442 // Make sure dispatch table is initialized
443 if ((malloc_dispatch_table.calloc == NULL) ||
444 (malloc_dispatch_table.free == NULL) ||
445 (malloc_dispatch_table.mallinfo == NULL) ||
446 (malloc_dispatch_table.malloc == NULL) ||
447 (malloc_dispatch_table.malloc_usable_size == NULL) ||
448 (malloc_dispatch_table.memalign == NULL) ||
449 (malloc_dispatch_table.posix_memalign == NULL) ||
450 (malloc_dispatch_table.pvalloc == NULL) ||
451 (malloc_dispatch_table.realloc == NULL) ||
452 (malloc_dispatch_table.valloc == NULL)) {
453 error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
454 getprogname(), g_malloc_debug_level);
455 dlclose(malloc_impl_handle);
456 } else {
457 __libc_malloc_dispatch = &malloc_dispatch_table;
458 libc_malloc_impl_handle = malloc_impl_handle;
459 }
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800460}
461
Elliott Hughesc4d1fec2012-08-28 14:15:04 -0700462static void malloc_fini_impl() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700463 // Our BSD stdio implementation doesn't close the standard streams, it only flushes them.
464 // And it doesn't do that until its atexit handler is run, and we run first!
465 // It's great that other unclosed FILE*s show up as malloc leaks, but we need to manually
466 // clean up the standard streams ourselves.
467 fclose(stdin);
468 fclose(stdout);
469 fclose(stderr);
Elliott Hughes1e980b62013-01-17 18:36:06 -0800470
Christopher Ferrisa4037802014-06-09 19:14:11 -0700471 if (libc_malloc_impl_handle != NULL) {
472 MallocDebugFini malloc_debug_finalize =
473 reinterpret_cast<MallocDebugFini>(dlsym(libc_malloc_impl_handle, "malloc_debug_finalize"));
474 if (malloc_debug_finalize != NULL) {
475 malloc_debug_finalize(g_malloc_debug_level);
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700476 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700477 }
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700478}
479
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800480#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800481
Christopher Ferrisa4037802014-06-09 19:14:11 -0700482// Initializes memory allocation framework.
483// This routine is called from __libc_init routines implemented
484// in libc_init_static.c and libc_init_dynamic.c files.
Kito Chengea489742013-04-12 16:13:34 +0800485extern "C" __LIBC_HIDDEN__ void malloc_debug_init() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700486#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700487 static pthread_once_t malloc_init_once_ctl = PTHREAD_ONCE_INIT;
488 if (pthread_once(&malloc_init_once_ctl, malloc_init_impl)) {
489 error_log("Unable to initialize malloc_debug component.");
490 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700491#endif // !LIBC_STATIC
Vladimir Chtchetkineb74ceb22009-11-17 14:13:38 -0800492}
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700493
Kito Chengea489742013-04-12 16:13:34 +0800494extern "C" __LIBC_HIDDEN__ void malloc_debug_fini() {
Christopher Ferrisa4037802014-06-09 19:14:11 -0700495#if !defined(LIBC_STATIC)
Elliott Hughes8e52e8f2014-06-04 12:07:11 -0700496 static pthread_once_t malloc_fini_once_ctl = PTHREAD_ONCE_INIT;
497 if (pthread_once(&malloc_fini_once_ctl, malloc_fini_impl)) {
498 error_log("Unable to finalize malloc_debug component.");
499 }
Christopher Ferrisa4037802014-06-09 19:14:11 -0700500#endif // !LIBC_STATIC
Iliyan Malcheve1dd3c22012-05-29 14:22:42 -0700501}