blob: eeeaff90ef99e4424edee34017cf0d27d40b8806 [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"
Peter Collingbourne5d3aa862020-09-11 15:05:17 -070073#include "memory_mitigation_state.h"
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080074
75// =============================================================================
76// Global variables instantations.
77// =============================================================================
78pthread_mutex_t gGlobalsMutateLock = PTHREAD_MUTEX_INITIALIZER;
79
80_Atomic bool gGlobalsMutating = false;
Ryan Savitski175c8862020-01-02 19:54:57 +000081
82static bool gZygoteChild = false;
83
84// In a Zygote child process, this is set to true if profiling of this process
85// is allowed. Note that this is set at a later time than gZygoteChild. The
86// latter is set during the fork (while still in zygote's SELinux domain). While
87// this bit is set after the child is specialized (and has transferred SELinux
88// domains if applicable). These two flags are read by the
89// BIONIC_SIGNAL_PROFILER handler, which does nothing if the process is not
90// profileable.
91static _Atomic bool gZygoteChildProfileable = false;
92
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080093// =============================================================================
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080094
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080095static constexpr char kHooksSharedLib[] = "libc_malloc_hooks.so";
96static constexpr char kHooksPrefix[] = "hooks";
97static constexpr char kHooksPropertyEnable[] = "libc.debug.hooks.enable";
98static constexpr char kHooksEnvEnable[] = "LIBC_HOOKS_ENABLE";
99
100static constexpr char kDebugSharedLib[] = "libc_malloc_debug.so";
101static constexpr char kDebugPrefix[] = "debug";
102static constexpr char kDebugPropertyOptions[] = "libc.debug.malloc.options";
103static constexpr char kDebugPropertyProgram[] = "libc.debug.malloc.program";
104static constexpr char kDebugEnvOptions[] = "LIBC_DEBUG_MALLOC_OPTIONS";
105
106typedef void (*finalize_func_t)();
Christopher Ferris8189e772019-04-09 16:37:23 -0700107typedef bool (*init_func_t)(const MallocDispatch*, bool*, const char*);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800108typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
109typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
110typedef bool (*write_malloc_leak_info_func_t)(FILE*);
111typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
112
113enum FunctionEnum : uint8_t {
114 FUNC_INITIALIZE,
115 FUNC_FINALIZE,
116 FUNC_GET_MALLOC_LEAK_INFO,
117 FUNC_FREE_MALLOC_LEAK_INFO,
118 FUNC_MALLOC_BACKTRACE,
119 FUNC_WRITE_LEAK_INFO,
120 FUNC_LAST,
121};
122static void* gFunctions[FUNC_LAST];
123
124extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
125
126template<typename FunctionType>
127static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
128 char symbol[128];
129 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
130 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
131 if (*func == nullptr) {
132 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
133 return false;
134 }
135 return true;
136}
137
138static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
139 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
140 return false;
141 }
142 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
143 return false;
144 }
145 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
146 return false;
147 }
148 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
149 return false;
150 }
151 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
152 return false;
153 }
Christopher Ferris6c619a02019-03-01 17:59:51 -0800154 if (!InitMallocFunction<MallocMallocInfo>(impl_handler, &table->malloc_info, prefix,
155 "malloc_info")) {
156 return false;
157 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800158 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
159 "malloc_usable_size")) {
160 return false;
161 }
162 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
163 return false;
164 }
165 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
166 "posix_memalign")) {
167 return false;
168 }
169 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
170 prefix, "aligned_alloc")) {
171 return false;
172 }
173 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
174 return false;
175 }
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800176 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->malloc_iterate, prefix,
177 "malloc_iterate")) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800178 return false;
179 }
180 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
181 "malloc_disable")) {
182 return false;
183 }
184 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
185 "malloc_enable")) {
186 return false;
187 }
188#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
189 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
190 return false;
191 }
192 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
193 return false;
194 }
195#endif
196
197 return true;
198}
199
200static void MallocFiniImpl(void*) {
201 // Our BSD stdio implementation doesn't close the standard streams,
202 // it only flushes them. Other unclosed FILE*s will show up as
203 // malloc leaks, but to avoid the standard streams showing up in
204 // leak reports, close them here.
205 fclose(stdin);
206 fclose(stdout);
207 fclose(stderr);
208
209 reinterpret_cast<finalize_func_t>(gFunctions[FUNC_FINALIZE])();
210}
211
212static bool CheckLoadMallocHooks(char** options) {
213 char* env = getenv(kHooksEnvEnable);
214 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
215 (__system_property_get(kHooksPropertyEnable, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
216 return false;
217 }
218 *options = nullptr;
219 return true;
220}
221
222static bool CheckLoadMallocDebug(char** options) {
223 // If kDebugMallocEnvOptions is set then it overrides the system properties.
224 char* env = getenv(kDebugEnvOptions);
225 if (env == nullptr || env[0] == '\0') {
226 if (__system_property_get(kDebugPropertyOptions, *options) == 0 || *options[0] == '\0') {
227 return false;
228 }
229
230 // Check to see if only a specific program should have debug malloc enabled.
231 char program[PROP_VALUE_MAX];
232 if (__system_property_get(kDebugPropertyProgram, program) != 0 &&
233 strstr(getprogname(), program) == nullptr) {
234 return false;
235 }
236 } else {
237 *options = env;
238 }
239 return true;
240}
241
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800242void SetGlobalFunctions(void* functions[]) {
243 for (size_t i = 0; i < FUNC_LAST; i++) {
244 gFunctions[i] = functions[i];
245 }
246}
247
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800248static void ClearGlobalFunctions() {
249 for (size_t i = 0; i < FUNC_LAST; i++) {
250 gFunctions[i] = nullptr;
251 }
252}
253
254bool InitSharedLibrary(void* impl_handle, const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
255 static constexpr const char* names[] = {
256 "initialize",
257 "finalize",
258 "get_malloc_leak_info",
259 "free_malloc_leak_info",
260 "malloc_backtrace",
261 "write_malloc_leak_info",
262 };
263 for (size_t i = 0; i < FUNC_LAST; i++) {
264 char symbol[128];
265 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
266 gFunctions[i] = dlsym(impl_handle, symbol);
267 if (gFunctions[i] == nullptr) {
268 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
269 ClearGlobalFunctions();
270 return false;
271 }
272 }
273
274 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
275 ClearGlobalFunctions();
276 return false;
277 }
278 return true;
279}
280
Jiyong Park3ff116a2019-04-02 23:04:52 +0900281extern "C" struct android_namespace_t* android_get_exported_namespace(const char* name);
282
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800283void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
Jiyong Park3ff116a2019-04-02 23:04:52 +0900284 void* impl_handle = nullptr;
285 // Try to load the libc_malloc_* libs from the "runtime" namespace and then
286 // fall back to dlopen() to load them from the default namespace.
287 //
288 // The libraries are packaged in the runtime APEX together with libc.so.
289 // However, since the libc.so is searched via the symlink in the system
Jooyung Hand55689b2020-02-08 03:49:22 +0900290 // partition (/system/lib/libc.so -> /apex/com.android.runtime/bionic/libc.so)
Jiyong Park3ff116a2019-04-02 23:04:52 +0900291 // libc.so is loaded into the default namespace. If we just dlopen() here, the
292 // linker will load the libs found in /system/lib which might be incompatible
293 // with libc.so in the runtime APEX. Use android_dlopen_ext to explicitly load
294 // the ones in the runtime APEX.
Kiyoung Kim8116b702020-02-19 16:18:11 +0900295 struct android_namespace_t* runtime_ns = android_get_exported_namespace("com_android_runtime");
Jiyong Park3ff116a2019-04-02 23:04:52 +0900296 if (runtime_ns != nullptr) {
297 const android_dlextinfo dlextinfo = {
298 .flags = ANDROID_DLEXT_USE_NAMESPACE,
299 .library_namespace = runtime_ns,
300 };
301 impl_handle = android_dlopen_ext(shared_lib, RTLD_NOW | RTLD_LOCAL, &dlextinfo);
302 }
303
304 if (impl_handle == nullptr) {
305 impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
306 }
307
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800308 if (impl_handle == nullptr) {
309 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
310 return nullptr;
311 }
312
313 if (!InitSharedLibrary(impl_handle, shared_lib, prefix, dispatch_table)) {
314 dlclose(impl_handle);
315 impl_handle = nullptr;
316 }
317
318 return impl_handle;
319}
320
321bool FinishInstallHooks(libc_globals* globals, const char* options, const char* prefix) {
322 init_func_t init_func = reinterpret_cast<init_func_t>(gFunctions[FUNC_INITIALIZE]);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800323
324 // If GWP-ASan was initialised, we should use it as the dispatch table for
325 // heapprofd/malloc_debug/malloc_debug.
326 const MallocDispatch* prev_dispatch = GetDefaultDispatchTable();
327 if (prev_dispatch == nullptr) {
328 prev_dispatch = NativeAllocatorDispatch();
329 }
330
331 if (!init_func(prev_dispatch, &gZygoteChild, options)) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800332 error_log("%s: failed to enable malloc %s", getprogname(), prefix);
333 ClearGlobalFunctions();
334 return false;
335 }
336
337 // Do a pointer swap so that all of the functions become valid at once to
338 // avoid any initialization order problems.
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800339 atomic_store(&globals->default_dispatch_table, &globals->malloc_dispatch_table);
Mitch Phillips3083cc92020-02-11 15:23:47 -0800340 if (!MallocLimitInstalled()) {
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800341 atomic_store(&globals->current_dispatch_table, &globals->malloc_dispatch_table);
342 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800343
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800344 // Use atexit to trigger the cleanup function. This avoids a problem
345 // where another atexit function is used to cleanup allocated memory,
346 // but the finalize function was already called. This particular error
347 // seems to be triggered by a zygote spawned process calling exit.
348 int ret_value = __cxa_atexit(MallocFiniImpl, nullptr, nullptr);
349 if (ret_value != 0) {
350 // We don't consider this a fatal error.
Christopher Ferrisc328e442019-04-01 19:31:26 -0700351 warning_log("failed to set atexit cleanup function: %d", ret_value);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800352 }
353 return true;
354}
355
Christopher Ferris28228562019-02-14 10:23:58 -0800356static bool InstallHooks(libc_globals* globals, const char* options, const char* prefix,
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800357 const char* shared_lib) {
358 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &globals->malloc_dispatch_table);
359 if (impl_handle == nullptr) {
Christopher Ferris28228562019-02-14 10:23:58 -0800360 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800361 }
362
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800363 if (!FinishInstallHooks(globals, options, prefix)) {
364 dlclose(impl_handle);
Christopher Ferris28228562019-02-14 10:23:58 -0800365 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800366 }
Christopher Ferris28228562019-02-14 10:23:58 -0800367 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800368}
369
Peter Collingbourned3060012020-04-01 19:54:48 -0700370extern "C" const char* __scudo_get_stack_depot_addr();
371extern "C" const char* __scudo_get_region_info_addr();
372
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800373// Initializes memory allocation framework once per process.
374static void MallocInitImpl(libc_globals* globals) {
375 char prop[PROP_VALUE_MAX];
376 char* options = prop;
377
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800378 MaybeInitGwpAsanFromLibc(globals);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800379
Peter Collingbourned3060012020-04-01 19:54:48 -0700380#if defined(USE_SCUDO)
381 __libc_shared_globals()->scudo_stack_depot = __scudo_get_stack_depot_addr();
382 __libc_shared_globals()->scudo_region_info = __scudo_get_region_info_addr();
383#endif
384
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800385 // Prefer malloc debug since it existed first and is a more complete
386 // malloc interceptor than the hooks.
Christopher Ferris28228562019-02-14 10:23:58 -0800387 bool hook_installed = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800388 if (CheckLoadMallocDebug(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800389 hook_installed = InstallHooks(globals, options, kDebugPrefix, kDebugSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800390 } else if (CheckLoadMallocHooks(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800391 hook_installed = InstallHooks(globals, options, kHooksPrefix, kHooksSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800392 }
393
Christopher Ferris28228562019-02-14 10:23:58 -0800394 if (!hook_installed) {
395 if (HeapprofdShouldLoad()) {
396 HeapprofdInstallHooksAtInit(globals);
397 }
Christopher Ferris28228562019-02-14 10:23:58 -0800398 } else {
Ryan Savitski175c8862020-01-02 19:54:57 +0000399 // Record the fact that incompatible hooks are active, to skip any later
400 // heapprofd signal handler invocations.
401 HeapprofdRememberHookConflict();
Christopher Ferris28228562019-02-14 10:23:58 -0800402 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800403}
404
405// Initializes memory allocation framework.
406// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
407__BIONIC_WEAK_FOR_NATIVE_BRIDGE
408__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
409 MallocInitImpl(globals);
410}
411
412// =============================================================================
413// Functions to support dumping of native heap allocations using malloc debug.
414// =============================================================================
Christopher Ferris30659fd2019-04-15 19:01:08 -0700415bool GetMallocLeakInfo(android_mallopt_leak_info_t* leak_info) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800416 void* func = gFunctions[FUNC_GET_MALLOC_LEAK_INFO];
417 if (func == nullptr) {
Christopher Ferris30659fd2019-04-15 19:01:08 -0700418 errno = ENOTSUP;
419 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800420 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700421 reinterpret_cast<get_malloc_leak_info_func_t>(func)(
422 &leak_info->buffer, &leak_info->overall_size, &leak_info->info_size,
423 &leak_info->total_memory, &leak_info->backtrace_size);
424 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800425}
426
Christopher Ferris30659fd2019-04-15 19:01:08 -0700427bool FreeMallocLeakInfo(android_mallopt_leak_info_t* leak_info) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800428 void* func = gFunctions[FUNC_FREE_MALLOC_LEAK_INFO];
429 if (func == nullptr) {
Christopher Ferris30659fd2019-04-15 19:01:08 -0700430 errno = ENOTSUP;
431 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800432 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700433 reinterpret_cast<free_malloc_leak_info_func_t>(func)(leak_info->buffer);
434 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800435}
436
Christopher Ferris30659fd2019-04-15 19:01:08 -0700437bool WriteMallocLeakInfo(FILE* fp) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800438 void* func = gFunctions[FUNC_WRITE_LEAK_INFO];
439 bool written = false;
440 if (func != nullptr) {
441 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
442 }
443
444 if (!written) {
445 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
446 fprintf(fp, "# adb shell stop\n");
447 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
448 fprintf(fp, "# adb shell start\n");
Christopher Ferris30659fd2019-04-15 19:01:08 -0700449 errno = ENOTSUP;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800450 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700451 return written;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800452}
453// =============================================================================
454
455// =============================================================================
456// Exported for use by libmemunreachable.
457// =============================================================================
458extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
459 void* func = gFunctions[FUNC_MALLOC_BACKTRACE];
460 if (func == nullptr) {
461 return 0;
462 }
463 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
464}
465// =============================================================================
466
467// =============================================================================
468// Platform-internal mallopt variant.
469// =============================================================================
Evgeny Eltsinedbc9e22019-12-16 16:37:44 +0100470__BIONIC_WEAK_FOR_NATIVE_BRIDGE
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800471extern "C" bool android_mallopt(int opcode, void* arg, size_t arg_size) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700472 if (opcode == M_SET_ZYGOTE_CHILD) {
473 if (arg != nullptr || arg_size != 0) {
474 errno = EINVAL;
475 return false;
476 }
477 gZygoteChild = true;
478 return true;
479 }
Ryan Savitski175c8862020-01-02 19:54:57 +0000480 if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) {
481 if (arg != nullptr || arg_size != 0) {
482 errno = EINVAL;
483 return false;
484 }
485 atomic_store_explicit(&gZygoteChildProfileable, true, memory_order_release);
486 // Also check if heapprofd should start profiling from app startup.
487 HeapprofdInitZygoteChildProfiling();
488 return true;
489 }
490 if (opcode == M_GET_PROCESS_PROFILEABLE) {
491 if (arg == nullptr || arg_size != sizeof(bool)) {
492 errno = EINVAL;
493 return false;
494 }
495 // Native processes are considered profileable. Zygote children are considered
496 // profileable only when appropriately tagged.
497 *reinterpret_cast<bool*>(arg) =
498 !gZygoteChild || atomic_load_explicit(&gZygoteChildProfileable, memory_order_acquire);
499 return true;
500 }
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800501 if (opcode == M_SET_ALLOCATION_LIMIT_BYTES) {
502 return LimitEnable(arg, arg_size);
503 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700504 if (opcode == M_WRITE_MALLOC_LEAK_INFO_TO_FILE) {
505 if (arg == nullptr || arg_size != sizeof(FILE*)) {
506 errno = EINVAL;
507 return false;
508 }
509 return WriteMallocLeakInfo(reinterpret_cast<FILE*>(arg));
510 }
511 if (opcode == M_GET_MALLOC_LEAK_INFO) {
512 if (arg == nullptr || arg_size != sizeof(android_mallopt_leak_info_t)) {
513 errno = EINVAL;
514 return false;
515 }
516 return GetMallocLeakInfo(reinterpret_cast<android_mallopt_leak_info_t*>(arg));
517 }
518 if (opcode == M_FREE_MALLOC_LEAK_INFO) {
519 if (arg == nullptr || arg_size != sizeof(android_mallopt_leak_info_t)) {
520 errno = EINVAL;
521 return false;
522 }
523 return FreeMallocLeakInfo(reinterpret_cast<android_mallopt_leak_info_t*>(arg));
524 }
Peter Collingbourne1e110fb2020-01-09 10:48:22 -0800525 if (opcode == M_SET_HEAP_TAGGING_LEVEL) {
526 return SetHeapTaggingLevel(arg, arg_size);
527 }
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800528 if (opcode == M_INITIALIZE_GWP_ASAN) {
529 if (arg == nullptr || arg_size != sizeof(bool)) {
530 errno = EINVAL;
531 return false;
532 }
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800533 __libc_globals.mutate([&](libc_globals* globals) {
534 return MaybeInitGwpAsan(globals, *reinterpret_cast<bool*>(arg));
535 });
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800536 }
Peter Collingbourne5d3aa862020-09-11 15:05:17 -0700537 if (opcode == M_DISABLE_MEMORY_MITIGATIONS) {
538 return DisableMemoryMitigations(arg, arg_size);
539 }
Ryan Savitski175c8862020-01-02 19:54:57 +0000540 // Try heapprofd's mallopt, as it handles options not covered here.
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800541 return HeapprofdMallopt(opcode, arg, arg_size);
542}
543// =============================================================================
Christopher Ferris23c056d2019-05-07 16:02:49 -0700544
545#if !defined(__LP64__) && defined(__arm__)
546// =============================================================================
547// Old platform only functions that some old 32 bit apps are still using.
548// See b/132175052.
549// Only compile the functions for 32 bit arm, so that new apps do not use
550// these functions.
551// =============================================================================
552extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
553 size_t* total_memory, size_t* backtrace_size) {
554 if (info == nullptr || overall_size == nullptr || info_size == nullptr ||
555 total_memory == nullptr || backtrace_size == nullptr) {
556 return;
557 }
558
559 *info = nullptr;
560 *overall_size = 0;
561 *info_size = 0;
562 *total_memory = 0;
563 *backtrace_size = 0;
564
565 android_mallopt_leak_info_t leak_info = {};
566 if (android_mallopt(M_GET_MALLOC_LEAK_INFO, &leak_info, sizeof(leak_info))) {
567 *info = leak_info.buffer;
568 *overall_size = leak_info.overall_size;
569 *info_size = leak_info.info_size;
570 *total_memory = leak_info.total_memory;
571 *backtrace_size = leak_info.backtrace_size;
572 }
573}
574
575extern "C" void free_malloc_leak_info(uint8_t* info) {
576 android_mallopt_leak_info_t leak_info = { .buffer = info };
577 android_mallopt(M_FREE_MALLOC_LEAK_INFO, &leak_info, sizeof(leak_info));
578}
579// =============================================================================
580#endif