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