blob: 64f9f6f7b605c911b90b376c1a0d00a677de3590 [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 Ferrise4cdbc42019-02-08 17:30:58 -080060#include <private/bionic_config.h>
61#include <private/bionic_defs.h>
62#include <private/bionic_malloc_dispatch.h>
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080063#include <private/bionic_malloc.h>
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080064
65#include <sys/system_properties.h>
66
67#include "malloc_common.h"
68#include "malloc_common_dynamic.h"
69#include "malloc_heapprofd.h"
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080070#include "malloc_limit.h"
71
72// =============================================================================
73// Global variables instantations.
74// =============================================================================
75pthread_mutex_t gGlobalsMutateLock = PTHREAD_MUTEX_INITIALIZER;
76
Christopher Ferris8189e772019-04-09 16:37:23 -070077bool gZygoteChild = false;
78
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -080079_Atomic bool gGlobalsMutating = false;
80// =============================================================================
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080081
82static constexpr MallocDispatch __libc_malloc_default_dispatch
83 __attribute__((unused)) = {
84 Malloc(calloc),
85 Malloc(free),
86 Malloc(mallinfo),
87 Malloc(malloc),
88 Malloc(malloc_usable_size),
89 Malloc(memalign),
90 Malloc(posix_memalign),
91#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
92 Malloc(pvalloc),
93#endif
94 Malloc(realloc),
95#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
96 Malloc(valloc),
97#endif
98 Malloc(iterate),
99 Malloc(malloc_disable),
100 Malloc(malloc_enable),
101 Malloc(mallopt),
102 Malloc(aligned_alloc),
Christopher Ferris6c619a02019-03-01 17:59:51 -0800103 Malloc(malloc_info),
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800104 };
105
106static constexpr char kHooksSharedLib[] = "libc_malloc_hooks.so";
107static constexpr char kHooksPrefix[] = "hooks";
108static constexpr char kHooksPropertyEnable[] = "libc.debug.hooks.enable";
109static constexpr char kHooksEnvEnable[] = "LIBC_HOOKS_ENABLE";
110
111static constexpr char kDebugSharedLib[] = "libc_malloc_debug.so";
112static constexpr char kDebugPrefix[] = "debug";
113static constexpr char kDebugPropertyOptions[] = "libc.debug.malloc.options";
114static constexpr char kDebugPropertyProgram[] = "libc.debug.malloc.program";
115static constexpr char kDebugEnvOptions[] = "LIBC_DEBUG_MALLOC_OPTIONS";
116
117typedef void (*finalize_func_t)();
Christopher Ferris8189e772019-04-09 16:37:23 -0700118typedef bool (*init_func_t)(const MallocDispatch*, bool*, const char*);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800119typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
120typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
121typedef bool (*write_malloc_leak_info_func_t)(FILE*);
122typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
123
124enum FunctionEnum : uint8_t {
125 FUNC_INITIALIZE,
126 FUNC_FINALIZE,
127 FUNC_GET_MALLOC_LEAK_INFO,
128 FUNC_FREE_MALLOC_LEAK_INFO,
129 FUNC_MALLOC_BACKTRACE,
130 FUNC_WRITE_LEAK_INFO,
131 FUNC_LAST,
132};
133static void* gFunctions[FUNC_LAST];
134
135extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
136
137template<typename FunctionType>
138static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
139 char symbol[128];
140 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
141 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
142 if (*func == nullptr) {
143 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
144 return false;
145 }
146 return true;
147}
148
149static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
150 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
151 return false;
152 }
153 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
154 return false;
155 }
156 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
157 return false;
158 }
159 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
160 return false;
161 }
162 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
163 return false;
164 }
Christopher Ferris6c619a02019-03-01 17:59:51 -0800165 if (!InitMallocFunction<MallocMallocInfo>(impl_handler, &table->malloc_info, prefix,
166 "malloc_info")) {
167 return false;
168 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800169 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
170 "malloc_usable_size")) {
171 return false;
172 }
173 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
174 return false;
175 }
176 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
177 "posix_memalign")) {
178 return false;
179 }
180 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
181 prefix, "aligned_alloc")) {
182 return false;
183 }
184 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
185 return false;
186 }
187 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->iterate, prefix, "iterate")) {
188 return false;
189 }
190 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
191 "malloc_disable")) {
192 return false;
193 }
194 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
195 "malloc_enable")) {
196 return false;
197 }
198#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
199 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
200 return false;
201 }
202 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
203 return false;
204 }
205#endif
206
207 return true;
208}
209
210static void MallocFiniImpl(void*) {
211 // Our BSD stdio implementation doesn't close the standard streams,
212 // it only flushes them. Other unclosed FILE*s will show up as
213 // malloc leaks, but to avoid the standard streams showing up in
214 // leak reports, close them here.
215 fclose(stdin);
216 fclose(stdout);
217 fclose(stderr);
218
219 reinterpret_cast<finalize_func_t>(gFunctions[FUNC_FINALIZE])();
220}
221
222static bool CheckLoadMallocHooks(char** options) {
223 char* env = getenv(kHooksEnvEnable);
224 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
225 (__system_property_get(kHooksPropertyEnable, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
226 return false;
227 }
228 *options = nullptr;
229 return true;
230}
231
232static bool CheckLoadMallocDebug(char** options) {
233 // If kDebugMallocEnvOptions is set then it overrides the system properties.
234 char* env = getenv(kDebugEnvOptions);
235 if (env == nullptr || env[0] == '\0') {
236 if (__system_property_get(kDebugPropertyOptions, *options) == 0 || *options[0] == '\0') {
237 return false;
238 }
239
240 // Check to see if only a specific program should have debug malloc enabled.
241 char program[PROP_VALUE_MAX];
242 if (__system_property_get(kDebugPropertyProgram, program) != 0 &&
243 strstr(getprogname(), program) == nullptr) {
244 return false;
245 }
246 } else {
247 *options = env;
248 }
249 return true;
250}
251
252static void ClearGlobalFunctions() {
253 for (size_t i = 0; i < FUNC_LAST; i++) {
254 gFunctions[i] = nullptr;
255 }
256}
257
258bool InitSharedLibrary(void* impl_handle, const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
259 static constexpr const char* names[] = {
260 "initialize",
261 "finalize",
262 "get_malloc_leak_info",
263 "free_malloc_leak_info",
264 "malloc_backtrace",
265 "write_malloc_leak_info",
266 };
267 for (size_t i = 0; i < FUNC_LAST; i++) {
268 char symbol[128];
269 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
270 gFunctions[i] = dlsym(impl_handle, symbol);
271 if (gFunctions[i] == nullptr) {
272 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
273 ClearGlobalFunctions();
274 return false;
275 }
276 }
277
278 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
279 ClearGlobalFunctions();
280 return false;
281 }
282 return true;
283}
284
Jiyong Park55696502019-04-10 02:29:25 +0900285// Note about USE_SCUDO. This file is compiled into libc.so and libc_scudo.so.
286// When compiled into libc_scudo.so, the libc_malloc_* libraries don't need
287// to be loaded from the runtime namespace since libc_scudo.so is not from
288// the runtime APEX, but is copied to any APEX that needs it.
289#ifndef USE_SCUDO
Jiyong Park3ff116a2019-04-02 23:04:52 +0900290extern "C" struct android_namespace_t* android_get_exported_namespace(const char* name);
Jiyong Park55696502019-04-10 02:29:25 +0900291#endif
Jiyong Park3ff116a2019-04-02 23:04:52 +0900292
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800293void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
Jiyong Park3ff116a2019-04-02 23:04:52 +0900294 void* impl_handle = nullptr;
Jiyong Park55696502019-04-10 02:29:25 +0900295#ifndef USE_SCUDO
Jiyong Park3ff116a2019-04-02 23:04:52 +0900296 // Try to load the libc_malloc_* libs from the "runtime" namespace and then
297 // fall back to dlopen() to load them from the default namespace.
298 //
299 // The libraries are packaged in the runtime APEX together with libc.so.
300 // However, since the libc.so is searched via the symlink in the system
301 // partition (/system/lib/libc.so -> /apex/com.android.runtime/bionic.libc.so)
302 // libc.so is loaded into the default namespace. If we just dlopen() here, the
303 // linker will load the libs found in /system/lib which might be incompatible
304 // with libc.so in the runtime APEX. Use android_dlopen_ext to explicitly load
305 // the ones in the runtime APEX.
306 struct android_namespace_t* runtime_ns = android_get_exported_namespace("runtime");
307 if (runtime_ns != nullptr) {
308 const android_dlextinfo dlextinfo = {
309 .flags = ANDROID_DLEXT_USE_NAMESPACE,
310 .library_namespace = runtime_ns,
311 };
312 impl_handle = android_dlopen_ext(shared_lib, RTLD_NOW | RTLD_LOCAL, &dlextinfo);
313 }
Jiyong Park55696502019-04-10 02:29:25 +0900314#endif
Jiyong Park3ff116a2019-04-02 23:04:52 +0900315
316 if (impl_handle == nullptr) {
317 impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
318 }
319
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800320 if (impl_handle == nullptr) {
321 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
322 return nullptr;
323 }
324
325 if (!InitSharedLibrary(impl_handle, shared_lib, prefix, dispatch_table)) {
326 dlclose(impl_handle);
327 impl_handle = nullptr;
328 }
329
330 return impl_handle;
331}
332
333bool FinishInstallHooks(libc_globals* globals, const char* options, const char* prefix) {
334 init_func_t init_func = reinterpret_cast<init_func_t>(gFunctions[FUNC_INITIALIZE]);
Christopher Ferris8189e772019-04-09 16:37:23 -0700335 if (!init_func(&__libc_malloc_default_dispatch, &gZygoteChild, options)) {
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800336 error_log("%s: failed to enable malloc %s", getprogname(), prefix);
337 ClearGlobalFunctions();
338 return false;
339 }
340
341 // Do a pointer swap so that all of the functions become valid at once to
342 // avoid any initialization order problems.
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800343 atomic_store(&globals->default_dispatch_table, &globals->malloc_dispatch_table);
344 if (GetDispatchTable() == nullptr) {
345 atomic_store(&globals->current_dispatch_table, &globals->malloc_dispatch_table);
346 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800347
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800348 // Use atexit to trigger the cleanup function. This avoids a problem
349 // where another atexit function is used to cleanup allocated memory,
350 // but the finalize function was already called. This particular error
351 // seems to be triggered by a zygote spawned process calling exit.
352 int ret_value = __cxa_atexit(MallocFiniImpl, nullptr, nullptr);
353 if (ret_value != 0) {
354 // We don't consider this a fatal error.
Christopher Ferrisc328e442019-04-01 19:31:26 -0700355 warning_log("failed to set atexit cleanup function: %d", ret_value);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800356 }
357 return true;
358}
359
Christopher Ferris28228562019-02-14 10:23:58 -0800360static bool InstallHooks(libc_globals* globals, const char* options, const char* prefix,
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800361 const char* shared_lib) {
362 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &globals->malloc_dispatch_table);
363 if (impl_handle == nullptr) {
Christopher Ferris28228562019-02-14 10:23:58 -0800364 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800365 }
366
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800367 if (!FinishInstallHooks(globals, options, prefix)) {
368 dlclose(impl_handle);
Christopher Ferris28228562019-02-14 10:23:58 -0800369 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800370 }
Christopher Ferris28228562019-02-14 10:23:58 -0800371 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800372}
373
374// Initializes memory allocation framework once per process.
375static void MallocInitImpl(libc_globals* globals) {
376 char prop[PROP_VALUE_MAX];
377 char* options = prop;
378
379 // Prefer malloc debug since it existed first and is a more complete
380 // malloc interceptor than the hooks.
Christopher Ferris28228562019-02-14 10:23:58 -0800381 bool hook_installed = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800382 if (CheckLoadMallocDebug(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800383 hook_installed = InstallHooks(globals, options, kDebugPrefix, kDebugSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800384 } else if (CheckLoadMallocHooks(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800385 hook_installed = InstallHooks(globals, options, kHooksPrefix, kHooksSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800386 }
387
Christopher Ferris28228562019-02-14 10:23:58 -0800388 if (!hook_installed) {
389 if (HeapprofdShouldLoad()) {
390 HeapprofdInstallHooksAtInit(globals);
391 }
392
393 // Install this last to avoid as many race conditions as possible.
394 HeapprofdInstallSignalHandler();
395 } else {
396 // Install a signal handler that prints an error since we don't support
397 // heapprofd and any other hook to be installed at the same time.
398 HeapprofdInstallErrorSignalHandler();
399 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800400}
401
402// Initializes memory allocation framework.
403// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
404__BIONIC_WEAK_FOR_NATIVE_BRIDGE
405__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
406 MallocInitImpl(globals);
407}
408
409// =============================================================================
410// Functions to support dumping of native heap allocations using malloc debug.
411// =============================================================================
412
413// Retrieve native heap information.
414//
415// "*info" is set to a buffer we allocate
416// "*overall_size" is set to the size of the "info" buffer
417// "*info_size" is set to the size of a single entry
418// "*total_memory" is set to the sum of all allocations we're tracking; does
419// not include heap overhead
420// "*backtrace_size" is set to the maximum number of entries in the back trace
421extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
422 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
423 void* func = gFunctions[FUNC_GET_MALLOC_LEAK_INFO];
424 if (func == nullptr) {
425 return;
426 }
427 reinterpret_cast<get_malloc_leak_info_func_t>(func)(info, overall_size, info_size, total_memory,
428 backtrace_size);
429}
430
431extern "C" void free_malloc_leak_info(uint8_t* info) {
432 void* func = gFunctions[FUNC_FREE_MALLOC_LEAK_INFO];
433 if (func == nullptr) {
434 return;
435 }
436 reinterpret_cast<free_malloc_leak_info_func_t>(func)(info);
437}
438
439extern "C" void write_malloc_leak_info(FILE* fp) {
440 if (fp == nullptr) {
441 error_log("write_malloc_leak_info called with a nullptr");
442 return;
443 }
444
445 void* func = gFunctions[FUNC_WRITE_LEAK_INFO];
446 bool written = false;
447 if (func != nullptr) {
448 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
449 }
450
451 if (!written) {
452 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
453 fprintf(fp, "# adb shell stop\n");
454 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
455 fprintf(fp, "# adb shell start\n");
456 }
457}
458// =============================================================================
459
460// =============================================================================
461// Exported for use by libmemunreachable.
462// =============================================================================
463extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
464 void* func = gFunctions[FUNC_MALLOC_BACKTRACE];
465 if (func == nullptr) {
466 return 0;
467 }
468 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
469}
470// =============================================================================
471
472// =============================================================================
473// Platform-internal mallopt variant.
474// =============================================================================
475extern "C" bool android_mallopt(int opcode, void* arg, size_t arg_size) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700476 if (opcode == M_SET_ZYGOTE_CHILD) {
477 if (arg != nullptr || arg_size != 0) {
478 errno = EINVAL;
479 return false;
480 }
481 gZygoteChild = true;
482 return true;
483 }
Christopher Ferris1fc5ccf2019-02-15 18:06:15 -0800484 if (opcode == M_SET_ALLOCATION_LIMIT_BYTES) {
485 return LimitEnable(arg, arg_size);
486 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800487 return HeapprofdMallopt(opcode, arg, arg_size);
488}
489// =============================================================================