blob: 7e961695f15dc02a726966d8f9dde103782ab6f9 [file] [log] [blame]
Christopher Ferris63860cb2015-11-16 17:30:32 -08001/*
2 * Copyright (C) 2012 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#include <errno.h>
30#include <inttypes.h>
31#include <malloc.h>
Christopher Ferrisd269fcc2019-05-06 19:03:59 -070032#include <pthread.h>
Christopher Ferris9bf78172020-05-20 15:37:30 -070033#include <signal.h>
Christopher Ferris6c619a02019-03-01 17:59:51 -080034#include <stdio.h>
Christopher Ferrisc328e442019-04-01 19:31:26 -070035#include <stdlib.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -080036#include <string.h>
37#include <sys/cdefs.h>
38#include <sys/param.h>
Christopher Ferris9bf78172020-05-20 15:37:30 -070039#include <sys/syscall.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -080040#include <unistd.h>
41
Christopher Ferris602b88c2017-08-04 13:04:04 -070042#include <mutex>
Christopher Ferris63860cb2015-11-16 17:30:32 -080043#include <vector>
44
Christopher Ferris602b88c2017-08-04 13:04:04 -070045#include <android-base/file.h>
Christopher Ferris2e1a40a2018-06-13 10:46:34 -070046#include <android-base/properties.h>
Christopher Ferris602b88c2017-08-04 13:04:04 -070047#include <android-base/stringprintf.h>
Mitch Phillips3b21ada2020-01-07 15:47:47 -080048#include <bionic/malloc_tagged_pointers.h>
Christopher Ferris9bf78172020-05-20 15:37:30 -070049#include <platform/bionic/reserved_signals.h>
Christopher Ferris6c619a02019-03-01 17:59:51 -080050#include <private/MallocXmlElem.h>
Christopher Ferris9bf78172020-05-20 15:37:30 -070051#include <private/bionic_malloc_dispatch.h>
Christopher Ferris459eecb2022-01-07 13:38:10 -080052#include <unwindstack/Unwinder.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -080053
Christopher Ferris72df6702016-02-11 15:51:31 -080054#include "Config.h"
Christopher Ferris63860cb2015-11-16 17:30:32 -080055#include "DebugData.h"
Christopher Ferris5610d5a2023-11-14 15:04:50 -080056#include "LogAllocatorStats.h"
Christopher Ferrise39602c2024-11-02 05:02:43 +000057#include "Nanotime.h"
Christopher Ferrisb42e8b42022-05-09 14:00:47 -070058#include "Unreachable.h"
59#include "UnwindBacktrace.h"
Christopher Ferris4da25032018-03-07 13:38:48 -080060#include "backtrace.h"
Christopher Ferris63860cb2015-11-16 17:30:32 -080061#include "debug_disable.h"
62#include "debug_log.h"
63#include "malloc_debug.h"
64
65// ------------------------------------------------------------------------
66// Global Data
67// ------------------------------------------------------------------------
68DebugData* g_debug;
69
Christopher Ferris8189e772019-04-09 16:37:23 -070070bool* g_zygote_child;
Christopher Ferris63860cb2015-11-16 17:30:32 -080071
72const MallocDispatch* g_dispatch;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +000073
Chia-hung Duanf7e8b172022-11-01 21:37:56 +000074namespace {
75// A TimedResult contains the result of from malloc end_ns al. functions and the
76// start/end timestamps.
77struct TimedResult {
78 uint64_t start_ns = 0;
79 uint64_t end_ns = 0;
80 union {
81 size_t s;
82 int i;
83 void* p;
84 } v;
85
86 uint64_t GetStartTimeNS() const { return start_ns; }
87 uint64_t GetEndTimeNS() const { return end_ns; }
88 void SetStartTimeNS(uint64_t t) { start_ns = t; }
89 void SetEndTimeNS(uint64_t t) { end_ns = t; }
90
91 template <typename T>
92 void setValue(T);
93 template <>
94 void setValue(size_t s) {
95 v.s = s;
96 }
97 template <>
98 void setValue(int i) {
99 v.i = i;
100 }
101 template <>
102 void setValue(void* p) {
103 v.p = p;
104 }
105
106 template <typename T>
107 T getValue() const;
108 template <>
109 size_t getValue<size_t>() const {
110 return v.s;
111 }
112 template <>
113 int getValue<int>() const {
114 return v.i;
115 }
116 template <>
117 void* getValue<void*>() const {
118 return v.p;
119 }
120};
121
122class ScopedTimer {
123 public:
124 ScopedTimer(TimedResult& res) : res_(res) { res_.start_ns = Nanotime(); }
125
126 ~ScopedTimer() { res_.end_ns = Nanotime(); }
127
128 private:
129 TimedResult& res_;
130};
131
132} // namespace
133
134template <typename MallocFn, typename... Args>
135static TimedResult TimerCall(MallocFn fn, Args... args) {
136 TimedResult ret;
137 decltype((g_dispatch->*fn)(args...)) r;
138 if (g_debug->config().options() & RECORD_ALLOCS) {
139 ScopedTimer t(ret);
140 r = (g_dispatch->*fn)(args...);
141 } else {
142 r = (g_dispatch->*fn)(args...);
143 }
144 ret.setValue<decltype(r)>(r);
145 return ret;
146}
147
148template <typename MallocFn, typename... Args>
149static TimedResult TimerCallVoid(MallocFn fn, Args... args) {
150 TimedResult ret;
151 {
152 ScopedTimer t(ret);
153 (g_dispatch->*fn)(args...);
154 }
155 return ret;
156}
157
158#define TCALL(FUNC, ...) TimerCall(&MallocDispatch::FUNC, __VA_ARGS__);
159#define TCALLVOID(FUNC, ...) TimerCallVoid(&MallocDispatch::FUNC, __VA_ARGS__);
160
Christopher Ferris63860cb2015-11-16 17:30:32 -0800161// ------------------------------------------------------------------------
162
163// ------------------------------------------------------------------------
164// Use C style prototypes for all exported functions. This makes it easy
165// to do dlsym lookups during libc initialization when malloc debug
166// is enabled.
167// ------------------------------------------------------------------------
168__BEGIN_DECLS
169
Christopher Ferris8189e772019-04-09 16:37:23 -0700170bool debug_initialize(const MallocDispatch* malloc_dispatch, bool* malloc_zygote_child,
Christopher Ferris4da25032018-03-07 13:38:48 -0800171 const char* options);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800172void debug_finalize();
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700173void debug_dump_heap(const char* file_name);
Christopher Ferris4da25032018-03-07 13:38:48 -0800174void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
175 size_t* total_memory, size_t* backtrace_size);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700176bool debug_write_malloc_leak_info(FILE* fp);
Colin Cross2d4721c2016-02-02 11:57:54 -0800177ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800178void debug_free_malloc_leak_info(uint8_t* info);
179size_t debug_malloc_usable_size(void* pointer);
180void* debug_malloc(size_t size);
181void debug_free(void* pointer);
Christopher Ferriscae21a92018-02-05 18:14:55 -0800182void* debug_aligned_alloc(size_t alignment, size_t size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800183void* debug_memalign(size_t alignment, size_t bytes);
184void* debug_realloc(void* pointer, size_t bytes);
185void* debug_calloc(size_t nmemb, size_t bytes);
186struct mallinfo debug_mallinfo();
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700187int debug_mallopt(int param, int value);
Christopher Ferris6c619a02019-03-01 17:59:51 -0800188int debug_malloc_info(int options, FILE* fp);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800189int debug_posix_memalign(void** memptr, size_t alignment, size_t size);
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800190int debug_malloc_iterate(uintptr_t base, size_t size,
191 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg);
Colin Cross869691c2016-01-29 12:48:18 -0800192void debug_malloc_disable();
193void debug_malloc_enable();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800194
195#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
196void* debug_pvalloc(size_t bytes);
197void* debug_valloc(size_t size);
198#endif
199
200__END_DECLS
201// ------------------------------------------------------------------------
202
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700203class ScopedConcurrentLock {
204 public:
205 ScopedConcurrentLock() {
206 pthread_rwlock_rdlock(&lock_);
207 }
208 ~ScopedConcurrentLock() {
209 pthread_rwlock_unlock(&lock_);
210 }
211
212 static void Init() {
213 pthread_rwlockattr_t attr;
214 // Set the attribute so that when a write lock is pending, read locks are no
215 // longer granted.
216 pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
217 pthread_rwlock_init(&lock_, &attr);
218 }
219
220 static void BlockAllOperations() {
221 pthread_rwlock_wrlock(&lock_);
222 }
223
224 private:
225 static pthread_rwlock_t lock_;
226};
227pthread_rwlock_t ScopedConcurrentLock::lock_;
228
Christopher Ferris9bf78172020-05-20 15:37:30 -0700229// Use this because the sigprocmask* functions filter out the reserved bionic
230// signals including the signal this code blocks.
231static inline int __rt_sigprocmask(int how, const sigset64_t* new_set, sigset64_t* old_set,
232 size_t sigset_size) {
233 return syscall(SYS_rt_sigprocmask, how, new_set, old_set, sigset_size);
234}
235
236// Need to block the backtrace signal while in malloc debug routines
237// otherwise there is a chance of a deadlock and timeout when unwinding.
238// This can occur if a thread is paused while owning a malloc debug
239// internal lock.
240class ScopedBacktraceSignalBlocker {
241 public:
242 ScopedBacktraceSignalBlocker() {
243 sigemptyset64(&backtrace_set_);
244 sigaddset64(&backtrace_set_, BIONIC_SIGNAL_BACKTRACE);
245 sigset64_t old_set;
246 __rt_sigprocmask(SIG_BLOCK, &backtrace_set_, &old_set, sizeof(backtrace_set_));
247 if (sigismember64(&old_set, BIONIC_SIGNAL_BACKTRACE)) {
248 unblock_ = false;
249 }
250 }
251
252 ~ScopedBacktraceSignalBlocker() {
253 if (unblock_) {
254 __rt_sigprocmask(SIG_UNBLOCK, &backtrace_set_, nullptr, sizeof(backtrace_set_));
255 }
256 }
257
258 private:
259 bool unblock_ = true;
260 sigset64_t backtrace_set_;
261};
262
Colin Cross7a28a3c2016-02-07 22:51:15 -0800263static void InitAtfork() {
264 static pthread_once_t atfork_init = PTHREAD_ONCE_INIT;
Christopher Ferris4da25032018-03-07 13:38:48 -0800265 pthread_once(&atfork_init, []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800266 pthread_atfork(
Christopher Ferris4da25032018-03-07 13:38:48 -0800267 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800268 if (g_debug != nullptr) {
269 g_debug->PrepareFork();
270 }
271 },
Christopher Ferris4da25032018-03-07 13:38:48 -0800272 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800273 if (g_debug != nullptr) {
274 g_debug->PostForkParent();
275 }
276 },
Christopher Ferris4da25032018-03-07 13:38:48 -0800277 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800278 if (g_debug != nullptr) {
279 g_debug->PostForkChild();
280 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800281 });
Colin Cross7a28a3c2016-02-07 22:51:15 -0800282 });
283}
Christopher Ferrisd0919622016-03-15 22:39:39 -0700284
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700285void BacktraceAndLog() {
286 if (g_debug->config().options() & BACKTRACE_FULL) {
287 std::vector<uintptr_t> frames;
Christopher Ferris459eecb2022-01-07 13:38:10 -0800288 std::vector<unwindstack::FrameData> frames_info;
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700289 if (!Unwind(&frames, &frames_info, 256)) {
290 error_log(" Backtrace failed to get any frames.");
291 } else {
292 UnwindLog(frames_info);
293 }
294 } else {
295 std::vector<uintptr_t> frames(256);
296 size_t num_frames = backtrace_get(frames.data(), frames.size());
297 if (num_frames == 0) {
298 error_log(" Backtrace failed to get any frames.");
299 } else {
300 backtrace_log(frames.data(), num_frames);
301 }
302 }
303}
304
Christopher Ferris4da25032018-03-07 13:38:48 -0800305static void LogError(const void* pointer, const char* error_str) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800306 error_log(LOG_DIVIDER);
Christopher Ferris4da25032018-03-07 13:38:48 -0800307 error_log("+++ ALLOCATION %p %s", pointer, error_str);
308
309 // If we are tracking already freed pointers, check to see if this is
310 // one so we can print extra information.
311 if (g_debug->config().options() & FREE_TRACK) {
312 PointerData::LogFreeBacktrace(pointer);
Christopher Ferris7993b802016-01-28 18:35:05 -0800313 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800314
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700315 error_log("Backtrace at time of failure:");
316 BacktraceAndLog();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800317 error_log(LOG_DIVIDER);
Iris Chang7f209a92019-01-16 11:17:15 +0800318 if (g_debug->config().options() & ABORT_ON_ERROR) {
319 abort();
320 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800321}
322
Christopher Ferris4da25032018-03-07 13:38:48 -0800323static bool VerifyPointer(const void* pointer, const char* function_name) {
324 if (g_debug->HeaderEnabled()) {
325 Header* header = g_debug->GetHeader(pointer);
326 if (header->tag != DEBUG_TAG) {
327 std::string error_str;
328 if (header->tag == DEBUG_FREE_TAG) {
329 error_str = std::string("USED AFTER FREE (") + function_name + ")";
330 } else {
331 error_str = android::base::StringPrintf("HAS INVALID TAG %" PRIx32 " (%s)", header->tag,
332 function_name);
333 }
334 LogError(pointer, error_str.c_str());
335 return false;
336 }
337 }
338
339 if (g_debug->TrackPointers()) {
340 if (!PointerData::Exists(pointer)) {
341 std::string error_str(std::string("UNKNOWN POINTER (") + function_name + ")");
342 LogError(pointer, error_str.c_str());
343 return false;
344 }
345 }
346 return true;
347}
348
349static size_t InternalMallocUsableSize(void* pointer) {
350 if (g_debug->HeaderEnabled()) {
351 return g_debug->GetHeader(pointer)->usable_size;
352 } else {
353 return g_dispatch->malloc_usable_size(pointer);
354 }
355}
356
Christopher Ferris63860cb2015-11-16 17:30:32 -0800357static void* InitHeader(Header* header, void* orig_pointer, size_t size) {
358 header->tag = DEBUG_TAG;
359 header->orig_pointer = orig_pointer;
360 header->size = size;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800361 header->usable_size = g_dispatch->malloc_usable_size(orig_pointer);
362 if (header->usable_size == 0) {
363 g_dispatch->free(orig_pointer);
364 return nullptr;
365 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800366 header->usable_size -= g_debug->pointer_offset() + reinterpret_cast<uintptr_t>(header) -
367 reinterpret_cast<uintptr_t>(orig_pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800368
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700369 if (g_debug->config().options() & FRONT_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800370 uint8_t* guard = g_debug->GetFrontGuard(header);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700371 memset(guard, g_debug->config().front_guard_value(), g_debug->config().front_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800372 }
373
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700374 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800375 uint8_t* guard = g_debug->GetRearGuard(header);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700376 memset(guard, g_debug->config().rear_guard_value(), g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800377 // If the rear guard is enabled, set the usable size to the exact size
378 // of the allocation.
Christopher Ferris4da25032018-03-07 13:38:48 -0800379 header->usable_size = header->size;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800380 }
381
382 return g_debug->GetPointer(header);
383}
384
Christopher Ferris705de3c2019-05-22 13:39:57 -0700385extern "C" void __asan_init() __attribute__((weak));
386
Christopher Ferris8189e772019-04-09 16:37:23 -0700387bool debug_initialize(const MallocDispatch* malloc_dispatch, bool* zygote_child,
Christopher Ferris4da25032018-03-07 13:38:48 -0800388 const char* options) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700389 if (zygote_child == nullptr || options == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800390 return false;
391 }
Colin Cross7a28a3c2016-02-07 22:51:15 -0800392
Christopher Ferris705de3c2019-05-22 13:39:57 -0700393 if (__asan_init != 0) {
394 error_log("malloc debug cannot be enabled alongside ASAN");
395 return false;
396 }
397
Colin Cross7a28a3c2016-02-07 22:51:15 -0800398 InitAtfork();
399
Christopher Ferris8189e772019-04-09 16:37:23 -0700400 g_zygote_child = zygote_child;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800401
402 g_dispatch = malloc_dispatch;
403
404 if (!DebugDisableInitialize()) {
405 return false;
406 }
407
408 DebugData* debug = new DebugData();
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700409 if (!debug->Initialize(options) || !Unreachable::Initialize(debug->config())) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800410 delete debug;
411 DebugDisableFinalize();
412 return false;
413 }
414 g_debug = debug;
415
416 // Always enable the backtrace code since we will use it in a number
417 // of different error cases.
418 backtrace_startup();
419
Christopher Ferrisc328e442019-04-01 19:31:26 -0700420 if (g_debug->config().options() & VERBOSE) {
421 info_log("%s: malloc debug enabled", getprogname());
422 }
423
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700424 ScopedConcurrentLock::Init();
425
Christopher Ferris63860cb2015-11-16 17:30:32 -0800426 return true;
427}
428
429void debug_finalize() {
430 if (g_debug == nullptr) {
431 return;
432 }
433
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700434 // Make sure that there are no other threads doing debug allocations
435 // before we kill everything.
436 ScopedConcurrentLock::BlockAllOperations();
437
Christopher Ferris97b47472018-07-10 14:45:24 -0700438 // Turn off capturing allocations calls.
439 DebugDisableSet(true);
440
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700441 if (g_debug->config().options() & FREE_TRACK) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800442 PointerData::VerifyAllFreed();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800443 }
444
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700445 if (g_debug->config().options() & LEAK_TRACK) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800446 PointerData::LogLeaks();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800447 }
448
Christopher Ferris9b88d0a2024-06-13 13:22:02 -0700449 if ((g_debug->config().options() & RECORD_ALLOCS) && g_debug->config().record_allocs_on_exit()) {
450 RecordData::WriteEntriesOnExit();
451 }
452
Christopher Ferris602b88c2017-08-04 13:04:04 -0700453 if ((g_debug->config().options() & BACKTRACE) && g_debug->config().backtrace_dump_on_exit()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800454 debug_dump_heap(android::base::StringPrintf("%s.%d.exit.txt",
455 g_debug->config().backtrace_dump_prefix().c_str(),
Christopher Ferris97b47472018-07-10 14:45:24 -0700456 getpid()).c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700457 }
458
Christopher Ferrisc1341e12024-07-11 19:48:08 -0700459 if (g_debug->config().options() & LOG_ALLOCATOR_STATS_ON_EXIT) {
460 LogAllocatorStats::Log();
461 }
462
Colin Cross2c759912016-02-05 16:17:39 -0800463 backtrace_shutdown();
464
Christopher Ferris33d73372021-07-02 15:46:18 -0700465 // In order to prevent any issues of threads freeing previous pointers
466 // after the main thread calls this code, simply leak the g_debug pointer
467 // and do not destroy the debug disable pthread key.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800468}
469
Christopher Ferris4da25032018-03-07 13:38:48 -0800470void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
471 size_t* total_memory, size_t* backtrace_size) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700472 ScopedConcurrentLock lock;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800473 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700474 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800475
476 // Verify the arguments.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700477 if (info == nullptr || overall_size == nullptr || info_size == nullptr || total_memory == nullptr ||
Christopher Ferris4da25032018-03-07 13:38:48 -0800478 backtrace_size == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800479 error_log("get_malloc_leak_info: At least one invalid parameter.");
480 return;
481 }
482
483 *info = nullptr;
484 *overall_size = 0;
485 *info_size = 0;
486 *total_memory = 0;
487 *backtrace_size = 0;
488
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700489 if (!(g_debug->config().options() & BACKTRACE)) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800490 error_log(
491 "get_malloc_leak_info: Allocations not being tracked, to enable "
492 "set the option 'backtrace'.");
Christopher Ferris63860cb2015-11-16 17:30:32 -0800493 return;
494 }
495
Christopher Ferris4da25032018-03-07 13:38:48 -0800496 PointerData::GetInfo(info, overall_size, info_size, total_memory, backtrace_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800497}
498
499void debug_free_malloc_leak_info(uint8_t* info) {
500 g_dispatch->free(info);
Christopher Ferrisaa3e5742023-01-31 01:31:52 +0000501 // Purge the memory that was freed since a significant amount of
502 // memory could have been allocated and freed.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -0700503 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800504}
505
Christopher Ferris55a89a42016-04-07 17:14:53 -0700506size_t debug_malloc_usable_size(void* pointer) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700507 Unreachable::CheckIfRequested(g_debug->config());
508
Christopher Ferris55a89a42016-04-07 17:14:53 -0700509 if (DebugCallsDisabled() || pointer == nullptr) {
510 return g_dispatch->malloc_usable_size(pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800511 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700512 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700513 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700514 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800515
Christopher Ferris4da25032018-03-07 13:38:48 -0800516 if (!VerifyPointer(pointer, "malloc_usable_size")) {
517 return 0;
518 }
519
520 return InternalMallocUsableSize(pointer);
Christopher Ferris55a89a42016-04-07 17:14:53 -0700521}
522
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000523static TimedResult InternalMalloc(size_t size) {
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800524 uint64_t options = g_debug->config().options();
525 if ((options & BACKTRACE) && g_debug->pointer->ShouldDumpAndReset()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800526 debug_dump_heap(android::base::StringPrintf(
527 "%s.%d.txt", g_debug->config().backtrace_dump_prefix().c_str(), getpid())
528 .c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700529 }
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800530 if (options & LOG_ALLOCATOR_STATS_ON_SIGNAL) {
531 LogAllocatorStats::CheckIfShouldLog();
532 }
Christopher Ferris602b88c2017-08-04 13:04:04 -0700533
Colin Cross9567c7b2016-03-09 17:56:14 -0800534 if (size == 0) {
535 size = 1;
536 }
537
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000538 TimedResult result;
539
Christopher Ferris63860cb2015-11-16 17:30:32 -0800540 size_t real_size = size + g_debug->extra_bytes();
541 if (real_size < size) {
542 // Overflow.
543 errno = ENOMEM;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000544 result.setValue<void*>(nullptr);
545 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800546 }
547
Christopher Ferris4da25032018-03-07 13:38:48 -0800548 if (size > PointerInfoType::MaxSize()) {
549 errno = ENOMEM;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000550 result.setValue<void*>(nullptr);
551 return result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800552 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800553
Christopher Ferris4da25032018-03-07 13:38:48 -0800554 if (g_debug->HeaderEnabled()) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000555 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
556 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800557 if (header == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000558 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800559 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000560 result.setValue<void*>(InitHeader(header, header, size));
Christopher Ferris63860cb2015-11-16 17:30:32 -0800561 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000562 result = TCALL(malloc, real_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800563 }
564
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000565 void* pointer = result.getValue<void*>();
566
Christopher Ferris4da25032018-03-07 13:38:48 -0800567 if (pointer != nullptr) {
568 if (g_debug->TrackPointers()) {
569 PointerData::Add(pointer, size);
570 }
571
572 if (g_debug->config().options() & FILL_ON_ALLOC) {
573 size_t bytes = InternalMallocUsableSize(pointer);
574 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
575 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
576 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
577 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800578 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000579
580 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800581}
582
Christopher Ferris55a89a42016-04-07 17:14:53 -0700583void* debug_malloc(size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700584 Unreachable::CheckIfRequested(g_debug->config());
585
Christopher Ferris55a89a42016-04-07 17:14:53 -0700586 if (DebugCallsDisabled()) {
587 return g_dispatch->malloc(size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800588 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700589 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700590 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700591 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800592
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000593 memory_trace::Entry* entry = nullptr;
594 if (g_debug->config().options() & RECORD_ALLOCS) {
595 // In order to preserve the order of operations, reserve the entry before
596 // performing the operation.
597 entry = g_debug->record->ReserveEntry();
598 }
599
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000600 TimedResult result = InternalMalloc(size);
Christopher Ferris7bd01782016-04-20 12:30:58 -0700601
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000602 if (entry != nullptr) {
603 *entry = memory_trace::Entry{.tid = gettid(),
604 .type = memory_trace::MALLOC,
605 .ptr = reinterpret_cast<uint64_t>(result.getValue<void*>()),
606 .size = size,
607 .start_ns = result.GetStartTimeNS(),
608 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -0700609 }
610
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000611 return result.getValue<void*>();
Christopher Ferris55a89a42016-04-07 17:14:53 -0700612}
613
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000614static TimedResult InternalFree(void* pointer) {
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800615 uint64_t options = g_debug->config().options();
616 if ((options & BACKTRACE) && g_debug->pointer->ShouldDumpAndReset()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800617 debug_dump_heap(android::base::StringPrintf(
618 "%s.%d.txt", g_debug->config().backtrace_dump_prefix().c_str(), getpid())
619 .c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700620 }
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800621 if (options & LOG_ALLOCATOR_STATS_ON_SIGNAL) {
622 LogAllocatorStats::CheckIfShouldLog();
623 }
Christopher Ferris602b88c2017-08-04 13:04:04 -0700624
Christopher Ferris63860cb2015-11-16 17:30:32 -0800625 void* free_pointer = pointer;
626 size_t bytes;
Christopher Ferrisd0919622016-03-15 22:39:39 -0700627 Header* header;
Christopher Ferris4da25032018-03-07 13:38:48 -0800628 if (g_debug->HeaderEnabled()) {
Christopher Ferrisd0919622016-03-15 22:39:39 -0700629 header = g_debug->GetHeader(pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800630 free_pointer = header->orig_pointer;
631
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700632 if (g_debug->config().options() & FRONT_GUARD) {
Christopher Ferris55a89a42016-04-07 17:14:53 -0700633 if (!g_debug->front_guard->Valid(header)) {
634 g_debug->front_guard->LogFailure(header);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800635 }
636 }
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700637 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris55a89a42016-04-07 17:14:53 -0700638 if (!g_debug->rear_guard->Valid(header)) {
639 g_debug->rear_guard->LogFailure(header);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800640 }
641 }
642
Christopher Ferris7993b802016-01-28 18:35:05 -0800643 header->tag = DEBUG_FREE_TAG;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800644
645 bytes = header->usable_size;
646 } else {
647 bytes = g_dispatch->malloc_usable_size(pointer);
648 }
649
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700650 if (g_debug->config().options() & FILL_ON_FREE) {
651 size_t fill_bytes = g_debug->config().fill_on_free_bytes();
Christopher Ferrisa3836482022-05-13 12:09:39 -0700652 fill_bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
653 memset(pointer, g_debug->config().fill_free_value(), fill_bytes);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800654 }
655
Christopher Ferris4da25032018-03-07 13:38:48 -0800656 if (g_debug->TrackPointers()) {
657 PointerData::Remove(pointer);
658 }
659
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000660 TimedResult result;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700661 if (g_debug->config().options() & FREE_TRACK) {
Christopher Ferrisd0919622016-03-15 22:39:39 -0700662 // Do not add the allocation until we are done modifying the pointer
663 // itself. This avoids a race if a lot of threads are all doing
664 // frees at the same time and we wind up trying to really free this
665 // pointer from another thread, while still trying to free it in
666 // this function.
Christopher Ferrisa3836482022-05-13 12:09:39 -0700667 pointer = PointerData::AddFreed(pointer, bytes);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000668 if (pointer != nullptr && g_debug->HeaderEnabled()) {
669 pointer = g_debug->GetHeader(pointer)->orig_pointer;
Christopher Ferris4da25032018-03-07 13:38:48 -0800670 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000671 result = TCALLVOID(free, pointer);
Christopher Ferrisd0919622016-03-15 22:39:39 -0700672 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000673 result = TCALLVOID(free, free_pointer);
Christopher Ferrisd0919622016-03-15 22:39:39 -0700674 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000675
676 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800677}
678
Christopher Ferris55a89a42016-04-07 17:14:53 -0700679void debug_free(void* pointer) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700680 Unreachable::CheckIfRequested(g_debug->config());
681
Christopher Ferris55a89a42016-04-07 17:14:53 -0700682 if (DebugCallsDisabled() || pointer == nullptr) {
683 return g_dispatch->free(pointer);
684 }
Christopher Ferris31199e72024-11-08 14:44:53 -0800685
686 size_t size;
687 if (g_debug->config().options() & RECORD_ALLOCS) {
688 // Need to get the size before disabling debug calls.
689 size = debug_malloc_usable_size(pointer);
690 }
691
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700692 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700693 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700694 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700695
Christopher Ferris4da25032018-03-07 13:38:48 -0800696 if (!VerifyPointer(pointer, "free")) {
697 return;
698 }
699
Christopher Ferris31199e72024-11-08 14:44:53 -0800700 int64_t present_bytes = -1;
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000701 memory_trace::Entry* entry = nullptr;
702 if (g_debug->config().options() & RECORD_ALLOCS) {
703 // In order to preserve the order of operations, reserve the entry before
704 // performing the operation.
705 entry = g_debug->record->ReserveEntry();
Christopher Ferris31199e72024-11-08 14:44:53 -0800706
707 // Need to get the present bytes before the pointer is freed in case the
708 // memory is released during the free call.
709 present_bytes = g_debug->record->GetPresentBytes(pointer, size);
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000710 }
711
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000712 TimedResult result = InternalFree(pointer);
713
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000714 if (entry != nullptr) {
715 *entry = memory_trace::Entry{.tid = gettid(),
716 .type = memory_trace::FREE,
717 .ptr = reinterpret_cast<uint64_t>(pointer),
Christopher Ferris31199e72024-11-08 14:44:53 -0800718 .present_bytes = present_bytes,
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000719 .start_ns = result.GetStartTimeNS(),
720 .end_ns = result.GetEndTimeNS()};
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000721 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700722}
723
Christopher Ferris63860cb2015-11-16 17:30:32 -0800724void* debug_memalign(size_t alignment, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700725 Unreachable::CheckIfRequested(g_debug->config());
726
Christopher Ferris63860cb2015-11-16 17:30:32 -0800727 if (DebugCallsDisabled()) {
728 return g_dispatch->memalign(alignment, bytes);
729 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700730 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700731 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700732 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800733
Colin Cross9567c7b2016-03-09 17:56:14 -0800734 if (bytes == 0) {
735 bytes = 1;
736 }
737
Christopher Ferris4da25032018-03-07 13:38:48 -0800738 if (bytes > PointerInfoType::MaxSize()) {
739 errno = ENOMEM;
740 return nullptr;
741 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800742
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000743 memory_trace::Entry* entry = nullptr;
744 if (g_debug->config().options() & RECORD_ALLOCS) {
745 // In order to preserve the order of operations, reserve the entry before
746 // performing the operation.
747 entry = g_debug->record->ReserveEntry();
748 }
749
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000750 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800751 void* pointer;
752 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800753 // Make the alignment a power of two.
754 if (!powerof2(alignment)) {
755 alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
756 }
Christopher Ferris72df6702016-02-11 15:51:31 -0800757 // Force the alignment to at least MINIMUM_ALIGNMENT_BYTES to guarantee
Christopher Ferris63860cb2015-11-16 17:30:32 -0800758 // that the header is aligned properly.
Christopher Ferris72df6702016-02-11 15:51:31 -0800759 if (alignment < MINIMUM_ALIGNMENT_BYTES) {
760 alignment = MINIMUM_ALIGNMENT_BYTES;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800761 }
762
763 // We don't have any idea what the natural alignment of
764 // the underlying native allocator is, so we always need to
765 // over allocate.
766 size_t real_size = alignment + bytes + g_debug->extra_bytes();
767 if (real_size < bytes) {
768 // Overflow.
769 errno = ENOMEM;
770 return nullptr;
771 }
772
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000773 result = TCALL(malloc, real_size);
774 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800775 if (pointer == nullptr) {
776 return nullptr;
777 }
778
779 uintptr_t value = reinterpret_cast<uintptr_t>(pointer) + g_debug->pointer_offset();
780 // Now align the pointer.
781 value += (-value % alignment);
782
783 Header* header = g_debug->GetHeader(reinterpret_cast<void*>(value));
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000784 // Don't need to update `result` here because we only need the timestamps.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800785 pointer = InitHeader(header, pointer, bytes);
786 } else {
787 size_t real_size = bytes + g_debug->extra_bytes();
788 if (real_size < bytes) {
789 // Overflow.
790 errno = ENOMEM;
791 return nullptr;
792 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000793 result = TCALL(memalign, alignment, real_size);
794 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800795 }
796
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000797 if (pointer == nullptr) {
798 return nullptr;
799 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700800
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000801 if (g_debug->TrackPointers()) {
802 PointerData::Add(pointer, bytes);
803 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800804
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000805 if (g_debug->config().options() & FILL_ON_ALLOC) {
806 size_t bytes = InternalMallocUsableSize(pointer);
807 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
808 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
809 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
810 }
811
812 if (entry != nullptr) {
813 *entry = memory_trace::Entry{.tid = gettid(),
814 .type = memory_trace::MEMALIGN,
815 .ptr = reinterpret_cast<uint64_t>(pointer),
816 .size = bytes,
817 .u.align = alignment,
818 .start_ns = result.GetStartTimeNS(),
819 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -0700820 }
821
Christopher Ferris63860cb2015-11-16 17:30:32 -0800822 return pointer;
823}
824
825void* debug_realloc(void* pointer, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700826 Unreachable::CheckIfRequested(g_debug->config());
827
Christopher Ferris63860cb2015-11-16 17:30:32 -0800828 if (DebugCallsDisabled()) {
829 return g_dispatch->realloc(pointer, bytes);
830 }
Christopher Ferris31199e72024-11-08 14:44:53 -0800831
832 size_t old_size;
833 if (pointer != nullptr && g_debug->config().options() & RECORD_ALLOCS) {
834 // Need to get the size before disabling debug calls.
835 old_size = debug_malloc_usable_size(pointer);
836 }
837
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700838 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700839 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700840 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800841
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000842 memory_trace::Entry* entry = nullptr;
843 if (g_debug->config().options() & RECORD_ALLOCS) {
844 // In order to preserve the order of operations, reserve the entry before
845 // performing the operation.
846 entry = g_debug->record->ReserveEntry();
847 }
848
Christopher Ferris63860cb2015-11-16 17:30:32 -0800849 if (pointer == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000850 TimedResult result = InternalMalloc(bytes);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000851 pointer = result.getValue<void*>();
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000852 if (entry != nullptr) {
853 *entry = memory_trace::Entry{.tid = gettid(),
854 .type = memory_trace::REALLOC,
855 .ptr = reinterpret_cast<uint64_t>(pointer),
856 .size = bytes,
857 .u.old_ptr = 0,
858 .start_ns = result.GetStartTimeNS(),
859 .end_ns = result.GetEndTimeNS()};
Christopher Ferrise39602c2024-11-02 05:02:43 +0000860 }
Christopher Ferris7bd01782016-04-20 12:30:58 -0700861 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800862 }
863
Christopher Ferris4da25032018-03-07 13:38:48 -0800864 if (!VerifyPointer(pointer, "realloc")) {
865 return nullptr;
866 }
867
Christopher Ferris31199e72024-11-08 14:44:53 -0800868 int64_t present_bytes = -1;
869 if (g_debug->config().options() & RECORD_ALLOCS) {
870 // Need to get the present bytes before the pointer is freed in case the
871 // memory is released during the free call.
872 present_bytes = g_debug->record->GetPresentBytes(pointer, old_size);
873 }
874
Christopher Ferris63860cb2015-11-16 17:30:32 -0800875 if (bytes == 0) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000876 TimedResult result = InternalFree(pointer);
877
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000878 if (entry != nullptr) {
879 *entry = memory_trace::Entry{.tid = gettid(),
880 .type = memory_trace::REALLOC,
881 .ptr = 0,
882 .size = 0,
883 .u.old_ptr = reinterpret_cast<uint64_t>(pointer),
Christopher Ferris31199e72024-11-08 14:44:53 -0800884 .present_bytes = present_bytes,
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000885 .start_ns = result.GetStartTimeNS(),
886 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -0700887 }
888
Christopher Ferris63860cb2015-11-16 17:30:32 -0800889 return nullptr;
890 }
891
892 size_t real_size = bytes;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700893 if (g_debug->config().options() & EXPAND_ALLOC) {
894 real_size += g_debug->config().expand_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800895 if (real_size < bytes) {
896 // Overflow.
897 errno = ENOMEM;
898 return nullptr;
899 }
900 }
901
Christopher Ferris4da25032018-03-07 13:38:48 -0800902 if (bytes > PointerInfoType::MaxSize()) {
903 errno = ENOMEM;
904 return nullptr;
905 }
906
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000907 TimedResult result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800908 void* new_pointer;
909 size_t prev_size;
Christopher Ferris4da25032018-03-07 13:38:48 -0800910 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800911 // Same size, do nothing.
Christopher Ferris4da25032018-03-07 13:38:48 -0800912 Header* header = g_debug->GetHeader(pointer);
913 if (real_size == header->size) {
914 if (g_debug->TrackPointers()) {
915 // Remove and re-add so that the backtrace is updated.
916 PointerData::Remove(pointer);
917 PointerData::Add(pointer, real_size);
918 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800919 return pointer;
920 }
921
922 // Allocation is shrinking.
923 if (real_size < header->usable_size) {
924 header->size = real_size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700925 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800926 // Don't bother allocating a smaller pointer in this case, simply
927 // change the header usable_size and reset the rear guard.
Christopher Ferris4da25032018-03-07 13:38:48 -0800928 header->usable_size = header->size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700929 memset(g_debug->GetRearGuard(header), g_debug->config().rear_guard_value(),
930 g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800931 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800932 if (g_debug->TrackPointers()) {
933 // Remove and re-add so that the backtrace is updated.
934 PointerData::Remove(pointer);
935 PointerData::Add(pointer, real_size);
936 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800937 return pointer;
938 }
939
940 // Allocate the new size.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000941 result = InternalMalloc(bytes);
942 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800943 if (new_pointer == nullptr) {
944 errno = ENOMEM;
945 return nullptr;
946 }
947
948 prev_size = header->usable_size;
949 memcpy(new_pointer, pointer, prev_size);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000950 TimedResult free_time = InternalFree(pointer);
951 // `realloc` is split into two steps, update the end time to the finish time
952 // of the second operation.
953 result.SetEndTimeNS(free_time.GetEndTimeNS());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800954 } else {
Christopher Ferris4da25032018-03-07 13:38:48 -0800955 if (g_debug->TrackPointers()) {
956 PointerData::Remove(pointer);
957 }
958
Christopher Ferris63860cb2015-11-16 17:30:32 -0800959 prev_size = g_dispatch->malloc_usable_size(pointer);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000960 result = TCALL(realloc, pointer, real_size);
961 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800962 if (new_pointer == nullptr) {
963 return nullptr;
964 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800965
966 if (g_debug->TrackPointers()) {
967 PointerData::Add(new_pointer, real_size);
968 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800969 }
970
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700971 if (g_debug->config().options() & FILL_ON_ALLOC) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800972 size_t bytes = InternalMallocUsableSize(new_pointer);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700973 if (bytes > g_debug->config().fill_on_alloc_bytes()) {
974 bytes = g_debug->config().fill_on_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800975 }
976 if (bytes > prev_size) {
977 memset(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(new_pointer) + prev_size),
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700978 g_debug->config().fill_alloc_value(), bytes - prev_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800979 }
980 }
981
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000982 if (entry != nullptr) {
983 *entry = memory_trace::Entry{.tid = gettid(),
984 .type = memory_trace::REALLOC,
985 .ptr = reinterpret_cast<uint64_t>(new_pointer),
986 .size = bytes,
987 .u.old_ptr = reinterpret_cast<uint64_t>(pointer),
Christopher Ferris31199e72024-11-08 14:44:53 -0800988 .present_bytes = present_bytes,
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000989 .start_ns = result.GetStartTimeNS(),
990 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -0700991 }
992
Christopher Ferris63860cb2015-11-16 17:30:32 -0800993 return new_pointer;
994}
995
996void* debug_calloc(size_t nmemb, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700997 Unreachable::CheckIfRequested(g_debug->config());
998
Christopher Ferris63860cb2015-11-16 17:30:32 -0800999 if (DebugCallsDisabled()) {
1000 return g_dispatch->calloc(nmemb, bytes);
1001 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001002 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -07001003 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001004 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -08001005
Colin Cross7877df62016-03-10 13:01:27 -08001006 size_t size;
1007 if (__builtin_mul_overflow(nmemb, bytes, &size)) {
1008 // Overflow
1009 errno = ENOMEM;
1010 return nullptr;
1011 }
1012
Colin Cross9567c7b2016-03-09 17:56:14 -08001013 if (size == 0) {
1014 size = 1;
1015 }
1016
Colin Cross7877df62016-03-10 13:01:27 -08001017 size_t real_size;
1018 if (__builtin_add_overflow(size, g_debug->extra_bytes(), &real_size)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001019 // Overflow.
1020 errno = ENOMEM;
1021 return nullptr;
1022 }
1023
Christopher Ferris4da25032018-03-07 13:38:48 -08001024 if (real_size > PointerInfoType::MaxSize()) {
1025 errno = ENOMEM;
1026 return nullptr;
1027 }
Christopher Ferris63860cb2015-11-16 17:30:32 -08001028
Christopher Ferrisf756e4c2024-11-19 04:28:20 +00001029 memory_trace::Entry* entry = nullptr;
1030 if (g_debug->config().options() & RECORD_ALLOCS) {
1031 // In order to preserve the order of operations, reserve the entry before
1032 // performing the operation.
1033 entry = g_debug->record->ReserveEntry();
1034 }
1035
Christopher Ferris4da25032018-03-07 13:38:48 -08001036 void* pointer;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +00001037 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -08001038 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001039 // Need to guarantee the alignment of the header.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +00001040 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
1041 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -08001042 if (header == nullptr) {
1043 return nullptr;
1044 }
1045 memset(header, 0, g_dispatch->malloc_usable_size(header));
Christopher Ferris7bd01782016-04-20 12:30:58 -07001046 pointer = InitHeader(header, header, size);
Christopher Ferris63860cb2015-11-16 17:30:32 -08001047 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +00001048 result = TCALL(calloc, 1, real_size);
1049 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -08001050 }
Christopher Ferris4da25032018-03-07 13:38:48 -08001051
Christopher Ferrisf756e4c2024-11-19 04:28:20 +00001052 if (entry != nullptr) {
1053 *entry = memory_trace::Entry{.tid = gettid(),
1054 .type = memory_trace::CALLOC,
1055 .ptr = reinterpret_cast<uint64_t>(pointer),
1056 .size = bytes,
1057 .u.n_elements = nmemb,
1058 .start_ns = result.GetStartTimeNS(),
1059 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -07001060 }
Christopher Ferris4da25032018-03-07 13:38:48 -08001061
1062 if (pointer != nullptr && g_debug->TrackPointers()) {
1063 PointerData::Add(pointer, size);
1064 }
Christopher Ferris7bd01782016-04-20 12:30:58 -07001065 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -08001066}
1067
1068struct mallinfo debug_mallinfo() {
1069 return g_dispatch->mallinfo();
1070}
1071
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -07001072int debug_mallopt(int param, int value) {
1073 return g_dispatch->mallopt(param, value);
1074}
1075
Christopher Ferris6c619a02019-03-01 17:59:51 -08001076int debug_malloc_info(int options, FILE* fp) {
1077 if (DebugCallsDisabled() || !g_debug->TrackPointers()) {
1078 return g_dispatch->malloc_info(options, fp);
1079 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001080
1081 // Make sure any pending output is written to the file.
1082 fflush(fp);
1083
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001084 ScopedConcurrentLock lock;
1085 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001086 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris6c619a02019-03-01 17:59:51 -08001087
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001088 // Avoid any issues where allocations are made that will be freed
1089 // in the fclose.
1090 int fd = fileno(fp);
1091 MallocXmlElem root(fd, "malloc", "version=\"debug-malloc-1\"");
Christopher Ferris6c619a02019-03-01 17:59:51 -08001092 std::vector<ListInfoType> list;
1093 PointerData::GetAllocList(&list);
1094
1095 size_t alloc_num = 0;
1096 for (size_t i = 0; i < list.size(); i++) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001097 MallocXmlElem alloc(fd, "allocation", "nr=\"%zu\"", alloc_num);
Christopher Ferris6c619a02019-03-01 17:59:51 -08001098
1099 size_t total = 1;
1100 size_t size = list[i].size;
1101 while (i < list.size() - 1 && list[i + 1].size == size) {
1102 i++;
1103 total++;
1104 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001105 MallocXmlElem(fd, "size").Contents("%zu", list[i].size);
1106 MallocXmlElem(fd, "total").Contents("%zu", total);
Christopher Ferris6c619a02019-03-01 17:59:51 -08001107 alloc_num++;
1108 }
1109 return 0;
1110}
1111
Christopher Ferriscae21a92018-02-05 18:14:55 -08001112void* debug_aligned_alloc(size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001113 Unreachable::CheckIfRequested(g_debug->config());
1114
Christopher Ferriscae21a92018-02-05 18:14:55 -08001115 if (DebugCallsDisabled()) {
1116 return g_dispatch->aligned_alloc(alignment, size);
1117 }
Christopher Ferrisa22f5d52019-03-01 16:40:59 -08001118 if (!powerof2(alignment) || (size % alignment) != 0) {
Christopher Ferriscae21a92018-02-05 18:14:55 -08001119 errno = EINVAL;
1120 return nullptr;
1121 }
1122 return debug_memalign(alignment, size);
1123}
1124
Christopher Ferris63860cb2015-11-16 17:30:32 -08001125int debug_posix_memalign(void** memptr, size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001126 Unreachable::CheckIfRequested(g_debug->config());
1127
Christopher Ferris63860cb2015-11-16 17:30:32 -08001128 if (DebugCallsDisabled()) {
1129 return g_dispatch->posix_memalign(memptr, alignment, size);
1130 }
1131
Christopher Ferris6c619a02019-03-01 17:59:51 -08001132 if (alignment < sizeof(void*) || !powerof2(alignment)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001133 return EINVAL;
1134 }
1135 int saved_errno = errno;
1136 *memptr = debug_memalign(alignment, size);
1137 errno = saved_errno;
1138 return (*memptr != nullptr) ? 0 : ENOMEM;
1139}
1140
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001141int debug_malloc_iterate(uintptr_t base, size_t size, void (*callback)(uintptr_t, size_t, void*),
Christopher Ferris4da25032018-03-07 13:38:48 -08001142 void* arg) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001143 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001144 if (g_debug->TrackPointers()) {
Christopher Ferrisf78486f2022-05-04 14:08:54 -07001145 PointerData::IteratePointers([&callback, &arg](uintptr_t pointer) {
1146 callback(pointer, InternalMallocUsableSize(reinterpret_cast<void*>(pointer)), arg);
1147 });
Christopher Ferris4da25032018-03-07 13:38:48 -08001148 return 0;
1149 }
Colin Cross869691c2016-01-29 12:48:18 -08001150
Christopher Ferris4da25032018-03-07 13:38:48 -08001151 // An option that adds a header will add pointer tracking, so no need to
1152 // check if headers are enabled.
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001153 return g_dispatch->malloc_iterate(base, size, callback, arg);
Colin Cross869691c2016-01-29 12:48:18 -08001154}
1155
1156void debug_malloc_disable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001157 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001158 if (g_debug->pointer) {
Abdelrahman Daim862bd502024-11-14 08:09:42 -08001159 // Acquire the pointer locks first, otherwise, the code can be holding
1160 // the allocation lock and deadlock trying to acquire a pointer lock.
Christopher Ferris4da25032018-03-07 13:38:48 -08001161 g_debug->pointer->PrepareFork();
Colin Cross869691c2016-01-29 12:48:18 -08001162 }
Abdelrahman Daim862bd502024-11-14 08:09:42 -08001163 g_dispatch->malloc_disable();
Colin Cross869691c2016-01-29 12:48:18 -08001164}
1165
1166void debug_malloc_enable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001167 ScopedConcurrentLock lock;
Abdelrahman Daim862bd502024-11-14 08:09:42 -08001168 g_dispatch->malloc_enable();
Christopher Ferris4da25032018-03-07 13:38:48 -08001169 if (g_debug->pointer) {
1170 g_debug->pointer->PostForkParent();
Colin Cross869691c2016-01-29 12:48:18 -08001171 }
Colin Cross869691c2016-01-29 12:48:18 -08001172}
1173
Christopher Ferris4da25032018-03-07 13:38:48 -08001174ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t max_frames) {
Colin Cross2d4721c2016-02-02 11:57:54 -08001175 if (DebugCallsDisabled() || pointer == nullptr) {
1176 return 0;
1177 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001178 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -07001179 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001180 ScopedBacktraceSignalBlocker blocked;
Colin Cross2d4721c2016-02-02 11:57:54 -08001181
Christopher Ferris4da25032018-03-07 13:38:48 -08001182 if (!(g_debug->config().options() & BACKTRACE)) {
1183 return 0;
Colin Cross2d4721c2016-02-02 11:57:54 -08001184 }
Mitch Phillips3b21ada2020-01-07 15:47:47 -08001185 pointer = UntagPointer(pointer);
Christopher Ferris4da25032018-03-07 13:38:48 -08001186 return PointerData::GetFrames(pointer, frames, max_frames);
Colin Cross2d4721c2016-02-02 11:57:54 -08001187}
1188
Christopher Ferris63860cb2015-11-16 17:30:32 -08001189#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
1190void* debug_pvalloc(size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001191 Unreachable::CheckIfRequested(g_debug->config());
1192
Christopher Ferris63860cb2015-11-16 17:30:32 -08001193 if (DebugCallsDisabled()) {
1194 return g_dispatch->pvalloc(bytes);
1195 }
1196
1197 size_t pagesize = getpagesize();
Dan Alberta613d0d2017-10-05 16:39:33 -07001198 size_t size = __BIONIC_ALIGN(bytes, pagesize);
Christopher Ferris63860cb2015-11-16 17:30:32 -08001199 if (size < bytes) {
1200 // Overflow
1201 errno = ENOMEM;
1202 return nullptr;
1203 }
1204 return debug_memalign(pagesize, size);
1205}
1206
1207void* debug_valloc(size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001208 Unreachable::CheckIfRequested(g_debug->config());
1209
Christopher Ferris63860cb2015-11-16 17:30:32 -08001210 if (DebugCallsDisabled()) {
1211 return g_dispatch->valloc(size);
1212 }
1213 return debug_memalign(getpagesize(), size);
1214}
1215#endif
Christopher Ferris602b88c2017-08-04 13:04:04 -07001216
1217static std::mutex g_dump_lock;
1218
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001219static void write_dump(int fd) {
1220 dprintf(fd, "Android Native Heap Dump v1.2\n\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001221
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001222 std::string fingerprint = android::base::GetProperty("ro.build.fingerprint", "unknown");
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001223 dprintf(fd, "Build fingerprint: '%s'\n\n", fingerprint.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001224
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001225 PointerData::DumpLiveToFile(fd);
Christopher Ferris602b88c2017-08-04 13:04:04 -07001226
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001227 dprintf(fd, "MAPS\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001228 std::string content;
1229 if (!android::base::ReadFileToString("/proc/self/maps", &content)) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001230 dprintf(fd, "Could not open /proc/self/maps\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001231 } else {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001232 dprintf(fd, "%s", content.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001233 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001234 dprintf(fd, "END\n");
Christopher Ferrisaa3e5742023-01-31 01:31:52 +00001235
1236 // Purge the memory that was allocated and freed during this operation
1237 // since it can be large enough to expand the RSS significantly.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -07001238 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001239}
1240
1241bool debug_write_malloc_leak_info(FILE* fp) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001242 // Make sure any pending output is written to the file.
1243 fflush(fp);
1244
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001245 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001246 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001247 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001248
1249 std::lock_guard<std::mutex> guard(g_dump_lock);
1250
1251 if (!(g_debug->config().options() & BACKTRACE)) {
1252 return false;
1253 }
1254
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001255 write_dump(fileno(fp));
1256
Christopher Ferris602b88c2017-08-04 13:04:04 -07001257 return true;
1258}
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001259
1260void debug_dump_heap(const char* file_name) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001261 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001262 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001263 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001264
1265 std::lock_guard<std::mutex> guard(g_dump_lock);
1266
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001267 int fd = open(file_name, O_RDWR | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0644);
1268 if (fd == -1) {
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001269 error_log("Unable to create file: %s", file_name);
1270 return;
1271 }
1272
1273 error_log("Dumping to file: %s\n", file_name);
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001274 write_dump(fd);
1275 close(fd);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001276}