blob: c183897b74f6191ac166ef301425942a82a19931 [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
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000593 TimedResult result = InternalMalloc(size);
Christopher Ferris7bd01782016-04-20 12:30:58 -0700594
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700595 if (g_debug->config().options() & RECORD_ALLOCS) {
Christopher Ferrise39602c2024-11-02 05:02:43 +0000596 g_debug->record->AddEntry(
597 memory_trace::Entry{.tid = gettid(),
598 .type = memory_trace::MALLOC,
599 .ptr = reinterpret_cast<uint64_t>(result.getValue<void*>()),
600 .size = size,
601 .start_ns = result.GetStartTimeNS(),
602 .end_ns = result.GetEndTimeNS()});
Christopher Ferris7bd01782016-04-20 12:30:58 -0700603 }
604
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000605 return result.getValue<void*>();
Christopher Ferris55a89a42016-04-07 17:14:53 -0700606}
607
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000608static TimedResult InternalFree(void* pointer) {
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800609 uint64_t options = g_debug->config().options();
610 if ((options & BACKTRACE) && g_debug->pointer->ShouldDumpAndReset()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800611 debug_dump_heap(android::base::StringPrintf(
612 "%s.%d.txt", g_debug->config().backtrace_dump_prefix().c_str(), getpid())
613 .c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700614 }
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800615 if (options & LOG_ALLOCATOR_STATS_ON_SIGNAL) {
616 LogAllocatorStats::CheckIfShouldLog();
617 }
Christopher Ferris602b88c2017-08-04 13:04:04 -0700618
Christopher Ferris63860cb2015-11-16 17:30:32 -0800619 void* free_pointer = pointer;
620 size_t bytes;
Christopher Ferrisd0919622016-03-15 22:39:39 -0700621 Header* header;
Christopher Ferris4da25032018-03-07 13:38:48 -0800622 if (g_debug->HeaderEnabled()) {
Christopher Ferrisd0919622016-03-15 22:39:39 -0700623 header = g_debug->GetHeader(pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800624 free_pointer = header->orig_pointer;
625
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700626 if (g_debug->config().options() & FRONT_GUARD) {
Christopher Ferris55a89a42016-04-07 17:14:53 -0700627 if (!g_debug->front_guard->Valid(header)) {
628 g_debug->front_guard->LogFailure(header);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800629 }
630 }
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700631 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris55a89a42016-04-07 17:14:53 -0700632 if (!g_debug->rear_guard->Valid(header)) {
633 g_debug->rear_guard->LogFailure(header);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800634 }
635 }
636
Christopher Ferris7993b802016-01-28 18:35:05 -0800637 header->tag = DEBUG_FREE_TAG;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800638
639 bytes = header->usable_size;
640 } else {
641 bytes = g_dispatch->malloc_usable_size(pointer);
642 }
643
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700644 if (g_debug->config().options() & FILL_ON_FREE) {
645 size_t fill_bytes = g_debug->config().fill_on_free_bytes();
Christopher Ferrisa3836482022-05-13 12:09:39 -0700646 fill_bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
647 memset(pointer, g_debug->config().fill_free_value(), fill_bytes);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800648 }
649
Christopher Ferris4da25032018-03-07 13:38:48 -0800650 if (g_debug->TrackPointers()) {
651 PointerData::Remove(pointer);
652 }
653
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000654 TimedResult result;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700655 if (g_debug->config().options() & FREE_TRACK) {
Christopher Ferrisd0919622016-03-15 22:39:39 -0700656 // Do not add the allocation until we are done modifying the pointer
657 // itself. This avoids a race if a lot of threads are all doing
658 // frees at the same time and we wind up trying to really free this
659 // pointer from another thread, while still trying to free it in
660 // this function.
Christopher Ferrisa3836482022-05-13 12:09:39 -0700661 pointer = PointerData::AddFreed(pointer, bytes);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000662 if (pointer != nullptr && g_debug->HeaderEnabled()) {
663 pointer = g_debug->GetHeader(pointer)->orig_pointer;
Christopher Ferris4da25032018-03-07 13:38:48 -0800664 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000665 result = TCALLVOID(free, pointer);
Christopher Ferrisd0919622016-03-15 22:39:39 -0700666 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000667 result = TCALLVOID(free, free_pointer);
Christopher Ferrisd0919622016-03-15 22:39:39 -0700668 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000669
670 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800671}
672
Christopher Ferris55a89a42016-04-07 17:14:53 -0700673void debug_free(void* pointer) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700674 Unreachable::CheckIfRequested(g_debug->config());
675
Christopher Ferris55a89a42016-04-07 17:14:53 -0700676 if (DebugCallsDisabled() || pointer == nullptr) {
677 return g_dispatch->free(pointer);
678 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700679 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700680 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700681 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700682
Christopher Ferris4da25032018-03-07 13:38:48 -0800683 if (!VerifyPointer(pointer, "free")) {
684 return;
685 }
686
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000687 TimedResult result = InternalFree(pointer);
688
689 if (g_debug->config().options() & RECORD_ALLOCS) {
Christopher Ferrise39602c2024-11-02 05:02:43 +0000690 g_debug->record->AddEntry(memory_trace::Entry{.tid = gettid(),
691 .type = memory_trace::FREE,
692 .ptr = reinterpret_cast<uint64_t>(pointer),
693 .start_ns = result.GetStartTimeNS(),
694 .end_ns = result.GetEndTimeNS()});
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000695 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700696}
697
Christopher Ferris63860cb2015-11-16 17:30:32 -0800698void* debug_memalign(size_t alignment, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700699 Unreachable::CheckIfRequested(g_debug->config());
700
Christopher Ferris63860cb2015-11-16 17:30:32 -0800701 if (DebugCallsDisabled()) {
702 return g_dispatch->memalign(alignment, bytes);
703 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700704 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700705 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700706 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800707
Colin Cross9567c7b2016-03-09 17:56:14 -0800708 if (bytes == 0) {
709 bytes = 1;
710 }
711
Christopher Ferris4da25032018-03-07 13:38:48 -0800712 if (bytes > PointerInfoType::MaxSize()) {
713 errno = ENOMEM;
714 return nullptr;
715 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800716
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000717 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800718 void* pointer;
719 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800720 // Make the alignment a power of two.
721 if (!powerof2(alignment)) {
722 alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
723 }
Christopher Ferris72df6702016-02-11 15:51:31 -0800724 // Force the alignment to at least MINIMUM_ALIGNMENT_BYTES to guarantee
Christopher Ferris63860cb2015-11-16 17:30:32 -0800725 // that the header is aligned properly.
Christopher Ferris72df6702016-02-11 15:51:31 -0800726 if (alignment < MINIMUM_ALIGNMENT_BYTES) {
727 alignment = MINIMUM_ALIGNMENT_BYTES;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800728 }
729
730 // We don't have any idea what the natural alignment of
731 // the underlying native allocator is, so we always need to
732 // over allocate.
733 size_t real_size = alignment + bytes + g_debug->extra_bytes();
734 if (real_size < bytes) {
735 // Overflow.
736 errno = ENOMEM;
737 return nullptr;
738 }
739
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000740 result = TCALL(malloc, real_size);
741 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800742 if (pointer == nullptr) {
743 return nullptr;
744 }
745
746 uintptr_t value = reinterpret_cast<uintptr_t>(pointer) + g_debug->pointer_offset();
747 // Now align the pointer.
748 value += (-value % alignment);
749
750 Header* header = g_debug->GetHeader(reinterpret_cast<void*>(value));
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000751 // Don't need to update `result` here because we only need the timestamps.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800752 pointer = InitHeader(header, pointer, bytes);
753 } else {
754 size_t real_size = bytes + g_debug->extra_bytes();
755 if (real_size < bytes) {
756 // Overflow.
757 errno = ENOMEM;
758 return nullptr;
759 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000760 result = TCALL(memalign, alignment, real_size);
761 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800762 }
763
Christopher Ferris4da25032018-03-07 13:38:48 -0800764 if (pointer != nullptr) {
765 if (g_debug->TrackPointers()) {
766 PointerData::Add(pointer, bytes);
767 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700768
Christopher Ferris4da25032018-03-07 13:38:48 -0800769 if (g_debug->config().options() & FILL_ON_ALLOC) {
770 size_t bytes = InternalMallocUsableSize(pointer);
771 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
772 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
773 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
774 }
775
776 if (g_debug->config().options() & RECORD_ALLOCS) {
Christopher Ferrise39602c2024-11-02 05:02:43 +0000777 g_debug->record->AddEntry(memory_trace::Entry{.tid = gettid(),
778 .type = memory_trace::MEMALIGN,
779 .ptr = reinterpret_cast<uint64_t>(pointer),
780 .size = bytes,
781 .u.align = alignment,
782 .start_ns = result.GetStartTimeNS(),
783 .end_ns = result.GetEndTimeNS()});
Christopher Ferris4da25032018-03-07 13:38:48 -0800784 }
Christopher Ferris7bd01782016-04-20 12:30:58 -0700785 }
786
Christopher Ferris63860cb2015-11-16 17:30:32 -0800787 return pointer;
788}
789
790void* debug_realloc(void* pointer, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700791 Unreachable::CheckIfRequested(g_debug->config());
792
Christopher Ferris63860cb2015-11-16 17:30:32 -0800793 if (DebugCallsDisabled()) {
794 return g_dispatch->realloc(pointer, bytes);
795 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700796 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700797 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700798 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800799
800 if (pointer == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000801 TimedResult result = InternalMalloc(bytes);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000802 pointer = result.getValue<void*>();
Christopher Ferrise39602c2024-11-02 05:02:43 +0000803 if (g_debug->config().options() & RECORD_ALLOCS) {
804 g_debug->record->AddEntry(memory_trace::Entry{.tid = gettid(),
805 .type = memory_trace::REALLOC,
806 .ptr = reinterpret_cast<uint64_t>(pointer),
807 .size = bytes,
808 .u.old_ptr = 0,
809 .start_ns = result.GetStartTimeNS(),
810 .end_ns = result.GetEndTimeNS()});
811 }
Christopher Ferris7bd01782016-04-20 12:30:58 -0700812 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800813 }
814
Christopher Ferris4da25032018-03-07 13:38:48 -0800815 if (!VerifyPointer(pointer, "realloc")) {
816 return nullptr;
817 }
818
Christopher Ferris63860cb2015-11-16 17:30:32 -0800819 if (bytes == 0) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000820 TimedResult result = InternalFree(pointer);
821
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700822 if (g_debug->config().options() & RECORD_ALLOCS) {
Christopher Ferrise39602c2024-11-02 05:02:43 +0000823 g_debug->record->AddEntry(
824 memory_trace::Entry{.tid = gettid(),
825 .type = memory_trace::REALLOC,
826 .ptr = 0,
827 .size = 0,
828 .u.old_ptr = reinterpret_cast<uint64_t>(pointer),
829 .start_ns = result.GetStartTimeNS(),
830 .end_ns = result.GetEndTimeNS()});
Christopher Ferris7bd01782016-04-20 12:30:58 -0700831 }
832
Christopher Ferris63860cb2015-11-16 17:30:32 -0800833 return nullptr;
834 }
835
836 size_t real_size = bytes;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700837 if (g_debug->config().options() & EXPAND_ALLOC) {
838 real_size += g_debug->config().expand_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800839 if (real_size < bytes) {
840 // Overflow.
841 errno = ENOMEM;
842 return nullptr;
843 }
844 }
845
Christopher Ferris4da25032018-03-07 13:38:48 -0800846 if (bytes > PointerInfoType::MaxSize()) {
847 errno = ENOMEM;
848 return nullptr;
849 }
850
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000851 TimedResult result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800852 void* new_pointer;
853 size_t prev_size;
Christopher Ferris4da25032018-03-07 13:38:48 -0800854 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800855 // Same size, do nothing.
Christopher Ferris4da25032018-03-07 13:38:48 -0800856 Header* header = g_debug->GetHeader(pointer);
857 if (real_size == header->size) {
858 if (g_debug->TrackPointers()) {
859 // Remove and re-add so that the backtrace is updated.
860 PointerData::Remove(pointer);
861 PointerData::Add(pointer, real_size);
862 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800863 return pointer;
864 }
865
866 // Allocation is shrinking.
867 if (real_size < header->usable_size) {
868 header->size = real_size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700869 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800870 // Don't bother allocating a smaller pointer in this case, simply
871 // change the header usable_size and reset the rear guard.
Christopher Ferris4da25032018-03-07 13:38:48 -0800872 header->usable_size = header->size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700873 memset(g_debug->GetRearGuard(header), g_debug->config().rear_guard_value(),
874 g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800875 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800876 if (g_debug->TrackPointers()) {
877 // Remove and re-add so that the backtrace is updated.
878 PointerData::Remove(pointer);
879 PointerData::Add(pointer, real_size);
880 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800881 return pointer;
882 }
883
884 // Allocate the new size.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000885 result = InternalMalloc(bytes);
886 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800887 if (new_pointer == nullptr) {
888 errno = ENOMEM;
889 return nullptr;
890 }
891
892 prev_size = header->usable_size;
893 memcpy(new_pointer, pointer, prev_size);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000894 TimedResult free_time = InternalFree(pointer);
895 // `realloc` is split into two steps, update the end time to the finish time
896 // of the second operation.
897 result.SetEndTimeNS(free_time.GetEndTimeNS());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800898 } else {
Christopher Ferris4da25032018-03-07 13:38:48 -0800899 if (g_debug->TrackPointers()) {
900 PointerData::Remove(pointer);
901 }
902
Christopher Ferris63860cb2015-11-16 17:30:32 -0800903 prev_size = g_dispatch->malloc_usable_size(pointer);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000904 result = TCALL(realloc, pointer, real_size);
905 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800906 if (new_pointer == nullptr) {
907 return nullptr;
908 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800909
910 if (g_debug->TrackPointers()) {
911 PointerData::Add(new_pointer, real_size);
912 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800913 }
914
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700915 if (g_debug->config().options() & FILL_ON_ALLOC) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800916 size_t bytes = InternalMallocUsableSize(new_pointer);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700917 if (bytes > g_debug->config().fill_on_alloc_bytes()) {
918 bytes = g_debug->config().fill_on_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800919 }
920 if (bytes > prev_size) {
921 memset(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(new_pointer) + prev_size),
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700922 g_debug->config().fill_alloc_value(), bytes - prev_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800923 }
924 }
925
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700926 if (g_debug->config().options() & RECORD_ALLOCS) {
Christopher Ferrise39602c2024-11-02 05:02:43 +0000927 g_debug->record->AddEntry(memory_trace::Entry{.tid = gettid(),
928 .type = memory_trace::REALLOC,
929 .ptr = reinterpret_cast<uint64_t>(new_pointer),
930 .size = bytes,
931 .u.old_ptr = reinterpret_cast<uint64_t>(pointer),
932 .start_ns = result.GetStartTimeNS(),
933 .end_ns = result.GetEndTimeNS()});
Christopher Ferris7bd01782016-04-20 12:30:58 -0700934 }
935
Christopher Ferris63860cb2015-11-16 17:30:32 -0800936 return new_pointer;
937}
938
939void* debug_calloc(size_t nmemb, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700940 Unreachable::CheckIfRequested(g_debug->config());
941
Christopher Ferris63860cb2015-11-16 17:30:32 -0800942 if (DebugCallsDisabled()) {
943 return g_dispatch->calloc(nmemb, bytes);
944 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700945 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700946 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700947 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800948
Colin Cross7877df62016-03-10 13:01:27 -0800949 size_t size;
950 if (__builtin_mul_overflow(nmemb, bytes, &size)) {
951 // Overflow
952 errno = ENOMEM;
953 return nullptr;
954 }
955
Colin Cross9567c7b2016-03-09 17:56:14 -0800956 if (size == 0) {
957 size = 1;
958 }
959
Colin Cross7877df62016-03-10 13:01:27 -0800960 size_t real_size;
961 if (__builtin_add_overflow(size, g_debug->extra_bytes(), &real_size)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800962 // Overflow.
963 errno = ENOMEM;
964 return nullptr;
965 }
966
Christopher Ferris4da25032018-03-07 13:38:48 -0800967 if (real_size > PointerInfoType::MaxSize()) {
968 errno = ENOMEM;
969 return nullptr;
970 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800971
Christopher Ferris4da25032018-03-07 13:38:48 -0800972 void* pointer;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000973 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800974 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800975 // Need to guarantee the alignment of the header.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000976 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
977 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800978 if (header == nullptr) {
979 return nullptr;
980 }
981 memset(header, 0, g_dispatch->malloc_usable_size(header));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700982 pointer = InitHeader(header, header, size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800983 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000984 result = TCALL(calloc, 1, real_size);
985 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800986 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800987
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700988 if (g_debug->config().options() & RECORD_ALLOCS) {
Christopher Ferrise39602c2024-11-02 05:02:43 +0000989 g_debug->record->AddEntry(memory_trace::Entry{.tid = gettid(),
990 .type = memory_trace::CALLOC,
991 .ptr = reinterpret_cast<uint64_t>(pointer),
992 .size = bytes,
993 .u.n_elements = nmemb,
994 .start_ns = result.GetStartTimeNS(),
995 .end_ns = result.GetEndTimeNS()});
Christopher Ferris7bd01782016-04-20 12:30:58 -0700996 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800997
998 if (pointer != nullptr && g_debug->TrackPointers()) {
999 PointerData::Add(pointer, size);
1000 }
Christopher Ferris7bd01782016-04-20 12:30:58 -07001001 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -08001002}
1003
1004struct mallinfo debug_mallinfo() {
1005 return g_dispatch->mallinfo();
1006}
1007
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -07001008int debug_mallopt(int param, int value) {
1009 return g_dispatch->mallopt(param, value);
1010}
1011
Christopher Ferris6c619a02019-03-01 17:59:51 -08001012int debug_malloc_info(int options, FILE* fp) {
1013 if (DebugCallsDisabled() || !g_debug->TrackPointers()) {
1014 return g_dispatch->malloc_info(options, fp);
1015 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001016
1017 // Make sure any pending output is written to the file.
1018 fflush(fp);
1019
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001020 ScopedConcurrentLock lock;
1021 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001022 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris6c619a02019-03-01 17:59:51 -08001023
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001024 // Avoid any issues where allocations are made that will be freed
1025 // in the fclose.
1026 int fd = fileno(fp);
1027 MallocXmlElem root(fd, "malloc", "version=\"debug-malloc-1\"");
Christopher Ferris6c619a02019-03-01 17:59:51 -08001028 std::vector<ListInfoType> list;
1029 PointerData::GetAllocList(&list);
1030
1031 size_t alloc_num = 0;
1032 for (size_t i = 0; i < list.size(); i++) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001033 MallocXmlElem alloc(fd, "allocation", "nr=\"%zu\"", alloc_num);
Christopher Ferris6c619a02019-03-01 17:59:51 -08001034
1035 size_t total = 1;
1036 size_t size = list[i].size;
1037 while (i < list.size() - 1 && list[i + 1].size == size) {
1038 i++;
1039 total++;
1040 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001041 MallocXmlElem(fd, "size").Contents("%zu", list[i].size);
1042 MallocXmlElem(fd, "total").Contents("%zu", total);
Christopher Ferris6c619a02019-03-01 17:59:51 -08001043 alloc_num++;
1044 }
1045 return 0;
1046}
1047
Christopher Ferriscae21a92018-02-05 18:14:55 -08001048void* debug_aligned_alloc(size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001049 Unreachable::CheckIfRequested(g_debug->config());
1050
Christopher Ferriscae21a92018-02-05 18:14:55 -08001051 if (DebugCallsDisabled()) {
1052 return g_dispatch->aligned_alloc(alignment, size);
1053 }
Christopher Ferrisa22f5d52019-03-01 16:40:59 -08001054 if (!powerof2(alignment) || (size % alignment) != 0) {
Christopher Ferriscae21a92018-02-05 18:14:55 -08001055 errno = EINVAL;
1056 return nullptr;
1057 }
1058 return debug_memalign(alignment, size);
1059}
1060
Christopher Ferris63860cb2015-11-16 17:30:32 -08001061int debug_posix_memalign(void** memptr, size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001062 Unreachable::CheckIfRequested(g_debug->config());
1063
Christopher Ferris63860cb2015-11-16 17:30:32 -08001064 if (DebugCallsDisabled()) {
1065 return g_dispatch->posix_memalign(memptr, alignment, size);
1066 }
1067
Christopher Ferris6c619a02019-03-01 17:59:51 -08001068 if (alignment < sizeof(void*) || !powerof2(alignment)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001069 return EINVAL;
1070 }
1071 int saved_errno = errno;
1072 *memptr = debug_memalign(alignment, size);
1073 errno = saved_errno;
1074 return (*memptr != nullptr) ? 0 : ENOMEM;
1075}
1076
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001077int debug_malloc_iterate(uintptr_t base, size_t size, void (*callback)(uintptr_t, size_t, void*),
Christopher Ferris4da25032018-03-07 13:38:48 -08001078 void* arg) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001079 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001080 if (g_debug->TrackPointers()) {
Christopher Ferrisf78486f2022-05-04 14:08:54 -07001081 PointerData::IteratePointers([&callback, &arg](uintptr_t pointer) {
1082 callback(pointer, InternalMallocUsableSize(reinterpret_cast<void*>(pointer)), arg);
1083 });
Christopher Ferris4da25032018-03-07 13:38:48 -08001084 return 0;
1085 }
Colin Cross869691c2016-01-29 12:48:18 -08001086
Christopher Ferris4da25032018-03-07 13:38:48 -08001087 // An option that adds a header will add pointer tracking, so no need to
1088 // check if headers are enabled.
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001089 return g_dispatch->malloc_iterate(base, size, callback, arg);
Colin Cross869691c2016-01-29 12:48:18 -08001090}
1091
1092void debug_malloc_disable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001093 ScopedConcurrentLock lock;
Colin Cross869691c2016-01-29 12:48:18 -08001094 g_dispatch->malloc_disable();
Christopher Ferris4da25032018-03-07 13:38:48 -08001095 if (g_debug->pointer) {
1096 g_debug->pointer->PrepareFork();
Colin Cross869691c2016-01-29 12:48:18 -08001097 }
1098}
1099
1100void debug_malloc_enable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001101 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001102 if (g_debug->pointer) {
1103 g_debug->pointer->PostForkParent();
Colin Cross869691c2016-01-29 12:48:18 -08001104 }
1105 g_dispatch->malloc_enable();
1106}
1107
Christopher Ferris4da25032018-03-07 13:38:48 -08001108ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t max_frames) {
Colin Cross2d4721c2016-02-02 11:57:54 -08001109 if (DebugCallsDisabled() || pointer == nullptr) {
1110 return 0;
1111 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001112 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -07001113 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001114 ScopedBacktraceSignalBlocker blocked;
Colin Cross2d4721c2016-02-02 11:57:54 -08001115
Christopher Ferris4da25032018-03-07 13:38:48 -08001116 if (!(g_debug->config().options() & BACKTRACE)) {
1117 return 0;
Colin Cross2d4721c2016-02-02 11:57:54 -08001118 }
Mitch Phillips3b21ada2020-01-07 15:47:47 -08001119 pointer = UntagPointer(pointer);
Christopher Ferris4da25032018-03-07 13:38:48 -08001120 return PointerData::GetFrames(pointer, frames, max_frames);
Colin Cross2d4721c2016-02-02 11:57:54 -08001121}
1122
Christopher Ferris63860cb2015-11-16 17:30:32 -08001123#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
1124void* debug_pvalloc(size_t bytes) {
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->pvalloc(bytes);
1129 }
1130
1131 size_t pagesize = getpagesize();
Dan Alberta613d0d2017-10-05 16:39:33 -07001132 size_t size = __BIONIC_ALIGN(bytes, pagesize);
Christopher Ferris63860cb2015-11-16 17:30:32 -08001133 if (size < bytes) {
1134 // Overflow
1135 errno = ENOMEM;
1136 return nullptr;
1137 }
1138 return debug_memalign(pagesize, size);
1139}
1140
1141void* debug_valloc(size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001142 Unreachable::CheckIfRequested(g_debug->config());
1143
Christopher Ferris63860cb2015-11-16 17:30:32 -08001144 if (DebugCallsDisabled()) {
1145 return g_dispatch->valloc(size);
1146 }
1147 return debug_memalign(getpagesize(), size);
1148}
1149#endif
Christopher Ferris602b88c2017-08-04 13:04:04 -07001150
1151static std::mutex g_dump_lock;
1152
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001153static void write_dump(int fd) {
1154 dprintf(fd, "Android Native Heap Dump v1.2\n\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001155
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001156 std::string fingerprint = android::base::GetProperty("ro.build.fingerprint", "unknown");
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001157 dprintf(fd, "Build fingerprint: '%s'\n\n", fingerprint.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001158
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001159 PointerData::DumpLiveToFile(fd);
Christopher Ferris602b88c2017-08-04 13:04:04 -07001160
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001161 dprintf(fd, "MAPS\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001162 std::string content;
1163 if (!android::base::ReadFileToString("/proc/self/maps", &content)) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001164 dprintf(fd, "Could not open /proc/self/maps\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001165 } else {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001166 dprintf(fd, "%s", content.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001167 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001168 dprintf(fd, "END\n");
Christopher Ferrisaa3e5742023-01-31 01:31:52 +00001169
1170 // Purge the memory that was allocated and freed during this operation
1171 // since it can be large enough to expand the RSS significantly.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -07001172 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001173}
1174
1175bool debug_write_malloc_leak_info(FILE* fp) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001176 // Make sure any pending output is written to the file.
1177 fflush(fp);
1178
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001179 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001180 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001181 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001182
1183 std::lock_guard<std::mutex> guard(g_dump_lock);
1184
1185 if (!(g_debug->config().options() & BACKTRACE)) {
1186 return false;
1187 }
1188
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001189 write_dump(fileno(fp));
1190
Christopher Ferris602b88c2017-08-04 13:04:04 -07001191 return true;
1192}
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001193
1194void debug_dump_heap(const char* file_name) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001195 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001196 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001197 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001198
1199 std::lock_guard<std::mutex> guard(g_dump_lock);
1200
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001201 int fd = open(file_name, O_RDWR | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0644);
1202 if (fd == -1) {
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001203 error_log("Unable to create file: %s", file_name);
1204 return;
1205 }
1206
1207 error_log("Dumping to file: %s\n", file_name);
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001208 write_dump(fd);
1209 close(fd);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001210}