2 * Copyright (C) 2009 The Android Open Source Project
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
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
29 // Contains a thin layer that calls whatever real native allocator
30 // has been defined. For the libc shared library, this allows the
31 // implementation of a debug malloc that can intercept all of the allocation
32 // calls and add special debugging code to attempt to catch allocation
33 // errors. All of the debugging code is implemented in a separate shared
34 // library that is only loaded when the property "libc.debug.malloc.options"
35 // is set to a non-zero value. There are two functions exported to
36 // allow ddms, or other external users to get information from the debug
38 // get_malloc_leak_info: Returns information about all of the known native
39 // allocations that are currently in use.
40 // free_malloc_leak_info: Frees the data allocated by the call to
41 // get_malloc_leak_info.
45 #include <private/bionic_config.h>
46 #include <private/bionic_globals.h>
47 #include <private/bionic_malloc_dispatch.h>
50 #define Malloc(function) je_ ## function
52 static constexpr MallocDispatch __libc_malloc_default_dispatch
53 __attribute__((unused)) = {
58 Malloc(malloc_usable_size),
60 Malloc(posix_memalign),
61 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
65 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
69 Malloc(malloc_disable),
70 Malloc(malloc_enable),
73 // In a VM process, this is set to 1 after fork()ing out of zygote.
74 int gMallocLeakZygoteChild = 0;
76 // =============================================================================
77 // Allocation functions
78 // =============================================================================
79 extern "C" void* calloc(size_t n_elements, size_t elem_size) {
80 auto _calloc = __libc_globals->malloc_dispatch.calloc;
81 if (__predict_false(_calloc != nullptr)) {
82 return _calloc(n_elements, elem_size);
84 return Malloc(calloc)(n_elements, elem_size);
87 extern "C" void free(void* mem) {
88 auto _free = __libc_globals->malloc_dispatch.free;
89 if (__predict_false(_free != nullptr)) {
96 extern "C" struct mallinfo mallinfo() {
97 auto _mallinfo = __libc_globals->malloc_dispatch.mallinfo;
98 if (__predict_false(_mallinfo != nullptr)) {
101 return Malloc(mallinfo)();
104 extern "C" void* malloc(size_t bytes) {
105 auto _malloc = __libc_globals->malloc_dispatch.malloc;
106 if (__predict_false(_malloc != nullptr)) {
107 return _malloc(bytes);
109 return Malloc(malloc)(bytes);
112 extern "C" size_t malloc_usable_size(const void* mem) {
113 auto _malloc_usable_size = __libc_globals->malloc_dispatch.malloc_usable_size;
114 if (__predict_false(_malloc_usable_size != nullptr)) {
115 return _malloc_usable_size(mem);
117 return Malloc(malloc_usable_size)(mem);
120 extern "C" void* memalign(size_t alignment, size_t bytes) {
121 auto _memalign = __libc_globals->malloc_dispatch.memalign;
122 if (__predict_false(_memalign != nullptr)) {
123 return _memalign(alignment, bytes);
125 return Malloc(memalign)(alignment, bytes);
128 extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
129 auto _posix_memalign = __libc_globals->malloc_dispatch.posix_memalign;
130 if (__predict_false(_posix_memalign != nullptr)) {
131 return _posix_memalign(memptr, alignment, size);
133 return Malloc(posix_memalign)(memptr, alignment, size);
136 extern "C" void* realloc(void* old_mem, size_t bytes) {
137 auto _realloc = __libc_globals->malloc_dispatch.realloc;
138 if (__predict_false(_realloc != nullptr)) {
139 return _realloc(old_mem, bytes);
141 return Malloc(realloc)(old_mem, bytes);
144 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
145 extern "C" void* pvalloc(size_t bytes) {
146 auto _pvalloc = __libc_globals->malloc_dispatch.pvalloc;
147 if (__predict_false(_pvalloc != nullptr)) {
148 return _pvalloc(bytes);
150 return Malloc(pvalloc)(bytes);
153 extern "C" void* valloc(size_t bytes) {
154 auto _valloc = __libc_globals->malloc_dispatch.valloc;
155 if (__predict_false(_valloc != nullptr)) {
156 return _valloc(bytes);
158 return Malloc(valloc)(bytes);
162 // We implement malloc debugging only in libc.so, so the code below
163 // must be excluded if we compile this file for static libc.a
164 #if !defined(LIBC_STATIC)
170 #include <private/libc_logging.h>
171 #include <sys/system_properties.h>
173 extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
175 static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
176 static const char* DEBUG_MALLOC_PROPERTY_OPTIONS = "libc.debug.malloc.options";
177 static const char* DEBUG_MALLOC_PROPERTY_PROGRAM = "libc.debug.malloc.program";
178 static const char* DEBUG_MALLOC_ENV_OPTIONS = "LIBC_DEBUG_MALLOC_OPTIONS";
180 static void* libc_malloc_impl_handle = nullptr;
182 static void (*g_debug_finalize_func)();
183 static void (*g_debug_get_malloc_leak_info_func)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
184 static void (*g_debug_free_malloc_leak_info_func)(uint8_t*);
185 static ssize_t (*g_debug_malloc_backtrace_func)(void*, uintptr_t*, size_t);
187 // =============================================================================
189 // =============================================================================
190 #define error_log(format, ...) \
191 __libc_format_log(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
192 #define info_log(format, ...) \
193 __libc_format_log(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
194 // =============================================================================
196 // =============================================================================
197 // Exported for use by ddms.
198 // =============================================================================
200 // Retrieve native heap information.
202 // "*info" is set to a buffer we allocate
203 // "*overall_size" is set to the size of the "info" buffer
204 // "*info_size" is set to the size of a single entry
205 // "*total_memory" is set to the sum of all allocations we're tracking; does
206 // not include heap overhead
207 // "*backtrace_size" is set to the maximum number of entries in the back trace
208 extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
209 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
210 if (g_debug_get_malloc_leak_info_func == nullptr) {
213 g_debug_get_malloc_leak_info_func(info, overall_size, info_size, total_memory, backtrace_size);
216 extern "C" void free_malloc_leak_info(uint8_t* info) {
217 if (g_debug_free_malloc_leak_info_func == nullptr) {
220 g_debug_free_malloc_leak_info_func(info);
223 // =============================================================================
225 template<typename FunctionType>
226 static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
228 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
229 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
230 if (*func == nullptr) {
231 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
237 static bool InitMalloc(void* malloc_impl_handler, MallocDispatch* table, const char* prefix) {
238 if (!InitMallocFunction<MallocCalloc>(malloc_impl_handler, &table->calloc,
242 if (!InitMallocFunction<MallocFree>(malloc_impl_handler, &table->free,
246 if (!InitMallocFunction<MallocMallinfo>(malloc_impl_handler, &table->mallinfo,
247 prefix, "mallinfo")) {
250 if (!InitMallocFunction<MallocMalloc>(malloc_impl_handler, &table->malloc,
254 if (!InitMallocFunction<MallocMallocUsableSize>(
255 malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size")) {
258 if (!InitMallocFunction<MallocMemalign>(malloc_impl_handler, &table->memalign,
259 prefix, "memalign")) {
262 if (!InitMallocFunction<MallocPosixMemalign>(malloc_impl_handler, &table->posix_memalign,
263 prefix, "posix_memalign")) {
266 if (!InitMallocFunction<MallocRealloc>(malloc_impl_handler, &table->realloc,
267 prefix, "realloc")) {
270 if (!InitMallocFunction<MallocIterate>(malloc_impl_handler, &table->iterate,
271 prefix, "iterate")) {
274 if (!InitMallocFunction<MallocMallocDisable>(malloc_impl_handler, &table->malloc_disable,
275 prefix, "malloc_disable")) {
278 if (!InitMallocFunction<MallocMallocEnable>(malloc_impl_handler, &table->malloc_enable,
279 prefix, "malloc_enable")) {
282 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
283 if (!InitMallocFunction<MallocPvalloc>(malloc_impl_handler, &table->pvalloc,
284 prefix, "pvalloc")) {
287 if (!InitMallocFunction<MallocValloc>(malloc_impl_handler, &table->valloc,
296 static void malloc_fini_impl(void*) {
297 // Our BSD stdio implementation doesn't close the standard streams,
298 // it only flushes them. Other unclosed FILE*s will show up as
299 // malloc leaks, but to avoid the standard streams showing up in
300 // leak reports, close them here.
305 g_debug_finalize_func();
308 // Initializes memory allocation framework once per process.
309 static void malloc_init_impl(libc_globals* globals) {
310 char value[PROP_VALUE_MAX];
312 // If DEBUG_MALLOC_ENV_OPTIONS is set then it overrides the system properties.
313 const char* options = getenv(DEBUG_MALLOC_ENV_OPTIONS);
314 if (options == nullptr || options[0] == '\0') {
315 if (__system_property_get(DEBUG_MALLOC_PROPERTY_OPTIONS, value) == 0 || value[0] == '\0') {
320 // Check to see if only a specific program should have debug malloc enabled.
321 char program[PROP_VALUE_MAX];
322 if (__system_property_get(DEBUG_MALLOC_PROPERTY_PROGRAM, program) != 0 &&
323 strstr(getprogname(), program) == nullptr) {
328 // Load the debug malloc shared library.
329 void* malloc_impl_handle = dlopen(DEBUG_SHARED_LIB, RTLD_NOW | RTLD_LOCAL);
330 if (malloc_impl_handle == nullptr) {
331 error_log("%s: Unable to open debug malloc shared library %s: %s",
332 getprogname(), DEBUG_SHARED_LIB, dlerror());
336 // Initialize malloc debugging in the loaded module.
337 auto init_func = reinterpret_cast<bool (*)(const MallocDispatch*, int*, const char*)>(
338 dlsym(malloc_impl_handle, "debug_initialize"));
339 if (init_func == nullptr) {
340 error_log("%s: debug_initialize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
341 dlclose(malloc_impl_handle);
345 // Get the syms for the external functions.
346 void* finalize_sym = dlsym(malloc_impl_handle, "debug_finalize");
347 if (finalize_sym == nullptr) {
348 error_log("%s: debug_finalize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
349 dlclose(malloc_impl_handle);
353 void* get_leak_info_sym = dlsym(malloc_impl_handle, "debug_get_malloc_leak_info");
354 if (get_leak_info_sym == nullptr) {
355 error_log("%s: debug_get_malloc_leak_info routine not found in %s", getprogname(),
357 dlclose(malloc_impl_handle);
361 void* free_leak_info_sym = dlsym(malloc_impl_handle, "debug_free_malloc_leak_info");
362 if (free_leak_info_sym == nullptr) {
363 error_log("%s: debug_free_malloc_leak_info routine not found in %s", getprogname(),
365 dlclose(malloc_impl_handle);
369 void* malloc_backtrace_sym = dlsym(malloc_impl_handle, "debug_malloc_backtrace");
370 if (malloc_backtrace_sym == nullptr) {
371 error_log("%s: debug_malloc_backtrace routine not found in %s", getprogname(),
373 dlclose(malloc_impl_handle);
377 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
378 dlclose(malloc_impl_handle);
382 MallocDispatch malloc_dispatch_table;
383 if (!InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "debug")) {
384 auto finalize_func = reinterpret_cast<void (*)()>(finalize_sym);
386 dlclose(malloc_impl_handle);
390 g_debug_finalize_func = reinterpret_cast<void (*)()>(finalize_sym);
391 g_debug_get_malloc_leak_info_func = reinterpret_cast<void (*)(
392 uint8_t**, size_t*, size_t*, size_t*, size_t*)>(get_leak_info_sym);
393 g_debug_free_malloc_leak_info_func = reinterpret_cast<void (*)(uint8_t*)>(free_leak_info_sym);
394 g_debug_malloc_backtrace_func = reinterpret_cast<ssize_t (*)(
395 void*, uintptr_t*, size_t)>(malloc_backtrace_sym);
397 globals->malloc_dispatch = malloc_dispatch_table;
398 libc_malloc_impl_handle = malloc_impl_handle;
400 info_log("%s: malloc debug enabled", getprogname());
402 // Use atexit to trigger the cleanup function. This avoids a problem
403 // where another atexit function is used to cleanup allocated memory,
404 // but the finalize function was already called. This particular error
405 // seems to be triggered by a zygote spawned process calling exit.
406 int ret_value = __cxa_atexit(malloc_fini_impl, nullptr, nullptr);
407 if (ret_value != 0) {
408 error_log("failed to set atexit cleanup function: %d", ret_value);
412 // Initializes memory allocation framework.
413 // This routine is called from __libc_init routines in libc_init_dynamic.cpp.
414 __LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
415 malloc_init_impl(globals);
417 #endif // !LIBC_STATIC
419 // =============================================================================
420 // Exported for use by libmemunreachable.
421 // =============================================================================
423 // Calls callback for every allocation in the anonymous heap mapping
424 // [base, base+size). Must be called between malloc_disable and malloc_enable.
425 extern "C" int malloc_iterate(uintptr_t base, size_t size,
426 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
427 auto _iterate = __libc_globals->malloc_dispatch.iterate;
428 if (__predict_false(_iterate != nullptr)) {
429 return _iterate(base, size, callback, arg);
431 return Malloc(iterate)(base, size, callback, arg);
434 // Disable calls to malloc so malloc_iterate gets a consistent view of
436 extern "C" void malloc_disable() {
437 auto _malloc_disable = __libc_globals->malloc_dispatch.malloc_disable;
438 if (__predict_false(_malloc_disable != nullptr)) {
439 return _malloc_disable();
441 return Malloc(malloc_disable)();
444 // Re-enable calls to malloc after a previous call to malloc_disable.
445 extern "C" void malloc_enable() {
446 auto _malloc_enable = __libc_globals->malloc_dispatch.malloc_enable;
447 if (__predict_false(_malloc_enable != nullptr)) {
448 return _malloc_enable();
450 return Malloc(malloc_enable)();
454 extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
455 if (g_debug_malloc_backtrace_func == nullptr) {
458 return g_debug_malloc_backtrace_func(pointer, frames, frame_count);
461 extern "C" ssize_t malloc_backtrace(void*, uintptr_t*, size_t) {