blob: 8bf44a16620fd6c01a113c2bfa65925360bf2fe6 [file] [log] [blame]
Christopher Ferris63860cb2015-11-16 17:30:32 -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
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
37// allocation.
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.
Christopher Ferris2e1a40a2018-06-13 10:46:34 -070042// write_malloc_leak_info: Writes the leak info data to a file.
Christopher Ferris63860cb2015-11-16 17:30:32 -080043
Colin Cross869691c2016-01-29 12:48:18 -080044#include <pthread.h>
45
Christopher Ferris63860cb2015-11-16 17:30:32 -080046#include <private/bionic_config.h>
47#include <private/bionic_globals.h>
48#include <private/bionic_malloc_dispatch.h>
49
Evgenii Stepanovbe551f52018-08-13 16:46:15 -070050#if __has_feature(hwaddress_sanitizer)
51// FIXME: implement these in HWASan allocator.
52extern "C" int __sanitizer_iterate(uintptr_t base __unused, size_t size __unused,
53 void (*callback)(uintptr_t base, size_t size, void* arg) __unused,
54 void* arg __unused) {
55 return 0;
56}
57
58extern "C" void __sanitizer_malloc_disable() {
59}
60
61extern "C" void __sanitizer_malloc_enable() {
62}
63#include <sanitizer/hwasan_interface.h>
64#define Malloc(function) __sanitizer_ ## function
65
66#else // __has_feature(hwaddress_sanitizer)
Christopher Ferris63860cb2015-11-16 17:30:32 -080067#include "jemalloc.h"
68#define Malloc(function) je_ ## function
Evgenii Stepanovbe551f52018-08-13 16:46:15 -070069#endif
Christopher Ferris63860cb2015-11-16 17:30:32 -080070
71static constexpr MallocDispatch __libc_malloc_default_dispatch
72 __attribute__((unused)) = {
73 Malloc(calloc),
74 Malloc(free),
75 Malloc(mallinfo),
76 Malloc(malloc),
77 Malloc(malloc_usable_size),
78 Malloc(memalign),
79 Malloc(posix_memalign),
80#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
81 Malloc(pvalloc),
82#endif
83 Malloc(realloc),
84#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
85 Malloc(valloc),
86#endif
Colin Cross869691c2016-01-29 12:48:18 -080087 Malloc(iterate),
88 Malloc(malloc_disable),
89 Malloc(malloc_enable),
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -070090 Malloc(mallopt),
Christopher Ferriscae21a92018-02-05 18:14:55 -080091 Malloc(aligned_alloc),
Christopher Ferris63860cb2015-11-16 17:30:32 -080092 };
93
Christopher Ferrisdb478a62018-02-07 18:42:14 -080094// Malloc hooks.
95void* (*volatile __malloc_hook)(size_t, const void*);
96void* (*volatile __realloc_hook)(void*, size_t, const void*);
97void (*volatile __free_hook)(void*, const void*);
98void* (*volatile __memalign_hook)(size_t, size_t, const void*);
99
Christopher Ferris63860cb2015-11-16 17:30:32 -0800100// In a VM process, this is set to 1 after fork()ing out of zygote.
101int gMallocLeakZygoteChild = 0;
102
103// =============================================================================
104// Allocation functions
105// =============================================================================
106extern "C" void* calloc(size_t n_elements, size_t elem_size) {
107 auto _calloc = __libc_globals->malloc_dispatch.calloc;
108 if (__predict_false(_calloc != nullptr)) {
109 return _calloc(n_elements, elem_size);
110 }
111 return Malloc(calloc)(n_elements, elem_size);
112}
113
114extern "C" void free(void* mem) {
115 auto _free = __libc_globals->malloc_dispatch.free;
116 if (__predict_false(_free != nullptr)) {
117 _free(mem);
118 } else {
119 Malloc(free)(mem);
120 }
121}
122
123extern "C" struct mallinfo mallinfo() {
124 auto _mallinfo = __libc_globals->malloc_dispatch.mallinfo;
125 if (__predict_false(_mallinfo != nullptr)) {
126 return _mallinfo();
127 }
128 return Malloc(mallinfo)();
129}
130
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700131extern "C" int mallopt(int param, int value) {
132 auto _mallopt = __libc_globals->malloc_dispatch.mallopt;
133 if (__predict_false(_mallopt != nullptr)) {
134 return _mallopt(param, value);
135 }
136 return Malloc(mallopt)(param, value);
137}
138
Christopher Ferris63860cb2015-11-16 17:30:32 -0800139extern "C" void* malloc(size_t bytes) {
140 auto _malloc = __libc_globals->malloc_dispatch.malloc;
141 if (__predict_false(_malloc != nullptr)) {
142 return _malloc(bytes);
143 }
144 return Malloc(malloc)(bytes);
145}
146
147extern "C" size_t malloc_usable_size(const void* mem) {
148 auto _malloc_usable_size = __libc_globals->malloc_dispatch.malloc_usable_size;
149 if (__predict_false(_malloc_usable_size != nullptr)) {
150 return _malloc_usable_size(mem);
151 }
152 return Malloc(malloc_usable_size)(mem);
153}
154
155extern "C" void* memalign(size_t alignment, size_t bytes) {
156 auto _memalign = __libc_globals->malloc_dispatch.memalign;
157 if (__predict_false(_memalign != nullptr)) {
158 return _memalign(alignment, bytes);
159 }
160 return Malloc(memalign)(alignment, bytes);
161}
162
163extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
164 auto _posix_memalign = __libc_globals->malloc_dispatch.posix_memalign;
165 if (__predict_false(_posix_memalign != nullptr)) {
166 return _posix_memalign(memptr, alignment, size);
167 }
168 return Malloc(posix_memalign)(memptr, alignment, size);
169}
170
Christopher Ferriscae21a92018-02-05 18:14:55 -0800171extern "C" void* aligned_alloc(size_t alignment, size_t size) {
172 auto _aligned_alloc = __libc_globals->malloc_dispatch.aligned_alloc;
173 if (__predict_false(_aligned_alloc != nullptr)) {
174 return _aligned_alloc(alignment, size);
175 }
176 return Malloc(aligned_alloc)(alignment, size);
177}
178
Christopher Ferris63860cb2015-11-16 17:30:32 -0800179extern "C" void* realloc(void* old_mem, size_t bytes) {
180 auto _realloc = __libc_globals->malloc_dispatch.realloc;
181 if (__predict_false(_realloc != nullptr)) {
182 return _realloc(old_mem, bytes);
183 }
184 return Malloc(realloc)(old_mem, bytes);
185}
186
Elliott Hughesb1770852018-09-18 12:52:42 -0700187extern "C" void* reallocarray(void* old_mem, size_t item_count, size_t item_size) {
188 size_t new_size;
189 if (__builtin_mul_overflow(item_count, item_size, &new_size)) {
190 errno = ENOMEM;
191 return nullptr;
192 }
193 return realloc(old_mem, new_size);
194}
195
Christopher Ferris63860cb2015-11-16 17:30:32 -0800196#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
197extern "C" void* pvalloc(size_t bytes) {
198 auto _pvalloc = __libc_globals->malloc_dispatch.pvalloc;
199 if (__predict_false(_pvalloc != nullptr)) {
200 return _pvalloc(bytes);
201 }
202 return Malloc(pvalloc)(bytes);
203}
204
205extern "C" void* valloc(size_t bytes) {
206 auto _valloc = __libc_globals->malloc_dispatch.valloc;
207 if (__predict_false(_valloc != nullptr)) {
208 return _valloc(bytes);
209 }
210 return Malloc(valloc)(bytes);
211}
212#endif
213
214// We implement malloc debugging only in libc.so, so the code below
215// must be excluded if we compile this file for static libc.a
216#if !defined(LIBC_STATIC)
217
218#include <dlfcn.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -0800219#include <stdio.h>
220#include <stdlib.h>
221
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700222#include <async_safe/log.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -0800223#include <sys/system_properties.h>
224
225extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
226
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800227static const char* HOOKS_SHARED_LIB = "libc_malloc_hooks.so";
228static const char* HOOKS_PROPERTY_ENABLE = "libc.debug.hooks.enable";
229static const char* HOOKS_ENV_ENABLE = "LIBC_HOOKS_ENABLE";
230
Christopher Ferris63860cb2015-11-16 17:30:32 -0800231static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800232static const char* DEBUG_PROPERTY_OPTIONS = "libc.debug.malloc.options";
233static const char* DEBUG_PROPERTY_PROGRAM = "libc.debug.malloc.program";
234static const char* DEBUG_ENV_OPTIONS = "LIBC_DEBUG_MALLOC_OPTIONS";
Christopher Ferris63860cb2015-11-16 17:30:32 -0800235
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800236enum FunctionEnum : uint8_t {
237 FUNC_INITIALIZE,
238 FUNC_FINALIZE,
239 FUNC_GET_MALLOC_LEAK_INFO,
240 FUNC_FREE_MALLOC_LEAK_INFO,
241 FUNC_MALLOC_BACKTRACE,
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700242 FUNC_WRITE_LEAK_INFO,
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800243 FUNC_LAST,
244};
245static void* g_functions[FUNC_LAST];
Christopher Ferris63860cb2015-11-16 17:30:32 -0800246
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800247typedef void (*finalize_func_t)();
248typedef bool (*init_func_t)(const MallocDispatch*, int*, const char*);
249typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
250typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700251typedef bool (*write_malloc_leak_info_func_t)(FILE*);
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800252typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800253
254// =============================================================================
255// Log functions
256// =============================================================================
257#define error_log(format, ...) \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700258 async_safe_format_log(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
Christopher Ferris63860cb2015-11-16 17:30:32 -0800259#define info_log(format, ...) \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700260 async_safe_format_log(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
Christopher Ferris63860cb2015-11-16 17:30:32 -0800261// =============================================================================
262
263// =============================================================================
264// Exported for use by ddms.
265// =============================================================================
266
267// Retrieve native heap information.
268//
269// "*info" is set to a buffer we allocate
270// "*overall_size" is set to the size of the "info" buffer
271// "*info_size" is set to the size of a single entry
272// "*total_memory" is set to the sum of all allocations we're tracking; does
273// not include heap overhead
274// "*backtrace_size" is set to the maximum number of entries in the back trace
275extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
276 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800277 void* func = g_functions[FUNC_GET_MALLOC_LEAK_INFO];
278 if (func == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800279 return;
280 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800281 reinterpret_cast<get_malloc_leak_info_func_t>(func)(info, overall_size, info_size, total_memory,
282 backtrace_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800283}
284
285extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800286 void* func = g_functions[FUNC_FREE_MALLOC_LEAK_INFO];
287 if (func == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800288 return;
289 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800290 reinterpret_cast<free_malloc_leak_info_func_t>(func)(info);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800291}
Colin Cross869691c2016-01-29 12:48:18 -0800292
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700293extern "C" void write_malloc_leak_info(FILE* fp) {
294 if (fp == nullptr) {
295 error_log("write_malloc_leak_info called with a nullptr");
296 return;
297 }
298
299 void* func = g_functions[FUNC_WRITE_LEAK_INFO];
300 bool written = false;
301 if (func != nullptr) {
302 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
303 }
304
305 if (!written) {
306 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
307 fprintf(fp, "# adb shell stop\n");
308 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
309 fprintf(fp, "# adb shell start\n");
310 }
311}
312
Christopher Ferris63860cb2015-11-16 17:30:32 -0800313// =============================================================================
314
315template<typename FunctionType>
316static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
317 char symbol[128];
318 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
319 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
320 if (*func == nullptr) {
321 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
322 return false;
323 }
324 return true;
325}
326
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800327static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
328 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800329 return false;
330 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800331 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800332 return false;
333 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800334 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800335 return false;
336 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800337 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700338 return false;
339 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800340 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800341 return false;
342 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800343 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
344 "malloc_usable_size")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800345 return false;
346 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800347 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800348 return false;
349 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800350 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
351 "posix_memalign")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800352 return false;
353 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800354 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
Christopher Ferriscae21a92018-02-05 18:14:55 -0800355 prefix, "aligned_alloc")) {
356 return false;
357 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800358 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800359 return false;
360 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800361 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->iterate, prefix, "iterate")) {
Colin Cross869691c2016-01-29 12:48:18 -0800362 return false;
363 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800364 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
365 "malloc_disable")) {
Colin Cross869691c2016-01-29 12:48:18 -0800366 return false;
367 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800368 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
369 "malloc_enable")) {
Colin Cross869691c2016-01-29 12:48:18 -0800370 return false;
371 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800372#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800373 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800374 return false;
375 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800376 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800377 return false;
378 }
379#endif
380
381 return true;
382}
383
384static void malloc_fini_impl(void*) {
385 // Our BSD stdio implementation doesn't close the standard streams,
386 // it only flushes them. Other unclosed FILE*s will show up as
387 // malloc leaks, but to avoid the standard streams showing up in
388 // leak reports, close them here.
389 fclose(stdin);
390 fclose(stdout);
391 fclose(stderr);
392
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800393 reinterpret_cast<finalize_func_t>(g_functions[FUNC_FINALIZE])();
394}
395
396static bool CheckLoadMallocHooks(char** options) {
397 char* env = getenv(HOOKS_ENV_ENABLE);
398 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
399 (__system_property_get(HOOKS_PROPERTY_ENABLE, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
400 return false;
401 }
402 *options = nullptr;
403 return true;
404}
405
406static bool CheckLoadMallocDebug(char** options) {
407 // If DEBUG_MALLOC_ENV_OPTIONS is set then it overrides the system properties.
408 char* env = getenv(DEBUG_ENV_OPTIONS);
409 if (env == nullptr || env[0] == '\0') {
410 if (__system_property_get(DEBUG_PROPERTY_OPTIONS, *options) == 0 || *options[0] == '\0') {
411 return false;
412 }
413
414 // Check to see if only a specific program should have debug malloc enabled.
415 char program[PROP_VALUE_MAX];
416 if (__system_property_get(DEBUG_PROPERTY_PROGRAM, program) != 0 &&
417 strstr(getprogname(), program) == nullptr) {
418 return false;
419 }
420 } else {
421 *options = env;
422 }
423 return true;
424}
425
426static void ClearGlobalFunctions() {
427 for (size_t i = 0; i < FUNC_LAST; i++) {
428 g_functions[i] = nullptr;
429 }
430}
431
432static void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
433 void* impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
434 if (impl_handle == nullptr) {
435 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
436 return nullptr;
437 }
438
439 static constexpr const char* names[] = {
440 "initialize",
441 "finalize",
442 "get_malloc_leak_info",
443 "free_malloc_leak_info",
444 "malloc_backtrace",
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700445 "write_malloc_leak_info",
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800446 };
447 for (size_t i = 0; i < FUNC_LAST; i++) {
448 char symbol[128];
449 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
450 g_functions[i] = dlsym(impl_handle, symbol);
451 if (g_functions[i] == nullptr) {
452 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
453 dlclose(impl_handle);
454 ClearGlobalFunctions();
455 return nullptr;
456 }
457 }
458
459 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
460 dlclose(impl_handle);
461 ClearGlobalFunctions();
462 return nullptr;
463 }
464
465 return impl_handle;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800466}
467
468// Initializes memory allocation framework once per process.
469static void malloc_init_impl(libc_globals* globals) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800470 const char* prefix;
471 const char* shared_lib;
472 char prop[PROP_VALUE_MAX];
473 char* options = prop;
474 // Prefer malloc debug since it existed first and is a more complete
475 // malloc interceptor than the hooks.
476 if (CheckLoadMallocDebug(&options)) {
477 prefix = "debug";
478 shared_lib = DEBUG_SHARED_LIB;
479 } else if (CheckLoadMallocHooks(&options)) {
480 prefix = "hooks";
481 shared_lib = HOOKS_SHARED_LIB;
482 } else {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800483 return;
484 }
485
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800486 MallocDispatch dispatch_table;
487 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &dispatch_table);
488 if (impl_handle == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800489 return;
490 }
491
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800492 init_func_t init_func = reinterpret_cast<init_func_t>(g_functions[FUNC_INITIALIZE]);
Tamas Berghammerac81fe82016-08-26 15:54:59 +0100493 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800494 dlclose(impl_handle);
495 ClearGlobalFunctions();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800496 return;
497 }
498
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800499 globals->malloc_dispatch = dispatch_table;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800500
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800501 info_log("%s: malloc %s enabled", getprogname(), prefix);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800502
503 // Use atexit to trigger the cleanup function. This avoids a problem
504 // where another atexit function is used to cleanup allocated memory,
505 // but the finalize function was already called. This particular error
506 // seems to be triggered by a zygote spawned process calling exit.
507 int ret_value = __cxa_atexit(malloc_fini_impl, nullptr, nullptr);
508 if (ret_value != 0) {
509 error_log("failed to set atexit cleanup function: %d", ret_value);
510 }
511}
512
513// Initializes memory allocation framework.
514// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
515__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
516 malloc_init_impl(globals);
517}
518#endif // !LIBC_STATIC
Colin Cross869691c2016-01-29 12:48:18 -0800519
520// =============================================================================
521// Exported for use by libmemunreachable.
522// =============================================================================
523
524// Calls callback for every allocation in the anonymous heap mapping
525// [base, base+size). Must be called between malloc_disable and malloc_enable.
526extern "C" int malloc_iterate(uintptr_t base, size_t size,
527 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
528 auto _iterate = __libc_globals->malloc_dispatch.iterate;
529 if (__predict_false(_iterate != nullptr)) {
530 return _iterate(base, size, callback, arg);
531 }
532 return Malloc(iterate)(base, size, callback, arg);
533}
534
535// Disable calls to malloc so malloc_iterate gets a consistent view of
536// allocated memory.
537extern "C" void malloc_disable() {
538 auto _malloc_disable = __libc_globals->malloc_dispatch.malloc_disable;
539 if (__predict_false(_malloc_disable != nullptr)) {
540 return _malloc_disable();
541 }
542 return Malloc(malloc_disable)();
543}
544
545// Re-enable calls to malloc after a previous call to malloc_disable.
546extern "C" void malloc_enable() {
547 auto _malloc_enable = __libc_globals->malloc_dispatch.malloc_enable;
548 if (__predict_false(_malloc_enable != nullptr)) {
549 return _malloc_enable();
550 }
551 return Malloc(malloc_enable)();
552}
Colin Cross2d4721c2016-02-02 11:57:54 -0800553
554#ifndef LIBC_STATIC
555extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800556 void* func = g_functions[FUNC_MALLOC_BACKTRACE];
557 if (func == nullptr) {
Colin Cross2d4721c2016-02-02 11:57:54 -0800558 return 0;
559 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800560 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
Colin Cross2d4721c2016-02-02 11:57:54 -0800561}
562#else
563extern "C" ssize_t malloc_backtrace(void*, uintptr_t*, size_t) {
564 return 0;
565}
566#endif