blob: da87c332e18a84760573f6302f09f55f4efc5a85 [file] [log] [blame]
Christopher Ferrise4cdbc42019-02-08 17:30:58 -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#if defined(LIBC_STATIC)
30#error This file should not be compiled for static targets.
31#endif
32
33// Contains a thin layer that calls whatever real native allocator
34// has been defined. For the libc shared library, this allows the
35// implementation of a debug malloc that can intercept all of the allocation
36// calls and add special debugging code to attempt to catch allocation
37// errors. All of the debugging code is implemented in a separate shared
38// library that is only loaded when the property "libc.debug.malloc.options"
39// is set to a non-zero value. There are three functions exported to
40// allow ddms, or other external users to get information from the debug
41// allocation.
42// get_malloc_leak_info: Returns information about all of the known native
43// allocations that are currently in use.
44// free_malloc_leak_info: Frees the data allocated by the call to
45// get_malloc_leak_info.
46// write_malloc_leak_info: Writes the leak info data to a file.
47
48#include <dlfcn.h>
Christopher Ferris8189e772019-04-09 16:37:23 -070049#include <errno.h>
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080050#include <fcntl.h>
51#include <pthread.h>
52#include <stdatomic.h>
53#include <stdbool.h>
54#include <stdio.h>
55#include <stdlib.h>
56#include <unistd.h>
57
Jiyong Park3ff116a2019-04-02 23:04:52 +090058#include <android/dlext.h>
59
Christopher Ferris2b0638e2019-09-11 19:05:29 -070060#include <platform/bionic/malloc.h>
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080061#include <private/bionic_config.h>
62#include <private/bionic_defs.h>
63#include <private/bionic_malloc_dispatch.h>
64
65#include <sys/system_properties.h>
66
Mitch Phillipsf3968e82020-01-31 19:57:04 -080067#include "gwp_asan_wrappers.h"
Peter Collingbourne1e110fb2020-01-09 10:48:22 -080068#include "heap_tagging.h"
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080069#include "malloc_common.h"
70#include "malloc_common_dynamic.h"
71#include "malloc_heapprofd.h"
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080072#include "malloc_limit.h"
73
74// =============================================================================
75// Global variables instantations.
76// =============================================================================
77pthread_mutex_t gGlobalsMutateLock = PTHREAD_MUTEX_INITIALIZER;
78
79_Atomic bool gGlobalsMutating = false;
Ryan Savitski175c8862020-01-02 19:54:57 +000080
81static bool gZygoteChild = false;
82
83// In a Zygote child process, this is set to true if profiling of this process
84// is allowed. Note that this is set at a later time than gZygoteChild. The
85// latter is set during the fork (while still in zygote's SELinux domain). While
86// this bit is set after the child is specialized (and has transferred SELinux
87// domains if applicable). These two flags are read by the
88// BIONIC_SIGNAL_PROFILER handler, which does nothing if the process is not
89// profileable.
90static _Atomic bool gZygoteChildProfileable = false;
91
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080092// =============================================================================
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080093
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080094static constexpr char kHooksSharedLib[] = "libc_malloc_hooks.so";
95static constexpr char kHooksPrefix[] = "hooks";
96static constexpr char kHooksPropertyEnable[] = "libc.debug.hooks.enable";
97static constexpr char kHooksEnvEnable[] = "LIBC_HOOKS_ENABLE";
98
99static constexpr char kDebugSharedLib[] = "libc_malloc_debug.so";
100static constexpr char kDebugPrefix[] = "debug";
101static constexpr char kDebugPropertyOptions[] = "libc.debug.malloc.options";
102static constexpr char kDebugPropertyProgram[] = "libc.debug.malloc.program";
103static constexpr char kDebugEnvOptions[] = "LIBC_DEBUG_MALLOC_OPTIONS";
104
105typedef void (*finalize_func_t)();
Christopher Ferris8189e772019-04-09 16:37:23 -0700106typedef bool (*init_func_t)(const MallocDispatch*, bool*, const char*);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800107typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
108typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
109typedef bool (*write_malloc_leak_info_func_t)(FILE*);
110typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
111
112enum FunctionEnum : uint8_t {
113 FUNC_INITIALIZE,
114 FUNC_FINALIZE,
115 FUNC_GET_MALLOC_LEAK_INFO,
116 FUNC_FREE_MALLOC_LEAK_INFO,
117 FUNC_MALLOC_BACKTRACE,
118 FUNC_WRITE_LEAK_INFO,
119 FUNC_LAST,
120};
121static void* gFunctions[FUNC_LAST];
122
123extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
124
125template<typename FunctionType>
126static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
127 char symbol[128];
128 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
129 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
130 if (*func == nullptr) {
131 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
132 return false;
133 }
134 return true;
135}
136
137static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
138 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
139 return false;
140 }
141 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
142 return false;
143 }
144 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
145 return false;
146 }
147 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
148 return false;
149 }
150 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
151 return false;
152 }
Christopher Ferris6c619a02019-03-01 17:59:51 -0800153 if (!InitMallocFunction<MallocMallocInfo>(impl_handler, &table->malloc_info, prefix,
154 "malloc_info")) {
155 return false;
156 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800157 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
158 "malloc_usable_size")) {
159 return false;
160 }
161 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
162 return false;
163 }
164 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
165 "posix_memalign")) {
166 return false;
167 }
168 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
169 prefix, "aligned_alloc")) {
170 return false;
171 }
172 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
173 return false;
174 }
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800175 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->malloc_iterate, prefix,
176 "malloc_iterate")) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800177 return false;
178 }
179 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
180 "malloc_disable")) {
181 return false;
182 }
183 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
184 "malloc_enable")) {
185 return false;
186 }
187#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
188 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
189 return false;
190 }
191 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
192 return false;
193 }
194#endif
195
196 return true;
197}
198
199static void MallocFiniImpl(void*) {
200 // Our BSD stdio implementation doesn't close the standard streams,
201 // it only flushes them. Other unclosed FILE*s will show up as
202 // malloc leaks, but to avoid the standard streams showing up in
203 // leak reports, close them here.
204 fclose(stdin);
205 fclose(stdout);
206 fclose(stderr);
207
208 reinterpret_cast<finalize_func_t>(gFunctions[FUNC_FINALIZE])();
209}
210
211static bool CheckLoadMallocHooks(char** options) {
212 char* env = getenv(kHooksEnvEnable);
213 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
214 (__system_property_get(kHooksPropertyEnable, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
215 return false;
216 }
217 *options = nullptr;
218 return true;
219}
220
221static bool CheckLoadMallocDebug(char** options) {
222 // If kDebugMallocEnvOptions is set then it overrides the system properties.
223 char* env = getenv(kDebugEnvOptions);
224 if (env == nullptr || env[0] == '\0') {
225 if (__system_property_get(kDebugPropertyOptions, *options) == 0 || *options[0] == '\0') {
226 return false;
227 }
228
229 // Check to see if only a specific program should have debug malloc enabled.
230 char program[PROP_VALUE_MAX];
231 if (__system_property_get(kDebugPropertyProgram, program) != 0 &&
232 strstr(getprogname(), program) == nullptr) {
233 return false;
234 }
235 } else {
236 *options = env;
237 }
238 return true;
239}
240
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800241void SetGlobalFunctions(void* functions[]) {
242 for (size_t i = 0; i < FUNC_LAST; i++) {
243 gFunctions[i] = functions[i];
244 }
245}
246
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800247static void ClearGlobalFunctions() {
248 for (size_t i = 0; i < FUNC_LAST; i++) {
249 gFunctions[i] = nullptr;
250 }
251}
252
253bool InitSharedLibrary(void* impl_handle, const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
254 static constexpr const char* names[] = {
255 "initialize",
256 "finalize",
257 "get_malloc_leak_info",
258 "free_malloc_leak_info",
259 "malloc_backtrace",
260 "write_malloc_leak_info",
261 };
262 for (size_t i = 0; i < FUNC_LAST; i++) {
263 char symbol[128];
264 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
265 gFunctions[i] = dlsym(impl_handle, symbol);
266 if (gFunctions[i] == nullptr) {
267 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
268 ClearGlobalFunctions();
269 return false;
270 }
271 }
272
273 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
274 ClearGlobalFunctions();
275 return false;
276 }
277 return true;
278}
279
Jiyong Park3ff116a2019-04-02 23:04:52 +0900280extern "C" struct android_namespace_t* android_get_exported_namespace(const char* name);
281
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800282void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
Jiyong Park3ff116a2019-04-02 23:04:52 +0900283 void* impl_handle = nullptr;
284 // Try to load the libc_malloc_* libs from the "runtime" namespace and then
285 // fall back to dlopen() to load them from the default namespace.
286 //
287 // The libraries are packaged in the runtime APEX together with libc.so.
288 // However, since the libc.so is searched via the symlink in the system
Jooyung Hand55689b2020-02-08 03:49:22 +0900289 // partition (/system/lib/libc.so -> /apex/com.android.runtime/bionic/libc.so)
Jiyong Park3ff116a2019-04-02 23:04:52 +0900290 // libc.so is loaded into the default namespace. If we just dlopen() here, the
291 // linker will load the libs found in /system/lib which might be incompatible
292 // with libc.so in the runtime APEX. Use android_dlopen_ext to explicitly load
293 // the ones in the runtime APEX.
Kiyoung Kim8116b702020-02-19 16:18:11 +0900294 struct android_namespace_t* runtime_ns = android_get_exported_namespace("com_android_runtime");
Jiyong Park3ff116a2019-04-02 23:04:52 +0900295 if (runtime_ns != nullptr) {
296 const android_dlextinfo dlextinfo = {
297 .flags = ANDROID_DLEXT_USE_NAMESPACE,
298 .library_namespace = runtime_ns,
299 };
300 impl_handle = android_dlopen_ext(shared_lib, RTLD_NOW | RTLD_LOCAL, &dlextinfo);
301 }
302
303 if (impl_handle == nullptr) {
304 impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
305 }
306
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800307 if (impl_handle == nullptr) {
308 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
309 return nullptr;
310 }
311
312 if (!InitSharedLibrary(impl_handle, shared_lib, prefix, dispatch_table)) {
313 dlclose(impl_handle);
314 impl_handle = nullptr;
315 }
316
317 return impl_handle;
318}
319
320bool FinishInstallHooks(libc_globals* globals, const char* options, const char* prefix) {
321 init_func_t init_func = reinterpret_cast<init_func_t>(gFunctions[FUNC_INITIALIZE]);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800322
323 // If GWP-ASan was initialised, we should use it as the dispatch table for
324 // heapprofd/malloc_debug/malloc_debug.
325 const MallocDispatch* prev_dispatch = GetDefaultDispatchTable();
326 if (prev_dispatch == nullptr) {
327 prev_dispatch = NativeAllocatorDispatch();
328 }
329
330 if (!init_func(prev_dispatch, &gZygoteChild, options)) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800331 error_log("%s: failed to enable malloc %s", getprogname(), prefix);
332 ClearGlobalFunctions();
333 return false;
334 }
335
336 // Do a pointer swap so that all of the functions become valid at once to
337 // avoid any initialization order problems.
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800338 atomic_store(&globals->default_dispatch_table, &globals->malloc_dispatch_table);
Mitch Phillips3083cc92020-02-11 15:23:47 -0800339 if (!MallocLimitInstalled()) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800340 atomic_store(&globals->current_dispatch_table, &globals->malloc_dispatch_table);
341 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800342
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800343 // Use atexit to trigger the cleanup function. This avoids a problem
344 // where another atexit function is used to cleanup allocated memory,
345 // but the finalize function was already called. This particular error
346 // seems to be triggered by a zygote spawned process calling exit.
347 int ret_value = __cxa_atexit(MallocFiniImpl, nullptr, nullptr);
348 if (ret_value != 0) {
349 // We don't consider this a fatal error.
Christopher Ferrisc328e442019-04-01 19:31:26 -0700350 warning_log("failed to set atexit cleanup function: %d", ret_value);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800351 }
352 return true;
353}
354
Christopher Ferris28228562019-02-14 10:23:58 -0800355static bool InstallHooks(libc_globals* globals, const char* options, const char* prefix,
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800356 const char* shared_lib) {
357 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &globals->malloc_dispatch_table);
358 if (impl_handle == nullptr) {
Christopher Ferris28228562019-02-14 10:23:58 -0800359 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800360 }
361
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800362 if (!FinishInstallHooks(globals, options, prefix)) {
363 dlclose(impl_handle);
Christopher Ferris28228562019-02-14 10:23:58 -0800364 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800365 }
Christopher Ferris28228562019-02-14 10:23:58 -0800366 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800367}
368
369// Initializes memory allocation framework once per process.
370static void MallocInitImpl(libc_globals* globals) {
371 char prop[PROP_VALUE_MAX];
372 char* options = prop;
373
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800374 MaybeInitGwpAsanFromLibc(globals);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800375
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800376 // Prefer malloc debug since it existed first and is a more complete
377 // malloc interceptor than the hooks.
Christopher Ferris28228562019-02-14 10:23:58 -0800378 bool hook_installed = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800379 if (CheckLoadMallocDebug(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800380 hook_installed = InstallHooks(globals, options, kDebugPrefix, kDebugSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800381 } else if (CheckLoadMallocHooks(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800382 hook_installed = InstallHooks(globals, options, kHooksPrefix, kHooksSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800383 }
384
Christopher Ferris28228562019-02-14 10:23:58 -0800385 if (!hook_installed) {
386 if (HeapprofdShouldLoad()) {
387 HeapprofdInstallHooksAtInit(globals);
388 }
Christopher Ferris28228562019-02-14 10:23:58 -0800389 } else {
Ryan Savitski175c8862020-01-02 19:54:57 +0000390 // Record the fact that incompatible hooks are active, to skip any later
391 // heapprofd signal handler invocations.
392 HeapprofdRememberHookConflict();
Christopher Ferris28228562019-02-14 10:23:58 -0800393 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800394}
395
396// Initializes memory allocation framework.
397// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
398__BIONIC_WEAK_FOR_NATIVE_BRIDGE
399__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
400 MallocInitImpl(globals);
401}
402
403// =============================================================================
404// Functions to support dumping of native heap allocations using malloc debug.
405// =============================================================================
Christopher Ferris30659fd2019-04-15 19:01:08 -0700406bool GetMallocLeakInfo(android_mallopt_leak_info_t* leak_info) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800407 void* func = gFunctions[FUNC_GET_MALLOC_LEAK_INFO];
408 if (func == nullptr) {
Christopher Ferris30659fd2019-04-15 19:01:08 -0700409 errno = ENOTSUP;
410 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800411 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700412 reinterpret_cast<get_malloc_leak_info_func_t>(func)(
413 &leak_info->buffer, &leak_info->overall_size, &leak_info->info_size,
414 &leak_info->total_memory, &leak_info->backtrace_size);
415 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800416}
417
Christopher Ferris30659fd2019-04-15 19:01:08 -0700418bool FreeMallocLeakInfo(android_mallopt_leak_info_t* leak_info) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800419 void* func = gFunctions[FUNC_FREE_MALLOC_LEAK_INFO];
420 if (func == nullptr) {
Christopher Ferris30659fd2019-04-15 19:01:08 -0700421 errno = ENOTSUP;
422 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800423 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700424 reinterpret_cast<free_malloc_leak_info_func_t>(func)(leak_info->buffer);
425 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800426}
427
Christopher Ferris30659fd2019-04-15 19:01:08 -0700428bool WriteMallocLeakInfo(FILE* fp) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800429 void* func = gFunctions[FUNC_WRITE_LEAK_INFO];
430 bool written = false;
431 if (func != nullptr) {
432 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
433 }
434
435 if (!written) {
436 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
437 fprintf(fp, "# adb shell stop\n");
438 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
439 fprintf(fp, "# adb shell start\n");
Christopher Ferris30659fd2019-04-15 19:01:08 -0700440 errno = ENOTSUP;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800441 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700442 return written;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800443}
444// =============================================================================
445
446// =============================================================================
447// Exported for use by libmemunreachable.
448// =============================================================================
449extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
450 void* func = gFunctions[FUNC_MALLOC_BACKTRACE];
451 if (func == nullptr) {
452 return 0;
453 }
454 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
455}
456// =============================================================================
457
458// =============================================================================
459// Platform-internal mallopt variant.
460// =============================================================================
Evgeny Eltsinedbc9e22019-12-16 16:37:44 +0100461__BIONIC_WEAK_FOR_NATIVE_BRIDGE
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800462extern "C" bool android_mallopt(int opcode, void* arg, size_t arg_size) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700463 if (opcode == M_SET_ZYGOTE_CHILD) {
464 if (arg != nullptr || arg_size != 0) {
465 errno = EINVAL;
466 return false;
467 }
468 gZygoteChild = true;
469 return true;
470 }
Ryan Savitski175c8862020-01-02 19:54:57 +0000471 if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) {
472 if (arg != nullptr || arg_size != 0) {
473 errno = EINVAL;
474 return false;
475 }
476 atomic_store_explicit(&gZygoteChildProfileable, true, memory_order_release);
477 // Also check if heapprofd should start profiling from app startup.
478 HeapprofdInitZygoteChildProfiling();
479 return true;
480 }
481 if (opcode == M_GET_PROCESS_PROFILEABLE) {
482 if (arg == nullptr || arg_size != sizeof(bool)) {
483 errno = EINVAL;
484 return false;
485 }
486 // Native processes are considered profileable. Zygote children are considered
487 // profileable only when appropriately tagged.
488 *reinterpret_cast<bool*>(arg) =
489 !gZygoteChild || atomic_load_explicit(&gZygoteChildProfileable, memory_order_acquire);
490 return true;
491 }
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800492 if (opcode == M_SET_ALLOCATION_LIMIT_BYTES) {
493 return LimitEnable(arg, arg_size);
494 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700495 if (opcode == M_WRITE_MALLOC_LEAK_INFO_TO_FILE) {
496 if (arg == nullptr || arg_size != sizeof(FILE*)) {
497 errno = EINVAL;
498 return false;
499 }
500 return WriteMallocLeakInfo(reinterpret_cast<FILE*>(arg));
501 }
502 if (opcode == M_GET_MALLOC_LEAK_INFO) {
503 if (arg == nullptr || arg_size != sizeof(android_mallopt_leak_info_t)) {
504 errno = EINVAL;
505 return false;
506 }
507 return GetMallocLeakInfo(reinterpret_cast<android_mallopt_leak_info_t*>(arg));
508 }
509 if (opcode == M_FREE_MALLOC_LEAK_INFO) {
510 if (arg == nullptr || arg_size != sizeof(android_mallopt_leak_info_t)) {
511 errno = EINVAL;
512 return false;
513 }
514 return FreeMallocLeakInfo(reinterpret_cast<android_mallopt_leak_info_t*>(arg));
515 }
Peter Collingbourne1e110fb2020-01-09 10:48:22 -0800516 if (opcode == M_SET_HEAP_TAGGING_LEVEL) {
517 return SetHeapTaggingLevel(arg, arg_size);
518 }
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800519 if (opcode == M_INITIALIZE_GWP_ASAN) {
520 if (arg == nullptr || arg_size != sizeof(bool)) {
521 errno = EINVAL;
522 return false;
523 }
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800524 __libc_globals.mutate([&](libc_globals* globals) {
525 return MaybeInitGwpAsan(globals, *reinterpret_cast<bool*>(arg));
526 });
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800527 }
Ryan Savitski175c8862020-01-02 19:54:57 +0000528 // Try heapprofd's mallopt, as it handles options not covered here.
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800529 return HeapprofdMallopt(opcode, arg, arg_size);
530}
531// =============================================================================
Christopher Ferris23c056d2019-05-07 16:02:49 -0700532
533#if !defined(__LP64__) && defined(__arm__)
534// =============================================================================
535// Old platform only functions that some old 32 bit apps are still using.
536// See b/132175052.
537// Only compile the functions for 32 bit arm, so that new apps do not use
538// these functions.
539// =============================================================================
540extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
541 size_t* total_memory, size_t* backtrace_size) {
542 if (info == nullptr || overall_size == nullptr || info_size == nullptr ||
543 total_memory == nullptr || backtrace_size == nullptr) {
544 return;
545 }
546
547 *info = nullptr;
548 *overall_size = 0;
549 *info_size = 0;
550 *total_memory = 0;
551 *backtrace_size = 0;
552
553 android_mallopt_leak_info_t leak_info = {};
554 if (android_mallopt(M_GET_MALLOC_LEAK_INFO, &leak_info, sizeof(leak_info))) {
555 *info = leak_info.buffer;
556 *overall_size = leak_info.overall_size;
557 *info_size = leak_info.info_size;
558 *total_memory = leak_info.total_memory;
559 *backtrace_size = leak_info.backtrace_size;
560 }
561}
562
563extern "C" void free_malloc_leak_info(uint8_t* info) {
564 android_mallopt_leak_info_t leak_info = { .buffer = info };
565 android_mallopt(M_FREE_MALLOC_LEAK_INFO, &leak_info, sizeof(leak_info));
566}
567// =============================================================================
568#endif