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