blob: 5a5ec76be7bc55f8f842af49f944b44e20bb90c5 [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
187#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
188extern "C" void* pvalloc(size_t bytes) {
189 auto _pvalloc = __libc_globals->malloc_dispatch.pvalloc;
190 if (__predict_false(_pvalloc != nullptr)) {
191 return _pvalloc(bytes);
192 }
193 return Malloc(pvalloc)(bytes);
194}
195
196extern "C" void* valloc(size_t bytes) {
197 auto _valloc = __libc_globals->malloc_dispatch.valloc;
198 if (__predict_false(_valloc != nullptr)) {
199 return _valloc(bytes);
200 }
201 return Malloc(valloc)(bytes);
202}
203#endif
204
205// We implement malloc debugging only in libc.so, so the code below
206// must be excluded if we compile this file for static libc.a
207#if !defined(LIBC_STATIC)
208
209#include <dlfcn.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -0800210#include <stdio.h>
211#include <stdlib.h>
212
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700213#include <async_safe/log.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -0800214#include <sys/system_properties.h>
215
216extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
217
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800218static const char* HOOKS_SHARED_LIB = "libc_malloc_hooks.so";
219static const char* HOOKS_PROPERTY_ENABLE = "libc.debug.hooks.enable";
220static const char* HOOKS_ENV_ENABLE = "LIBC_HOOKS_ENABLE";
221
Christopher Ferris63860cb2015-11-16 17:30:32 -0800222static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800223static const char* DEBUG_PROPERTY_OPTIONS = "libc.debug.malloc.options";
224static const char* DEBUG_PROPERTY_PROGRAM = "libc.debug.malloc.program";
225static const char* DEBUG_ENV_OPTIONS = "LIBC_DEBUG_MALLOC_OPTIONS";
Christopher Ferris63860cb2015-11-16 17:30:32 -0800226
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800227enum FunctionEnum : uint8_t {
228 FUNC_INITIALIZE,
229 FUNC_FINALIZE,
230 FUNC_GET_MALLOC_LEAK_INFO,
231 FUNC_FREE_MALLOC_LEAK_INFO,
232 FUNC_MALLOC_BACKTRACE,
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700233 FUNC_WRITE_LEAK_INFO,
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800234 FUNC_LAST,
235};
236static void* g_functions[FUNC_LAST];
Christopher Ferris63860cb2015-11-16 17:30:32 -0800237
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800238typedef void (*finalize_func_t)();
239typedef bool (*init_func_t)(const MallocDispatch*, int*, const char*);
240typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
241typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700242typedef bool (*write_malloc_leak_info_func_t)(FILE*);
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800243typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800244
245// =============================================================================
246// Log functions
247// =============================================================================
248#define error_log(format, ...) \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700249 async_safe_format_log(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
Christopher Ferris63860cb2015-11-16 17:30:32 -0800250#define info_log(format, ...) \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700251 async_safe_format_log(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
Christopher Ferris63860cb2015-11-16 17:30:32 -0800252// =============================================================================
253
254// =============================================================================
255// Exported for use by ddms.
256// =============================================================================
257
258// Retrieve native heap information.
259//
260// "*info" is set to a buffer we allocate
261// "*overall_size" is set to the size of the "info" buffer
262// "*info_size" is set to the size of a single entry
263// "*total_memory" is set to the sum of all allocations we're tracking; does
264// not include heap overhead
265// "*backtrace_size" is set to the maximum number of entries in the back trace
266extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
267 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800268 void* func = g_functions[FUNC_GET_MALLOC_LEAK_INFO];
269 if (func == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800270 return;
271 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800272 reinterpret_cast<get_malloc_leak_info_func_t>(func)(info, overall_size, info_size, total_memory,
273 backtrace_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800274}
275
276extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800277 void* func = g_functions[FUNC_FREE_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<free_malloc_leak_info_func_t>(func)(info);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800282}
Colin Cross869691c2016-01-29 12:48:18 -0800283
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700284extern "C" void write_malloc_leak_info(FILE* fp) {
285 if (fp == nullptr) {
286 error_log("write_malloc_leak_info called with a nullptr");
287 return;
288 }
289
290 void* func = g_functions[FUNC_WRITE_LEAK_INFO];
291 bool written = false;
292 if (func != nullptr) {
293 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
294 }
295
296 if (!written) {
297 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
298 fprintf(fp, "# adb shell stop\n");
299 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
300 fprintf(fp, "# adb shell start\n");
301 }
302}
303
Christopher Ferris63860cb2015-11-16 17:30:32 -0800304// =============================================================================
305
306template<typename FunctionType>
307static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
308 char symbol[128];
309 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
310 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
311 if (*func == nullptr) {
312 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
313 return false;
314 }
315 return true;
316}
317
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800318static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
319 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800320 return false;
321 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800322 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800323 return false;
324 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800325 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800326 return false;
327 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800328 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700329 return false;
330 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800331 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800332 return false;
333 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800334 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
335 "malloc_usable_size")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800336 return false;
337 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800338 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800339 return false;
340 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800341 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
342 "posix_memalign")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800343 return false;
344 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800345 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
Christopher Ferriscae21a92018-02-05 18:14:55 -0800346 prefix, "aligned_alloc")) {
347 return false;
348 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800349 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800350 return false;
351 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800352 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->iterate, prefix, "iterate")) {
Colin Cross869691c2016-01-29 12:48:18 -0800353 return false;
354 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800355 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
356 "malloc_disable")) {
Colin Cross869691c2016-01-29 12:48:18 -0800357 return false;
358 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800359 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
360 "malloc_enable")) {
Colin Cross869691c2016-01-29 12:48:18 -0800361 return false;
362 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800363#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800364 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800365 return false;
366 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800367 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800368 return false;
369 }
370#endif
371
372 return true;
373}
374
375static void malloc_fini_impl(void*) {
376 // Our BSD stdio implementation doesn't close the standard streams,
377 // it only flushes them. Other unclosed FILE*s will show up as
378 // malloc leaks, but to avoid the standard streams showing up in
379 // leak reports, close them here.
380 fclose(stdin);
381 fclose(stdout);
382 fclose(stderr);
383
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800384 reinterpret_cast<finalize_func_t>(g_functions[FUNC_FINALIZE])();
385}
386
387static bool CheckLoadMallocHooks(char** options) {
388 char* env = getenv(HOOKS_ENV_ENABLE);
389 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
390 (__system_property_get(HOOKS_PROPERTY_ENABLE, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
391 return false;
392 }
393 *options = nullptr;
394 return true;
395}
396
397static bool CheckLoadMallocDebug(char** options) {
398 // If DEBUG_MALLOC_ENV_OPTIONS is set then it overrides the system properties.
399 char* env = getenv(DEBUG_ENV_OPTIONS);
400 if (env == nullptr || env[0] == '\0') {
401 if (__system_property_get(DEBUG_PROPERTY_OPTIONS, *options) == 0 || *options[0] == '\0') {
402 return false;
403 }
404
405 // Check to see if only a specific program should have debug malloc enabled.
406 char program[PROP_VALUE_MAX];
407 if (__system_property_get(DEBUG_PROPERTY_PROGRAM, program) != 0 &&
408 strstr(getprogname(), program) == nullptr) {
409 return false;
410 }
411 } else {
412 *options = env;
413 }
414 return true;
415}
416
417static void ClearGlobalFunctions() {
418 for (size_t i = 0; i < FUNC_LAST; i++) {
419 g_functions[i] = nullptr;
420 }
421}
422
423static void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
424 void* impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
425 if (impl_handle == nullptr) {
426 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
427 return nullptr;
428 }
429
430 static constexpr const char* names[] = {
431 "initialize",
432 "finalize",
433 "get_malloc_leak_info",
434 "free_malloc_leak_info",
435 "malloc_backtrace",
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700436 "write_malloc_leak_info",
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800437 };
438 for (size_t i = 0; i < FUNC_LAST; i++) {
439 char symbol[128];
440 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
441 g_functions[i] = dlsym(impl_handle, symbol);
442 if (g_functions[i] == nullptr) {
443 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
444 dlclose(impl_handle);
445 ClearGlobalFunctions();
446 return nullptr;
447 }
448 }
449
450 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
451 dlclose(impl_handle);
452 ClearGlobalFunctions();
453 return nullptr;
454 }
455
456 return impl_handle;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800457}
458
459// Initializes memory allocation framework once per process.
460static void malloc_init_impl(libc_globals* globals) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800461 const char* prefix;
462 const char* shared_lib;
463 char prop[PROP_VALUE_MAX];
464 char* options = prop;
465 // Prefer malloc debug since it existed first and is a more complete
466 // malloc interceptor than the hooks.
467 if (CheckLoadMallocDebug(&options)) {
468 prefix = "debug";
469 shared_lib = DEBUG_SHARED_LIB;
470 } else if (CheckLoadMallocHooks(&options)) {
471 prefix = "hooks";
472 shared_lib = HOOKS_SHARED_LIB;
473 } else {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800474 return;
475 }
476
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800477 MallocDispatch dispatch_table;
478 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &dispatch_table);
479 if (impl_handle == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800480 return;
481 }
482
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800483 init_func_t init_func = reinterpret_cast<init_func_t>(g_functions[FUNC_INITIALIZE]);
Tamas Berghammerac81fe82016-08-26 15:54:59 +0100484 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800485 dlclose(impl_handle);
486 ClearGlobalFunctions();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800487 return;
488 }
489
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800490 globals->malloc_dispatch = dispatch_table;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800491
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800492 info_log("%s: malloc %s enabled", getprogname(), prefix);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800493
494 // Use atexit to trigger the cleanup function. This avoids a problem
495 // where another atexit function is used to cleanup allocated memory,
496 // but the finalize function was already called. This particular error
497 // seems to be triggered by a zygote spawned process calling exit.
498 int ret_value = __cxa_atexit(malloc_fini_impl, nullptr, nullptr);
499 if (ret_value != 0) {
500 error_log("failed to set atexit cleanup function: %d", ret_value);
501 }
502}
503
504// Initializes memory allocation framework.
505// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
506__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
507 malloc_init_impl(globals);
508}
509#endif // !LIBC_STATIC
Colin Cross869691c2016-01-29 12:48:18 -0800510
511// =============================================================================
512// Exported for use by libmemunreachable.
513// =============================================================================
514
515// Calls callback for every allocation in the anonymous heap mapping
516// [base, base+size). Must be called between malloc_disable and malloc_enable.
517extern "C" int malloc_iterate(uintptr_t base, size_t size,
518 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
519 auto _iterate = __libc_globals->malloc_dispatch.iterate;
520 if (__predict_false(_iterate != nullptr)) {
521 return _iterate(base, size, callback, arg);
522 }
523 return Malloc(iterate)(base, size, callback, arg);
524}
525
526// Disable calls to malloc so malloc_iterate gets a consistent view of
527// allocated memory.
528extern "C" void malloc_disable() {
529 auto _malloc_disable = __libc_globals->malloc_dispatch.malloc_disable;
530 if (__predict_false(_malloc_disable != nullptr)) {
531 return _malloc_disable();
532 }
533 return Malloc(malloc_disable)();
534}
535
536// Re-enable calls to malloc after a previous call to malloc_disable.
537extern "C" void malloc_enable() {
538 auto _malloc_enable = __libc_globals->malloc_dispatch.malloc_enable;
539 if (__predict_false(_malloc_enable != nullptr)) {
540 return _malloc_enable();
541 }
542 return Malloc(malloc_enable)();
543}
Colin Cross2d4721c2016-02-02 11:57:54 -0800544
545#ifndef LIBC_STATIC
546extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800547 void* func = g_functions[FUNC_MALLOC_BACKTRACE];
548 if (func == nullptr) {
Colin Cross2d4721c2016-02-02 11:57:54 -0800549 return 0;
550 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800551 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
Colin Cross2d4721c2016-02-02 11:57:54 -0800552}
553#else
554extern "C" ssize_t malloc_backtrace(void*, uintptr_t*, size_t) {
555 return 0;
556}
557#endif