blob: 56f1c1067a1ac09c2e3420a759f5cf0a98eb550f [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.
42
43#include <private/bionic_config.h>
44#include <private/bionic_globals.h>
45#include <private/bionic_malloc_dispatch.h>
46
47#include "jemalloc.h"
48#define Malloc(function) je_ ## function
49
50static constexpr MallocDispatch __libc_malloc_default_dispatch
51 __attribute__((unused)) = {
52 Malloc(calloc),
53 Malloc(free),
54 Malloc(mallinfo),
55 Malloc(malloc),
56 Malloc(malloc_usable_size),
57 Malloc(memalign),
58 Malloc(posix_memalign),
59#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
60 Malloc(pvalloc),
61#endif
62 Malloc(realloc),
63#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
64 Malloc(valloc),
65#endif
66 };
67
68// In a VM process, this is set to 1 after fork()ing out of zygote.
69int gMallocLeakZygoteChild = 0;
70
71// =============================================================================
72// Allocation functions
73// =============================================================================
74extern "C" void* calloc(size_t n_elements, size_t elem_size) {
75 auto _calloc = __libc_globals->malloc_dispatch.calloc;
76 if (__predict_false(_calloc != nullptr)) {
77 return _calloc(n_elements, elem_size);
78 }
79 return Malloc(calloc)(n_elements, elem_size);
80}
81
82extern "C" void free(void* mem) {
83 auto _free = __libc_globals->malloc_dispatch.free;
84 if (__predict_false(_free != nullptr)) {
85 _free(mem);
86 } else {
87 Malloc(free)(mem);
88 }
89}
90
91extern "C" struct mallinfo mallinfo() {
92 auto _mallinfo = __libc_globals->malloc_dispatch.mallinfo;
93 if (__predict_false(_mallinfo != nullptr)) {
94 return _mallinfo();
95 }
96 return Malloc(mallinfo)();
97}
98
99extern "C" void* malloc(size_t bytes) {
100 auto _malloc = __libc_globals->malloc_dispatch.malloc;
101 if (__predict_false(_malloc != nullptr)) {
102 return _malloc(bytes);
103 }
104 return Malloc(malloc)(bytes);
105}
106
107extern "C" size_t malloc_usable_size(const void* mem) {
108 auto _malloc_usable_size = __libc_globals->malloc_dispatch.malloc_usable_size;
109 if (__predict_false(_malloc_usable_size != nullptr)) {
110 return _malloc_usable_size(mem);
111 }
112 return Malloc(malloc_usable_size)(mem);
113}
114
115extern "C" void* memalign(size_t alignment, size_t bytes) {
116 auto _memalign = __libc_globals->malloc_dispatch.memalign;
117 if (__predict_false(_memalign != nullptr)) {
118 return _memalign(alignment, bytes);
119 }
120 return Malloc(memalign)(alignment, bytes);
121}
122
123extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
124 auto _posix_memalign = __libc_globals->malloc_dispatch.posix_memalign;
125 if (__predict_false(_posix_memalign != nullptr)) {
126 return _posix_memalign(memptr, alignment, size);
127 }
128 return Malloc(posix_memalign)(memptr, alignment, size);
129}
130
131extern "C" void* realloc(void* old_mem, size_t bytes) {
132 auto _realloc = __libc_globals->malloc_dispatch.realloc;
133 if (__predict_false(_realloc != nullptr)) {
134 return _realloc(old_mem, bytes);
135 }
136 return Malloc(realloc)(old_mem, bytes);
137}
138
139#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
140extern "C" void* pvalloc(size_t bytes) {
141 auto _pvalloc = __libc_globals->malloc_dispatch.pvalloc;
142 if (__predict_false(_pvalloc != nullptr)) {
143 return _pvalloc(bytes);
144 }
145 return Malloc(pvalloc)(bytes);
146}
147
148extern "C" void* valloc(size_t bytes) {
149 auto _valloc = __libc_globals->malloc_dispatch.valloc;
150 if (__predict_false(_valloc != nullptr)) {
151 return _valloc(bytes);
152 }
153 return Malloc(valloc)(bytes);
154}
155#endif
156
157// We implement malloc debugging only in libc.so, so the code below
158// must be excluded if we compile this file for static libc.a
159#if !defined(LIBC_STATIC)
160
161#include <dlfcn.h>
162#include <pthread.h>
163#include <stdio.h>
164#include <stdlib.h>
165
166#include <private/libc_logging.h>
167#include <sys/system_properties.h>
168
169extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
170
171static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
172static const char* DEBUG_MALLOC_PROPERTY_OPTIONS = "libc.debug.malloc.options";
173static const char* DEBUG_MALLOC_PROPERTY_PROGRAM = "libc.debug.malloc.program";
174static const char* DEBUG_MALLOC_PROPERTY_ENV_ENABLED = "libc.debug.malloc.env_enabled";
175static const char* DEBUG_MALLOC_ENV_ENABLE = "LIBC_DEBUG_MALLOC_ENABLE";
176
177static void* libc_malloc_impl_handle = nullptr;
178
179static void (*g_debug_finalize_func)();
180static void (*g_debug_get_malloc_leak_info_func)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
181static void (*g_debug_free_malloc_leak_info_func)(uint8_t*);
182
183// =============================================================================
184// Log functions
185// =============================================================================
186#define error_log(format, ...) \
187 __libc_format_log(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
188#define info_log(format, ...) \
189 __libc_format_log(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
190// =============================================================================
191
192// =============================================================================
193// Exported for use by ddms.
194// =============================================================================
195
196// Retrieve native heap information.
197//
198// "*info" is set to a buffer we allocate
199// "*overall_size" is set to the size of the "info" buffer
200// "*info_size" is set to the size of a single entry
201// "*total_memory" is set to the sum of all allocations we're tracking; does
202// not include heap overhead
203// "*backtrace_size" is set to the maximum number of entries in the back trace
204extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
205 size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
206 if (g_debug_get_malloc_leak_info_func == nullptr) {
207 return;
208 }
209 g_debug_get_malloc_leak_info_func(info, overall_size, info_size, total_memory, backtrace_size);
210}
211
212extern "C" void free_malloc_leak_info(uint8_t* info) {
213 if (g_debug_free_malloc_leak_info_func == nullptr) {
214 return;
215 }
216 g_debug_free_malloc_leak_info_func(info);
217}
218// =============================================================================
219
220template<typename FunctionType>
221static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
222 char symbol[128];
223 snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
224 *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
225 if (*func == nullptr) {
226 error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
227 return false;
228 }
229 return true;
230}
231
232static bool InitMalloc(void* malloc_impl_handler, MallocDispatch* table, const char* prefix) {
233 if (!InitMallocFunction<MallocCalloc>(malloc_impl_handler, &table->calloc,
234 prefix, "calloc")) {
235 return false;
236 }
237 if (!InitMallocFunction<MallocFree>(malloc_impl_handler, &table->free,
238 prefix, "free")) {
239 return false;
240 }
241 if (!InitMallocFunction<MallocMallinfo>(malloc_impl_handler, &table->mallinfo,
242 prefix, "mallinfo")) {
243 return false;
244 }
245 if (!InitMallocFunction<MallocMalloc>(malloc_impl_handler, &table->malloc,
246 prefix, "malloc")) {
247 return false;
248 }
249 if (!InitMallocFunction<MallocMallocUsableSize>(
250 malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size")) {
251 return false;
252 }
253 if (!InitMallocFunction<MallocMemalign>(malloc_impl_handler, &table->memalign,
254 prefix, "memalign")) {
255 return false;
256 }
257 if (!InitMallocFunction<MallocPosixMemalign>(malloc_impl_handler, &table->posix_memalign,
258 prefix, "posix_memalign")) {
259 return false;
260 }
261 if (!InitMallocFunction<MallocRealloc>(malloc_impl_handler, &table->realloc,
262 prefix, "realloc")) {
263 return false;
264 }
265#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
266 if (!InitMallocFunction<MallocPvalloc>(malloc_impl_handler, &table->pvalloc,
267 prefix, "pvalloc")) {
268 return false;
269 }
270 if (!InitMallocFunction<MallocValloc>(malloc_impl_handler, &table->valloc,
271 prefix, "valloc")) {
272 return false;
273 }
274#endif
275
276 return true;
277}
278
279static void malloc_fini_impl(void*) {
280 // Our BSD stdio implementation doesn't close the standard streams,
281 // it only flushes them. Other unclosed FILE*s will show up as
282 // malloc leaks, but to avoid the standard streams showing up in
283 // leak reports, close them here.
284 fclose(stdin);
285 fclose(stdout);
286 fclose(stderr);
287
288 g_debug_finalize_func();
289}
290
291// Initializes memory allocation framework once per process.
292static void malloc_init_impl(libc_globals* globals) {
293 char value[PROP_VALUE_MAX];
294 if (__system_property_get(DEBUG_MALLOC_PROPERTY_OPTIONS, value) == 0 || value[0] == '\0') {
295 return;
296 }
297
298 // Check to see if only a specific program should have debug malloc enabled.
299 if (__system_property_get(DEBUG_MALLOC_PROPERTY_PROGRAM, value) != 0 &&
300 strstr(getprogname(), value) == nullptr) {
301 return;
302 }
303
304 // Check for the special environment variable instead.
305 if (__system_property_get(DEBUG_MALLOC_PROPERTY_ENV_ENABLED, value) != 0
306 && value[0] != '\0' && getenv(DEBUG_MALLOC_ENV_ENABLE) == nullptr) {
307 return;
308 }
309
310 // Load the debug malloc shared library.
311 void* malloc_impl_handle = dlopen(DEBUG_SHARED_LIB, RTLD_NOW | RTLD_LOCAL);
312 if (malloc_impl_handle == nullptr) {
313 error_log("%s: Unable to open debug malloc shared library %s: %s",
314 getprogname(), DEBUG_SHARED_LIB, dlerror());
315 return;
316 }
317
318 // Initialize malloc debugging in the loaded module.
319 void* sym = dlsym(malloc_impl_handle, "debug_initialize");
320 auto init_func = reinterpret_cast<bool (*)(const MallocDispatch*, int*)>(sym);
321 if (init_func == nullptr) {
322 error_log("%s: debug_initialize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
323 dlclose(malloc_impl_handle);
324 return;
325 }
326
327 // Get the syms for the external functions.
328 sym = dlsym(malloc_impl_handle, "debug_finalize");
329 if (sym == nullptr) {
330 error_log("%s: debug_finalize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
331 dlclose(malloc_impl_handle);
332 return;
333 }
334 g_debug_finalize_func = reinterpret_cast<void (*)()>(sym);
335
336 sym = dlsym(malloc_impl_handle, "debug_get_malloc_leak_info");
337 if (sym == nullptr) {
338 error_log("%s: debug_get_malloc_leak_info routine not found in %s", getprogname(),
339 DEBUG_SHARED_LIB);
340 dlclose(malloc_impl_handle);
341 return;
342 }
343 g_debug_get_malloc_leak_info_func = reinterpret_cast<void (*)(uint8_t**, size_t*, size_t*,
344 size_t*, size_t*)>(sym);
345
346 sym = dlsym(malloc_impl_handle, "debug_free_malloc_leak_info");
347 if (sym == nullptr) {
348 error_log("%s: debug_free_malloc_leak_info routine not found in %s", getprogname(),
349 DEBUG_SHARED_LIB);
350 dlclose(malloc_impl_handle);
351 return;
352 }
353 g_debug_free_malloc_leak_info_func = reinterpret_cast<void (*)(uint8_t*)>(sym);
354
355 if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild)) {
356 dlclose(malloc_impl_handle);
357 return;
358 }
359
360 MallocDispatch malloc_dispatch_table;
361 if (!InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "debug")) {
362 g_debug_finalize_func();
363 dlclose(malloc_impl_handle);
364 return;
365 }
366
367 globals->malloc_dispatch = malloc_dispatch_table;
368 libc_malloc_impl_handle = malloc_impl_handle;
369
370 info_log("%s: malloc debug enabled", getprogname());
371
372 // Use atexit to trigger the cleanup function. This avoids a problem
373 // where another atexit function is used to cleanup allocated memory,
374 // but the finalize function was already called. This particular error
375 // seems to be triggered by a zygote spawned process calling exit.
376 int ret_value = __cxa_atexit(malloc_fini_impl, nullptr, nullptr);
377 if (ret_value != 0) {
378 error_log("failed to set atexit cleanup function: %d", ret_value);
379 }
380}
381
382// Initializes memory allocation framework.
383// This routine is called from __libc_init routines in libc_init_dynamic.cpp.
384__LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
385 malloc_init_impl(globals);
386}
387#endif // !LIBC_STATIC