blob: 2cb1e8a56128523c8f6171dfe59dd3effe005523 [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
Peter Collingbourne1e110fb2020-01-09 10:48:22 -080067#include "heap_tagging.h"
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080068#include "malloc_common.h"
69#include "malloc_common_dynamic.h"
70#include "malloc_heapprofd.h"
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080071#include "malloc_limit.h"
72
73// =============================================================================
74// Global variables instantations.
75// =============================================================================
76pthread_mutex_t gGlobalsMutateLock = PTHREAD_MUTEX_INITIALIZER;
77
78_Atomic bool gGlobalsMutating = false;
Ryan Savitski175c8862020-01-02 19:54:57 +000079
80static bool gZygoteChild = false;
81
82// In a Zygote child process, this is set to true if profiling of this process
83// is allowed. Note that this is set at a later time than gZygoteChild. The
84// latter is set during the fork (while still in zygote's SELinux domain). While
85// this bit is set after the child is specialized (and has transferred SELinux
86// domains if applicable). These two flags are read by the
87// BIONIC_SIGNAL_PROFILER handler, which does nothing if the process is not
88// profileable.
89static _Atomic bool gZygoteChildProfileable = false;
90
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080091// =============================================================================
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080092
93static constexpr MallocDispatch __libc_malloc_default_dispatch
94 __attribute__((unused)) = {
95 Malloc(calloc),
96 Malloc(free),
97 Malloc(mallinfo),
98 Malloc(malloc),
99 Malloc(malloc_usable_size),
100 Malloc(memalign),
101 Malloc(posix_memalign),
102#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
103 Malloc(pvalloc),
104#endif
105 Malloc(realloc),
106#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
107 Malloc(valloc),
108#endif
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800109 Malloc(malloc_iterate),
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800110 Malloc(malloc_disable),
111 Malloc(malloc_enable),
112 Malloc(mallopt),
113 Malloc(aligned_alloc),
Christopher Ferris6c619a02019-03-01 17:59:51 -0800114 Malloc(malloc_info),
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800115 };
116
117static constexpr char kHooksSharedLib[] = "libc_malloc_hooks.so";
118static constexpr char kHooksPrefix[] = "hooks";
119static constexpr char kHooksPropertyEnable[] = "libc.debug.hooks.enable";
120static constexpr char kHooksEnvEnable[] = "LIBC_HOOKS_ENABLE";
121
122static constexpr char kDebugSharedLib[] = "libc_malloc_debug.so";
123static constexpr char kDebugPrefix[] = "debug";
124static constexpr char kDebugPropertyOptions[] = "libc.debug.malloc.options";
125static constexpr char kDebugPropertyProgram[] = "libc.debug.malloc.program";
126static constexpr char kDebugEnvOptions[] = "LIBC_DEBUG_MALLOC_OPTIONS";
127
128typedef void (*finalize_func_t)();
Christopher Ferris8189e772019-04-09 16:37:23 -0700129typedef bool (*init_func_t)(const MallocDispatch*, bool*, const char*);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800130typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
131typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
132typedef bool (*write_malloc_leak_info_func_t)(FILE*);
133typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
134
135enum FunctionEnum : uint8_t {
136 FUNC_INITIALIZE,
137 FUNC_FINALIZE,
138 FUNC_GET_MALLOC_LEAK_INFO,
139 FUNC_FREE_MALLOC_LEAK_INFO,
140 FUNC_MALLOC_BACKTRACE,
141 FUNC_WRITE_LEAK_INFO,
142 FUNC_LAST,
143};
144static void* gFunctions[FUNC_LAST];
145
146extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
147
148template<typename FunctionType>
149static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
150 char symbol[128];
151 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
152 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
153 if (*func == nullptr) {
154 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
155 return false;
156 }
157 return true;
158}
159
160static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
161 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
162 return false;
163 }
164 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
165 return false;
166 }
167 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
168 return false;
169 }
170 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
171 return false;
172 }
173 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
174 return false;
175 }
Christopher Ferris6c619a02019-03-01 17:59:51 -0800176 if (!InitMallocFunction<MallocMallocInfo>(impl_handler, &table->malloc_info, prefix,
177 "malloc_info")) {
178 return false;
179 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800180 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
181 "malloc_usable_size")) {
182 return false;
183 }
184 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
185 return false;
186 }
187 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
188 "posix_memalign")) {
189 return false;
190 }
191 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
192 prefix, "aligned_alloc")) {
193 return false;
194 }
195 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
196 return false;
197 }
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800198 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->malloc_iterate, prefix,
199 "malloc_iterate")) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800200 return false;
201 }
202 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
203 "malloc_disable")) {
204 return false;
205 }
206 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
207 "malloc_enable")) {
208 return false;
209 }
210#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
211 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
212 return false;
213 }
214 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
215 return false;
216 }
217#endif
218
219 return true;
220}
221
222static void MallocFiniImpl(void*) {
223 // Our BSD stdio implementation doesn't close the standard streams,
224 // it only flushes them. Other unclosed FILE*s will show up as
225 // malloc leaks, but to avoid the standard streams showing up in
226 // leak reports, close them here.
227 fclose(stdin);
228 fclose(stdout);
229 fclose(stderr);
230
231 reinterpret_cast<finalize_func_t>(gFunctions[FUNC_FINALIZE])();
232}
233
234static bool CheckLoadMallocHooks(char** options) {
235 char* env = getenv(kHooksEnvEnable);
236 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
237 (__system_property_get(kHooksPropertyEnable, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
238 return false;
239 }
240 *options = nullptr;
241 return true;
242}
243
244static bool CheckLoadMallocDebug(char** options) {
245 // If kDebugMallocEnvOptions is set then it overrides the system properties.
246 char* env = getenv(kDebugEnvOptions);
247 if (env == nullptr || env[0] == '\0') {
248 if (__system_property_get(kDebugPropertyOptions, *options) == 0 || *options[0] == '\0') {
249 return false;
250 }
251
252 // Check to see if only a specific program should have debug malloc enabled.
253 char program[PROP_VALUE_MAX];
254 if (__system_property_get(kDebugPropertyProgram, program) != 0 &&
255 strstr(getprogname(), program) == nullptr) {
256 return false;
257 }
258 } else {
259 *options = env;
260 }
261 return true;
262}
263
264static void ClearGlobalFunctions() {
265 for (size_t i = 0; i < FUNC_LAST; i++) {
266 gFunctions[i] = nullptr;
267 }
268}
269
270bool InitSharedLibrary(void* impl_handle, const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
271 static constexpr const char* names[] = {
272 "initialize",
273 "finalize",
274 "get_malloc_leak_info",
275 "free_malloc_leak_info",
276 "malloc_backtrace",
277 "write_malloc_leak_info",
278 };
279 for (size_t i = 0; i < FUNC_LAST; i++) {
280 char symbol[128];
281 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
282 gFunctions[i] = dlsym(impl_handle, symbol);
283 if (gFunctions[i] == nullptr) {
284 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
285 ClearGlobalFunctions();
286 return false;
287 }
288 }
289
290 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
291 ClearGlobalFunctions();
292 return false;
293 }
294 return true;
295}
296
Ytai Ben-tsvi5105ece2019-12-19 19:08:58 +0000297// Note about USE_SCUDO. This file is compiled into libc.so and libc_scudo.so.
298// When compiled into libc_scudo.so, the libc_malloc_* libraries don't need
299// to be loaded from the runtime namespace since libc_scudo.so is not from
300// the runtime APEX, but is copied to any APEX that needs it.
301#ifndef USE_SCUDO
Jiyong Park3ff116a2019-04-02 23:04:52 +0900302extern "C" struct android_namespace_t* android_get_exported_namespace(const char* name);
Ytai Ben-tsvi5105ece2019-12-19 19:08:58 +0000303#endif
Jiyong Park3ff116a2019-04-02 23:04:52 +0900304
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800305void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
Jiyong Park3ff116a2019-04-02 23:04:52 +0900306 void* impl_handle = nullptr;
Ytai Ben-tsvi5105ece2019-12-19 19:08:58 +0000307#ifndef USE_SCUDO
Jiyong Park3ff116a2019-04-02 23:04:52 +0900308 // Try to load the libc_malloc_* libs from the "runtime" namespace and then
309 // fall back to dlopen() to load them from the default namespace.
310 //
311 // The libraries are packaged in the runtime APEX together with libc.so.
312 // However, since the libc.so is searched via the symlink in the system
313 // partition (/system/lib/libc.so -> /apex/com.android.runtime/bionic.libc.so)
314 // libc.so is loaded into the default namespace. If we just dlopen() here, the
315 // linker will load the libs found in /system/lib which might be incompatible
316 // with libc.so in the runtime APEX. Use android_dlopen_ext to explicitly load
317 // the ones in the runtime APEX.
318 struct android_namespace_t* runtime_ns = android_get_exported_namespace("runtime");
319 if (runtime_ns != nullptr) {
320 const android_dlextinfo dlextinfo = {
321 .flags = ANDROID_DLEXT_USE_NAMESPACE,
322 .library_namespace = runtime_ns,
323 };
324 impl_handle = android_dlopen_ext(shared_lib, RTLD_NOW | RTLD_LOCAL, &dlextinfo);
325 }
Ytai Ben-tsvi5105ece2019-12-19 19:08:58 +0000326#endif
Jiyong Park3ff116a2019-04-02 23:04:52 +0900327
328 if (impl_handle == nullptr) {
329 impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
330 }
331
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800332 if (impl_handle == nullptr) {
333 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
334 return nullptr;
335 }
336
337 if (!InitSharedLibrary(impl_handle, shared_lib, prefix, dispatch_table)) {
338 dlclose(impl_handle);
339 impl_handle = nullptr;
340 }
341
342 return impl_handle;
343}
344
345bool FinishInstallHooks(libc_globals* globals, const char* options, const char* prefix) {
346 init_func_t init_func = reinterpret_cast<init_func_t>(gFunctions[FUNC_INITIALIZE]);
Christopher Ferris8189e772019-04-09 16:37:23 -0700347 if (!init_func(&__libc_malloc_default_dispatch, &gZygoteChild, options)) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800348 error_log("%s: failed to enable malloc %s", getprogname(), prefix);
349 ClearGlobalFunctions();
350 return false;
351 }
352
353 // Do a pointer swap so that all of the functions become valid at once to
354 // avoid any initialization order problems.
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800355 atomic_store(&globals->default_dispatch_table, &globals->malloc_dispatch_table);
356 if (GetDispatchTable() == nullptr) {
357 atomic_store(&globals->current_dispatch_table, &globals->malloc_dispatch_table);
358 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800359
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800360 // Use atexit to trigger the cleanup function. This avoids a problem
361 // where another atexit function is used to cleanup allocated memory,
362 // but the finalize function was already called. This particular error
363 // seems to be triggered by a zygote spawned process calling exit.
364 int ret_value = __cxa_atexit(MallocFiniImpl, nullptr, nullptr);
365 if (ret_value != 0) {
366 // We don't consider this a fatal error.
Christopher Ferrisc328e442019-04-01 19:31:26 -0700367 warning_log("failed to set atexit cleanup function: %d", ret_value);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800368 }
369 return true;
370}
371
Christopher Ferris28228562019-02-14 10:23:58 -0800372static bool InstallHooks(libc_globals* globals, const char* options, const char* prefix,
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800373 const char* shared_lib) {
374 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &globals->malloc_dispatch_table);
375 if (impl_handle == nullptr) {
Christopher Ferris28228562019-02-14 10:23:58 -0800376 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800377 }
378
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800379 if (!FinishInstallHooks(globals, options, prefix)) {
380 dlclose(impl_handle);
Christopher Ferris28228562019-02-14 10:23:58 -0800381 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800382 }
Christopher Ferris28228562019-02-14 10:23:58 -0800383 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800384}
385
386// Initializes memory allocation framework once per process.
387static void MallocInitImpl(libc_globals* globals) {
388 char prop[PROP_VALUE_MAX];
389 char* options = prop;
390
391 // Prefer malloc debug since it existed first and is a more complete
392 // malloc interceptor than the hooks.
Christopher Ferris28228562019-02-14 10:23:58 -0800393 bool hook_installed = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800394 if (CheckLoadMallocDebug(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800395 hook_installed = InstallHooks(globals, options, kDebugPrefix, kDebugSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800396 } else if (CheckLoadMallocHooks(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800397 hook_installed = InstallHooks(globals, options, kHooksPrefix, kHooksSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800398 }
399
Christopher Ferris28228562019-02-14 10:23:58 -0800400 if (!hook_installed) {
401 if (HeapprofdShouldLoad()) {
402 HeapprofdInstallHooksAtInit(globals);
403 }
Christopher Ferris28228562019-02-14 10:23:58 -0800404 } else {
Ryan Savitski175c8862020-01-02 19:54:57 +0000405 // Record the fact that incompatible hooks are active, to skip any later
406 // heapprofd signal handler invocations.
407 HeapprofdRememberHookConflict();
Christopher Ferris28228562019-02-14 10:23:58 -0800408 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800409}
410
411// Initializes memory allocation framework.
412// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
413__BIONIC_WEAK_FOR_NATIVE_BRIDGE
414__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
415 MallocInitImpl(globals);
416}
417
418// =============================================================================
419// Functions to support dumping of native heap allocations using malloc debug.
420// =============================================================================
Christopher Ferris30659fd2019-04-15 19:01:08 -0700421bool GetMallocLeakInfo(android_mallopt_leak_info_t* leak_info) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800422 void* func = gFunctions[FUNC_GET_MALLOC_LEAK_INFO];
423 if (func == nullptr) {
Christopher Ferris30659fd2019-04-15 19:01:08 -0700424 errno = ENOTSUP;
425 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800426 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700427 reinterpret_cast<get_malloc_leak_info_func_t>(func)(
428 &leak_info->buffer, &leak_info->overall_size, &leak_info->info_size,
429 &leak_info->total_memory, &leak_info->backtrace_size);
430 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800431}
432
Christopher Ferris30659fd2019-04-15 19:01:08 -0700433bool FreeMallocLeakInfo(android_mallopt_leak_info_t* leak_info) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800434 void* func = gFunctions[FUNC_FREE_MALLOC_LEAK_INFO];
435 if (func == nullptr) {
Christopher Ferris30659fd2019-04-15 19:01:08 -0700436 errno = ENOTSUP;
437 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800438 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700439 reinterpret_cast<free_malloc_leak_info_func_t>(func)(leak_info->buffer);
440 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800441}
442
Christopher Ferris30659fd2019-04-15 19:01:08 -0700443bool WriteMallocLeakInfo(FILE* fp) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800444 void* func = gFunctions[FUNC_WRITE_LEAK_INFO];
445 bool written = false;
446 if (func != nullptr) {
447 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
448 }
449
450 if (!written) {
451 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
452 fprintf(fp, "# adb shell stop\n");
453 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
454 fprintf(fp, "# adb shell start\n");
Christopher Ferris30659fd2019-04-15 19:01:08 -0700455 errno = ENOTSUP;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800456 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700457 return written;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800458}
459// =============================================================================
460
461// =============================================================================
462// Exported for use by libmemunreachable.
463// =============================================================================
464extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
465 void* func = gFunctions[FUNC_MALLOC_BACKTRACE];
466 if (func == nullptr) {
467 return 0;
468 }
469 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
470}
471// =============================================================================
472
473// =============================================================================
474// Platform-internal mallopt variant.
475// =============================================================================
Evgeny Eltsinedbc9e22019-12-16 16:37:44 +0100476__BIONIC_WEAK_FOR_NATIVE_BRIDGE
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800477extern "C" bool android_mallopt(int opcode, void* arg, size_t arg_size) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700478 if (opcode == M_SET_ZYGOTE_CHILD) {
479 if (arg != nullptr || arg_size != 0) {
480 errno = EINVAL;
481 return false;
482 }
483 gZygoteChild = true;
484 return true;
485 }
Ryan Savitski175c8862020-01-02 19:54:57 +0000486 if (opcode == M_INIT_ZYGOTE_CHILD_PROFILING) {
487 if (arg != nullptr || arg_size != 0) {
488 errno = EINVAL;
489 return false;
490 }
491 atomic_store_explicit(&gZygoteChildProfileable, true, memory_order_release);
492 // Also check if heapprofd should start profiling from app startup.
493 HeapprofdInitZygoteChildProfiling();
494 return true;
495 }
496 if (opcode == M_GET_PROCESS_PROFILEABLE) {
497 if (arg == nullptr || arg_size != sizeof(bool)) {
498 errno = EINVAL;
499 return false;
500 }
501 // Native processes are considered profileable. Zygote children are considered
502 // profileable only when appropriately tagged.
503 *reinterpret_cast<bool*>(arg) =
504 !gZygoteChild || atomic_load_explicit(&gZygoteChildProfileable, memory_order_acquire);
505 return true;
506 }
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800507 if (opcode == M_SET_ALLOCATION_LIMIT_BYTES) {
508 return LimitEnable(arg, arg_size);
509 }
Christopher Ferris30659fd2019-04-15 19:01:08 -0700510 if (opcode == M_WRITE_MALLOC_LEAK_INFO_TO_FILE) {
511 if (arg == nullptr || arg_size != sizeof(FILE*)) {
512 errno = EINVAL;
513 return false;
514 }
515 return WriteMallocLeakInfo(reinterpret_cast<FILE*>(arg));
516 }
517 if (opcode == M_GET_MALLOC_LEAK_INFO) {
518 if (arg == nullptr || arg_size != sizeof(android_mallopt_leak_info_t)) {
519 errno = EINVAL;
520 return false;
521 }
522 return GetMallocLeakInfo(reinterpret_cast<android_mallopt_leak_info_t*>(arg));
523 }
524 if (opcode == M_FREE_MALLOC_LEAK_INFO) {
525 if (arg == nullptr || arg_size != sizeof(android_mallopt_leak_info_t)) {
526 errno = EINVAL;
527 return false;
528 }
529 return FreeMallocLeakInfo(reinterpret_cast<android_mallopt_leak_info_t*>(arg));
530 }
Peter Collingbourne1e110fb2020-01-09 10:48:22 -0800531 if (opcode == M_SET_HEAP_TAGGING_LEVEL) {
532 return SetHeapTaggingLevel(arg, arg_size);
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