blob: 79d25212e35674facab02cfc8d6c0dcf41196db9 [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
Anna Trostanetski9981a1d2020-01-20 20:16:29 +0000280// Note about USE_SCUDO. This file is compiled into libc.so and libc_scudo.so.
281// When compiled into libc_scudo.so, the libc_malloc_* libraries don't need
282// to be loaded from the runtime namespace since libc_scudo.so is not from
283// the runtime APEX, but is copied to any APEX that needs it.
284#ifndef USE_SCUDO
Jiyong Park3ff116a2019-04-02 23:04:52 +0900285extern "C" struct android_namespace_t* android_get_exported_namespace(const char* name);
Anna Trostanetski9981a1d2020-01-20 20:16:29 +0000286#endif
Jiyong Park3ff116a2019-04-02 23:04:52 +0900287
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800288void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
Jiyong Park3ff116a2019-04-02 23:04:52 +0900289 void* impl_handle = nullptr;
Anna Trostanetski9981a1d2020-01-20 20:16:29 +0000290#ifndef USE_SCUDO
Jiyong Park3ff116a2019-04-02 23:04:52 +0900291 // Try to load the libc_malloc_* libs from the "runtime" namespace and then
292 // fall back to dlopen() to load them from the default namespace.
293 //
294 // The libraries are packaged in the runtime APEX together with libc.so.
295 // However, since the libc.so is searched via the symlink in the system
296 // partition (/system/lib/libc.so -> /apex/com.android.runtime/bionic.libc.so)
297 // libc.so is loaded into the default namespace. If we just dlopen() here, the
298 // linker will load the libs found in /system/lib which might be incompatible
299 // with libc.so in the runtime APEX. Use android_dlopen_ext to explicitly load
300 // the ones in the runtime APEX.
301 struct android_namespace_t* runtime_ns = android_get_exported_namespace("runtime");
302 if (runtime_ns != nullptr) {
303 const android_dlextinfo dlextinfo = {
304 .flags = ANDROID_DLEXT_USE_NAMESPACE,
305 .library_namespace = runtime_ns,
306 };
307 impl_handle = android_dlopen_ext(shared_lib, RTLD_NOW | RTLD_LOCAL, &dlextinfo);
308 }
Anna Trostanetski9981a1d2020-01-20 20:16:29 +0000309#endif
Jiyong Park3ff116a2019-04-02 23:04:52 +0900310
311 if (impl_handle == nullptr) {
312 impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
313 }
314
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800315 if (impl_handle == nullptr) {
316 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
317 return nullptr;
318 }
319
320 if (!InitSharedLibrary(impl_handle, shared_lib, prefix, dispatch_table)) {
321 dlclose(impl_handle);
322 impl_handle = nullptr;
323 }
324
325 return impl_handle;
326}
327
328bool FinishInstallHooks(libc_globals* globals, const char* options, const char* prefix) {
329 init_func_t init_func = reinterpret_cast<init_func_t>(gFunctions[FUNC_INITIALIZE]);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800330
331 // If GWP-ASan was initialised, we should use it as the dispatch table for
332 // heapprofd/malloc_debug/malloc_debug.
333 const MallocDispatch* prev_dispatch = GetDefaultDispatchTable();
334 if (prev_dispatch == nullptr) {
335 prev_dispatch = NativeAllocatorDispatch();
336 }
337
338 if (!init_func(prev_dispatch, &gZygoteChild, options)) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800339 error_log("%s: failed to enable malloc %s", getprogname(), prefix);
340 ClearGlobalFunctions();
341 return false;
342 }
343
344 // Do a pointer swap so that all of the functions become valid at once to
345 // avoid any initialization order problems.
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800346 atomic_store(&globals->default_dispatch_table, &globals->malloc_dispatch_table);
347 if (GetDispatchTable() == nullptr) {
348 atomic_store(&globals->current_dispatch_table, &globals->malloc_dispatch_table);
349 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800350
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800351 // Use atexit to trigger the cleanup function. This avoids a problem
352 // where another atexit function is used to cleanup allocated memory,
353 // but the finalize function was already called. This particular error
354 // seems to be triggered by a zygote spawned process calling exit.
355 int ret_value = __cxa_atexit(MallocFiniImpl, nullptr, nullptr);
356 if (ret_value != 0) {
357 // We don't consider this a fatal error.
Christopher Ferrisc328e442019-04-01 19:31:26 -0700358 warning_log("failed to set atexit cleanup function: %d", ret_value);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800359 }
360 return true;
361}
362
Christopher Ferris28228562019-02-14 10:23:58 -0800363static bool InstallHooks(libc_globals* globals, const char* options, const char* prefix,
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800364 const char* shared_lib) {
365 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &globals->malloc_dispatch_table);
366 if (impl_handle == nullptr) {
Christopher Ferris28228562019-02-14 10:23:58 -0800367 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800368 }
369
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800370 if (!FinishInstallHooks(globals, options, prefix)) {
371 dlclose(impl_handle);
Christopher Ferris28228562019-02-14 10:23:58 -0800372 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800373 }
Christopher Ferris28228562019-02-14 10:23:58 -0800374 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800375}
376
377// Initializes memory allocation framework once per process.
378static void MallocInitImpl(libc_globals* globals) {
379 char prop[PROP_VALUE_MAX];
380 char* options = prop;
381
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800382 MaybeInitGwpAsanFromLibc();
383
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800384 // Prefer malloc debug since it existed first and is a more complete
385 // malloc interceptor than the hooks.
Christopher Ferris28228562019-02-14 10:23:58 -0800386 bool hook_installed = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800387 if (CheckLoadMallocDebug(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800388 hook_installed = InstallHooks(globals, options, kDebugPrefix, kDebugSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800389 } else if (CheckLoadMallocHooks(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800390 hook_installed = InstallHooks(globals, options, kHooksPrefix, kHooksSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800391 }
392
Christopher Ferris28228562019-02-14 10:23:58 -0800393 if (!hook_installed) {
394 if (HeapprofdShouldLoad()) {
395 HeapprofdInstallHooksAtInit(globals);
396 }
Christopher Ferris28228562019-02-14 10:23:58 -0800397 } else {
Ryan Savitski175c8862020-01-02 19:54:57 +0000398 // Record the fact that incompatible hooks are active, to skip any later
399 // heapprofd signal handler invocations.
400 HeapprofdRememberHookConflict();
Christopher Ferris28228562019-02-14 10:23:58 -0800401 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800402}
403
404// Initializes memory allocation framework.
405// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
406__BIONIC_WEAK_FOR_NATIVE_BRIDGE
407__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
408 MallocInitImpl(globals);
409}
410
411// =============================================================================
412// Functions to support dumping of native heap allocations using malloc debug.
413// =============================================================================
Christopher Ferris30659fd2019-04-15 19:01:08 -0700414bool GetMallocLeakInfo(android_mallopt_leak_info_t* leak_info) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800415 void* func = gFunctions[FUNC_GET_MALLOC_LEAK_INFO];
416 if (func == nullptr) {
Christopher Ferris30659fd2019-04-15 19:01:08 -0700417 errno = ENOTSUP;
418 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800419 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700420 reinterpret_cast<get_malloc_leak_info_func_t>(func)(
421 &leak_info->buffer, &leak_info->overall_size, &leak_info->info_size,
422 &leak_info->total_memory, &leak_info->backtrace_size);
423 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800424}
425
Christopher Ferris30659fd2019-04-15 19:01:08 -0700426bool FreeMallocLeakInfo(android_mallopt_leak_info_t* leak_info) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800427 void* func = gFunctions[FUNC_FREE_MALLOC_LEAK_INFO];
428 if (func == nullptr) {
Christopher Ferris30659fd2019-04-15 19:01:08 -0700429 errno = ENOTSUP;
430 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800431 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700432 reinterpret_cast<free_malloc_leak_info_func_t>(func)(leak_info->buffer);
433 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800434}
435
Christopher Ferris30659fd2019-04-15 19:01:08 -0700436bool WriteMallocLeakInfo(FILE* fp) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800437 void* func = gFunctions[FUNC_WRITE_LEAK_INFO];
438 bool written = false;
439 if (func != nullptr) {
440 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
441 }
442
443 if (!written) {
444 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
445 fprintf(fp, "# adb shell stop\n");
446 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
447 fprintf(fp, "# adb shell start\n");
Christopher Ferris30659fd2019-04-15 19:01:08 -0700448 errno = ENOTSUP;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800449 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700450 return written;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800451}
452// =============================================================================
453
454// =============================================================================
455// Exported for use by libmemunreachable.
456// =============================================================================
457extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
458 void* func = gFunctions[FUNC_MALLOC_BACKTRACE];
459 if (func == nullptr) {
460 return 0;
461 }
462 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
463}
464// =============================================================================
465
466// =============================================================================
467// Platform-internal mallopt variant.
468// =============================================================================
Evgeny Eltsinedbc9e22019-12-16 16:37:44 +0100469__BIONIC_WEAK_FOR_NATIVE_BRIDGE
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800470extern "C" bool android_mallopt(int opcode, void* arg, size_t arg_size) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700471 if (opcode == M_SET_ZYGOTE_CHILD) {
472 if (arg != nullptr || arg_size != 0) {
473 errno = EINVAL;
474 return false;
475 }
476 gZygoteChild = true;
477 return true;
478 }
Ryan Savitski175c8862020-01-02 19:54:57 +0000479 if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) {
480 if (arg != nullptr || arg_size != 0) {
481 errno = EINVAL;
482 return false;
483 }
484 atomic_store_explicit(&gZygoteChildProfileable, true, memory_order_release);
485 // Also check if heapprofd should start profiling from app startup.
486 HeapprofdInitZygoteChildProfiling();
487 return true;
488 }
489 if (opcode == M_GET_PROCESS_PROFILEABLE) {
490 if (arg == nullptr || arg_size != sizeof(bool)) {
491 errno = EINVAL;
492 return false;
493 }
494 // Native processes are considered profileable. Zygote children are considered
495 // profileable only when appropriately tagged.
496 *reinterpret_cast<bool*>(arg) =
497 !gZygoteChild || atomic_load_explicit(&gZygoteChildProfileable, memory_order_acquire);
498 return true;
499 }
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800500 if (opcode == M_SET_ALLOCATION_LIMIT_BYTES) {
501 return LimitEnable(arg, arg_size);
502 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700503 if (opcode == M_WRITE_MALLOC_LEAK_INFO_TO_FILE) {
504 if (arg == nullptr || arg_size != sizeof(FILE*)) {
505 errno = EINVAL;
506 return false;
507 }
508 return WriteMallocLeakInfo(reinterpret_cast<FILE*>(arg));
509 }
510 if (opcode == M_GET_MALLOC_LEAK_INFO) {
511 if (arg == nullptr || arg_size != sizeof(android_mallopt_leak_info_t)) {
512 errno = EINVAL;
513 return false;
514 }
515 return GetMallocLeakInfo(reinterpret_cast<android_mallopt_leak_info_t*>(arg));
516 }
517 if (opcode == M_FREE_MALLOC_LEAK_INFO) {
518 if (arg == nullptr || arg_size != sizeof(android_mallopt_leak_info_t)) {
519 errno = EINVAL;
520 return false;
521 }
522 return FreeMallocLeakInfo(reinterpret_cast<android_mallopt_leak_info_t*>(arg));
523 }
Peter Collingbourne1e110fb2020-01-09 10:48:22 -0800524 if (opcode == M_SET_HEAP_TAGGING_LEVEL) {
525 return SetHeapTaggingLevel(arg, arg_size);
526 }
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800527 if (opcode == M_INITIALIZE_GWP_ASAN) {
528 if (arg == nullptr || arg_size != sizeof(bool)) {
529 errno = EINVAL;
530 return false;
531 }
532 return MaybeInitGwpAsan(*reinterpret_cast<bool*>(arg));
533 }
Ryan Savitski175c8862020-01-02 19:54:57 +0000534 // Try heapprofd's mallopt, as it handles options not covered here.
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800535 return HeapprofdMallopt(opcode, arg, arg_size);
536}
537// =============================================================================
Christopher Ferris23c056d2019-05-07 16:02:49 -0700538
539#if !defined(__LP64__) && defined(__arm__)
540// =============================================================================
541// Old platform only functions that some old 32 bit apps are still using.
542// See b/132175052.
543// Only compile the functions for 32 bit arm, so that new apps do not use
544// these functions.
545// =============================================================================
546extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
547 size_t* total_memory, size_t* backtrace_size) {
548 if (info == nullptr || overall_size == nullptr || info_size == nullptr ||
549 total_memory == nullptr || backtrace_size == nullptr) {
550 return;
551 }
552
553 *info = nullptr;
554 *overall_size = 0;
555 *info_size = 0;
556 *total_memory = 0;
557 *backtrace_size = 0;
558
559 android_mallopt_leak_info_t leak_info = {};
560 if (android_mallopt(M_GET_MALLOC_LEAK_INFO, &leak_info, sizeof(leak_info))) {
561 *info = leak_info.buffer;
562 *overall_size = leak_info.overall_size;
563 *info_size = leak_info.info_size;
564 *total_memory = leak_info.total_memory;
565 *backtrace_size = leak_info.backtrace_size;
566 }
567}
568
569extern "C" void free_malloc_leak_info(uint8_t* info) {
570 android_mallopt_leak_info_t leak_info = { .buffer = info };
571 android_mallopt(M_FREE_MALLOC_LEAK_INFO, &leak_info, sizeof(leak_info));
572}
573// =============================================================================
574#endif