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),
74 // In a VM process, this is set to 1 after fork()ing out of zygote.
75 int gMallocLeakZygoteChild = 0;
77 // =============================================================================
78 // Allocation functions
79 // =============================================================================
80 extern "C" void* calloc(size_t n_elements, size_t elem_size) {
81 auto _calloc = __libc_globals->malloc_dispatch.calloc;
82 if (__predict_false(_calloc != nullptr)) {
83 return _calloc(n_elements, elem_size);
85 return Malloc(calloc)(n_elements, elem_size);
88 extern "C" void free(void* mem) {
89 auto _free = __libc_globals->malloc_dispatch.free;
90 if (__predict_false(_free != nullptr)) {
97 extern "C" struct mallinfo mallinfo() {
98 auto _mallinfo = __libc_globals->malloc_dispatch.mallinfo;
99 if (__predict_false(_mallinfo != nullptr)) {
102 return Malloc(mallinfo)();
105 extern "C" int mallopt(int param, int value) {
106 auto _mallopt = __libc_globals->malloc_dispatch.mallopt;
107 if (__predict_false(_mallopt != nullptr)) {
108 return _mallopt(param, value);
110 return Malloc(mallopt)(param, value);
113 extern "C" void* malloc(size_t bytes) {
114 auto _malloc = __libc_globals->malloc_dispatch.malloc;
115 if (__predict_false(_malloc != nullptr)) {
116 return _malloc(bytes);
118 return Malloc(malloc)(bytes);
121 extern "C" size_t malloc_usable_size(const void* mem) {
122 auto _malloc_usable_size = __libc_globals->malloc_dispatch.malloc_usable_size;
123 if (__predict_false(_malloc_usable_size != nullptr)) {
124 return _malloc_usable_size(mem);
126 return Malloc(malloc_usable_size)(mem);
129 extern "C" void* memalign(size_t alignment, size_t bytes) {
130 auto _memalign = __libc_globals->malloc_dispatch.memalign;
131 if (__predict_false(_memalign != nullptr)) {
132 return _memalign(alignment, bytes);
134 return Malloc(memalign)(alignment, bytes);
137 extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
138 auto _posix_memalign = __libc_globals->malloc_dispatch.posix_memalign;
139 if (__predict_false(_posix_memalign != nullptr)) {
140 return _posix_memalign(memptr, alignment, size);
142 return Malloc(posix_memalign)(memptr, alignment, size);
145 extern "C" void* realloc(void* old_mem, size_t bytes) {
146 auto _realloc = __libc_globals->malloc_dispatch.realloc;
147 if (__predict_false(_realloc != nullptr)) {
148 return _realloc(old_mem, bytes);
150 return Malloc(realloc)(old_mem, bytes);
153 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
154 extern "C" void* pvalloc(size_t bytes) {
155 auto _pvalloc = __libc_globals->malloc_dispatch.pvalloc;
156 if (__predict_false(_pvalloc != nullptr)) {
157 return _pvalloc(bytes);
159 return Malloc(pvalloc)(bytes);
162 extern "C" void* valloc(size_t bytes) {
163 auto _valloc = __libc_globals->malloc_dispatch.valloc;
164 if (__predict_false(_valloc != nullptr)) {
165 return _valloc(bytes);
167 return Malloc(valloc)(bytes);
171 // We implement malloc debugging only in libc.so, so the code below
172 // must be excluded if we compile this file for static libc.a
173 #if !defined(LIBC_STATIC)
179 #include <async_safe/log.h>
180 #include <sys/system_properties.h>
182 extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
184 static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
185 static const char* DEBUG_MALLOC_PROPERTY_OPTIONS = "libc.debug.malloc.options";
186 static const char* DEBUG_MALLOC_PROPERTY_PROGRAM = "libc.debug.malloc.program";
187 static const char* DEBUG_MALLOC_ENV_OPTIONS = "LIBC_DEBUG_MALLOC_OPTIONS";
189 static void* libc_malloc_impl_handle = nullptr;
191 static void (*g_debug_finalize_func)();
192 static void (*g_debug_get_malloc_leak_info_func)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
193 static void (*g_debug_free_malloc_leak_info_func)(uint8_t*);
194 static ssize_t (*g_debug_malloc_backtrace_func)(void*, uintptr_t*, size_t);
196 // =============================================================================
198 // =============================================================================
199 #define error_log(format, ...) \
200 async_safe_format_log(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
201 #define info_log(format, ...) \
202 async_safe_format_log(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
203 // =============================================================================
205 // =============================================================================
206 // Exported for use by ddms.
207 // =============================================================================
209 // Retrieve native heap information.
211 // "*info" is set to a buffer we allocate
212 // "*overall_size" is set to the size of the "info" buffer
213 // "*info_size" is set to the size of a single entry
214 // "*total_memory" is set to the sum of all allocations we're tracking; does
215 // not include heap overhead
216 // "*backtrace_size" is set to the maximum number of entries in the back trace
217 extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
218 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
219 if (g_debug_get_malloc_leak_info_func == nullptr) {
222 g_debug_get_malloc_leak_info_func(info, overall_size, info_size, total_memory, backtrace_size);
225 extern "C" void free_malloc_leak_info(uint8_t* info) {
226 if (g_debug_free_malloc_leak_info_func == nullptr) {
229 g_debug_free_malloc_leak_info_func(info);
232 // =============================================================================
234 template<typename FunctionType>
235 static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
237 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
238 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
239 if (*func == nullptr) {
240 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
246 static bool InitMalloc(void* malloc_impl_handler, MallocDispatch* table, const char* prefix) {
247 if (!InitMallocFunction<MallocCalloc>(malloc_impl_handler, &table->calloc,
251 if (!InitMallocFunction<MallocFree>(malloc_impl_handler, &table->free,
255 if (!InitMallocFunction<MallocMallinfo>(malloc_impl_handler, &table->mallinfo,
256 prefix, "mallinfo")) {
259 if (!InitMallocFunction<MallocMallopt>(malloc_impl_handler, &table->mallopt,
260 prefix, "mallopt")) {
263 if (!InitMallocFunction<MallocMalloc>(malloc_impl_handler, &table->malloc,
267 if (!InitMallocFunction<MallocMallocUsableSize>(
268 malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size")) {
271 if (!InitMallocFunction<MallocMemalign>(malloc_impl_handler, &table->memalign,
272 prefix, "memalign")) {
275 if (!InitMallocFunction<MallocPosixMemalign>(malloc_impl_handler, &table->posix_memalign,
276 prefix, "posix_memalign")) {
279 if (!InitMallocFunction<MallocRealloc>(malloc_impl_handler, &table->realloc,
280 prefix, "realloc")) {
283 if (!InitMallocFunction<MallocIterate>(malloc_impl_handler, &table->iterate,
284 prefix, "iterate")) {
287 if (!InitMallocFunction<MallocMallocDisable>(malloc_impl_handler, &table->malloc_disable,
288 prefix, "malloc_disable")) {
291 if (!InitMallocFunction<MallocMallocEnable>(malloc_impl_handler, &table->malloc_enable,
292 prefix, "malloc_enable")) {
295 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
296 if (!InitMallocFunction<MallocPvalloc>(malloc_impl_handler, &table->pvalloc,
297 prefix, "pvalloc")) {
300 if (!InitMallocFunction<MallocValloc>(malloc_impl_handler, &table->valloc,
309 static void malloc_fini_impl(void*) {
310 // Our BSD stdio implementation doesn't close the standard streams,
311 // it only flushes them. Other unclosed FILE*s will show up as
312 // malloc leaks, but to avoid the standard streams showing up in
313 // leak reports, close them here.
318 g_debug_finalize_func();
321 // Initializes memory allocation framework once per process.
322 static void malloc_init_impl(libc_globals* globals) {
323 char value[PROP_VALUE_MAX];
325 // If DEBUG_MALLOC_ENV_OPTIONS is set then it overrides the system properties.
326 const char* options = getenv(DEBUG_MALLOC_ENV_OPTIONS);
327 if (options == nullptr || options[0] == '\0') {
328 if (__system_property_get(DEBUG_MALLOC_PROPERTY_OPTIONS, value) == 0 || value[0] == '\0') {
333 // Check to see if only a specific program should have debug malloc enabled.
334 char program[PROP_VALUE_MAX];
335 if (__system_property_get(DEBUG_MALLOC_PROPERTY_PROGRAM, program) != 0 &&
336 strstr(getprogname(), program) == nullptr) {
341 // Load the debug malloc shared library.
342 void* malloc_impl_handle = dlopen(DEBUG_SHARED_LIB, RTLD_NOW | RTLD_LOCAL);
343 if (malloc_impl_handle == nullptr) {
344 error_log("%s: Unable to open debug malloc shared library %s: %s",
345 getprogname(), DEBUG_SHARED_LIB, dlerror());
349 // Initialize malloc debugging in the loaded module.
350 auto init_func = reinterpret_cast<bool (*)(const MallocDispatch*, int*, const char*)>(
351 dlsym(malloc_impl_handle, "debug_initialize"));
352 if (init_func == nullptr) {
353 error_log("%s: debug_initialize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
354 dlclose(malloc_impl_handle);
358 // Get the syms for the external functions.
359 void* finalize_sym = dlsym(malloc_impl_handle, "debug_finalize");
360 if (finalize_sym == nullptr) {
361 error_log("%s: debug_finalize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
362 dlclose(malloc_impl_handle);
366 void* get_leak_info_sym = dlsym(malloc_impl_handle, "debug_get_malloc_leak_info");
367 if (get_leak_info_sym == nullptr) {
368 error_log("%s: debug_get_malloc_leak_info routine not found in %s", getprogname(),
370 dlclose(malloc_impl_handle);
374 void* free_leak_info_sym = dlsym(malloc_impl_handle, "debug_free_malloc_leak_info");
375 if (free_leak_info_sym == nullptr) {
376 error_log("%s: debug_free_malloc_leak_info routine not found in %s", getprogname(),
378 dlclose(malloc_impl_handle);
382 void* malloc_backtrace_sym = dlsym(malloc_impl_handle, "debug_malloc_backtrace");
383 if (malloc_backtrace_sym == nullptr) {
384 error_log("%s: debug_malloc_backtrace routine not found in %s", getprogname(),
386 dlclose(malloc_impl_handle);
390 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
391 dlclose(malloc_impl_handle);
395 MallocDispatch malloc_dispatch_table;
396 if (!InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "debug")) {
397 auto finalize_func = reinterpret_cast<void (*)()>(finalize_sym);
399 dlclose(malloc_impl_handle);
403 g_debug_finalize_func = reinterpret_cast<void (*)()>(finalize_sym);
404 g_debug_get_malloc_leak_info_func = reinterpret_cast<void (*)(
405 uint8_t**, size_t*, size_t*, size_t*, size_t*)>(get_leak_info_sym);
406 g_debug_free_malloc_leak_info_func = reinterpret_cast<void (*)(uint8_t*)>(free_leak_info_sym);
407 g_debug_malloc_backtrace_func = reinterpret_cast<ssize_t (*)(
408 void*, uintptr_t*, size_t)>(malloc_backtrace_sym);
410 globals->malloc_dispatch = malloc_dispatch_table;
411 libc_malloc_impl_handle = malloc_impl_handle;
413 info_log("%s: malloc debug enabled", getprogname());
415 // Use atexit to trigger the cleanup function. This avoids a problem
416 // where another atexit function is used to cleanup allocated memory,
417 // but the finalize function was already called. This particular error
418 // seems to be triggered by a zygote spawned process calling exit.
419 int ret_value = __cxa_atexit(malloc_fini_impl, nullptr, nullptr);
420 if (ret_value != 0) {
421 error_log("failed to set atexit cleanup function: %d", ret_value);
425 // Initializes memory allocation framework.
426 // This routine is called from __libc_init routines in libc_init_dynamic.cpp.
427 __LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
428 malloc_init_impl(globals);
430 #endif // !LIBC_STATIC
432 // =============================================================================
433 // Exported for use by libmemunreachable.
434 // =============================================================================
436 // Calls callback for every allocation in the anonymous heap mapping
437 // [base, base+size). Must be called between malloc_disable and malloc_enable.
438 extern "C" int malloc_iterate(uintptr_t base, size_t size,
439 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
440 auto _iterate = __libc_globals->malloc_dispatch.iterate;
441 if (__predict_false(_iterate != nullptr)) {
442 return _iterate(base, size, callback, arg);
444 return Malloc(iterate)(base, size, callback, arg);
447 // Disable calls to malloc so malloc_iterate gets a consistent view of
449 extern "C" void malloc_disable() {
450 auto _malloc_disable = __libc_globals->malloc_dispatch.malloc_disable;
451 if (__predict_false(_malloc_disable != nullptr)) {
452 return _malloc_disable();
454 return Malloc(malloc_disable)();
457 // Re-enable calls to malloc after a previous call to malloc_disable.
458 extern "C" void malloc_enable() {
459 auto _malloc_enable = __libc_globals->malloc_dispatch.malloc_enable;
460 if (__predict_false(_malloc_enable != nullptr)) {
461 return _malloc_enable();
463 return Malloc(malloc_enable)();
467 extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
468 if (g_debug_malloc_backtrace_func == nullptr) {
471 return g_debug_malloc_backtrace_func(pointer, frames, frame_count);
474 extern "C" ssize_t malloc_backtrace(void*, uintptr_t*, size_t) {