blob: dbf2d641771b3e92f55adc11ea72c2cc057e5df4 [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
Elliott Hughes731da1b2025-07-23 10:52:52 -070042#include <bit>
Christopher Ferris602b88c2017-08-04 13:04:04 -070043#include <mutex>
Christopher Ferris63860cb2015-11-16 17:30:32 -080044#include <vector>
45
Christopher Ferris602b88c2017-08-04 13:04:04 -070046#include <android-base/file.h>
Christopher Ferris2e1a40a2018-06-13 10:46:34 -070047#include <android-base/properties.h>
Christopher Ferris602b88c2017-08-04 13:04:04 -070048#include <android-base/stringprintf.h>
Mitch Phillips3b21ada2020-01-07 15:47:47 -080049#include <bionic/malloc_tagged_pointers.h>
Christopher Ferris9bf78172020-05-20 15:37:30 -070050#include <platform/bionic/reserved_signals.h>
Christopher Ferris6c619a02019-03-01 17:59:51 -080051#include <private/MallocXmlElem.h>
Christopher Ferris9bf78172020-05-20 15:37:30 -070052#include <private/bionic_malloc_dispatch.h>
Christopher Ferris459eecb2022-01-07 13:38:10 -080053#include <unwindstack/Unwinder.h>
Christopher Ferris63860cb2015-11-16 17:30:32 -080054
Christopher Ferris72df6702016-02-11 15:51:31 -080055#include "Config.h"
Christopher Ferris63860cb2015-11-16 17:30:32 -080056#include "DebugData.h"
Christopher Ferris5610d5a2023-11-14 15:04:50 -080057#include "LogAllocatorStats.h"
Christopher Ferrise39602c2024-11-02 05:02:43 +000058#include "Nanotime.h"
Christopher Ferrisb42e8b42022-05-09 14:00:47 -070059#include "Unreachable.h"
60#include "UnwindBacktrace.h"
Christopher Ferris4da25032018-03-07 13:38:48 -080061#include "backtrace.h"
Christopher Ferris63860cb2015-11-16 17:30:32 -080062#include "debug_disable.h"
63#include "debug_log.h"
64#include "malloc_debug.h"
65
66// ------------------------------------------------------------------------
67// Global Data
68// ------------------------------------------------------------------------
69DebugData* g_debug;
70
Christopher Ferris8189e772019-04-09 16:37:23 -070071bool* g_zygote_child;
Christopher Ferris63860cb2015-11-16 17:30:32 -080072
73const MallocDispatch* g_dispatch;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +000074
Chia-hung Duanf7e8b172022-11-01 21:37:56 +000075namespace {
76// A TimedResult contains the result of from malloc end_ns al. functions and the
77// start/end timestamps.
78struct TimedResult {
79 uint64_t start_ns = 0;
80 uint64_t end_ns = 0;
81 union {
82 size_t s;
83 int i;
84 void* p;
85 } v;
86
87 uint64_t GetStartTimeNS() const { return start_ns; }
88 uint64_t GetEndTimeNS() const { return end_ns; }
89 void SetStartTimeNS(uint64_t t) { start_ns = t; }
90 void SetEndTimeNS(uint64_t t) { end_ns = t; }
91
92 template <typename T>
93 void setValue(T);
94 template <>
95 void setValue(size_t s) {
96 v.s = s;
97 }
98 template <>
99 void setValue(int i) {
100 v.i = i;
101 }
102 template <>
103 void setValue(void* p) {
104 v.p = p;
105 }
106
107 template <typename T>
108 T getValue() const;
109 template <>
110 size_t getValue<size_t>() const {
111 return v.s;
112 }
113 template <>
114 int getValue<int>() const {
115 return v.i;
116 }
117 template <>
118 void* getValue<void*>() const {
119 return v.p;
120 }
121};
122
123class ScopedTimer {
124 public:
125 ScopedTimer(TimedResult& res) : res_(res) { res_.start_ns = Nanotime(); }
126
127 ~ScopedTimer() { res_.end_ns = Nanotime(); }
128
129 private:
130 TimedResult& res_;
131};
132
133} // namespace
134
135template <typename MallocFn, typename... Args>
136static TimedResult TimerCall(MallocFn fn, Args... args) {
137 TimedResult ret;
138 decltype((g_dispatch->*fn)(args...)) r;
139 if (g_debug->config().options() & RECORD_ALLOCS) {
140 ScopedTimer t(ret);
141 r = (g_dispatch->*fn)(args...);
142 } else {
143 r = (g_dispatch->*fn)(args...);
144 }
145 ret.setValue<decltype(r)>(r);
146 return ret;
147}
148
149template <typename MallocFn, typename... Args>
150static TimedResult TimerCallVoid(MallocFn fn, Args... args) {
151 TimedResult ret;
152 {
153 ScopedTimer t(ret);
154 (g_dispatch->*fn)(args...);
155 }
156 return ret;
157}
158
159#define TCALL(FUNC, ...) TimerCall(&MallocDispatch::FUNC, __VA_ARGS__);
160#define TCALLVOID(FUNC, ...) TimerCallVoid(&MallocDispatch::FUNC, __VA_ARGS__);
161
Christopher Ferris63860cb2015-11-16 17:30:32 -0800162// ------------------------------------------------------------------------
163
164// ------------------------------------------------------------------------
165// Use C style prototypes for all exported functions. This makes it easy
166// to do dlsym lookups during libc initialization when malloc debug
167// is enabled.
168// ------------------------------------------------------------------------
169__BEGIN_DECLS
170
Christopher Ferris8189e772019-04-09 16:37:23 -0700171bool debug_initialize(const MallocDispatch* malloc_dispatch, bool* malloc_zygote_child,
Christopher Ferris4da25032018-03-07 13:38:48 -0800172 const char* options);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800173void debug_finalize();
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700174void debug_dump_heap(const char* file_name);
Christopher Ferris4da25032018-03-07 13:38:48 -0800175void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
176 size_t* total_memory, size_t* backtrace_size);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700177bool debug_write_malloc_leak_info(FILE* fp);
Colin Cross2d4721c2016-02-02 11:57:54 -0800178ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800179void debug_free_malloc_leak_info(uint8_t* info);
180size_t debug_malloc_usable_size(void* pointer);
181void* debug_malloc(size_t size);
182void debug_free(void* pointer);
Christopher Ferriscae21a92018-02-05 18:14:55 -0800183void* debug_aligned_alloc(size_t alignment, size_t size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800184void* debug_memalign(size_t alignment, size_t bytes);
185void* debug_realloc(void* pointer, size_t bytes);
186void* debug_calloc(size_t nmemb, size_t bytes);
187struct mallinfo debug_mallinfo();
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700188int debug_mallopt(int param, int value);
Christopher Ferris6c619a02019-03-01 17:59:51 -0800189int debug_malloc_info(int options, FILE* fp);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800190int debug_posix_memalign(void** memptr, size_t alignment, size_t size);
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800191int debug_malloc_iterate(uintptr_t base, size_t size,
192 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg);
Colin Cross869691c2016-01-29 12:48:18 -0800193void debug_malloc_disable();
194void debug_malloc_enable();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800195
196#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
197void* debug_pvalloc(size_t bytes);
198void* debug_valloc(size_t size);
199#endif
200
201__END_DECLS
202// ------------------------------------------------------------------------
203
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700204class ScopedConcurrentLock {
205 public:
206 ScopedConcurrentLock() {
207 pthread_rwlock_rdlock(&lock_);
208 }
209 ~ScopedConcurrentLock() {
210 pthread_rwlock_unlock(&lock_);
211 }
212
213 static void Init() {
214 pthread_rwlockattr_t attr;
215 // Set the attribute so that when a write lock is pending, read locks are no
216 // longer granted.
217 pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
218 pthread_rwlock_init(&lock_, &attr);
219 }
220
221 static void BlockAllOperations() {
222 pthread_rwlock_wrlock(&lock_);
223 }
224
225 private:
226 static pthread_rwlock_t lock_;
227};
228pthread_rwlock_t ScopedConcurrentLock::lock_;
229
Christopher Ferris9bf78172020-05-20 15:37:30 -0700230// Use this because the sigprocmask* functions filter out the reserved bionic
231// signals including the signal this code blocks.
232static inline int __rt_sigprocmask(int how, const sigset64_t* new_set, sigset64_t* old_set,
233 size_t sigset_size) {
234 return syscall(SYS_rt_sigprocmask, how, new_set, old_set, sigset_size);
235}
236
237// Need to block the backtrace signal while in malloc debug routines
238// otherwise there is a chance of a deadlock and timeout when unwinding.
239// This can occur if a thread is paused while owning a malloc debug
240// internal lock.
241class ScopedBacktraceSignalBlocker {
242 public:
243 ScopedBacktraceSignalBlocker() {
244 sigemptyset64(&backtrace_set_);
245 sigaddset64(&backtrace_set_, BIONIC_SIGNAL_BACKTRACE);
246 sigset64_t old_set;
247 __rt_sigprocmask(SIG_BLOCK, &backtrace_set_, &old_set, sizeof(backtrace_set_));
248 if (sigismember64(&old_set, BIONIC_SIGNAL_BACKTRACE)) {
249 unblock_ = false;
250 }
251 }
252
253 ~ScopedBacktraceSignalBlocker() {
254 if (unblock_) {
255 __rt_sigprocmask(SIG_UNBLOCK, &backtrace_set_, nullptr, sizeof(backtrace_set_));
256 }
257 }
258
259 private:
260 bool unblock_ = true;
261 sigset64_t backtrace_set_;
262};
263
Colin Cross7a28a3c2016-02-07 22:51:15 -0800264static void InitAtfork() {
265 static pthread_once_t atfork_init = PTHREAD_ONCE_INIT;
Christopher Ferris4da25032018-03-07 13:38:48 -0800266 pthread_once(&atfork_init, []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800267 pthread_atfork(
Christopher Ferris4da25032018-03-07 13:38:48 -0800268 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800269 if (g_debug != nullptr) {
270 g_debug->PrepareFork();
271 }
272 },
Christopher Ferris4da25032018-03-07 13:38:48 -0800273 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800274 if (g_debug != nullptr) {
275 g_debug->PostForkParent();
276 }
277 },
Christopher Ferris4da25032018-03-07 13:38:48 -0800278 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800279 if (g_debug != nullptr) {
280 g_debug->PostForkChild();
281 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800282 });
Colin Cross7a28a3c2016-02-07 22:51:15 -0800283 });
284}
Christopher Ferrisd0919622016-03-15 22:39:39 -0700285
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700286void BacktraceAndLog() {
287 if (g_debug->config().options() & BACKTRACE_FULL) {
288 std::vector<uintptr_t> frames;
Christopher Ferris459eecb2022-01-07 13:38:10 -0800289 std::vector<unwindstack::FrameData> frames_info;
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700290 if (!Unwind(&frames, &frames_info, 256)) {
291 error_log(" Backtrace failed to get any frames.");
292 } else {
293 UnwindLog(frames_info);
294 }
295 } else {
296 std::vector<uintptr_t> frames(256);
297 size_t num_frames = backtrace_get(frames.data(), frames.size());
298 if (num_frames == 0) {
299 error_log(" Backtrace failed to get any frames.");
300 } else {
301 backtrace_log(frames.data(), num_frames);
302 }
303 }
304}
305
Christopher Ferris4da25032018-03-07 13:38:48 -0800306static void LogError(const void* pointer, const char* error_str) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800307 error_log(LOG_DIVIDER);
Christopher Ferris4da25032018-03-07 13:38:48 -0800308 error_log("+++ ALLOCATION %p %s", pointer, error_str);
309
310 // If we are tracking already freed pointers, check to see if this is
311 // one so we can print extra information.
312 if (g_debug->config().options() & FREE_TRACK) {
313 PointerData::LogFreeBacktrace(pointer);
Christopher Ferris7993b802016-01-28 18:35:05 -0800314 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800315
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700316 error_log("Backtrace at time of failure:");
317 BacktraceAndLog();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800318 error_log(LOG_DIVIDER);
Iris Chang7f209a92019-01-16 11:17:15 +0800319 if (g_debug->config().options() & ABORT_ON_ERROR) {
320 abort();
321 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800322}
323
Christopher Ferris4da25032018-03-07 13:38:48 -0800324static bool VerifyPointer(const void* pointer, const char* function_name) {
325 if (g_debug->HeaderEnabled()) {
326 Header* header = g_debug->GetHeader(pointer);
327 if (header->tag != DEBUG_TAG) {
328 std::string error_str;
329 if (header->tag == DEBUG_FREE_TAG) {
330 error_str = std::string("USED AFTER FREE (") + function_name + ")";
331 } else {
332 error_str = android::base::StringPrintf("HAS INVALID TAG %" PRIx32 " (%s)", header->tag,
333 function_name);
334 }
335 LogError(pointer, error_str.c_str());
336 return false;
337 }
338 }
339
340 if (g_debug->TrackPointers()) {
341 if (!PointerData::Exists(pointer)) {
342 std::string error_str(std::string("UNKNOWN POINTER (") + function_name + ")");
343 LogError(pointer, error_str.c_str());
344 return false;
345 }
346 }
347 return true;
348}
349
350static size_t InternalMallocUsableSize(void* pointer) {
351 if (g_debug->HeaderEnabled()) {
352 return g_debug->GetHeader(pointer)->usable_size;
353 } else {
354 return g_dispatch->malloc_usable_size(pointer);
355 }
356}
357
Christopher Ferris63860cb2015-11-16 17:30:32 -0800358static void* InitHeader(Header* header, void* orig_pointer, size_t size) {
359 header->tag = DEBUG_TAG;
360 header->orig_pointer = orig_pointer;
361 header->size = size;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800362 header->usable_size = g_dispatch->malloc_usable_size(orig_pointer);
363 if (header->usable_size == 0) {
364 g_dispatch->free(orig_pointer);
365 return nullptr;
366 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800367 header->usable_size -= g_debug->pointer_offset() + reinterpret_cast<uintptr_t>(header) -
368 reinterpret_cast<uintptr_t>(orig_pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800369
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700370 if (g_debug->config().options() & FRONT_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800371 uint8_t* guard = g_debug->GetFrontGuard(header);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700372 memset(guard, g_debug->config().front_guard_value(), g_debug->config().front_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800373 }
374
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700375 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800376 uint8_t* guard = g_debug->GetRearGuard(header);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700377 memset(guard, g_debug->config().rear_guard_value(), g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800378 // If the rear guard is enabled, set the usable size to the exact size
379 // of the allocation.
Christopher Ferris4da25032018-03-07 13:38:48 -0800380 header->usable_size = header->size;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800381 }
382
383 return g_debug->GetPointer(header);
384}
385
Christopher Ferris705de3c2019-05-22 13:39:57 -0700386extern "C" void __asan_init() __attribute__((weak));
387
Christopher Ferris8189e772019-04-09 16:37:23 -0700388bool debug_initialize(const MallocDispatch* malloc_dispatch, bool* zygote_child,
Christopher Ferris4da25032018-03-07 13:38:48 -0800389 const char* options) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700390 if (zygote_child == nullptr || options == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800391 return false;
392 }
Colin Cross7a28a3c2016-02-07 22:51:15 -0800393
Christopher Ferris705de3c2019-05-22 13:39:57 -0700394 if (__asan_init != 0) {
395 error_log("malloc debug cannot be enabled alongside ASAN");
396 return false;
397 }
398
Colin Cross7a28a3c2016-02-07 22:51:15 -0800399 InitAtfork();
400
Christopher Ferris8189e772019-04-09 16:37:23 -0700401 g_zygote_child = zygote_child;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800402
403 g_dispatch = malloc_dispatch;
404
405 if (!DebugDisableInitialize()) {
406 return false;
407 }
408
409 DebugData* debug = new DebugData();
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700410 if (!debug->Initialize(options) || !Unreachable::Initialize(debug->config())) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800411 delete debug;
412 DebugDisableFinalize();
413 return false;
414 }
415 g_debug = debug;
416
417 // Always enable the backtrace code since we will use it in a number
418 // of different error cases.
419 backtrace_startup();
420
Christopher Ferrisc328e442019-04-01 19:31:26 -0700421 if (g_debug->config().options() & VERBOSE) {
422 info_log("%s: malloc debug enabled", getprogname());
423 }
424
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700425 ScopedConcurrentLock::Init();
426
Christopher Ferris63860cb2015-11-16 17:30:32 -0800427 return true;
428}
429
430void debug_finalize() {
431 if (g_debug == nullptr) {
432 return;
433 }
434
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700435 // Make sure that there are no other threads doing debug allocations
436 // before we kill everything.
437 ScopedConcurrentLock::BlockAllOperations();
438
Christopher Ferris97b47472018-07-10 14:45:24 -0700439 // Turn off capturing allocations calls.
440 DebugDisableSet(true);
441
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700442 if (g_debug->config().options() & FREE_TRACK) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800443 PointerData::VerifyAllFreed();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800444 }
445
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700446 if (g_debug->config().options() & LEAK_TRACK) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800447 PointerData::LogLeaks();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800448 }
449
Christopher Ferris9b88d0a2024-06-13 13:22:02 -0700450 if ((g_debug->config().options() & RECORD_ALLOCS) && g_debug->config().record_allocs_on_exit()) {
451 RecordData::WriteEntriesOnExit();
452 }
453
Christopher Ferris602b88c2017-08-04 13:04:04 -0700454 if ((g_debug->config().options() & BACKTRACE) && g_debug->config().backtrace_dump_on_exit()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800455 debug_dump_heap(android::base::StringPrintf("%s.%d.exit.txt",
456 g_debug->config().backtrace_dump_prefix().c_str(),
Christopher Ferris97b47472018-07-10 14:45:24 -0700457 getpid()).c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700458 }
459
Christopher Ferrisc1341e12024-07-11 19:48:08 -0700460 if (g_debug->config().options() & LOG_ALLOCATOR_STATS_ON_EXIT) {
461 LogAllocatorStats::Log();
462 }
463
Colin Cross2c759912016-02-05 16:17:39 -0800464 backtrace_shutdown();
465
Christopher Ferris33d73372021-07-02 15:46:18 -0700466 // In order to prevent any issues of threads freeing previous pointers
467 // after the main thread calls this code, simply leak the g_debug pointer
468 // and do not destroy the debug disable pthread key.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800469}
470
Christopher Ferris4da25032018-03-07 13:38:48 -0800471void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
472 size_t* total_memory, size_t* backtrace_size) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700473 ScopedConcurrentLock lock;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800474 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700475 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800476
477 // Verify the arguments.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700478 if (info == nullptr || overall_size == nullptr || info_size == nullptr || total_memory == nullptr ||
Christopher Ferris4da25032018-03-07 13:38:48 -0800479 backtrace_size == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800480 error_log("get_malloc_leak_info: At least one invalid parameter.");
481 return;
482 }
483
484 *info = nullptr;
485 *overall_size = 0;
486 *info_size = 0;
487 *total_memory = 0;
488 *backtrace_size = 0;
489
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700490 if (!(g_debug->config().options() & BACKTRACE)) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800491 error_log(
492 "get_malloc_leak_info: Allocations not being tracked, to enable "
493 "set the option 'backtrace'.");
Christopher Ferris63860cb2015-11-16 17:30:32 -0800494 return;
495 }
496
Christopher Ferris4da25032018-03-07 13:38:48 -0800497 PointerData::GetInfo(info, overall_size, info_size, total_memory, backtrace_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800498}
499
500void debug_free_malloc_leak_info(uint8_t* info) {
501 g_dispatch->free(info);
Christopher Ferrisaa3e5742023-01-31 01:31:52 +0000502 // Purge the memory that was freed since a significant amount of
503 // memory could have been allocated and freed.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -0700504 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800505}
506
Christopher Ferris55a89a42016-04-07 17:14:53 -0700507size_t debug_malloc_usable_size(void* pointer) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700508 Unreachable::CheckIfRequested(g_debug->config());
509
Christopher Ferris55a89a42016-04-07 17:14:53 -0700510 if (DebugCallsDisabled() || pointer == nullptr) {
511 return g_dispatch->malloc_usable_size(pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800512 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700513 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700514 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700515 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800516
Christopher Ferris4da25032018-03-07 13:38:48 -0800517 if (!VerifyPointer(pointer, "malloc_usable_size")) {
518 return 0;
519 }
520
521 return InternalMallocUsableSize(pointer);
Christopher Ferris55a89a42016-04-07 17:14:53 -0700522}
523
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000524static TimedResult InternalMalloc(size_t size) {
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800525 uint64_t options = g_debug->config().options();
526 if ((options & BACKTRACE) && g_debug->pointer->ShouldDumpAndReset()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800527 debug_dump_heap(android::base::StringPrintf(
528 "%s.%d.txt", g_debug->config().backtrace_dump_prefix().c_str(), getpid())
529 .c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700530 }
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800531 if (options & LOG_ALLOCATOR_STATS_ON_SIGNAL) {
532 LogAllocatorStats::CheckIfShouldLog();
533 }
Christopher Ferris602b88c2017-08-04 13:04:04 -0700534
Colin Cross9567c7b2016-03-09 17:56:14 -0800535 if (size == 0) {
536 size = 1;
537 }
538
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000539 TimedResult result;
540
Christopher Ferris63860cb2015-11-16 17:30:32 -0800541 size_t real_size = size + g_debug->extra_bytes();
542 if (real_size < size) {
543 // Overflow.
544 errno = ENOMEM;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000545 result.setValue<void*>(nullptr);
546 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800547 }
548
Christopher Ferris4da25032018-03-07 13:38:48 -0800549 if (size > PointerInfoType::MaxSize()) {
550 errno = ENOMEM;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000551 result.setValue<void*>(nullptr);
552 return result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800553 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800554
Christopher Ferris4da25032018-03-07 13:38:48 -0800555 if (g_debug->HeaderEnabled()) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000556 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
557 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800558 if (header == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000559 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800560 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000561 result.setValue<void*>(InitHeader(header, header, size));
Christopher Ferris63860cb2015-11-16 17:30:32 -0800562 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000563 result = TCALL(malloc, real_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800564 }
565
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000566 void* pointer = result.getValue<void*>();
567
Christopher Ferris4da25032018-03-07 13:38:48 -0800568 if (pointer != nullptr) {
569 if (g_debug->TrackPointers()) {
570 PointerData::Add(pointer, size);
571 }
572
573 if (g_debug->config().options() & FILL_ON_ALLOC) {
574 size_t bytes = InternalMallocUsableSize(pointer);
575 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
576 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
577 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
578 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800579 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000580
581 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800582}
583
Christopher Ferris55a89a42016-04-07 17:14:53 -0700584void* debug_malloc(size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700585 Unreachable::CheckIfRequested(g_debug->config());
586
Christopher Ferris55a89a42016-04-07 17:14:53 -0700587 if (DebugCallsDisabled()) {
588 return g_dispatch->malloc(size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800589 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700590 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700591 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700592 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800593
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000594 memory_trace::Entry* entry = nullptr;
595 if (g_debug->config().options() & RECORD_ALLOCS) {
596 // In order to preserve the order of operations, reserve the entry before
597 // performing the operation.
598 entry = g_debug->record->ReserveEntry();
599 }
600
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000601 TimedResult result = InternalMalloc(size);
Christopher Ferris7bd01782016-04-20 12:30:58 -0700602
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000603 if (entry != nullptr) {
604 *entry = memory_trace::Entry{.tid = gettid(),
605 .type = memory_trace::MALLOC,
606 .ptr = reinterpret_cast<uint64_t>(result.getValue<void*>()),
607 .size = size,
608 .start_ns = result.GetStartTimeNS(),
609 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -0700610 }
611
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000612 return result.getValue<void*>();
Christopher Ferris55a89a42016-04-07 17:14:53 -0700613}
614
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000615static TimedResult InternalFree(void* pointer) {
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800616 uint64_t options = g_debug->config().options();
617 if ((options & BACKTRACE) && g_debug->pointer->ShouldDumpAndReset()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800618 debug_dump_heap(android::base::StringPrintf(
619 "%s.%d.txt", g_debug->config().backtrace_dump_prefix().c_str(), getpid())
620 .c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700621 }
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800622 if (options & LOG_ALLOCATOR_STATS_ON_SIGNAL) {
623 LogAllocatorStats::CheckIfShouldLog();
624 }
Christopher Ferris602b88c2017-08-04 13:04:04 -0700625
Christopher Ferris63860cb2015-11-16 17:30:32 -0800626 void* free_pointer = pointer;
627 size_t bytes;
Christopher Ferrisd0919622016-03-15 22:39:39 -0700628 Header* header;
Christopher Ferris4da25032018-03-07 13:38:48 -0800629 if (g_debug->HeaderEnabled()) {
Christopher Ferrisd0919622016-03-15 22:39:39 -0700630 header = g_debug->GetHeader(pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800631 free_pointer = header->orig_pointer;
632
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700633 if (g_debug->config().options() & FRONT_GUARD) {
Christopher Ferris55a89a42016-04-07 17:14:53 -0700634 if (!g_debug->front_guard->Valid(header)) {
635 g_debug->front_guard->LogFailure(header);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800636 }
637 }
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700638 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris55a89a42016-04-07 17:14:53 -0700639 if (!g_debug->rear_guard->Valid(header)) {
640 g_debug->rear_guard->LogFailure(header);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800641 }
642 }
643
Christopher Ferris7993b802016-01-28 18:35:05 -0800644 header->tag = DEBUG_FREE_TAG;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800645
646 bytes = header->usable_size;
647 } else {
648 bytes = g_dispatch->malloc_usable_size(pointer);
649 }
650
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700651 if (g_debug->config().options() & FILL_ON_FREE) {
652 size_t fill_bytes = g_debug->config().fill_on_free_bytes();
Christopher Ferrisa3836482022-05-13 12:09:39 -0700653 fill_bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
654 memset(pointer, g_debug->config().fill_free_value(), fill_bytes);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800655 }
656
Christopher Ferris4da25032018-03-07 13:38:48 -0800657 if (g_debug->TrackPointers()) {
658 PointerData::Remove(pointer);
659 }
660
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000661 TimedResult result;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700662 if (g_debug->config().options() & FREE_TRACK) {
Christopher Ferrisd0919622016-03-15 22:39:39 -0700663 // Do not add the allocation until we are done modifying the pointer
664 // itself. This avoids a race if a lot of threads are all doing
665 // frees at the same time and we wind up trying to really free this
666 // pointer from another thread, while still trying to free it in
667 // this function.
Christopher Ferrisa3836482022-05-13 12:09:39 -0700668 pointer = PointerData::AddFreed(pointer, bytes);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000669 if (pointer != nullptr && g_debug->HeaderEnabled()) {
670 pointer = g_debug->GetHeader(pointer)->orig_pointer;
Christopher Ferris4da25032018-03-07 13:38:48 -0800671 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000672 result = TCALLVOID(free, pointer);
Christopher Ferrisd0919622016-03-15 22:39:39 -0700673 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000674 result = TCALLVOID(free, free_pointer);
Christopher Ferrisd0919622016-03-15 22:39:39 -0700675 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000676
677 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800678}
679
Christopher Ferris55a89a42016-04-07 17:14:53 -0700680void debug_free(void* pointer) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700681 Unreachable::CheckIfRequested(g_debug->config());
682
Christopher Ferris55a89a42016-04-07 17:14:53 -0700683 if (DebugCallsDisabled() || pointer == nullptr) {
684 return g_dispatch->free(pointer);
685 }
Christopher Ferris31199e72024-11-08 14:44:53 -0800686
687 size_t size;
688 if (g_debug->config().options() & RECORD_ALLOCS) {
689 // Need to get the size before disabling debug calls.
690 size = debug_malloc_usable_size(pointer);
691 }
692
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700693 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700694 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700695 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700696
Christopher Ferris4da25032018-03-07 13:38:48 -0800697 if (!VerifyPointer(pointer, "free")) {
698 return;
699 }
700
Christopher Ferris31199e72024-11-08 14:44:53 -0800701 int64_t present_bytes = -1;
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000702 memory_trace::Entry* entry = nullptr;
703 if (g_debug->config().options() & RECORD_ALLOCS) {
704 // In order to preserve the order of operations, reserve the entry before
705 // performing the operation.
706 entry = g_debug->record->ReserveEntry();
Christopher Ferris31199e72024-11-08 14:44:53 -0800707
708 // Need to get the present bytes before the pointer is freed in case the
709 // memory is released during the free call.
710 present_bytes = g_debug->record->GetPresentBytes(pointer, size);
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000711 }
712
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000713 TimedResult result = InternalFree(pointer);
714
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000715 if (entry != nullptr) {
716 *entry = memory_trace::Entry{.tid = gettid(),
717 .type = memory_trace::FREE,
718 .ptr = reinterpret_cast<uint64_t>(pointer),
Christopher Ferris31199e72024-11-08 14:44:53 -0800719 .present_bytes = present_bytes,
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000720 .start_ns = result.GetStartTimeNS(),
721 .end_ns = result.GetEndTimeNS()};
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000722 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700723}
724
Christopher Ferris63860cb2015-11-16 17:30:32 -0800725void* debug_memalign(size_t alignment, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700726 Unreachable::CheckIfRequested(g_debug->config());
727
Christopher Ferris63860cb2015-11-16 17:30:32 -0800728 if (DebugCallsDisabled()) {
729 return g_dispatch->memalign(alignment, bytes);
730 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700731 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700732 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700733 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800734
Colin Cross9567c7b2016-03-09 17:56:14 -0800735 if (bytes == 0) {
736 bytes = 1;
737 }
738
Christopher Ferris4da25032018-03-07 13:38:48 -0800739 if (bytes > PointerInfoType::MaxSize()) {
740 errno = ENOMEM;
741 return nullptr;
742 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800743
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000744 memory_trace::Entry* entry = nullptr;
745 if (g_debug->config().options() & RECORD_ALLOCS) {
746 // In order to preserve the order of operations, reserve the entry before
747 // performing the operation.
748 entry = g_debug->record->ReserveEntry();
749 }
750
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000751 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800752 void* pointer;
753 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800754 // Make the alignment a power of two.
Elliott Hughes731da1b2025-07-23 10:52:52 -0700755 alignment = std::bit_ceil(alignment);
Christopher Ferris72df6702016-02-11 15:51:31 -0800756 // Force the alignment to at least MINIMUM_ALIGNMENT_BYTES to guarantee
Christopher Ferris63860cb2015-11-16 17:30:32 -0800757 // that the header is aligned properly.
Christopher Ferris72df6702016-02-11 15:51:31 -0800758 if (alignment < MINIMUM_ALIGNMENT_BYTES) {
759 alignment = MINIMUM_ALIGNMENT_BYTES;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800760 }
761
762 // We don't have any idea what the natural alignment of
763 // the underlying native allocator is, so we always need to
764 // over allocate.
765 size_t real_size = alignment + bytes + g_debug->extra_bytes();
766 if (real_size < bytes) {
767 // Overflow.
768 errno = ENOMEM;
769 return nullptr;
770 }
771
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000772 result = TCALL(malloc, real_size);
773 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800774 if (pointer == nullptr) {
775 return nullptr;
776 }
777
778 uintptr_t value = reinterpret_cast<uintptr_t>(pointer) + g_debug->pointer_offset();
779 // Now align the pointer.
780 value += (-value % alignment);
781
782 Header* header = g_debug->GetHeader(reinterpret_cast<void*>(value));
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000783 // Don't need to update `result` here because we only need the timestamps.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800784 pointer = InitHeader(header, pointer, bytes);
785 } else {
786 size_t real_size = bytes + g_debug->extra_bytes();
787 if (real_size < bytes) {
788 // Overflow.
789 errno = ENOMEM;
790 return nullptr;
791 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000792 result = TCALL(memalign, alignment, real_size);
793 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800794 }
795
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000796 if (pointer == nullptr) {
797 return nullptr;
798 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700799
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000800 if (g_debug->TrackPointers()) {
801 PointerData::Add(pointer, bytes);
802 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800803
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000804 if (g_debug->config().options() & FILL_ON_ALLOC) {
805 size_t bytes = InternalMallocUsableSize(pointer);
806 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
807 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
808 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
809 }
810
811 if (entry != nullptr) {
812 *entry = memory_trace::Entry{.tid = gettid(),
813 .type = memory_trace::MEMALIGN,
814 .ptr = reinterpret_cast<uint64_t>(pointer),
815 .size = bytes,
816 .u.align = alignment,
817 .start_ns = result.GetStartTimeNS(),
818 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -0700819 }
820
Christopher Ferris63860cb2015-11-16 17:30:32 -0800821 return pointer;
822}
823
824void* debug_realloc(void* pointer, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700825 Unreachable::CheckIfRequested(g_debug->config());
826
Christopher Ferris63860cb2015-11-16 17:30:32 -0800827 if (DebugCallsDisabled()) {
828 return g_dispatch->realloc(pointer, bytes);
829 }
Christopher Ferris31199e72024-11-08 14:44:53 -0800830
831 size_t old_size;
832 if (pointer != nullptr && g_debug->config().options() & RECORD_ALLOCS) {
833 // Need to get the size before disabling debug calls.
834 old_size = debug_malloc_usable_size(pointer);
835 }
836
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700837 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700838 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700839 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800840
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000841 memory_trace::Entry* entry = nullptr;
842 if (g_debug->config().options() & RECORD_ALLOCS) {
843 // In order to preserve the order of operations, reserve the entry before
844 // performing the operation.
845 entry = g_debug->record->ReserveEntry();
846 }
847
Christopher Ferris63860cb2015-11-16 17:30:32 -0800848 if (pointer == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000849 TimedResult result = InternalMalloc(bytes);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000850 pointer = result.getValue<void*>();
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000851 if (entry != nullptr) {
852 *entry = memory_trace::Entry{.tid = gettid(),
853 .type = memory_trace::REALLOC,
854 .ptr = reinterpret_cast<uint64_t>(pointer),
855 .size = bytes,
856 .u.old_ptr = 0,
857 .start_ns = result.GetStartTimeNS(),
858 .end_ns = result.GetEndTimeNS()};
Christopher Ferrise39602c2024-11-02 05:02:43 +0000859 }
Christopher Ferris7bd01782016-04-20 12:30:58 -0700860 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800861 }
862
Christopher Ferris4da25032018-03-07 13:38:48 -0800863 if (!VerifyPointer(pointer, "realloc")) {
864 return nullptr;
865 }
866
Christopher Ferris31199e72024-11-08 14:44:53 -0800867 int64_t present_bytes = -1;
868 if (g_debug->config().options() & RECORD_ALLOCS) {
869 // Need to get the present bytes before the pointer is freed in case the
870 // memory is released during the free call.
871 present_bytes = g_debug->record->GetPresentBytes(pointer, old_size);
872 }
873
Christopher Ferris63860cb2015-11-16 17:30:32 -0800874 if (bytes == 0) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000875 TimedResult result = InternalFree(pointer);
876
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000877 if (entry != nullptr) {
878 *entry = memory_trace::Entry{.tid = gettid(),
879 .type = memory_trace::REALLOC,
880 .ptr = 0,
881 .size = 0,
882 .u.old_ptr = reinterpret_cast<uint64_t>(pointer),
Christopher Ferris31199e72024-11-08 14:44:53 -0800883 .present_bytes = present_bytes,
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000884 .start_ns = result.GetStartTimeNS(),
885 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -0700886 }
887
Christopher Ferris63860cb2015-11-16 17:30:32 -0800888 return nullptr;
889 }
890
891 size_t real_size = bytes;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700892 if (g_debug->config().options() & EXPAND_ALLOC) {
893 real_size += g_debug->config().expand_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800894 if (real_size < bytes) {
895 // Overflow.
896 errno = ENOMEM;
897 return nullptr;
898 }
899 }
900
Christopher Ferris4da25032018-03-07 13:38:48 -0800901 if (bytes > PointerInfoType::MaxSize()) {
902 errno = ENOMEM;
903 return nullptr;
904 }
905
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000906 TimedResult result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800907 void* new_pointer;
908 size_t prev_size;
Christopher Ferris4da25032018-03-07 13:38:48 -0800909 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800910 // Same size, do nothing.
Christopher Ferris4da25032018-03-07 13:38:48 -0800911 Header* header = g_debug->GetHeader(pointer);
912 if (real_size == header->size) {
913 if (g_debug->TrackPointers()) {
914 // Remove and re-add so that the backtrace is updated.
915 PointerData::Remove(pointer);
916 PointerData::Add(pointer, real_size);
917 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800918 return pointer;
919 }
920
921 // Allocation is shrinking.
922 if (real_size < header->usable_size) {
923 header->size = real_size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700924 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800925 // Don't bother allocating a smaller pointer in this case, simply
926 // change the header usable_size and reset the rear guard.
Christopher Ferris4da25032018-03-07 13:38:48 -0800927 header->usable_size = header->size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700928 memset(g_debug->GetRearGuard(header), g_debug->config().rear_guard_value(),
929 g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800930 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800931 if (g_debug->TrackPointers()) {
932 // Remove and re-add so that the backtrace is updated.
933 PointerData::Remove(pointer);
934 PointerData::Add(pointer, real_size);
935 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800936 return pointer;
937 }
938
939 // Allocate the new size.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000940 result = InternalMalloc(bytes);
941 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800942 if (new_pointer == nullptr) {
943 errno = ENOMEM;
944 return nullptr;
945 }
946
947 prev_size = header->usable_size;
948 memcpy(new_pointer, pointer, prev_size);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000949 TimedResult free_time = InternalFree(pointer);
950 // `realloc` is split into two steps, update the end time to the finish time
951 // of the second operation.
952 result.SetEndTimeNS(free_time.GetEndTimeNS());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800953 } else {
Christopher Ferris4da25032018-03-07 13:38:48 -0800954 if (g_debug->TrackPointers()) {
955 PointerData::Remove(pointer);
956 }
957
Christopher Ferris63860cb2015-11-16 17:30:32 -0800958 prev_size = g_dispatch->malloc_usable_size(pointer);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000959 result = TCALL(realloc, pointer, real_size);
960 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800961 if (new_pointer == nullptr) {
962 return nullptr;
963 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800964
965 if (g_debug->TrackPointers()) {
966 PointerData::Add(new_pointer, real_size);
967 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800968 }
969
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700970 if (g_debug->config().options() & FILL_ON_ALLOC) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800971 size_t bytes = InternalMallocUsableSize(new_pointer);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700972 if (bytes > g_debug->config().fill_on_alloc_bytes()) {
973 bytes = g_debug->config().fill_on_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800974 }
975 if (bytes > prev_size) {
976 memset(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(new_pointer) + prev_size),
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700977 g_debug->config().fill_alloc_value(), bytes - prev_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800978 }
979 }
980
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000981 if (entry != nullptr) {
982 *entry = memory_trace::Entry{.tid = gettid(),
983 .type = memory_trace::REALLOC,
984 .ptr = reinterpret_cast<uint64_t>(new_pointer),
985 .size = bytes,
986 .u.old_ptr = reinterpret_cast<uint64_t>(pointer),
Christopher Ferris31199e72024-11-08 14:44:53 -0800987 .present_bytes = present_bytes,
Christopher Ferrisf756e4c2024-11-19 04:28:20 +0000988 .start_ns = result.GetStartTimeNS(),
989 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -0700990 }
991
Christopher Ferris63860cb2015-11-16 17:30:32 -0800992 return new_pointer;
993}
994
995void* debug_calloc(size_t nmemb, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700996 Unreachable::CheckIfRequested(g_debug->config());
997
Christopher Ferris63860cb2015-11-16 17:30:32 -0800998 if (DebugCallsDisabled()) {
999 return g_dispatch->calloc(nmemb, bytes);
1000 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001001 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -07001002 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001003 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -08001004
Colin Cross7877df62016-03-10 13:01:27 -08001005 size_t size;
1006 if (__builtin_mul_overflow(nmemb, bytes, &size)) {
1007 // Overflow
1008 errno = ENOMEM;
1009 return nullptr;
1010 }
1011
Colin Cross9567c7b2016-03-09 17:56:14 -08001012 if (size == 0) {
1013 size = 1;
1014 }
1015
Colin Cross7877df62016-03-10 13:01:27 -08001016 size_t real_size;
1017 if (__builtin_add_overflow(size, g_debug->extra_bytes(), &real_size)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001018 // Overflow.
1019 errno = ENOMEM;
1020 return nullptr;
1021 }
1022
Christopher Ferris4da25032018-03-07 13:38:48 -08001023 if (real_size > PointerInfoType::MaxSize()) {
1024 errno = ENOMEM;
1025 return nullptr;
1026 }
Christopher Ferris63860cb2015-11-16 17:30:32 -08001027
Christopher Ferrisf756e4c2024-11-19 04:28:20 +00001028 memory_trace::Entry* entry = nullptr;
1029 if (g_debug->config().options() & RECORD_ALLOCS) {
1030 // In order to preserve the order of operations, reserve the entry before
1031 // performing the operation.
1032 entry = g_debug->record->ReserveEntry();
1033 }
1034
Christopher Ferris4da25032018-03-07 13:38:48 -08001035 void* pointer;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +00001036 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -08001037 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001038 // Need to guarantee the alignment of the header.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +00001039 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
1040 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -08001041 if (header == nullptr) {
1042 return nullptr;
1043 }
1044 memset(header, 0, g_dispatch->malloc_usable_size(header));
Christopher Ferris7bd01782016-04-20 12:30:58 -07001045 pointer = InitHeader(header, header, size);
Christopher Ferris63860cb2015-11-16 17:30:32 -08001046 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +00001047 result = TCALL(calloc, 1, real_size);
1048 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -08001049 }
Christopher Ferris4da25032018-03-07 13:38:48 -08001050
Christopher Ferrisf756e4c2024-11-19 04:28:20 +00001051 if (entry != nullptr) {
1052 *entry = memory_trace::Entry{.tid = gettid(),
1053 .type = memory_trace::CALLOC,
1054 .ptr = reinterpret_cast<uint64_t>(pointer),
1055 .size = bytes,
1056 .u.n_elements = nmemb,
1057 .start_ns = result.GetStartTimeNS(),
1058 .end_ns = result.GetEndTimeNS()};
Christopher Ferris7bd01782016-04-20 12:30:58 -07001059 }
Christopher Ferris4da25032018-03-07 13:38:48 -08001060
1061 if (pointer != nullptr && g_debug->TrackPointers()) {
1062 PointerData::Add(pointer, size);
1063 }
Christopher Ferris7bd01782016-04-20 12:30:58 -07001064 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -08001065}
1066
1067struct mallinfo debug_mallinfo() {
1068 return g_dispatch->mallinfo();
1069}
1070
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -07001071int debug_mallopt(int param, int value) {
1072 return g_dispatch->mallopt(param, value);
1073}
1074
Christopher Ferris6c619a02019-03-01 17:59:51 -08001075int debug_malloc_info(int options, FILE* fp) {
1076 if (DebugCallsDisabled() || !g_debug->TrackPointers()) {
1077 return g_dispatch->malloc_info(options, fp);
1078 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001079
1080 // Make sure any pending output is written to the file.
1081 fflush(fp);
1082
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001083 ScopedConcurrentLock lock;
1084 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001085 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris6c619a02019-03-01 17:59:51 -08001086
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001087 // Avoid any issues where allocations are made that will be freed
1088 // in the fclose.
1089 int fd = fileno(fp);
1090 MallocXmlElem root(fd, "malloc", "version=\"debug-malloc-1\"");
Christopher Ferris6c619a02019-03-01 17:59:51 -08001091 std::vector<ListInfoType> list;
1092 PointerData::GetAllocList(&list);
1093
1094 size_t alloc_num = 0;
1095 for (size_t i = 0; i < list.size(); i++) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001096 MallocXmlElem alloc(fd, "allocation", "nr=\"%zu\"", alloc_num);
Christopher Ferris6c619a02019-03-01 17:59:51 -08001097
1098 size_t total = 1;
1099 size_t size = list[i].size;
1100 while (i < list.size() - 1 && list[i + 1].size == size) {
1101 i++;
1102 total++;
1103 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001104 MallocXmlElem(fd, "size").Contents("%zu", list[i].size);
1105 MallocXmlElem(fd, "total").Contents("%zu", total);
Christopher Ferris6c619a02019-03-01 17:59:51 -08001106 alloc_num++;
1107 }
1108 return 0;
1109}
1110
Christopher Ferriscae21a92018-02-05 18:14:55 -08001111void* debug_aligned_alloc(size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001112 Unreachable::CheckIfRequested(g_debug->config());
1113
Christopher Ferriscae21a92018-02-05 18:14:55 -08001114 if (DebugCallsDisabled()) {
1115 return g_dispatch->aligned_alloc(alignment, size);
1116 }
Christopher Ferrisa22f5d52019-03-01 16:40:59 -08001117 if (!powerof2(alignment) || (size % alignment) != 0) {
Christopher Ferriscae21a92018-02-05 18:14:55 -08001118 errno = EINVAL;
1119 return nullptr;
1120 }
1121 return debug_memalign(alignment, size);
1122}
1123
Christopher Ferris63860cb2015-11-16 17:30:32 -08001124int debug_posix_memalign(void** memptr, size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001125 Unreachable::CheckIfRequested(g_debug->config());
1126
Christopher Ferris63860cb2015-11-16 17:30:32 -08001127 if (DebugCallsDisabled()) {
1128 return g_dispatch->posix_memalign(memptr, alignment, size);
1129 }
1130
Christopher Ferris6c619a02019-03-01 17:59:51 -08001131 if (alignment < sizeof(void*) || !powerof2(alignment)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001132 return EINVAL;
1133 }
1134 int saved_errno = errno;
1135 *memptr = debug_memalign(alignment, size);
1136 errno = saved_errno;
1137 return (*memptr != nullptr) ? 0 : ENOMEM;
1138}
1139
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001140int debug_malloc_iterate(uintptr_t base, size_t size, void (*callback)(uintptr_t, size_t, void*),
Christopher Ferris4da25032018-03-07 13:38:48 -08001141 void* arg) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001142 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001143 if (g_debug->TrackPointers()) {
Christopher Ferrisf78486f2022-05-04 14:08:54 -07001144 PointerData::IteratePointers([&callback, &arg](uintptr_t pointer) {
1145 callback(pointer, InternalMallocUsableSize(reinterpret_cast<void*>(pointer)), arg);
1146 });
Christopher Ferris4da25032018-03-07 13:38:48 -08001147 return 0;
1148 }
Colin Cross869691c2016-01-29 12:48:18 -08001149
Christopher Ferris4da25032018-03-07 13:38:48 -08001150 // An option that adds a header will add pointer tracking, so no need to
1151 // check if headers are enabled.
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001152 return g_dispatch->malloc_iterate(base, size, callback, arg);
Colin Cross869691c2016-01-29 12:48:18 -08001153}
1154
1155void debug_malloc_disable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001156 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001157 if (g_debug->pointer) {
Abdelrahman Daim862bd502024-11-14 08:09:42 -08001158 // Acquire the pointer locks first, otherwise, the code can be holding
1159 // the allocation lock and deadlock trying to acquire a pointer lock.
Christopher Ferris4da25032018-03-07 13:38:48 -08001160 g_debug->pointer->PrepareFork();
Colin Cross869691c2016-01-29 12:48:18 -08001161 }
Abdelrahman Daim862bd502024-11-14 08:09:42 -08001162 g_dispatch->malloc_disable();
Colin Cross869691c2016-01-29 12:48:18 -08001163}
1164
1165void debug_malloc_enable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001166 ScopedConcurrentLock lock;
Abdelrahman Daim862bd502024-11-14 08:09:42 -08001167 g_dispatch->malloc_enable();
Christopher Ferris4da25032018-03-07 13:38:48 -08001168 if (g_debug->pointer) {
1169 g_debug->pointer->PostForkParent();
Colin Cross869691c2016-01-29 12:48:18 -08001170 }
Colin Cross869691c2016-01-29 12:48:18 -08001171}
1172
Christopher Ferris4da25032018-03-07 13:38:48 -08001173ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t max_frames) {
Colin Cross2d4721c2016-02-02 11:57:54 -08001174 if (DebugCallsDisabled() || pointer == nullptr) {
1175 return 0;
1176 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001177 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -07001178 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001179 ScopedBacktraceSignalBlocker blocked;
Colin Cross2d4721c2016-02-02 11:57:54 -08001180
Christopher Ferris4da25032018-03-07 13:38:48 -08001181 if (!(g_debug->config().options() & BACKTRACE)) {
1182 return 0;
Colin Cross2d4721c2016-02-02 11:57:54 -08001183 }
Mitch Phillips3b21ada2020-01-07 15:47:47 -08001184 pointer = UntagPointer(pointer);
Christopher Ferris4da25032018-03-07 13:38:48 -08001185 return PointerData::GetFrames(pointer, frames, max_frames);
Colin Cross2d4721c2016-02-02 11:57:54 -08001186}
1187
Christopher Ferris63860cb2015-11-16 17:30:32 -08001188#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
1189void* debug_pvalloc(size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001190 Unreachable::CheckIfRequested(g_debug->config());
1191
Christopher Ferris63860cb2015-11-16 17:30:32 -08001192 if (DebugCallsDisabled()) {
1193 return g_dispatch->pvalloc(bytes);
1194 }
1195
1196 size_t pagesize = getpagesize();
Elliott Hughes193b0bc2025-05-14 06:35:50 -07001197 size_t size = __builtin_align_up(bytes, pagesize);
Christopher Ferris63860cb2015-11-16 17:30:32 -08001198 if (size < bytes) {
1199 // Overflow
1200 errno = ENOMEM;
1201 return nullptr;
1202 }
1203 return debug_memalign(pagesize, size);
1204}
1205
1206void* debug_valloc(size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001207 Unreachable::CheckIfRequested(g_debug->config());
1208
Christopher Ferris63860cb2015-11-16 17:30:32 -08001209 if (DebugCallsDisabled()) {
1210 return g_dispatch->valloc(size);
1211 }
1212 return debug_memalign(getpagesize(), size);
1213}
1214#endif
Christopher Ferris602b88c2017-08-04 13:04:04 -07001215
1216static std::mutex g_dump_lock;
1217
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001218static void write_dump(int fd) {
1219 dprintf(fd, "Android Native Heap Dump v1.2\n\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001220
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001221 std::string fingerprint = android::base::GetProperty("ro.build.fingerprint", "unknown");
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001222 dprintf(fd, "Build fingerprint: '%s'\n\n", fingerprint.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001223
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001224 PointerData::DumpLiveToFile(fd);
Christopher Ferris602b88c2017-08-04 13:04:04 -07001225
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001226 dprintf(fd, "MAPS\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001227 std::string content;
1228 if (!android::base::ReadFileToString("/proc/self/maps", &content)) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001229 dprintf(fd, "Could not open /proc/self/maps\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001230 } else {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001231 dprintf(fd, "%s", content.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001232 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001233 dprintf(fd, "END\n");
Christopher Ferrisaa3e5742023-01-31 01:31:52 +00001234
1235 // Purge the memory that was allocated and freed during this operation
1236 // since it can be large enough to expand the RSS significantly.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -07001237 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001238}
1239
1240bool debug_write_malloc_leak_info(FILE* fp) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001241 // Make sure any pending output is written to the file.
1242 fflush(fp);
1243
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001244 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001245 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001246 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001247
1248 std::lock_guard<std::mutex> guard(g_dump_lock);
1249
1250 if (!(g_debug->config().options() & BACKTRACE)) {
1251 return false;
1252 }
1253
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001254 write_dump(fileno(fp));
1255
Christopher Ferris602b88c2017-08-04 13:04:04 -07001256 return true;
1257}
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001258
1259void debug_dump_heap(const char* file_name) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001260 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001261 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001262 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001263
1264 std::lock_guard<std::mutex> guard(g_dump_lock);
1265
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001266 int fd = open(file_name, O_RDWR | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0644);
1267 if (fd == -1) {
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001268 error_log("Unable to create file: %s", file_name);
1269 return;
1270 }
1271
1272 error_log("Dumping to file: %s\n", file_name);
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001273 write_dump(fd);
1274 close(fd);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001275}