blob: 61b3f3351fc8ea98b614c5e106a8559a27349754 [file] [log] [blame]
Christopher Ferris63860cb2015-11-16 17:30:32 -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// Contains a thin layer that calls whatever real native allocator
30// has been defined. For the libc shared library, this allows the
31// implementation of a debug malloc that can intercept all of the allocation
32// calls and add special debugging code to attempt to catch allocation
33// errors. All of the debugging code is implemented in a separate shared
34// library that is only loaded when the property "libc.debug.malloc.options"
35// is set to a non-zero value. There are two functions exported to
36// allow ddms, or other external users to get information from the debug
37// allocation.
38// get_malloc_leak_info: Returns information about all of the known native
39// allocations that are currently in use.
40// free_malloc_leak_info: Frees the data allocated by the call to
41// get_malloc_leak_info.
Christopher Ferris2e1a40a2018-06-13 10:46:34 -070042// write_malloc_leak_info: Writes the leak info data to a file.
Christopher Ferris63860cb2015-11-16 17:30:32 -080043
Colin Cross869691c2016-01-29 12:48:18 -080044#include <pthread.h>
Florian Mayerf7f71e32018-08-31 15:36:48 -070045#include <stdatomic.h>
Colin Cross869691c2016-01-29 12:48:18 -080046
Christopher Ferris63860cb2015-11-16 17:30:32 -080047#include <private/bionic_config.h>
48#include <private/bionic_globals.h>
49#include <private/bionic_malloc_dispatch.h>
50
Evgenii Stepanovbe551f52018-08-13 16:46:15 -070051#if __has_feature(hwaddress_sanitizer)
52// FIXME: implement these in HWASan allocator.
53extern "C" int __sanitizer_iterate(uintptr_t base __unused, size_t size __unused,
54 void (*callback)(uintptr_t base, size_t size, void* arg) __unused,
55 void* arg __unused) {
56 return 0;
57}
58
59extern "C" void __sanitizer_malloc_disable() {
60}
61
62extern "C" void __sanitizer_malloc_enable() {
63}
64#include <sanitizer/hwasan_interface.h>
65#define Malloc(function) __sanitizer_ ## function
66
67#else // __has_feature(hwaddress_sanitizer)
Christopher Ferris63860cb2015-11-16 17:30:32 -080068#include "jemalloc.h"
69#define Malloc(function) je_ ## function
Evgenii Stepanovbe551f52018-08-13 16:46:15 -070070#endif
Christopher Ferris63860cb2015-11-16 17:30:32 -080071
Florian Mayerf7f71e32018-08-31 15:36:48 -070072template <typename T>
73static T* RemoveConst(const T* x) {
74 return const_cast<T*>(x);
75}
76
77// RemoveConst is a workaround for bug in current libcxx. Fix in
78// https://reviews.llvm.org/D47613
79#define atomic_load_explicit_const(obj, order) atomic_load_explicit(RemoveConst(obj), order)
80
81static constexpr memory_order default_read_memory_order = memory_order_acquire;
82
Christopher Ferris63860cb2015-11-16 17:30:32 -080083static constexpr MallocDispatch __libc_malloc_default_dispatch
84 __attribute__((unused)) = {
85 Malloc(calloc),
86 Malloc(free),
87 Malloc(mallinfo),
88 Malloc(malloc),
89 Malloc(malloc_usable_size),
90 Malloc(memalign),
91 Malloc(posix_memalign),
92#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
93 Malloc(pvalloc),
94#endif
95 Malloc(realloc),
96#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
97 Malloc(valloc),
98#endif
Colin Cross869691c2016-01-29 12:48:18 -080099 Malloc(iterate),
100 Malloc(malloc_disable),
101 Malloc(malloc_enable),
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700102 Malloc(mallopt),
Christopher Ferriscae21a92018-02-05 18:14:55 -0800103 Malloc(aligned_alloc),
Christopher Ferris63860cb2015-11-16 17:30:32 -0800104 };
105
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800106// Malloc hooks.
107void* (*volatile __malloc_hook)(size_t, const void*);
108void* (*volatile __realloc_hook)(void*, size_t, const void*);
109void (*volatile __free_hook)(void*, const void*);
110void* (*volatile __memalign_hook)(size_t, size_t, const void*);
111
Christopher Ferris63860cb2015-11-16 17:30:32 -0800112// In a VM process, this is set to 1 after fork()ing out of zygote.
113int gMallocLeakZygoteChild = 0;
114
115// =============================================================================
116// Allocation functions
117// =============================================================================
118extern "C" void* calloc(size_t n_elements, size_t elem_size) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700119 auto _calloc = atomic_load_explicit_const(
120 &__libc_globals->malloc_dispatch.calloc,
121 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800122 if (__predict_false(_calloc != nullptr)) {
123 return _calloc(n_elements, elem_size);
124 }
125 return Malloc(calloc)(n_elements, elem_size);
126}
127
128extern "C" void free(void* mem) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700129 auto _free = atomic_load_explicit_const(
130 &__libc_globals->malloc_dispatch.free,
131 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800132 if (__predict_false(_free != nullptr)) {
133 _free(mem);
134 } else {
135 Malloc(free)(mem);
136 }
137}
138
139extern "C" struct mallinfo mallinfo() {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700140 auto _mallinfo = atomic_load_explicit_const(
141 &__libc_globals->malloc_dispatch.mallinfo,
142 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800143 if (__predict_false(_mallinfo != nullptr)) {
144 return _mallinfo();
145 }
146 return Malloc(mallinfo)();
147}
148
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700149extern "C" int mallopt(int param, int value) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700150 auto _mallopt = atomic_load_explicit_const(
151 &__libc_globals->malloc_dispatch.mallopt,
152 default_read_memory_order);
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700153 if (__predict_false(_mallopt != nullptr)) {
154 return _mallopt(param, value);
155 }
156 return Malloc(mallopt)(param, value);
157}
158
Christopher Ferris63860cb2015-11-16 17:30:32 -0800159extern "C" void* malloc(size_t bytes) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700160 auto _malloc = atomic_load_explicit_const(
161 &__libc_globals->malloc_dispatch.malloc,
162 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800163 if (__predict_false(_malloc != nullptr)) {
164 return _malloc(bytes);
165 }
166 return Malloc(malloc)(bytes);
167}
168
169extern "C" size_t malloc_usable_size(const void* mem) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700170 auto _malloc_usable_size = atomic_load_explicit_const(
171 &__libc_globals->malloc_dispatch.malloc_usable_size,
172 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800173 if (__predict_false(_malloc_usable_size != nullptr)) {
174 return _malloc_usable_size(mem);
175 }
176 return Malloc(malloc_usable_size)(mem);
177}
178
179extern "C" void* memalign(size_t alignment, size_t bytes) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700180 auto _memalign = atomic_load_explicit_const(
181 &__libc_globals->malloc_dispatch.memalign,
182 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800183 if (__predict_false(_memalign != nullptr)) {
184 return _memalign(alignment, bytes);
185 }
186 return Malloc(memalign)(alignment, bytes);
187}
188
189extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700190 auto _posix_memalign = atomic_load_explicit_const(
191 &__libc_globals->malloc_dispatch.posix_memalign,
192 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800193 if (__predict_false(_posix_memalign != nullptr)) {
194 return _posix_memalign(memptr, alignment, size);
195 }
196 return Malloc(posix_memalign)(memptr, alignment, size);
197}
198
Christopher Ferriscae21a92018-02-05 18:14:55 -0800199extern "C" void* aligned_alloc(size_t alignment, size_t size) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700200 auto _aligned_alloc = atomic_load_explicit_const(
201 &__libc_globals->malloc_dispatch.aligned_alloc,
202 default_read_memory_order);
Christopher Ferriscae21a92018-02-05 18:14:55 -0800203 if (__predict_false(_aligned_alloc != nullptr)) {
204 return _aligned_alloc(alignment, size);
205 }
206 return Malloc(aligned_alloc)(alignment, size);
207}
208
Christopher Ferris63860cb2015-11-16 17:30:32 -0800209extern "C" void* realloc(void* old_mem, size_t bytes) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700210 auto _realloc = atomic_load_explicit_const(
211 &__libc_globals->malloc_dispatch.realloc,
212 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800213 if (__predict_false(_realloc != nullptr)) {
214 return _realloc(old_mem, bytes);
215 }
216 return Malloc(realloc)(old_mem, bytes);
217}
218
Elliott Hughesb1770852018-09-18 12:52:42 -0700219extern "C" void* reallocarray(void* old_mem, size_t item_count, size_t item_size) {
220 size_t new_size;
221 if (__builtin_mul_overflow(item_count, item_size, &new_size)) {
222 errno = ENOMEM;
223 return nullptr;
224 }
225 return realloc(old_mem, new_size);
226}
227
Christopher Ferris63860cb2015-11-16 17:30:32 -0800228#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
229extern "C" void* pvalloc(size_t bytes) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700230 auto _pvalloc = atomic_load_explicit_const(
231 &__libc_globals->malloc_dispatch.pvalloc,
232 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800233 if (__predict_false(_pvalloc != nullptr)) {
234 return _pvalloc(bytes);
235 }
236 return Malloc(pvalloc)(bytes);
237}
238
239extern "C" void* valloc(size_t bytes) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700240 auto _valloc = atomic_load_explicit_const(
241 &__libc_globals->malloc_dispatch.valloc,
242 default_read_memory_order);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800243 if (__predict_false(_valloc != nullptr)) {
244 return _valloc(bytes);
245 }
246 return Malloc(valloc)(bytes);
247}
248#endif
249
250// We implement malloc debugging only in libc.so, so the code below
251// must be excluded if we compile this file for static libc.a
252#if !defined(LIBC_STATIC)
253
254#include <dlfcn.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -0800255#include <stdio.h>
256#include <stdlib.h>
257
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700258#include <async_safe/log.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -0800259#include <sys/system_properties.h>
260
261extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
262
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800263static const char* HOOKS_SHARED_LIB = "libc_malloc_hooks.so";
264static const char* HOOKS_PROPERTY_ENABLE = "libc.debug.hooks.enable";
265static const char* HOOKS_ENV_ENABLE = "LIBC_HOOKS_ENABLE";
266
Christopher Ferris63860cb2015-11-16 17:30:32 -0800267static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800268static const char* DEBUG_PROPERTY_OPTIONS = "libc.debug.malloc.options";
269static const char* DEBUG_PROPERTY_PROGRAM = "libc.debug.malloc.program";
270static const char* DEBUG_ENV_OPTIONS = "LIBC_DEBUG_MALLOC_OPTIONS";
Christopher Ferris63860cb2015-11-16 17:30:32 -0800271
Florian Mayerf7f71e32018-08-31 15:36:48 -0700272static const char* HEAPPROFD_SHARED_LIB = "heapprofd_client.so";
273static const char* HEAPPROFD_PREFIX = "heapprofd";
274static const int HEAPPROFD_SIGNAL = __SIGRTMIN + 4;
275
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800276enum FunctionEnum : uint8_t {
277 FUNC_INITIALIZE,
278 FUNC_FINALIZE,
279 FUNC_GET_MALLOC_LEAK_INFO,
280 FUNC_FREE_MALLOC_LEAK_INFO,
281 FUNC_MALLOC_BACKTRACE,
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700282 FUNC_WRITE_LEAK_INFO,
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800283 FUNC_LAST,
284};
285static void* g_functions[FUNC_LAST];
Christopher Ferris63860cb2015-11-16 17:30:32 -0800286
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800287typedef void (*finalize_func_t)();
288typedef bool (*init_func_t)(const MallocDispatch*, int*, const char*);
289typedef void (*get_malloc_leak_info_func_t)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
290typedef void (*free_malloc_leak_info_func_t)(uint8_t*);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700291typedef bool (*write_malloc_leak_info_func_t)(FILE*);
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800292typedef ssize_t (*malloc_backtrace_func_t)(void*, uintptr_t*, size_t);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800293
294// =============================================================================
295// Log functions
296// =============================================================================
297#define error_log(format, ...) \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700298 async_safe_format_log(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
Christopher Ferris63860cb2015-11-16 17:30:32 -0800299#define info_log(format, ...) \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700300 async_safe_format_log(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
Christopher Ferris63860cb2015-11-16 17:30:32 -0800301// =============================================================================
302
303// =============================================================================
304// Exported for use by ddms.
305// =============================================================================
306
307// Retrieve native heap information.
308//
309// "*info" is set to a buffer we allocate
310// "*overall_size" is set to the size of the "info" buffer
311// "*info_size" is set to the size of a single entry
312// "*total_memory" is set to the sum of all allocations we're tracking; does
313// not include heap overhead
314// "*backtrace_size" is set to the maximum number of entries in the back trace
315extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
316 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800317 void* func = g_functions[FUNC_GET_MALLOC_LEAK_INFO];
318 if (func == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800319 return;
320 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800321 reinterpret_cast<get_malloc_leak_info_func_t>(func)(info, overall_size, info_size, total_memory,
322 backtrace_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800323}
324
325extern "C" void free_malloc_leak_info(uint8_t* info) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800326 void* func = g_functions[FUNC_FREE_MALLOC_LEAK_INFO];
327 if (func == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800328 return;
329 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800330 reinterpret_cast<free_malloc_leak_info_func_t>(func)(info);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800331}
Colin Cross869691c2016-01-29 12:48:18 -0800332
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700333extern "C" void write_malloc_leak_info(FILE* fp) {
334 if (fp == nullptr) {
335 error_log("write_malloc_leak_info called with a nullptr");
336 return;
337 }
338
339 void* func = g_functions[FUNC_WRITE_LEAK_INFO];
340 bool written = false;
341 if (func != nullptr) {
342 written = reinterpret_cast<write_malloc_leak_info_func_t>(func)(fp);
343 }
344
345 if (!written) {
346 fprintf(fp, "Native heap dump not available. To enable, run these commands (requires root):\n");
347 fprintf(fp, "# adb shell stop\n");
348 fprintf(fp, "# adb shell setprop libc.debug.malloc.options backtrace\n");
349 fprintf(fp, "# adb shell start\n");
350 }
351}
352
Christopher Ferris63860cb2015-11-16 17:30:32 -0800353// =============================================================================
354
355template<typename FunctionType>
Florian Mayerf7f71e32018-08-31 15:36:48 -0700356static bool InitMallocFunction(void* malloc_impl_handler, _Atomic(FunctionType)* func, const char* prefix, const char* suffix) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800357 char symbol[128];
358 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
359 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
360 if (*func == nullptr) {
361 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
362 return false;
363 }
364 return true;
365}
366
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800367static bool InitMallocFunctions(void* impl_handler, MallocDispatch* table, const char* prefix) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700368 // We initialize free first to prevent the following situation:
369 // Heapprofd's MallocMalloc is installed, and an allocation is observed
370 // and logged to the heap dump. The corresponding free happens before
371 // heapprofd's MallocFree is installed, and is not logged in the heap
372 // dump. This leads to the allocation wrongly being active in the heap
373 // dump indefinitely.
374 if (!InitMallocFunction<MallocFree>(impl_handler, &table->free, prefix, "free")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800375 return false;
376 }
Florian Mayerf7f71e32018-08-31 15:36:48 -0700377 if (!InitMallocFunction<MallocCalloc>(impl_handler, &table->calloc, prefix, "calloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800378 return false;
379 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800380 if (!InitMallocFunction<MallocMallinfo>(impl_handler, &table->mallinfo, prefix, "mallinfo")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800381 return false;
382 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800383 if (!InitMallocFunction<MallocMallopt>(impl_handler, &table->mallopt, prefix, "mallopt")) {
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700384 return false;
385 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800386 if (!InitMallocFunction<MallocMalloc>(impl_handler, &table->malloc, prefix, "malloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800387 return false;
388 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800389 if (!InitMallocFunction<MallocMallocUsableSize>(impl_handler, &table->malloc_usable_size, prefix,
390 "malloc_usable_size")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800391 return false;
392 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800393 if (!InitMallocFunction<MallocMemalign>(impl_handler, &table->memalign, prefix, "memalign")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800394 return false;
395 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800396 if (!InitMallocFunction<MallocPosixMemalign>(impl_handler, &table->posix_memalign, prefix,
397 "posix_memalign")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800398 return false;
399 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800400 if (!InitMallocFunction<MallocAlignedAlloc>(impl_handler, &table->aligned_alloc,
Christopher Ferriscae21a92018-02-05 18:14:55 -0800401 prefix, "aligned_alloc")) {
402 return false;
403 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800404 if (!InitMallocFunction<MallocRealloc>(impl_handler, &table->realloc, prefix, "realloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800405 return false;
406 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800407 if (!InitMallocFunction<MallocIterate>(impl_handler, &table->iterate, prefix, "iterate")) {
Colin Cross869691c2016-01-29 12:48:18 -0800408 return false;
409 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800410 if (!InitMallocFunction<MallocMallocDisable>(impl_handler, &table->malloc_disable, prefix,
411 "malloc_disable")) {
Colin Cross869691c2016-01-29 12:48:18 -0800412 return false;
413 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800414 if (!InitMallocFunction<MallocMallocEnable>(impl_handler, &table->malloc_enable, prefix,
415 "malloc_enable")) {
Colin Cross869691c2016-01-29 12:48:18 -0800416 return false;
417 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800418#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800419 if (!InitMallocFunction<MallocPvalloc>(impl_handler, &table->pvalloc, prefix, "pvalloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800420 return false;
421 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800422 if (!InitMallocFunction<MallocValloc>(impl_handler, &table->valloc, prefix, "valloc")) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800423 return false;
424 }
425#endif
426
427 return true;
428}
429
430static void malloc_fini_impl(void*) {
431 // Our BSD stdio implementation doesn't close the standard streams,
432 // it only flushes them. Other unclosed FILE*s will show up as
433 // malloc leaks, but to avoid the standard streams showing up in
434 // leak reports, close them here.
435 fclose(stdin);
436 fclose(stdout);
437 fclose(stderr);
438
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800439 reinterpret_cast<finalize_func_t>(g_functions[FUNC_FINALIZE])();
440}
441
442static bool CheckLoadMallocHooks(char** options) {
443 char* env = getenv(HOOKS_ENV_ENABLE);
444 if ((env == nullptr || env[0] == '\0' || env[0] == '0') &&
445 (__system_property_get(HOOKS_PROPERTY_ENABLE, *options) == 0 || *options[0] == '\0' || *options[0] == '0')) {
446 return false;
447 }
448 *options = nullptr;
449 return true;
450}
451
452static bool CheckLoadMallocDebug(char** options) {
453 // If DEBUG_MALLOC_ENV_OPTIONS is set then it overrides the system properties.
454 char* env = getenv(DEBUG_ENV_OPTIONS);
455 if (env == nullptr || env[0] == '\0') {
456 if (__system_property_get(DEBUG_PROPERTY_OPTIONS, *options) == 0 || *options[0] == '\0') {
457 return false;
458 }
459
460 // Check to see if only a specific program should have debug malloc enabled.
461 char program[PROP_VALUE_MAX];
462 if (__system_property_get(DEBUG_PROPERTY_PROGRAM, program) != 0 &&
463 strstr(getprogname(), program) == nullptr) {
464 return false;
465 }
466 } else {
467 *options = env;
468 }
469 return true;
470}
471
472static void ClearGlobalFunctions() {
473 for (size_t i = 0; i < FUNC_LAST; i++) {
474 g_functions[i] = nullptr;
475 }
476}
477
478static void* LoadSharedLibrary(const char* shared_lib, const char* prefix, MallocDispatch* dispatch_table) {
479 void* impl_handle = dlopen(shared_lib, RTLD_NOW | RTLD_LOCAL);
480 if (impl_handle == nullptr) {
481 error_log("%s: Unable to open shared library %s: %s", getprogname(), shared_lib, dlerror());
482 return nullptr;
483 }
484
485 static constexpr const char* names[] = {
486 "initialize",
487 "finalize",
488 "get_malloc_leak_info",
489 "free_malloc_leak_info",
490 "malloc_backtrace",
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700491 "write_malloc_leak_info",
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800492 };
493 for (size_t i = 0; i < FUNC_LAST; i++) {
494 char symbol[128];
495 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, names[i]);
496 g_functions[i] = dlsym(impl_handle, symbol);
497 if (g_functions[i] == nullptr) {
498 error_log("%s: %s routine not found in %s", getprogname(), symbol, shared_lib);
499 dlclose(impl_handle);
500 ClearGlobalFunctions();
501 return nullptr;
502 }
503 }
504
505 if (!InitMallocFunctions(impl_handle, dispatch_table, prefix)) {
506 dlclose(impl_handle);
507 ClearGlobalFunctions();
508 return nullptr;
509 }
510
511 return impl_handle;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800512}
513
Florian Mayerf7f71e32018-08-31 15:36:48 -0700514static void install_hooks(libc_globals* globals, const char* options,
515 const char* prefix, const char* shared_lib) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800516 MallocDispatch dispatch_table;
517 void* impl_handle = LoadSharedLibrary(shared_lib, prefix, &dispatch_table);
518 if (impl_handle == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800519 return;
520 }
521
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800522 init_func_t init_func = reinterpret_cast<init_func_t>(g_functions[FUNC_INITIALIZE]);
Tamas Berghammerac81fe82016-08-26 15:54:59 +0100523 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800524 dlclose(impl_handle);
525 ClearGlobalFunctions();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800526 return;
527 }
528
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800529 globals->malloc_dispatch = dispatch_table;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800530
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800531 info_log("%s: malloc %s enabled", getprogname(), prefix);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800532
533 // Use atexit to trigger the cleanup function. This avoids a problem
534 // where another atexit function is used to cleanup allocated memory,
535 // but the finalize function was already called. This particular error
536 // seems to be triggered by a zygote spawned process calling exit.
537 int ret_value = __cxa_atexit(malloc_fini_impl, nullptr, nullptr);
538 if (ret_value != 0) {
539 error_log("failed to set atexit cleanup function: %d", ret_value);
540 }
541}
542
Florian Mayerf7f71e32018-08-31 15:36:48 -0700543extern "C" void InstallInitHeapprofdHook(int);
544
545// Initializes memory allocation framework once per process.
546static void malloc_init_impl(libc_globals* globals) {
547 struct sigaction action = {};
548 action.sa_handler = InstallInitHeapprofdHook;
549 sigaction(HEAPPROFD_SIGNAL, &action, nullptr);
550
551 const char* prefix;
552 const char* shared_lib;
553 char prop[PROP_VALUE_MAX];
554 char* options = prop;
555 // Prefer malloc debug since it existed first and is a more complete
556 // malloc interceptor than the hooks.
557 if (CheckLoadMallocDebug(&options)) {
558 prefix = "debug";
559 shared_lib = DEBUG_SHARED_LIB;
560 } else if (CheckLoadMallocHooks(&options)) {
561 prefix = "hooks";
562 shared_lib = HOOKS_SHARED_LIB;
563 } else {
564 return;
565 }
566 install_hooks(globals, options, prefix, shared_lib);
567}
568
Christopher Ferris63860cb2015-11-16 17:30:32 -0800569// Initializes memory allocation framework.
570// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
571__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
572 malloc_init_impl(globals);
573}
Florian Mayerf7f71e32018-08-31 15:36:48 -0700574
575// The logic for triggering heapprofd below is as following.
576// 1. HEAPPROFD_SIGNAL is received by the process.
577// 2a. If the signal is currently being handled (g_heapprofd_init_in_progress
578// is true), no action is taken.
579// 2b. Otherwise, The signal handler (InstallInitHeapprofdHook) installs a
580// temporary malloc hook (InitHeapprofdHook).
581// 3. When this hook gets run the first time, it uninstalls itself and spawns
582// a thread running InitHeapprofd that loads heapprofd.so and installs the
583// hooks within.
584//
585// This roundabout way is needed because we are running non AS-safe code, so
586// we cannot run it directly in the signal handler. The other approach of
587// running a standby thread and signalling through write(2) and read(2) would
588// significantly increase the number of active threads in the system.
589
590static _Atomic bool g_heapprofd_init_in_progress = false;
591static _Atomic bool g_init_heapprofd_ran = false;
592
593static void* InitHeapprofd(void*) {
594 __libc_globals.mutate([](libc_globals* globals) {
595 install_hooks(globals, nullptr, HEAPPROFD_PREFIX, HEAPPROFD_SHARED_LIB);
596 });
597 atomic_store(&g_heapprofd_init_in_progress, false);
598 return nullptr;
599}
600
601static void* InitHeapprofdHook(size_t bytes) {
602 if (!atomic_exchange(&g_init_heapprofd_ran, true)) {
603 __libc_globals.mutate([](libc_globals* globals) {
604 atomic_store(&globals->malloc_dispatch.malloc, nullptr);
605 });
606
607 pthread_t thread_id;
608 if (pthread_create(&thread_id, nullptr, InitHeapprofd, nullptr) == -1)
609 error_log("%s: heapprofd: failed to pthread_create.", getprogname());
610 else if (pthread_detach(thread_id) == -1)
611 error_log("%s: heapprofd: failed to pthread_detach", getprogname());
612 if (pthread_setname_np(thread_id, "heapprofdinit") == -1)
613 error_log("%s: heapprod: failed to pthread_setname_np", getprogname());
614 }
615 return Malloc(malloc)(bytes);
616}
617
618extern "C" void InstallInitHeapprofdHook(int) {
619 if (!atomic_exchange(&g_heapprofd_init_in_progress, true)) {
620 __libc_globals.mutate([](libc_globals* globals) {
621 globals->malloc_dispatch.malloc = InitHeapprofdHook;
622 });
623 }
624}
625
Christopher Ferris63860cb2015-11-16 17:30:32 -0800626#endif // !LIBC_STATIC
Colin Cross869691c2016-01-29 12:48:18 -0800627
628// =============================================================================
629// Exported for use by libmemunreachable.
630// =============================================================================
631
632// Calls callback for every allocation in the anonymous heap mapping
633// [base, base+size). Must be called between malloc_disable and malloc_enable.
634extern "C" int malloc_iterate(uintptr_t base, size_t size,
635 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700636 auto _iterate = atomic_load_explicit_const(
637 &__libc_globals->malloc_dispatch.iterate,
638 default_read_memory_order);
Colin Cross869691c2016-01-29 12:48:18 -0800639 if (__predict_false(_iterate != nullptr)) {
640 return _iterate(base, size, callback, arg);
641 }
642 return Malloc(iterate)(base, size, callback, arg);
643}
644
645// Disable calls to malloc so malloc_iterate gets a consistent view of
646// allocated memory.
647extern "C" void malloc_disable() {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700648 auto _malloc_disable = atomic_load_explicit_const(
649 & __libc_globals->malloc_dispatch.malloc_disable,
650 default_read_memory_order);
Colin Cross869691c2016-01-29 12:48:18 -0800651 if (__predict_false(_malloc_disable != nullptr)) {
652 return _malloc_disable();
653 }
654 return Malloc(malloc_disable)();
655}
656
657// Re-enable calls to malloc after a previous call to malloc_disable.
658extern "C" void malloc_enable() {
Florian Mayerf7f71e32018-08-31 15:36:48 -0700659 auto _malloc_enable = atomic_load_explicit_const(
660 &__libc_globals->malloc_dispatch.malloc_enable,
661 default_read_memory_order);
Colin Cross869691c2016-01-29 12:48:18 -0800662 if (__predict_false(_malloc_enable != nullptr)) {
663 return _malloc_enable();
664 }
665 return Malloc(malloc_enable)();
666}
Colin Cross2d4721c2016-02-02 11:57:54 -0800667
668#ifndef LIBC_STATIC
669extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800670 void* func = g_functions[FUNC_MALLOC_BACKTRACE];
671 if (func == nullptr) {
Colin Cross2d4721c2016-02-02 11:57:54 -0800672 return 0;
673 }
Christopher Ferrisdb478a62018-02-07 18:42:14 -0800674 return reinterpret_cast<malloc_backtrace_func_t>(func)(pointer, frames, frame_count);
Colin Cross2d4721c2016-02-02 11:57:54 -0800675}
676#else
677extern "C" ssize_t malloc_backtrace(void*, uintptr_t*, size_t) {
678 return 0;
679}
680#endif