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