blob: 40a0023a8491ca0c213cf00fa0784f360eef4b55 [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
50#include "jemalloc.h"
51#define Malloc(function) je_ ## function
52
53static constexpr MallocDispatch __libc_malloc_default_dispatch
54 __attribute__((unused)) = {
55 Malloc(calloc),
56 Malloc(free),
57 Malloc(mallinfo),
58 Malloc(malloc),
59 Malloc(malloc_usable_size),
60 Malloc(memalign),
61 Malloc(posix_memalign),
62#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
63 Malloc(pvalloc),
64#endif
65 Malloc(realloc),
66#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
67 Malloc(valloc),
68#endif
Colin Cross869691c2016-01-29 12:48:18 -080069 Malloc(iterate),
70 Malloc(malloc_disable),
71 Malloc(malloc_enable),
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -070072 Malloc(mallopt),
Christopher Ferriscae21a92018-02-05 18:14:55 -080073 Malloc(aligned_alloc),
Christopher Ferris63860cb2015-11-16 17:30:32 -080074 };
75
Christopher Ferrisdb478a62018-02-07 18:42:14 -080076// Malloc hooks.
77void* (*volatile __malloc_hook)(size_t, const void*);
78void* (*volatile __realloc_hook)(void*, size_t, const void*);
79void (*volatile __free_hook)(void*, const void*);
80void* (*volatile __memalign_hook)(size_t, size_t, const void*);
81
Christopher Ferris63860cb2015-11-16 17:30:32 -080082// In a VM process, this is set to 1 after fork()ing out of zygote.
83int gMallocLeakZygoteChild = 0;
84
85// =============================================================================
86// Allocation functions
87// =============================================================================
88extern "C" void* calloc(size_t n_elements, size_t elem_size) {
89 auto _calloc = __libc_globals->malloc_dispatch.calloc;
90 if (__predict_false(_calloc != nullptr)) {
91 return _calloc(n_elements, elem_size);
92 }
93 return Malloc(calloc)(n_elements, elem_size);
94}
95
96extern "C" void free(void* mem) {
97 auto _free = __libc_globals->malloc_dispatch.free;
98 if (__predict_false(_free != nullptr)) {
99 _free(mem);
100 } else {
101 Malloc(free)(mem);
102 }
103}
104
105extern "C" struct mallinfo mallinfo() {
106 auto _mallinfo = __libc_globals->malloc_dispatch.mallinfo;
107 if (__predict_false(_mallinfo != nullptr)) {
108 return _mallinfo();
109 }
110 return Malloc(mallinfo)();
111}
112
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700113extern "C" int mallopt(int param, int value) {
114 auto _mallopt = __libc_globals->malloc_dispatch.mallopt;
115 if (__predict_false(_mallopt != nullptr)) {
116 return _mallopt(param, value);
117 }
118 return Malloc(mallopt)(param, value);
119}
120
Christopher Ferris63860cb2015-11-16 17:30:32 -0800121extern "C" void* malloc(size_t bytes) {
122 auto _malloc = __libc_globals->malloc_dispatch.malloc;
123 if (__predict_false(_malloc != nullptr)) {
124 return _malloc(bytes);
125 }
126 return Malloc(malloc)(bytes);
127}
128
129extern "C" size_t malloc_usable_size(const void* mem) {
130 auto _malloc_usable_size = __libc_globals->malloc_dispatch.malloc_usable_size;
131 if (__predict_false(_malloc_usable_size != nullptr)) {
132 return _malloc_usable_size(mem);
133 }
134 return Malloc(malloc_usable_size)(mem);
135}
136
137extern "C" void* memalign(size_t alignment, size_t bytes) {
138 auto _memalign = __libc_globals->malloc_dispatch.memalign;
139 if (__predict_false(_memalign != nullptr)) {
140 return _memalign(alignment, bytes);
141 }
142 return Malloc(memalign)(alignment, bytes);
143}
144
145extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
146 auto _posix_memalign = __libc_globals->malloc_dispatch.posix_memalign;
147 if (__predict_false(_posix_memalign != nullptr)) {
148 return _posix_memalign(memptr, alignment, size);
149 }
150 return Malloc(posix_memalign)(memptr, alignment, size);
151}
152
Christopher Ferriscae21a92018-02-05 18:14:55 -0800153extern "C" void* aligned_alloc(size_t alignment, size_t size) {
154 auto _aligned_alloc = __libc_globals->malloc_dispatch.aligned_alloc;
155 if (__predict_false(_aligned_alloc != nullptr)) {
156 return _aligned_alloc(alignment, size);
157 }
158 return Malloc(aligned_alloc)(alignment, size);
159}
160
Christopher Ferris63860cb2015-11-16 17:30:32 -0800161extern "C" void* realloc(void* old_mem, size_t bytes) {
162 auto _realloc = __libc_globals->malloc_dispatch.realloc;
163 if (__predict_false(_realloc != nullptr)) {
164 return _realloc(old_mem, bytes);
165 }
166 return Malloc(realloc)(old_mem, bytes);
167}
168
169#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
170extern "C" void* pvalloc(size_t bytes) {
171 auto _pvalloc = __libc_globals->malloc_dispatch.pvalloc;
172 if (__predict_false(_pvalloc != nullptr)) {
173 return _pvalloc(bytes);
174 }
175 return Malloc(pvalloc)(bytes);
176}
177
178extern "C" void* valloc(size_t bytes) {
179 auto _valloc = __libc_globals->malloc_dispatch.valloc;
180 if (__predict_false(_valloc != nullptr)) {
181 return _valloc(bytes);
182 }
183 return Malloc(valloc)(bytes);
184}
185#endif
186
187// We implement malloc debugging only in libc.so, so the code below
188// must be excluded if we compile this file for static libc.a
189#if !defined(LIBC_STATIC)
190
191#include <dlfcn.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -0800192#include <stdio.h>
193#include <stdlib.h>
194
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700195#include <async_safe/log.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -0800196#include <sys/system_properties.h>
197
198extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
199
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800200static const char* HOOKS_SHARED_LIB = "libc_malloc_hooks.so";
201static const char* HOOKS_PROPERTY_ENABLE = "libc.debug.hooks.enable";
202static const char* HOOKS_ENV_ENABLE = "LIBC_HOOKS_ENABLE";
203
Christopher Ferris63860cb2015-11-16 17:30:32 -0800204static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800205static const char* DEBUG_PROPERTY_OPTIONS = "libc.debug.malloc.options";
206static const char* DEBUG_PROPERTY_PROGRAM = "libc.debug.malloc.program";
207static const char* DEBUG_ENV_OPTIONS = "LIBC_DEBUG_MALLOC_OPTIONS";
Christopher Ferris63860cb2015-11-16 17:30:32 -0800208
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800209enum FunctionEnum : uint8_t {
210 FUNC_INITIALIZE,
211 FUNC_FINALIZE,
212 FUNC_GET_MALLOC_LEAK_INFO,
213 FUNC_FREE_MALLOC_LEAK_INFO,
214 FUNC_MALLOC_BACKTRACE,
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700215 FUNC_WRITE_LEAK_INFO,
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800216 FUNC_LAST,
217};
218static void* g_functions[FUNC_LAST];
Christopher Ferris63860cb2015-11-16 17:30:32 -0800219
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800220typedef void (*finalize_func_t)();
221typedef bool (*init_func_t)(const MallocDispatch*, int*, const char*);
222typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
223typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700224typedef bool (*write_malloc_leak_info_func_t)(FILE*);
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800225typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800226
227// =============================================================================
228// Log functions
229// =============================================================================
230#define error_log(format, ...) \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700231 async_safe_format_log(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
Christopher Ferris63860cb2015-11-16 17:30:32 -0800232#define info_log(format, ...) \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700233 async_safe_format_log(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
Christopher Ferris63860cb2015-11-16 17:30:32 -0800234// =============================================================================
235
236// =============================================================================
237// Exported for use by ddms.
238// =============================================================================
239
240// Retrieve native heap information.
241//
242// "*info" is set to a buffer we allocate
243// "*overall_size" is set to the size of the "info" buffer
244// "*info_size" is set to the size of a single entry
245// "*total_memory" is set to the sum of all allocations we're tracking; does
246// not include heap overhead
247// "*backtrace_size" is set to the maximum number of entries in the back trace
248extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
249 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800250 void* func = g_functions[FUNC_GET_MALLOC_LEAK_INFO];
251 if (func == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800252 return;
253 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800254 reinterpret_cast<get_malloc_leak_info_func_t>(func)(info, overall_size, info_size, total_memory,
255 backtrace_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800256}
257
258extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800259 void* func = g_functions[FUNC_FREE_MALLOC_LEAK_INFO];
260 if (func == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800261 return;
262 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800263 reinterpret_cast<free_malloc_leak_info_func_t>(func)(info);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800264}
Colin Cross869691c2016-01-29 12:48:18 -0800265
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700266extern "C" void write_malloc_leak_info(FILE* fp) {
267 if (fp == nullptr) {
268 error_log("write_malloc_leak_info called with a nullptr");
269 return;
270 }
271
272 void* func = g_functions[FUNC_WRITE_LEAK_INFO];
273 bool written = false;
274 if (func != nullptr) {
275 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
276 }
277
278 if (!written) {
279 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
280 fprintf(fp, "# adb shell stop\n");
281 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
282 fprintf(fp, "# adb shell start\n");
283 }
284}
285
Christopher Ferris63860cb2015-11-16 17:30:32 -0800286// =============================================================================
287
288template<typename FunctionType>
289static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
290 char symbol[128];
291 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
292 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
293 if (*func == nullptr) {
294 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
295 return false;
296 }
297 return true;
298}
299
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800300static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
301 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800302 return false;
303 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800304 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800305 return false;
306 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800307 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800308 return false;
309 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800310 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700311 return false;
312 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800313 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800314 return false;
315 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800316 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
317 "malloc_usable_size")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800318 return false;
319 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800320 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800321 return false;
322 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800323 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
324 "posix_memalign")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800325 return false;
326 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800327 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
Christopher Ferriscae21a92018-02-05 18:14:55 -0800328 prefix, "aligned_alloc")) {
329 return false;
330 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800331 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800332 return false;
333 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800334 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->iterate, prefix, "iterate")) {
Colin Cross869691c2016-01-29 12:48:18 -0800335 return false;
336 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800337 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
338 "malloc_disable")) {
Colin Cross869691c2016-01-29 12:48:18 -0800339 return false;
340 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800341 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
342 "malloc_enable")) {
Colin Cross869691c2016-01-29 12:48:18 -0800343 return false;
344 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800345#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800346 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800347 return false;
348 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800349 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800350 return false;
351 }
352#endif
353
354 return true;
355}
356
357static void malloc_fini_impl(void*) {
358 // Our BSD stdio implementation doesn't close the standard streams,
359 // it only flushes them. Other unclosed FILE*s will show up as
360 // malloc leaks, but to avoid the standard streams showing up in
361 // leak reports, close them here.
362 fclose(stdin);
363 fclose(stdout);
364 fclose(stderr);
365
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800366 reinterpret_cast<finalize_func_t>(g_functions[FUNC_FINALIZE])();
367}
368
369static bool CheckLoadMallocHooks(char** options) {
370 char* env = getenv(HOOKS_ENV_ENABLE);
371 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
372 (__system_property_get(HOOKS_PROPERTY_ENABLE, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
373 return false;
374 }
375 *options = nullptr;
376 return true;
377}
378
379static bool CheckLoadMallocDebug(char** options) {
380 // If DEBUG_MALLOC_ENV_OPTIONS is set then it overrides the system properties.
381 char* env = getenv(DEBUG_ENV_OPTIONS);
382 if (env == nullptr || env[0] == '\0') {
383 if (__system_property_get(DEBUG_PROPERTY_OPTIONS, *options) == 0 || *options[0] == '\0') {
384 return false;
385 }
386
387 // Check to see if only a specific program should have debug malloc enabled.
388 char program[PROP_VALUE_MAX];
389 if (__system_property_get(DEBUG_PROPERTY_PROGRAM, program) != 0 &&
390 strstr(getprogname(), program) == nullptr) {
391 return false;
392 }
393 } else {
394 *options = env;
395 }
396 return true;
397}
398
399static void ClearGlobalFunctions() {
400 for (size_t i = 0; i < FUNC_LAST; i++) {
401 g_functions[i] = nullptr;
402 }
403}
404
405static void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
406 void* impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
407 if (impl_handle == nullptr) {
408 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
409 return nullptr;
410 }
411
412 static constexpr const char* names[] = {
413 "initialize",
414 "finalize",
415 "get_malloc_leak_info",
416 "free_malloc_leak_info",
417 "malloc_backtrace",
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700418 "write_malloc_leak_info",
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800419 };
420 for (size_t i = 0; i < FUNC_LAST; i++) {
421 char symbol[128];
422 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
423 g_functions[i] = dlsym(impl_handle, symbol);
424 if (g_functions[i] == nullptr) {
425 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
426 dlclose(impl_handle);
427 ClearGlobalFunctions();
428 return nullptr;
429 }
430 }
431
432 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
433 dlclose(impl_handle);
434 ClearGlobalFunctions();
435 return nullptr;
436 }
437
438 return impl_handle;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800439}
440
441// Initializes memory allocation framework once per process.
442static void malloc_init_impl(libc_globals* globals) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800443 const char* prefix;
444 const char* shared_lib;
445 char prop[PROP_VALUE_MAX];
446 char* options = prop;
447 // Prefer malloc debug since it existed first and is a more complete
448 // malloc interceptor than the hooks.
449 if (CheckLoadMallocDebug(&options)) {
450 prefix = "debug";
451 shared_lib = DEBUG_SHARED_LIB;
452 } else if (CheckLoadMallocHooks(&options)) {
453 prefix = "hooks";
454 shared_lib = HOOKS_SHARED_LIB;
455 } else {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800456 return;
457 }
458
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800459 MallocDispatch dispatch_table;
460 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &dispatch_table);
461 if (impl_handle == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800462 return;
463 }
464
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800465 init_func_t init_func = reinterpret_cast<init_func_t>(g_functions[FUNC_INITIALIZE]);
Tamas Berghammerac81fe82016-08-26 15:54:59 +0100466 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800467 dlclose(impl_handle);
468 ClearGlobalFunctions();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800469 return;
470 }
471
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800472 globals->malloc_dispatch = dispatch_table;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800473
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800474 info_log("%s: malloc %s enabled", getprogname(), prefix);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800475
476 // Use atexit to trigger the cleanup function. This avoids a problem
477 // where another atexit function is used to cleanup allocated memory,
478 // but the finalize function was already called. This particular error
479 // seems to be triggered by a zygote spawned process calling exit.
480 int ret_value = __cxa_atexit(malloc_fini_impl, nullptr, nullptr);
481 if (ret_value != 0) {
482 error_log("failed to set atexit cleanup function: %d", ret_value);
483 }
484}
485
486// Initializes memory allocation framework.
487// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
488__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
489 malloc_init_impl(globals);
490}
491#endif // !LIBC_STATIC
Colin Cross869691c2016-01-29 12:48:18 -0800492
493// =============================================================================
494// Exported for use by libmemunreachable.
495// =============================================================================
496
497// Calls callback for every allocation in the anonymous heap mapping
498// [base, base+size). Must be called between malloc_disable and malloc_enable.
499extern "C" int malloc_iterate(uintptr_t base, size_t size,
500 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
501 auto _iterate = __libc_globals->malloc_dispatch.iterate;
502 if (__predict_false(_iterate != nullptr)) {
503 return _iterate(base, size, callback, arg);
504 }
505 return Malloc(iterate)(base, size, callback, arg);
506}
507
508// Disable calls to malloc so malloc_iterate gets a consistent view of
509// allocated memory.
510extern "C" void malloc_disable() {
511 auto _malloc_disable = __libc_globals->malloc_dispatch.malloc_disable;
512 if (__predict_false(_malloc_disable != nullptr)) {
513 return _malloc_disable();
514 }
515 return Malloc(malloc_disable)();
516}
517
518// Re-enable calls to malloc after a previous call to malloc_disable.
519extern "C" void malloc_enable() {
520 auto _malloc_enable = __libc_globals->malloc_dispatch.malloc_enable;
521 if (__predict_false(_malloc_enable != nullptr)) {
522 return _malloc_enable();
523 }
524 return Malloc(malloc_enable)();
525}
Colin Cross2d4721c2016-02-02 11:57:54 -0800526
527#ifndef LIBC_STATIC
528extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800529 void* func = g_functions[FUNC_MALLOC_BACKTRACE];
530 if (func == nullptr) {
Colin Cross2d4721c2016-02-02 11:57:54 -0800531 return 0;
532 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800533 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
Colin Cross2d4721c2016-02-02 11:57:54 -0800534}
535#else
536extern "C" ssize_t malloc_backtrace(void*, uintptr_t*, size_t) {
537 return 0;
538}
539#endif