OSDN Git Service

Merge tag 'android-8.1.0_r29' into oreo-x86
[android-x86/bionic.git] / libc / bionic / malloc_common.cpp
1 /*
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 <pthread.h>
44
45 #include <private/bionic_config.h>
46 #include <private/bionic_globals.h>
47 #include <private/bionic_malloc_dispatch.h>
48
49 #include "jemalloc.h"
50 #define Malloc(function)  je_ ## function
51
52 static constexpr MallocDispatch __libc_malloc_default_dispatch
53   __attribute__((unused)) = {
54     Malloc(calloc),
55     Malloc(free),
56     Malloc(mallinfo),
57     Malloc(malloc),
58     Malloc(malloc_usable_size),
59     Malloc(memalign),
60     Malloc(posix_memalign),
61 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
62     Malloc(pvalloc),
63 #endif
64     Malloc(realloc),
65 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
66     Malloc(valloc),
67 #endif
68     Malloc(iterate),
69     Malloc(malloc_disable),
70     Malloc(malloc_enable),
71     Malloc(mallopt),
72   };
73
74 // In a VM process, this is set to 1 after fork()ing out of zygote.
75 int gMallocLeakZygoteChild = 0;
76
77 // =============================================================================
78 // Allocation functions
79 // =============================================================================
80 extern "C" void* calloc(size_t n_elements, size_t elem_size) {
81   auto _calloc = __libc_globals->malloc_dispatch.calloc;
82   if (__predict_false(_calloc != nullptr)) {
83     return _calloc(n_elements, elem_size);
84   }
85   return Malloc(calloc)(n_elements, elem_size);
86 }
87
88 extern "C" void free(void* mem) {
89   auto _free = __libc_globals->malloc_dispatch.free;
90   if (__predict_false(_free != nullptr)) {
91     _free(mem);
92   } else {
93     Malloc(free)(mem);
94   }
95 }
96
97 extern "C" struct mallinfo mallinfo() {
98   auto _mallinfo = __libc_globals->malloc_dispatch.mallinfo;
99   if (__predict_false(_mallinfo != nullptr)) {
100     return _mallinfo();
101   }
102   return Malloc(mallinfo)();
103 }
104
105 extern "C" int mallopt(int param, int value) {
106   auto _mallopt = __libc_globals->malloc_dispatch.mallopt;
107   if (__predict_false(_mallopt != nullptr)) {
108     return _mallopt(param, value);
109   }
110   return Malloc(mallopt)(param, value);
111 }
112
113 extern "C" void* malloc(size_t bytes) {
114   auto _malloc = __libc_globals->malloc_dispatch.malloc;
115   if (__predict_false(_malloc != nullptr)) {
116     return _malloc(bytes);
117   }
118   return Malloc(malloc)(bytes);
119 }
120
121 extern "C" size_t malloc_usable_size(const void* mem) {
122   auto _malloc_usable_size = __libc_globals->malloc_dispatch.malloc_usable_size;
123   if (__predict_false(_malloc_usable_size != nullptr)) {
124     return _malloc_usable_size(mem);
125   }
126   return Malloc(malloc_usable_size)(mem);
127 }
128
129 extern "C" void* memalign(size_t alignment, size_t bytes) {
130   auto _memalign = __libc_globals->malloc_dispatch.memalign;
131   if (__predict_false(_memalign != nullptr)) {
132     return _memalign(alignment, bytes);
133   }
134   return Malloc(memalign)(alignment, bytes);
135 }
136
137 extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size) {
138   auto _posix_memalign = __libc_globals->malloc_dispatch.posix_memalign;
139   if (__predict_false(_posix_memalign != nullptr)) {
140     return _posix_memalign(memptr, alignment, size);
141   }
142   return Malloc(posix_memalign)(memptr, alignment, size);
143 }
144
145 extern "C" void* realloc(void* old_mem, size_t bytes) {
146   auto _realloc = __libc_globals->malloc_dispatch.realloc;
147   if (__predict_false(_realloc != nullptr)) {
148     return _realloc(old_mem, bytes);
149   }
150   return Malloc(realloc)(old_mem, bytes);
151 }
152
153 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
154 extern "C" void* pvalloc(size_t bytes) {
155   auto _pvalloc = __libc_globals->malloc_dispatch.pvalloc;
156   if (__predict_false(_pvalloc != nullptr)) {
157     return _pvalloc(bytes);
158   }
159   return Malloc(pvalloc)(bytes);
160 }
161
162 extern "C" void* valloc(size_t bytes) {
163   auto _valloc = __libc_globals->malloc_dispatch.valloc;
164   if (__predict_false(_valloc != nullptr)) {
165     return _valloc(bytes);
166   }
167   return Malloc(valloc)(bytes);
168 }
169 #endif
170
171 // We implement malloc debugging only in libc.so, so the code below
172 // must be excluded if we compile this file for static libc.a
173 #if !defined(LIBC_STATIC)
174
175 #include <dlfcn.h>
176 #include <stdio.h>
177 #include <stdlib.h>
178
179 #include <async_safe/log.h>
180 #include <sys/system_properties.h>
181
182 extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
183
184 static const char* DEBUG_SHARED_LIB = "libc_malloc_debug.so";
185 static const char* DEBUG_MALLOC_PROPERTY_OPTIONS = "libc.debug.malloc.options";
186 static const char* DEBUG_MALLOC_PROPERTY_PROGRAM = "libc.debug.malloc.program";
187 static const char* DEBUG_MALLOC_ENV_OPTIONS = "LIBC_DEBUG_MALLOC_OPTIONS";
188
189 static void* libc_malloc_impl_handle = nullptr;
190
191 static void (*g_debug_finalize_func)();
192 static void (*g_debug_get_malloc_leak_info_func)(uint8_t**, size_t*, size_t*, size_t*, size_t*);
193 static void (*g_debug_free_malloc_leak_info_func)(uint8_t*);
194 static ssize_t (*g_debug_malloc_backtrace_func)(void*, uintptr_t*, size_t);
195
196 // =============================================================================
197 // Log functions
198 // =============================================================================
199 #define error_log(format, ...)  \
200     async_safe_format_log(ANDROID_LOG_ERROR, "libc", (format), ##__VA_ARGS__ )
201 #define info_log(format, ...)  \
202     async_safe_format_log(ANDROID_LOG_INFO, "libc", (format), ##__VA_ARGS__ )
203 // =============================================================================
204
205 // =============================================================================
206 // Exported for use by ddms.
207 // =============================================================================
208
209 // Retrieve native heap information.
210 //
211 // "*info" is set to a buffer we allocate
212 // "*overall_size" is set to the size of the "info" buffer
213 // "*info_size" is set to the size of a single entry
214 // "*total_memory" is set to the sum of all allocations we're tracking; does
215 //   not include heap overhead
216 // "*backtrace_size" is set to the maximum number of entries in the back trace
217 extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overall_size,
218     size_t* info_size, size_t* total_memory, size_t* backtrace_size) {
219   if (g_debug_get_malloc_leak_info_func == nullptr) {
220     return;
221   }
222   g_debug_get_malloc_leak_info_func(info, overall_size, info_size, total_memory, backtrace_size);
223 }
224
225 extern "C" void free_malloc_leak_info(uint8_t* info) {
226   if (g_debug_free_malloc_leak_info_func == nullptr) {
227     return;
228   }
229   g_debug_free_malloc_leak_info_func(info);
230 }
231
232 // =============================================================================
233
234 template<typename FunctionType>
235 static bool InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
236   char symbol[128];
237   snprintf(symbol, sizeof(symbol), "%s_%s", prefix, suffix);
238   *func = reinterpret_cast<FunctionType>(dlsym(malloc_impl_handler, symbol));
239   if (*func == nullptr) {
240     error_log("%s: dlsym(\"%s\") failed", getprogname(), symbol);
241     return false;
242   }
243   return true;
244 }
245
246 static bool InitMalloc(void* malloc_impl_handler, MallocDispatch* table, const char* prefix) {
247   if (!InitMallocFunction<MallocCalloc>(malloc_impl_handler, &table->calloc,
248                                         prefix, "calloc")) {
249     return false;
250   }
251   if (!InitMallocFunction<MallocFree>(malloc_impl_handler, &table->free,
252                                       prefix, "free")) {
253     return false;
254   }
255   if (!InitMallocFunction<MallocMallinfo>(malloc_impl_handler, &table->mallinfo,
256                                           prefix, "mallinfo")) {
257     return false;
258   }
259   if (!InitMallocFunction<MallocMallopt>(malloc_impl_handler, &table->mallopt,
260                                          prefix, "mallopt")) {
261     return false;
262   }
263   if (!InitMallocFunction<MallocMalloc>(malloc_impl_handler, &table->malloc,
264                                         prefix, "malloc")) {
265     return false;
266   }
267   if (!InitMallocFunction<MallocMallocUsableSize>(
268       malloc_impl_handler, &table->malloc_usable_size, prefix, "malloc_usable_size")) {
269     return false;
270   }
271   if (!InitMallocFunction<MallocMemalign>(malloc_impl_handler, &table->memalign,
272                                           prefix, "memalign")) {
273     return false;
274   }
275   if (!InitMallocFunction<MallocPosixMemalign>(malloc_impl_handler, &table->posix_memalign,
276                                                prefix, "posix_memalign")) {
277     return false;
278   }
279   if (!InitMallocFunction<MallocRealloc>(malloc_impl_handler, &table->realloc,
280                                          prefix, "realloc")) {
281     return false;
282   }
283   if (!InitMallocFunction<MallocIterate>(malloc_impl_handler, &table->iterate,
284                                          prefix, "iterate")) {
285     return false;
286   }
287   if (!InitMallocFunction<MallocMallocDisable>(malloc_impl_handler, &table->malloc_disable,
288                                          prefix, "malloc_disable")) {
289     return false;
290   }
291   if (!InitMallocFunction<MallocMallocEnable>(malloc_impl_handler, &table->malloc_enable,
292                                          prefix, "malloc_enable")) {
293     return false;
294   }
295 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
296   if (!InitMallocFunction<MallocPvalloc>(malloc_impl_handler, &table->pvalloc,
297                                          prefix, "pvalloc")) {
298     return false;
299   }
300   if (!InitMallocFunction<MallocValloc>(malloc_impl_handler, &table->valloc,
301                                         prefix, "valloc")) {
302     return false;
303   }
304 #endif
305
306   return true;
307 }
308
309 static void malloc_fini_impl(void*) {
310   // Our BSD stdio implementation doesn't close the standard streams,
311   // it only flushes them. Other unclosed FILE*s will show up as
312   // malloc leaks, but to avoid the standard streams showing up in
313   // leak reports, close them here.
314   fclose(stdin);
315   fclose(stdout);
316   fclose(stderr);
317
318   g_debug_finalize_func();
319 }
320
321 // Initializes memory allocation framework once per process.
322 static void malloc_init_impl(libc_globals* globals) {
323   char value[PROP_VALUE_MAX];
324
325   // If DEBUG_MALLOC_ENV_OPTIONS is set then it overrides the system properties.
326   const char* options = getenv(DEBUG_MALLOC_ENV_OPTIONS);
327   if (options == nullptr || options[0] == '\0') {
328     if (__system_property_get(DEBUG_MALLOC_PROPERTY_OPTIONS, value) == 0 || value[0] == '\0') {
329       return;
330     }
331     options = value;
332
333     // Check to see if only a specific program should have debug malloc enabled.
334     char program[PROP_VALUE_MAX];
335     if (__system_property_get(DEBUG_MALLOC_PROPERTY_PROGRAM, program) != 0 &&
336         strstr(getprogname(), program) == nullptr) {
337       return;
338     }
339   }
340
341   // Load the debug malloc shared library.
342   void* malloc_impl_handle = dlopen(DEBUG_SHARED_LIB, RTLD_NOW | RTLD_LOCAL);
343   if (malloc_impl_handle == nullptr) {
344     error_log("%s: Unable to open debug malloc shared library %s: %s",
345               getprogname(), DEBUG_SHARED_LIB, dlerror());
346     return;
347   }
348
349   // Initialize malloc debugging in the loaded module.
350   auto init_func = reinterpret_cast<bool (*)(const MallocDispatch*, int*, const char*)>(
351       dlsym(malloc_impl_handle, "debug_initialize"));
352   if (init_func == nullptr) {
353     error_log("%s: debug_initialize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
354     dlclose(malloc_impl_handle);
355     return;
356   }
357
358   // Get the syms for the external functions.
359   void* finalize_sym = dlsym(malloc_impl_handle, "debug_finalize");
360   if (finalize_sym == nullptr) {
361     error_log("%s: debug_finalize routine not found in %s", getprogname(), DEBUG_SHARED_LIB);
362     dlclose(malloc_impl_handle);
363     return;
364   }
365
366   void* get_leak_info_sym = dlsym(malloc_impl_handle, "debug_get_malloc_leak_info");
367   if (get_leak_info_sym == nullptr) {
368     error_log("%s: debug_get_malloc_leak_info routine not found in %s", getprogname(),
369               DEBUG_SHARED_LIB);
370     dlclose(malloc_impl_handle);
371     return;
372   }
373
374   void* free_leak_info_sym = dlsym(malloc_impl_handle, "debug_free_malloc_leak_info");
375   if (free_leak_info_sym == nullptr) {
376     error_log("%s: debug_free_malloc_leak_info routine not found in %s", getprogname(),
377               DEBUG_SHARED_LIB);
378     dlclose(malloc_impl_handle);
379     return;
380   }
381
382   void* malloc_backtrace_sym = dlsym(malloc_impl_handle, "debug_malloc_backtrace");
383   if (malloc_backtrace_sym == nullptr) {
384     error_log("%s: debug_malloc_backtrace routine not found in %s", getprogname(),
385               DEBUG_SHARED_LIB);
386     dlclose(malloc_impl_handle);
387     return;
388   }
389
390   if (!init_func(&__libc_malloc_default_dispatch, &gMallocLeakZygoteChild, options)) {
391     dlclose(malloc_impl_handle);
392     return;
393   }
394
395   MallocDispatch malloc_dispatch_table;
396   if (!InitMalloc(malloc_impl_handle, &malloc_dispatch_table, "debug")) {
397     auto finalize_func = reinterpret_cast<void (*)()>(finalize_sym);
398     finalize_func();
399     dlclose(malloc_impl_handle);
400     return;
401   }
402
403   g_debug_finalize_func = reinterpret_cast<void (*)()>(finalize_sym);
404   g_debug_get_malloc_leak_info_func = reinterpret_cast<void (*)(
405       uint8_t**, size_t*, size_t*, size_t*, size_t*)>(get_leak_info_sym);
406   g_debug_free_malloc_leak_info_func = reinterpret_cast<void (*)(uint8_t*)>(free_leak_info_sym);
407   g_debug_malloc_backtrace_func = reinterpret_cast<ssize_t (*)(
408       void*, uintptr_t*, size_t)>(malloc_backtrace_sym);
409
410   globals->malloc_dispatch = malloc_dispatch_table;
411   libc_malloc_impl_handle = malloc_impl_handle;
412
413   info_log("%s: malloc debug enabled", getprogname());
414
415   // Use atexit to trigger the cleanup function. This avoids a problem
416   // where another atexit function is used to cleanup allocated memory,
417   // but the finalize function was already called. This particular error
418   // seems to be triggered by a zygote spawned process calling exit.
419   int ret_value = __cxa_atexit(malloc_fini_impl, nullptr, nullptr);
420   if (ret_value != 0) {
421     error_log("failed to set atexit cleanup function: %d", ret_value);
422   }
423 }
424
425 // Initializes memory allocation framework.
426 // This routine is called from __libc_init routines in libc_init_dynamic.cpp.
427 __LIBC_HIDDEN__ void __libc_init_malloc(libc_globals* globals) {
428   malloc_init_impl(globals);
429 }
430 #endif  // !LIBC_STATIC
431
432 // =============================================================================
433 // Exported for use by libmemunreachable.
434 // =============================================================================
435
436 // Calls callback for every allocation in the anonymous heap mapping
437 // [base, base+size).  Must be called between malloc_disable and malloc_enable.
438 extern "C" int malloc_iterate(uintptr_t base, size_t size,
439     void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
440   auto _iterate = __libc_globals->malloc_dispatch.iterate;
441   if (__predict_false(_iterate != nullptr)) {
442     return _iterate(base, size, callback, arg);
443   }
444   return Malloc(iterate)(base, size, callback, arg);
445 }
446
447 // Disable calls to malloc so malloc_iterate gets a consistent view of
448 // allocated memory.
449 extern "C" void malloc_disable() {
450   auto _malloc_disable = __libc_globals->malloc_dispatch.malloc_disable;
451   if (__predict_false(_malloc_disable != nullptr)) {
452     return _malloc_disable();
453   }
454   return Malloc(malloc_disable)();
455 }
456
457 // Re-enable calls to malloc after a previous call to malloc_disable.
458 extern "C" void malloc_enable() {
459   auto _malloc_enable = __libc_globals->malloc_dispatch.malloc_enable;
460   if (__predict_false(_malloc_enable != nullptr)) {
461     return _malloc_enable();
462   }
463   return Malloc(malloc_enable)();
464 }
465
466 #ifndef LIBC_STATIC
467 extern "C" ssize_t malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count) {
468   if (g_debug_malloc_backtrace_func == nullptr) {
469     return 0;
470   }
471   return g_debug_malloc_backtrace_func(pointer, frames, frame_count);
472 }
473 #else
474 extern "C" ssize_t malloc_backtrace(void*, uintptr_t*, size_t) {
475   return 0;
476 }
477 #endif