blob: 9656718496125546f4b3d927ed3a4ef5725ca485 [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
57#include <private/bionic_config.h>
58#include <private/bionic_defs.h>
59#include <private/bionic_malloc_dispatch.h>
60
61#include <sys/system_properties.h>
62
63#include "malloc_common.h"
64#include "malloc_common_dynamic.h"
65#include "malloc_heapprofd.h"
66
67static constexpr MallocDispatch __libc_malloc_default_dispatch
68 __attribute__((unused)) = {
69 Malloc(calloc),
70 Malloc(free),
71 Malloc(mallinfo),
72 Malloc(malloc),
73 Malloc(malloc_usable_size),
74 Malloc(memalign),
75 Malloc(posix_memalign),
76#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
77 Malloc(pvalloc),
78#endif
79 Malloc(realloc),
80#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
81 Malloc(valloc),
82#endif
83 Malloc(iterate),
84 Malloc(malloc_disable),
85 Malloc(malloc_enable),
86 Malloc(mallopt),
87 Malloc(aligned_alloc),
Christopher Ferris6c619a02019-03-01 17:59:51 -080088 Malloc(malloc_info),
Christopher Ferrise4cdbc42019-02-08 17:30:58 -080089 };
90
91static constexpr char kHooksSharedLib[] = "libc_malloc_hooks.so";
92static constexpr char kHooksPrefix[] = "hooks";
93static constexpr char kHooksPropertyEnable[] = "libc.debug.hooks.enable";
94static constexpr char kHooksEnvEnable[] = "LIBC_HOOKS_ENABLE";
95
96static constexpr char kDebugSharedLib[] = "libc_malloc_debug.so";
97static constexpr char kDebugPrefix[] = "debug";
98static constexpr char kDebugPropertyOptions[] = "libc.debug.malloc.options";
99static constexpr char kDebugPropertyProgram[] = "libc.debug.malloc.program";
100static constexpr char kDebugEnvOptions[] = "LIBC_DEBUG_MALLOC_OPTIONS";
101
102typedef void (*finalize_func_t)();
103typedef bool (*init_func_t)(const MallocDispatch*, int*, const char*);
104typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
105typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
106typedef bool (*write_malloc_leak_info_func_t)(FILE*);
107typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
108
109enum FunctionEnum : uint8_t {
110 FUNC_INITIALIZE,
111 FUNC_FINALIZE,
112 FUNC_GET_MALLOC_LEAK_INFO,
113 FUNC_FREE_MALLOC_LEAK_INFO,
114 FUNC_MALLOC_BACKTRACE,
115 FUNC_WRITE_LEAK_INFO,
116 FUNC_LAST,
117};
118static void* gFunctions[FUNC_LAST];
119
120extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
121
122template<typename FunctionType>
123static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
124 char symbol[128];
125 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
126 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
127 if (*func == nullptr) {
128 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
129 return false;
130 }
131 return true;
132}
133
134static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
135 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
136 return false;
137 }
138 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
139 return false;
140 }
141 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
142 return false;
143 }
144 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
145 return false;
146 }
147 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
148 return false;
149 }
Christopher Ferris6c619a02019-03-01 17:59:51 -0800150 if (!InitMallocFunction<MallocMallocInfo>(impl_handler, &table->malloc_info, prefix,
151 "malloc_info")) {
152 return false;
153 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800154 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
155 "malloc_usable_size")) {
156 return false;
157 }
158 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
159 return false;
160 }
161 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
162 "posix_memalign")) {
163 return false;
164 }
165 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
166 prefix, "aligned_alloc")) {
167 return false;
168 }
169 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
170 return false;
171 }
172 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->iterate, prefix, "iterate")) {
173 return false;
174 }
175 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
176 "malloc_disable")) {
177 return false;
178 }
179 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
180 "malloc_enable")) {
181 return false;
182 }
183#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
184 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
185 return false;
186 }
187 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
188 return false;
189 }
190#endif
191
192 return true;
193}
194
195static void MallocFiniImpl(void*) {
196 // Our BSD stdio implementation doesn't close the standard streams,
197 // it only flushes them. Other unclosed FILE*s will show up as
198 // malloc leaks, but to avoid the standard streams showing up in
199 // leak reports, close them here.
200 fclose(stdin);
201 fclose(stdout);
202 fclose(stderr);
203
204 reinterpret_cast<finalize_func_t>(gFunctions[FUNC_FINALIZE])();
205}
206
207static bool CheckLoadMallocHooks(char** options) {
208 char* env = getenv(kHooksEnvEnable);
209 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
210 (__system_property_get(kHooksPropertyEnable, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
211 return false;
212 }
213 *options = nullptr;
214 return true;
215}
216
217static bool CheckLoadMallocDebug(char** options) {
218 // If kDebugMallocEnvOptions is set then it overrides the system properties.
219 char* env = getenv(kDebugEnvOptions);
220 if (env == nullptr || env[0] == '\0') {
221 if (__system_property_get(kDebugPropertyOptions, *options) == 0 || *options[0] == '\0') {
222 return false;
223 }
224
225 // Check to see if only a specific program should have debug malloc enabled.
226 char program[PROP_VALUE_MAX];
227 if (__system_property_get(kDebugPropertyProgram, program) != 0 &&
228 strstr(getprogname(), program) == nullptr) {
229 return false;
230 }
231 } else {
232 *options = env;
233 }
234 return true;
235}
236
237static void ClearGlobalFunctions() {
238 for (size_t i = 0; i < FUNC_LAST; i++) {
239 gFunctions[i] = nullptr;
240 }
241}
242
243bool InitSharedLibrary(void* impl_handle, const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
244 static constexpr const char* names[] = {
245 "initialize",
246 "finalize",
247 "get_malloc_leak_info",
248 "free_malloc_leak_info",
249 "malloc_backtrace",
250 "write_malloc_leak_info",
251 };
252 for (size_t i = 0; i < FUNC_LAST; i++) {
253 char symbol[128];
254 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
255 gFunctions[i] = dlsym(impl_handle, symbol);
256 if (gFunctions[i] == nullptr) {
257 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
258 ClearGlobalFunctions();
259 return false;
260 }
261 }
262
263 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
264 ClearGlobalFunctions();
265 return false;
266 }
267 return true;
268}
269
270void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
271 void* impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
272 if (impl_handle == nullptr) {
273 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
274 return nullptr;
275 }
276
277 if (!InitSharedLibrary(impl_handle, shared_lib, prefix, dispatch_table)) {
278 dlclose(impl_handle);
279 impl_handle = nullptr;
280 }
281
282 return impl_handle;
283}
284
285bool FinishInstallHooks(libc_globals* globals, const char* options, const char* prefix) {
286 init_func_t init_func = reinterpret_cast<init_func_t>(gFunctions[FUNC_INITIALIZE]);
287 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
288 error_log("%s: failed to enable malloc %s", getprogname(), prefix);
289 ClearGlobalFunctions();
290 return false;
291 }
292
293 // Do a pointer swap so that all of the functions become valid at once to
294 // avoid any initialization order problems.
295 atomic_store(&globals->current_dispatch_table, &globals->malloc_dispatch_table);
296
297 info_log("%s: malloc %s enabled", getprogname(), prefix);
298
299 // Use atexit to trigger the cleanup function. This avoids a problem
300 // where another atexit function is used to cleanup allocated memory,
301 // but the finalize function was already called. This particular error
302 // seems to be triggered by a zygote spawned process calling exit.
303 int ret_value = __cxa_atexit(MallocFiniImpl, nullptr, nullptr);
304 if (ret_value != 0) {
305 // We don't consider this a fatal error.
306 info_log("failed to set atexit cleanup function: %d", ret_value);
307 }
308 return true;
309}
310
Christopher Ferris28228562019-02-14 10:23:58 -0800311static bool InstallHooks(libc_globals* globals, const char* options, const char* prefix,
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800312 const char* shared_lib) {
313 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &globals->malloc_dispatch_table);
314 if (impl_handle == nullptr) {
Christopher Ferris28228562019-02-14 10:23:58 -0800315 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800316 }
317
318 init_func_t init_func = reinterpret_cast<init_func_t>(gFunctions[FUNC_INITIALIZE]);
319 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
320 error_log("%s: failed to enable malloc %s", getprogname(), prefix);
321 ClearGlobalFunctions();
Christopher Ferris28228562019-02-14 10:23:58 -0800322 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800323 }
324
325 if (!FinishInstallHooks(globals, options, prefix)) {
326 dlclose(impl_handle);
Christopher Ferris28228562019-02-14 10:23:58 -0800327 return false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800328 }
Christopher Ferris28228562019-02-14 10:23:58 -0800329 return true;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800330}
331
332// Initializes memory allocation framework once per process.
333static void MallocInitImpl(libc_globals* globals) {
334 char prop[PROP_VALUE_MAX];
335 char* options = prop;
336
337 // Prefer malloc debug since it existed first and is a more complete
338 // malloc interceptor than the hooks.
Christopher Ferris28228562019-02-14 10:23:58 -0800339 bool hook_installed = false;
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800340 if (CheckLoadMallocDebug(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800341 hook_installed = InstallHooks(globals, options, kDebugPrefix, kDebugSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800342 } else if (CheckLoadMallocHooks(&options)) {
Christopher Ferris28228562019-02-14 10:23:58 -0800343 hook_installed = InstallHooks(globals, options, kHooksPrefix, kHooksSharedLib);
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800344 }
345
Christopher Ferris28228562019-02-14 10:23:58 -0800346 if (!hook_installed) {
347 if (HeapprofdShouldLoad()) {
348 HeapprofdInstallHooksAtInit(globals);
349 }
350
351 // Install this last to avoid as many race conditions as possible.
352 HeapprofdInstallSignalHandler();
353 } else {
354 // Install a signal handler that prints an error since we don't support
355 // heapprofd and any other hook to be installed at the same time.
356 HeapprofdInstallErrorSignalHandler();
357 }
Christopher Ferrise4cdbc42019-02-08 17:30:58 -0800358}
359
360// Initializes memory allocation framework.
361// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
362__BIONIC_WEAK_FOR_NATIVE_BRIDGE
363__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
364 MallocInitImpl(globals);
365}
366
367// =============================================================================
368// Functions to support dumping of native heap allocations using malloc debug.
369// =============================================================================
370
371// Retrieve native heap information.
372//
373// "*info" is set to a buffer we allocate
374// "*overall_size" is set to the size of the "info" buffer
375// "*info_size" is set to the size of a single entry
376// "*total_memory" is set to the sum of all allocations we're tracking; does
377// not include heap overhead
378// "*backtrace_size" is set to the maximum number of entries in the back trace
379extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
380 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
381 void* func = gFunctions[FUNC_GET_MALLOC_LEAK_INFO];
382 if (func == nullptr) {
383 return;
384 }
385 reinterpret_cast<get_malloc_leak_info_func_t>(func)(info, overall_size, info_size, total_memory,
386 backtrace_size);
387}
388
389extern "C" void free_malloc_leak_info(uint8_t* info) {
390 void* func = gFunctions[FUNC_FREE_MALLOC_LEAK_INFO];
391 if (func == nullptr) {
392 return;
393 }
394 reinterpret_cast<free_malloc_leak_info_func_t>(func)(info);
395}
396
397extern "C" void write_malloc_leak_info(FILE* fp) {
398 if (fp == nullptr) {
399 error_log("write_malloc_leak_info called with a nullptr");
400 return;
401 }
402
403 void* func = gFunctions[FUNC_WRITE_LEAK_INFO];
404 bool written = false;
405 if (func != nullptr) {
406 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
407 }
408
409 if (!written) {
410 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
411 fprintf(fp, "# adb shell stop\n");
412 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
413 fprintf(fp, "# adb shell start\n");
414 }
415}
416// =============================================================================
417
418// =============================================================================
419// Exported for use by libmemunreachable.
420// =============================================================================
421extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
422 void* func = gFunctions[FUNC_MALLOC_BACKTRACE];
423 if (func == nullptr) {
424 return 0;
425 }
426 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
427}
428// =============================================================================
429
430// =============================================================================
431// Platform-internal mallopt variant.
432// =============================================================================
433extern "C" bool android_mallopt(int opcode, void* arg, size_t arg_size) {
434 return HeapprofdMallopt(opcode, arg, arg_size);
435}
436// =============================================================================