blob: 374385252149f528eef899f706cbe9f45473e39a [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 Ferrisb42e8b42022-05-09 14:00:47 -070057#include "Unreachable.h"
58#include "UnwindBacktrace.h"
Christopher Ferris4da25032018-03-07 13:38:48 -080059#include "backtrace.h"
Christopher Ferris63860cb2015-11-16 17:30:32 -080060#include "debug_disable.h"
61#include "debug_log.h"
62#include "malloc_debug.h"
63
64// ------------------------------------------------------------------------
65// Global Data
66// ------------------------------------------------------------------------
67DebugData* g_debug;
68
Christopher Ferris8189e772019-04-09 16:37:23 -070069bool* g_zygote_child;
Christopher Ferris63860cb2015-11-16 17:30:32 -080070
71const MallocDispatch* g_dispatch;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +000072
Nick Desaulniersc574f792024-04-17 09:49:59 -070073static inline __always_inline uint64_t Nanotime() {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +000074 struct timespec t = {};
75 clock_gettime(CLOCK_MONOTONIC, &t);
76 return static_cast<uint64_t>(t.tv_sec) * 1000000000LL + t.tv_nsec;
77}
78
79namespace {
80// A TimedResult contains the result of from malloc end_ns al. functions and the
81// start/end timestamps.
82struct TimedResult {
83 uint64_t start_ns = 0;
84 uint64_t end_ns = 0;
85 union {
86 size_t s;
87 int i;
88 void* p;
89 } v;
90
91 uint64_t GetStartTimeNS() const { return start_ns; }
92 uint64_t GetEndTimeNS() const { return end_ns; }
93 void SetStartTimeNS(uint64_t t) { start_ns = t; }
94 void SetEndTimeNS(uint64_t t) { end_ns = t; }
95
96 template <typename T>
97 void setValue(T);
98 template <>
99 void setValue(size_t s) {
100 v.s = s;
101 }
102 template <>
103 void setValue(int i) {
104 v.i = i;
105 }
106 template <>
107 void setValue(void* p) {
108 v.p = p;
109 }
110
111 template <typename T>
112 T getValue() const;
113 template <>
114 size_t getValue<size_t>() const {
115 return v.s;
116 }
117 template <>
118 int getValue<int>() const {
119 return v.i;
120 }
121 template <>
122 void* getValue<void*>() const {
123 return v.p;
124 }
125};
126
127class ScopedTimer {
128 public:
129 ScopedTimer(TimedResult& res) : res_(res) { res_.start_ns = Nanotime(); }
130
131 ~ScopedTimer() { res_.end_ns = Nanotime(); }
132
133 private:
134 TimedResult& res_;
135};
136
137} // namespace
138
139template <typename MallocFn, typename... Args>
140static TimedResult TimerCall(MallocFn fn, Args... args) {
141 TimedResult ret;
142 decltype((g_dispatch->*fn)(args...)) r;
143 if (g_debug->config().options() & RECORD_ALLOCS) {
144 ScopedTimer t(ret);
145 r = (g_dispatch->*fn)(args...);
146 } else {
147 r = (g_dispatch->*fn)(args...);
148 }
149 ret.setValue<decltype(r)>(r);
150 return ret;
151}
152
153template <typename MallocFn, typename... Args>
154static TimedResult TimerCallVoid(MallocFn fn, Args... args) {
155 TimedResult ret;
156 {
157 ScopedTimer t(ret);
158 (g_dispatch->*fn)(args...);
159 }
160 return ret;
161}
162
163#define TCALL(FUNC, ...) TimerCall(&MallocDispatch::FUNC, __VA_ARGS__);
164#define TCALLVOID(FUNC, ...) TimerCallVoid(&MallocDispatch::FUNC, __VA_ARGS__);
165
Christopher Ferris63860cb2015-11-16 17:30:32 -0800166// ------------------------------------------------------------------------
167
168// ------------------------------------------------------------------------
169// Use C style prototypes for all exported functions. This makes it easy
170// to do dlsym lookups during libc initialization when malloc debug
171// is enabled.
172// ------------------------------------------------------------------------
173__BEGIN_DECLS
174
Christopher Ferris8189e772019-04-09 16:37:23 -0700175bool debug_initialize(const MallocDispatch* malloc_dispatch, bool* malloc_zygote_child,
Christopher Ferris4da25032018-03-07 13:38:48 -0800176 const char* options);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800177void debug_finalize();
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700178void debug_dump_heap(const char* file_name);
Christopher Ferris4da25032018-03-07 13:38:48 -0800179void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
180 size_t* total_memory, size_t* backtrace_size);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700181bool debug_write_malloc_leak_info(FILE* fp);
Colin Cross2d4721c2016-02-02 11:57:54 -0800182ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800183void debug_free_malloc_leak_info(uint8_t* info);
184size_t debug_malloc_usable_size(void* pointer);
185void* debug_malloc(size_t size);
186void debug_free(void* pointer);
Christopher Ferriscae21a92018-02-05 18:14:55 -0800187void* debug_aligned_alloc(size_t alignment, size_t size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800188void* debug_memalign(size_t alignment, size_t bytes);
189void* debug_realloc(void* pointer, size_t bytes);
190void* debug_calloc(size_t nmemb, size_t bytes);
191struct mallinfo debug_mallinfo();
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700192int debug_mallopt(int param, int value);
Christopher Ferris6c619a02019-03-01 17:59:51 -0800193int debug_malloc_info(int options, FILE* fp);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800194int debug_posix_memalign(void** memptr, size_t alignment, size_t size);
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800195int debug_malloc_iterate(uintptr_t base, size_t size,
196 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg);
Colin Cross869691c2016-01-29 12:48:18 -0800197void debug_malloc_disable();
198void debug_malloc_enable();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800199
200#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
201void* debug_pvalloc(size_t bytes);
202void* debug_valloc(size_t size);
203#endif
204
205__END_DECLS
206// ------------------------------------------------------------------------
207
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700208class ScopedConcurrentLock {
209 public:
210 ScopedConcurrentLock() {
211 pthread_rwlock_rdlock(&lock_);
212 }
213 ~ScopedConcurrentLock() {
214 pthread_rwlock_unlock(&lock_);
215 }
216
217 static void Init() {
218 pthread_rwlockattr_t attr;
219 // Set the attribute so that when a write lock is pending, read locks are no
220 // longer granted.
221 pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
222 pthread_rwlock_init(&lock_, &attr);
223 }
224
225 static void BlockAllOperations() {
226 pthread_rwlock_wrlock(&lock_);
227 }
228
229 private:
230 static pthread_rwlock_t lock_;
231};
232pthread_rwlock_t ScopedConcurrentLock::lock_;
233
Christopher Ferris9bf78172020-05-20 15:37:30 -0700234// Use this because the sigprocmask* functions filter out the reserved bionic
235// signals including the signal this code blocks.
236static inline int __rt_sigprocmask(int how, const sigset64_t* new_set, sigset64_t* old_set,
237 size_t sigset_size) {
238 return syscall(SYS_rt_sigprocmask, how, new_set, old_set, sigset_size);
239}
240
241// Need to block the backtrace signal while in malloc debug routines
242// otherwise there is a chance of a deadlock and timeout when unwinding.
243// This can occur if a thread is paused while owning a malloc debug
244// internal lock.
245class ScopedBacktraceSignalBlocker {
246 public:
247 ScopedBacktraceSignalBlocker() {
248 sigemptyset64(&backtrace_set_);
249 sigaddset64(&backtrace_set_, BIONIC_SIGNAL_BACKTRACE);
250 sigset64_t old_set;
251 __rt_sigprocmask(SIG_BLOCK, &backtrace_set_, &old_set, sizeof(backtrace_set_));
252 if (sigismember64(&old_set, BIONIC_SIGNAL_BACKTRACE)) {
253 unblock_ = false;
254 }
255 }
256
257 ~ScopedBacktraceSignalBlocker() {
258 if (unblock_) {
259 __rt_sigprocmask(SIG_UNBLOCK, &backtrace_set_, nullptr, sizeof(backtrace_set_));
260 }
261 }
262
263 private:
264 bool unblock_ = true;
265 sigset64_t backtrace_set_;
266};
267
Colin Cross7a28a3c2016-02-07 22:51:15 -0800268static void InitAtfork() {
269 static pthread_once_t atfork_init = PTHREAD_ONCE_INIT;
Christopher Ferris4da25032018-03-07 13:38:48 -0800270 pthread_once(&atfork_init, []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800271 pthread_atfork(
Christopher Ferris4da25032018-03-07 13:38:48 -0800272 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800273 if (g_debug != nullptr) {
274 g_debug->PrepareFork();
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->PostForkParent();
280 }
281 },
Christopher Ferris4da25032018-03-07 13:38:48 -0800282 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800283 if (g_debug != nullptr) {
284 g_debug->PostForkChild();
285 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800286 });
Colin Cross7a28a3c2016-02-07 22:51:15 -0800287 });
288}
Christopher Ferrisd0919622016-03-15 22:39:39 -0700289
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700290void BacktraceAndLog() {
291 if (g_debug->config().options() & BACKTRACE_FULL) {
292 std::vector<uintptr_t> frames;
Christopher Ferris459eecb2022-01-07 13:38:10 -0800293 std::vector<unwindstack::FrameData> frames_info;
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700294 if (!Unwind(&frames, &frames_info, 256)) {
295 error_log(" Backtrace failed to get any frames.");
296 } else {
297 UnwindLog(frames_info);
298 }
299 } else {
300 std::vector<uintptr_t> frames(256);
301 size_t num_frames = backtrace_get(frames.data(), frames.size());
302 if (num_frames == 0) {
303 error_log(" Backtrace failed to get any frames.");
304 } else {
305 backtrace_log(frames.data(), num_frames);
306 }
307 }
308}
309
Christopher Ferris4da25032018-03-07 13:38:48 -0800310static void LogError(const void* pointer, const char* error_str) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800311 error_log(LOG_DIVIDER);
Christopher Ferris4da25032018-03-07 13:38:48 -0800312 error_log("+++ ALLOCATION %p %s", pointer, error_str);
313
314 // If we are tracking already freed pointers, check to see if this is
315 // one so we can print extra information.
316 if (g_debug->config().options() & FREE_TRACK) {
317 PointerData::LogFreeBacktrace(pointer);
Christopher Ferris7993b802016-01-28 18:35:05 -0800318 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800319
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700320 error_log("Backtrace at time of failure:");
321 BacktraceAndLog();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800322 error_log(LOG_DIVIDER);
Iris Chang7f209a92019-01-16 11:17:15 +0800323 if (g_debug->config().options() & ABORT_ON_ERROR) {
324 abort();
325 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800326}
327
Christopher Ferris4da25032018-03-07 13:38:48 -0800328static bool VerifyPointer(const void* pointer, const char* function_name) {
329 if (g_debug->HeaderEnabled()) {
330 Header* header = g_debug->GetHeader(pointer);
331 if (header->tag != DEBUG_TAG) {
332 std::string error_str;
333 if (header->tag == DEBUG_FREE_TAG) {
334 error_str = std::string("USED AFTER FREE (") + function_name + ")";
335 } else {
336 error_str = android::base::StringPrintf("HAS INVALID TAG %" PRIx32 " (%s)", header->tag,
337 function_name);
338 }
339 LogError(pointer, error_str.c_str());
340 return false;
341 }
342 }
343
344 if (g_debug->TrackPointers()) {
345 if (!PointerData::Exists(pointer)) {
346 std::string error_str(std::string("UNKNOWN POINTER (") + function_name + ")");
347 LogError(pointer, error_str.c_str());
348 return false;
349 }
350 }
351 return true;
352}
353
354static size_t InternalMallocUsableSize(void* pointer) {
355 if (g_debug->HeaderEnabled()) {
356 return g_debug->GetHeader(pointer)->usable_size;
357 } else {
358 return g_dispatch->malloc_usable_size(pointer);
359 }
360}
361
Christopher Ferris63860cb2015-11-16 17:30:32 -0800362static void* InitHeader(Header* header, void* orig_pointer, size_t size) {
363 header->tag = DEBUG_TAG;
364 header->orig_pointer = orig_pointer;
365 header->size = size;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800366 header->usable_size = g_dispatch->malloc_usable_size(orig_pointer);
367 if (header->usable_size == 0) {
368 g_dispatch->free(orig_pointer);
369 return nullptr;
370 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800371 header->usable_size -= g_debug->pointer_offset() + reinterpret_cast<uintptr_t>(header) -
372 reinterpret_cast<uintptr_t>(orig_pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800373
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700374 if (g_debug->config().options() & FRONT_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800375 uint8_t* guard = g_debug->GetFrontGuard(header);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700376 memset(guard, g_debug->config().front_guard_value(), g_debug->config().front_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800377 }
378
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700379 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800380 uint8_t* guard = g_debug->GetRearGuard(header);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700381 memset(guard, g_debug->config().rear_guard_value(), g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800382 // If the rear guard is enabled, set the usable size to the exact size
383 // of the allocation.
Christopher Ferris4da25032018-03-07 13:38:48 -0800384 header->usable_size = header->size;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800385 }
386
387 return g_debug->GetPointer(header);
388}
389
Christopher Ferris705de3c2019-05-22 13:39:57 -0700390extern "C" void __asan_init() __attribute__((weak));
391
Christopher Ferris8189e772019-04-09 16:37:23 -0700392bool debug_initialize(const MallocDispatch* malloc_dispatch, bool* zygote_child,
Christopher Ferris4da25032018-03-07 13:38:48 -0800393 const char* options) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700394 if (zygote_child == nullptr || options == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800395 return false;
396 }
Colin Cross7a28a3c2016-02-07 22:51:15 -0800397
Christopher Ferris705de3c2019-05-22 13:39:57 -0700398 if (__asan_init != 0) {
399 error_log("malloc debug cannot be enabled alongside ASAN");
400 return false;
401 }
402
Colin Cross7a28a3c2016-02-07 22:51:15 -0800403 InitAtfork();
404
Christopher Ferris8189e772019-04-09 16:37:23 -0700405 g_zygote_child = zygote_child;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800406
407 g_dispatch = malloc_dispatch;
408
409 if (!DebugDisableInitialize()) {
410 return false;
411 }
412
413 DebugData* debug = new DebugData();
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700414 if (!debug->Initialize(options) || !Unreachable::Initialize(debug->config())) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800415 delete debug;
416 DebugDisableFinalize();
417 return false;
418 }
419 g_debug = debug;
420
421 // Always enable the backtrace code since we will use it in a number
422 // of different error cases.
423 backtrace_startup();
424
Christopher Ferrisc328e442019-04-01 19:31:26 -0700425 if (g_debug->config().options() & VERBOSE) {
426 info_log("%s: malloc debug enabled", getprogname());
427 }
428
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700429 ScopedConcurrentLock::Init();
430
Christopher Ferris63860cb2015-11-16 17:30:32 -0800431 return true;
432}
433
434void debug_finalize() {
435 if (g_debug == nullptr) {
436 return;
437 }
438
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700439 // Make sure that there are no other threads doing debug allocations
440 // before we kill everything.
441 ScopedConcurrentLock::BlockAllOperations();
442
Christopher Ferris97b47472018-07-10 14:45:24 -0700443 // Turn off capturing allocations calls.
444 DebugDisableSet(true);
445
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700446 if (g_debug->config().options() & FREE_TRACK) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800447 PointerData::VerifyAllFreed();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800448 }
449
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700450 if (g_debug->config().options() & LEAK_TRACK) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800451 PointerData::LogLeaks();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800452 }
453
Christopher Ferris9b88d0a2024-06-13 13:22:02 -0700454 if ((g_debug->config().options() & RECORD_ALLOCS) && g_debug->config().record_allocs_on_exit()) {
455 RecordData::WriteEntriesOnExit();
456 }
457
Christopher Ferris602b88c2017-08-04 13:04:04 -0700458 if ((g_debug->config().options() & BACKTRACE) && g_debug->config().backtrace_dump_on_exit()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800459 debug_dump_heap(android::base::StringPrintf("%s.%d.exit.txt",
460 g_debug->config().backtrace_dump_prefix().c_str(),
Christopher Ferris97b47472018-07-10 14:45:24 -0700461 getpid()).c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700462 }
463
Christopher Ferrisc1341e12024-07-11 19:48:08 -0700464 if (g_debug->config().options() & LOG_ALLOCATOR_STATS_ON_EXIT) {
465 LogAllocatorStats::Log();
466 }
467
Colin Cross2c759912016-02-05 16:17:39 -0800468 backtrace_shutdown();
469
Christopher Ferris33d73372021-07-02 15:46:18 -0700470 // In order to prevent any issues of threads freeing previous pointers
471 // after the main thread calls this code, simply leak the g_debug pointer
472 // and do not destroy the debug disable pthread key.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800473}
474
Christopher Ferris4da25032018-03-07 13:38:48 -0800475void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
476 size_t* total_memory, size_t* backtrace_size) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700477 ScopedConcurrentLock lock;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800478 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700479 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800480
481 // Verify the arguments.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700482 if (info == nullptr || overall_size == nullptr || info_size == nullptr || total_memory == nullptr ||
Christopher Ferris4da25032018-03-07 13:38:48 -0800483 backtrace_size == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800484 error_log("get_malloc_leak_info: At least one invalid parameter.");
485 return;
486 }
487
488 *info = nullptr;
489 *overall_size = 0;
490 *info_size = 0;
491 *total_memory = 0;
492 *backtrace_size = 0;
493
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700494 if (!(g_debug->config().options() & BACKTRACE)) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800495 error_log(
496 "get_malloc_leak_info: Allocations not being tracked, to enable "
497 "set the option 'backtrace'.");
Christopher Ferris63860cb2015-11-16 17:30:32 -0800498 return;
499 }
500
Christopher Ferris4da25032018-03-07 13:38:48 -0800501 PointerData::GetInfo(info, overall_size, info_size, total_memory, backtrace_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800502}
503
504void debug_free_malloc_leak_info(uint8_t* info) {
505 g_dispatch->free(info);
Christopher Ferrisaa3e5742023-01-31 01:31:52 +0000506 // Purge the memory that was freed since a significant amount of
507 // memory could have been allocated and freed.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -0700508 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800509}
510
Christopher Ferris55a89a42016-04-07 17:14:53 -0700511size_t debug_malloc_usable_size(void* pointer) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700512 Unreachable::CheckIfRequested(g_debug->config());
513
Christopher Ferris55a89a42016-04-07 17:14:53 -0700514 if (DebugCallsDisabled() || pointer == nullptr) {
515 return g_dispatch->malloc_usable_size(pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800516 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700517 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700518 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700519 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800520
Christopher Ferris4da25032018-03-07 13:38:48 -0800521 if (!VerifyPointer(pointer, "malloc_usable_size")) {
522 return 0;
523 }
524
525 return InternalMallocUsableSize(pointer);
Christopher Ferris55a89a42016-04-07 17:14:53 -0700526}
527
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000528static TimedResult InternalMalloc(size_t size) {
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800529 uint64_t options = g_debug->config().options();
530 if ((options & BACKTRACE) && g_debug->pointer->ShouldDumpAndReset()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800531 debug_dump_heap(android::base::StringPrintf(
532 "%s.%d.txt", g_debug->config().backtrace_dump_prefix().c_str(), getpid())
533 .c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700534 }
Christopher Ferris5610d5a2023-11-14 15:04:50 -0800535 if (options & LOG_ALLOCATOR_STATS_ON_SIGNAL) {
536 LogAllocatorStats::CheckIfShouldLog();
537 }
Christopher Ferris602b88c2017-08-04 13:04:04 -0700538
Colin Cross9567c7b2016-03-09 17:56:14 -0800539 if (size == 0) {
540 size = 1;
541 }
542
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000543 TimedResult result;
544
Christopher Ferris63860cb2015-11-16 17:30:32 -0800545 size_t real_size = size + g_debug->extra_bytes();
546 if (real_size < size) {
547 // Overflow.
548 errno = ENOMEM;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000549 result.setValue<void*>(nullptr);
550 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800551 }
552
Christopher Ferris4da25032018-03-07 13:38:48 -0800553 if (size > PointerInfoType::MaxSize()) {
554 errno = ENOMEM;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000555 result.setValue<void*>(nullptr);
556 return result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800557 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800558
Christopher Ferris4da25032018-03-07 13:38:48 -0800559 if (g_debug->HeaderEnabled()) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000560 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
561 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800562 if (header == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000563 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800564 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000565 result.setValue<void*>(InitHeader(header, header, size));
Christopher Ferris63860cb2015-11-16 17:30:32 -0800566 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000567 result = TCALL(malloc, real_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800568 }
569
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000570 void* pointer = result.getValue<void*>();
571
Christopher Ferris4da25032018-03-07 13:38:48 -0800572 if (pointer != nullptr) {
573 if (g_debug->TrackPointers()) {
574 PointerData::Add(pointer, size);
575 }
576
577 if (g_debug->config().options() & FILL_ON_ALLOC) {
578 size_t bytes = InternalMallocUsableSize(pointer);
579 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
580 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
581 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
582 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800583 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000584
585 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800586}
587
Christopher Ferris55a89a42016-04-07 17:14:53 -0700588void* debug_malloc(size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700589 Unreachable::CheckIfRequested(g_debug->config());
590
Christopher Ferris55a89a42016-04-07 17:14:53 -0700591 if (DebugCallsDisabled()) {
592 return g_dispatch->malloc(size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800593 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700594 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700595 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700596 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800597
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000598 TimedResult result = InternalMalloc(size);
Christopher Ferris7bd01782016-04-20 12:30:58 -0700599
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700600 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000601 g_debug->record->AddEntry(new MallocEntry(result.getValue<void*>(), size,
602 result.GetStartTimeNS(), 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) {
690 g_debug->record->AddEntry(
691 new FreeEntry(pointer, result.GetStartTimeNS(), result.GetEndTimeNS()));
692 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700693}
694
Christopher Ferris63860cb2015-11-16 17:30:32 -0800695void* debug_memalign(size_t alignment, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700696 Unreachable::CheckIfRequested(g_debug->config());
697
Christopher Ferris63860cb2015-11-16 17:30:32 -0800698 if (DebugCallsDisabled()) {
699 return g_dispatch->memalign(alignment, bytes);
700 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700701 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700702 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700703 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800704
Colin Cross9567c7b2016-03-09 17:56:14 -0800705 if (bytes == 0) {
706 bytes = 1;
707 }
708
Christopher Ferris4da25032018-03-07 13:38:48 -0800709 if (bytes > PointerInfoType::MaxSize()) {
710 errno = ENOMEM;
711 return nullptr;
712 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800713
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000714 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800715 void* pointer;
716 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800717 // Make the alignment a power of two.
718 if (!powerof2(alignment)) {
719 alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
720 }
Christopher Ferris72df6702016-02-11 15:51:31 -0800721 // Force the alignment to at least MINIMUM_ALIGNMENT_BYTES to guarantee
Christopher Ferris63860cb2015-11-16 17:30:32 -0800722 // that the header is aligned properly.
Christopher Ferris72df6702016-02-11 15:51:31 -0800723 if (alignment < MINIMUM_ALIGNMENT_BYTES) {
724 alignment = MINIMUM_ALIGNMENT_BYTES;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800725 }
726
727 // We don't have any idea what the natural alignment of
728 // the underlying native allocator is, so we always need to
729 // over allocate.
730 size_t real_size = alignment + bytes + g_debug->extra_bytes();
731 if (real_size < bytes) {
732 // Overflow.
733 errno = ENOMEM;
734 return nullptr;
735 }
736
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000737 result = TCALL(malloc, real_size);
738 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800739 if (pointer == nullptr) {
740 return nullptr;
741 }
742
743 uintptr_t value = reinterpret_cast<uintptr_t>(pointer) + g_debug->pointer_offset();
744 // Now align the pointer.
745 value += (-value % alignment);
746
747 Header* header = g_debug->GetHeader(reinterpret_cast<void*>(value));
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000748 // Don't need to update `result` here because we only need the timestamps.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800749 pointer = InitHeader(header, pointer, bytes);
750 } else {
751 size_t real_size = bytes + g_debug->extra_bytes();
752 if (real_size < bytes) {
753 // Overflow.
754 errno = ENOMEM;
755 return nullptr;
756 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000757 result = TCALL(memalign, alignment, real_size);
758 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800759 }
760
Christopher Ferris4da25032018-03-07 13:38:48 -0800761 if (pointer != nullptr) {
762 if (g_debug->TrackPointers()) {
763 PointerData::Add(pointer, bytes);
764 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700765
Christopher Ferris4da25032018-03-07 13:38:48 -0800766 if (g_debug->config().options() & FILL_ON_ALLOC) {
767 size_t bytes = InternalMallocUsableSize(pointer);
768 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
769 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
770 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
771 }
772
773 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000774 g_debug->record->AddEntry(new MemalignEntry(pointer, bytes, alignment,
775 result.GetStartTimeNS(), result.GetEndTimeNS()));
Christopher Ferris4da25032018-03-07 13:38:48 -0800776 }
Christopher Ferris7bd01782016-04-20 12:30:58 -0700777 }
778
Christopher Ferris63860cb2015-11-16 17:30:32 -0800779 return pointer;
780}
781
782void* debug_realloc(void* pointer, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700783 Unreachable::CheckIfRequested(g_debug->config());
784
Christopher Ferris63860cb2015-11-16 17:30:32 -0800785 if (DebugCallsDisabled()) {
786 return g_dispatch->realloc(pointer, bytes);
787 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700788 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700789 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700790 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800791
792 if (pointer == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000793 TimedResult result = InternalMalloc(bytes);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700794 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000795 g_debug->record->AddEntry(new ReallocEntry(result.getValue<void*>(), bytes, nullptr,
796 result.GetStartTimeNS(), result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700797 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000798 pointer = result.getValue<void*>();
Christopher Ferris7bd01782016-04-20 12:30:58 -0700799 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800800 }
801
Christopher Ferris4da25032018-03-07 13:38:48 -0800802 if (!VerifyPointer(pointer, "realloc")) {
803 return nullptr;
804 }
805
Christopher Ferris63860cb2015-11-16 17:30:32 -0800806 if (bytes == 0) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000807 TimedResult result = InternalFree(pointer);
808
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700809 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000810 g_debug->record->AddEntry(new ReallocEntry(nullptr, bytes, pointer, result.GetStartTimeNS(),
811 result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700812 }
813
Christopher Ferris63860cb2015-11-16 17:30:32 -0800814 return nullptr;
815 }
816
817 size_t real_size = bytes;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700818 if (g_debug->config().options() & EXPAND_ALLOC) {
819 real_size += g_debug->config().expand_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800820 if (real_size < bytes) {
821 // Overflow.
822 errno = ENOMEM;
823 return nullptr;
824 }
825 }
826
Christopher Ferris4da25032018-03-07 13:38:48 -0800827 if (bytes > PointerInfoType::MaxSize()) {
828 errno = ENOMEM;
829 return nullptr;
830 }
831
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000832 TimedResult result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800833 void* new_pointer;
834 size_t prev_size;
Christopher Ferris4da25032018-03-07 13:38:48 -0800835 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800836 // Same size, do nothing.
Christopher Ferris4da25032018-03-07 13:38:48 -0800837 Header* header = g_debug->GetHeader(pointer);
838 if (real_size == header->size) {
839 if (g_debug->TrackPointers()) {
840 // Remove and re-add so that the backtrace is updated.
841 PointerData::Remove(pointer);
842 PointerData::Add(pointer, real_size);
843 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800844 return pointer;
845 }
846
847 // Allocation is shrinking.
848 if (real_size < header->usable_size) {
849 header->size = real_size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700850 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800851 // Don't bother allocating a smaller pointer in this case, simply
852 // change the header usable_size and reset the rear guard.
Christopher Ferris4da25032018-03-07 13:38:48 -0800853 header->usable_size = header->size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700854 memset(g_debug->GetRearGuard(header), g_debug->config().rear_guard_value(),
855 g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800856 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800857 if (g_debug->TrackPointers()) {
858 // Remove and re-add so that the backtrace is updated.
859 PointerData::Remove(pointer);
860 PointerData::Add(pointer, real_size);
861 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800862 return pointer;
863 }
864
865 // Allocate the new size.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000866 result = InternalMalloc(bytes);
867 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800868 if (new_pointer == nullptr) {
869 errno = ENOMEM;
870 return nullptr;
871 }
872
873 prev_size = header->usable_size;
874 memcpy(new_pointer, pointer, prev_size);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000875 TimedResult free_time = InternalFree(pointer);
876 // `realloc` is split into two steps, update the end time to the finish time
877 // of the second operation.
878 result.SetEndTimeNS(free_time.GetEndTimeNS());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800879 } else {
Christopher Ferris4da25032018-03-07 13:38:48 -0800880 if (g_debug->TrackPointers()) {
881 PointerData::Remove(pointer);
882 }
883
Christopher Ferris63860cb2015-11-16 17:30:32 -0800884 prev_size = g_dispatch->malloc_usable_size(pointer);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000885 result = TCALL(realloc, pointer, real_size);
886 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800887 if (new_pointer == nullptr) {
888 return nullptr;
889 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800890
891 if (g_debug->TrackPointers()) {
892 PointerData::Add(new_pointer, real_size);
893 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800894 }
895
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700896 if (g_debug->config().options() & FILL_ON_ALLOC) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800897 size_t bytes = InternalMallocUsableSize(new_pointer);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700898 if (bytes > g_debug->config().fill_on_alloc_bytes()) {
899 bytes = g_debug->config().fill_on_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800900 }
901 if (bytes > prev_size) {
902 memset(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(new_pointer) + prev_size),
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700903 g_debug->config().fill_alloc_value(), bytes - prev_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800904 }
905 }
906
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700907 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000908 g_debug->record->AddEntry(new ReallocEntry(new_pointer, bytes, pointer, result.GetStartTimeNS(),
909 result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700910 }
911
Christopher Ferris63860cb2015-11-16 17:30:32 -0800912 return new_pointer;
913}
914
915void* debug_calloc(size_t nmemb, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700916 Unreachable::CheckIfRequested(g_debug->config());
917
Christopher Ferris63860cb2015-11-16 17:30:32 -0800918 if (DebugCallsDisabled()) {
919 return g_dispatch->calloc(nmemb, bytes);
920 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700921 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700922 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700923 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800924
Colin Cross7877df62016-03-10 13:01:27 -0800925 size_t size;
926 if (__builtin_mul_overflow(nmemb, bytes, &size)) {
927 // Overflow
928 errno = ENOMEM;
929 return nullptr;
930 }
931
Colin Cross9567c7b2016-03-09 17:56:14 -0800932 if (size == 0) {
933 size = 1;
934 }
935
Colin Cross7877df62016-03-10 13:01:27 -0800936 size_t real_size;
937 if (__builtin_add_overflow(size, g_debug->extra_bytes(), &real_size)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800938 // Overflow.
939 errno = ENOMEM;
940 return nullptr;
941 }
942
Christopher Ferris4da25032018-03-07 13:38:48 -0800943 if (real_size > PointerInfoType::MaxSize()) {
944 errno = ENOMEM;
945 return nullptr;
946 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800947
Christopher Ferris4da25032018-03-07 13:38:48 -0800948 void* pointer;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000949 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800950 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800951 // Need to guarantee the alignment of the header.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000952 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
953 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800954 if (header == nullptr) {
955 return nullptr;
956 }
957 memset(header, 0, g_dispatch->malloc_usable_size(header));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700958 pointer = InitHeader(header, header, size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800959 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000960 result = TCALL(calloc, 1, real_size);
961 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800962 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800963
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700964 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000965 g_debug->record->AddEntry(
Greg Kaiser23352132023-01-09 17:53:07 +0000966 new CallocEntry(pointer, nmemb, bytes, result.GetStartTimeNS(), result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700967 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800968
969 if (pointer != nullptr && g_debug->TrackPointers()) {
970 PointerData::Add(pointer, size);
971 }
Christopher Ferris7bd01782016-04-20 12:30:58 -0700972 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800973}
974
975struct mallinfo debug_mallinfo() {
976 return g_dispatch->mallinfo();
977}
978
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700979int debug_mallopt(int param, int value) {
980 return g_dispatch->mallopt(param, value);
981}
982
Christopher Ferris6c619a02019-03-01 17:59:51 -0800983int debug_malloc_info(int options, FILE* fp) {
984 if (DebugCallsDisabled() || !g_debug->TrackPointers()) {
985 return g_dispatch->malloc_info(options, fp);
986 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800987
988 // Make sure any pending output is written to the file.
989 fflush(fp);
990
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700991 ScopedConcurrentLock lock;
992 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700993 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris6c619a02019-03-01 17:59:51 -0800994
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800995 // Avoid any issues where allocations are made that will be freed
996 // in the fclose.
997 int fd = fileno(fp);
998 MallocXmlElem root(fd, "malloc", "version=\"debug-malloc-1\"");
Christopher Ferris6c619a02019-03-01 17:59:51 -0800999 std::vector<ListInfoType> list;
1000 PointerData::GetAllocList(&list);
1001
1002 size_t alloc_num = 0;
1003 for (size_t i = 0; i < list.size(); i++) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001004 MallocXmlElem alloc(fd, "allocation", "nr=\"%zu\"", alloc_num);
Christopher Ferris6c619a02019-03-01 17:59:51 -08001005
1006 size_t total = 1;
1007 size_t size = list[i].size;
1008 while (i < list.size() - 1 && list[i + 1].size == size) {
1009 i++;
1010 total++;
1011 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001012 MallocXmlElem(fd, "size").Contents("%zu", list[i].size);
1013 MallocXmlElem(fd, "total").Contents("%zu", total);
Christopher Ferris6c619a02019-03-01 17:59:51 -08001014 alloc_num++;
1015 }
1016 return 0;
1017}
1018
Christopher Ferriscae21a92018-02-05 18:14:55 -08001019void* debug_aligned_alloc(size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001020 Unreachable::CheckIfRequested(g_debug->config());
1021
Christopher Ferriscae21a92018-02-05 18:14:55 -08001022 if (DebugCallsDisabled()) {
1023 return g_dispatch->aligned_alloc(alignment, size);
1024 }
Christopher Ferrisa22f5d52019-03-01 16:40:59 -08001025 if (!powerof2(alignment) || (size % alignment) != 0) {
Christopher Ferriscae21a92018-02-05 18:14:55 -08001026 errno = EINVAL;
1027 return nullptr;
1028 }
1029 return debug_memalign(alignment, size);
1030}
1031
Christopher Ferris63860cb2015-11-16 17:30:32 -08001032int debug_posix_memalign(void** memptr, size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001033 Unreachable::CheckIfRequested(g_debug->config());
1034
Christopher Ferris63860cb2015-11-16 17:30:32 -08001035 if (DebugCallsDisabled()) {
1036 return g_dispatch->posix_memalign(memptr, alignment, size);
1037 }
1038
Christopher Ferris6c619a02019-03-01 17:59:51 -08001039 if (alignment < sizeof(void*) || !powerof2(alignment)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001040 return EINVAL;
1041 }
1042 int saved_errno = errno;
1043 *memptr = debug_memalign(alignment, size);
1044 errno = saved_errno;
1045 return (*memptr != nullptr) ? 0 : ENOMEM;
1046}
1047
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001048int debug_malloc_iterate(uintptr_t base, size_t size, void (*callback)(uintptr_t, size_t, void*),
Christopher Ferris4da25032018-03-07 13:38:48 -08001049 void* arg) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001050 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001051 if (g_debug->TrackPointers()) {
Christopher Ferrisf78486f2022-05-04 14:08:54 -07001052 PointerData::IteratePointers([&callback, &arg](uintptr_t pointer) {
1053 callback(pointer, InternalMallocUsableSize(reinterpret_cast<void*>(pointer)), arg);
1054 });
Christopher Ferris4da25032018-03-07 13:38:48 -08001055 return 0;
1056 }
Colin Cross869691c2016-01-29 12:48:18 -08001057
Christopher Ferris4da25032018-03-07 13:38:48 -08001058 // An option that adds a header will add pointer tracking, so no need to
1059 // check if headers are enabled.
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001060 return g_dispatch->malloc_iterate(base, size, callback, arg);
Colin Cross869691c2016-01-29 12:48:18 -08001061}
1062
1063void debug_malloc_disable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001064 ScopedConcurrentLock lock;
Colin Cross869691c2016-01-29 12:48:18 -08001065 g_dispatch->malloc_disable();
Christopher Ferris4da25032018-03-07 13:38:48 -08001066 if (g_debug->pointer) {
1067 g_debug->pointer->PrepareFork();
Colin Cross869691c2016-01-29 12:48:18 -08001068 }
1069}
1070
1071void debug_malloc_enable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001072 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001073 if (g_debug->pointer) {
1074 g_debug->pointer->PostForkParent();
Colin Cross869691c2016-01-29 12:48:18 -08001075 }
1076 g_dispatch->malloc_enable();
1077}
1078
Christopher Ferris4da25032018-03-07 13:38:48 -08001079ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t max_frames) {
Colin Cross2d4721c2016-02-02 11:57:54 -08001080 if (DebugCallsDisabled() || pointer == nullptr) {
1081 return 0;
1082 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001083 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -07001084 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001085 ScopedBacktraceSignalBlocker blocked;
Colin Cross2d4721c2016-02-02 11:57:54 -08001086
Christopher Ferris4da25032018-03-07 13:38:48 -08001087 if (!(g_debug->config().options() & BACKTRACE)) {
1088 return 0;
Colin Cross2d4721c2016-02-02 11:57:54 -08001089 }
Mitch Phillips3b21ada2020-01-07 15:47:47 -08001090 pointer = UntagPointer(pointer);
Christopher Ferris4da25032018-03-07 13:38:48 -08001091 return PointerData::GetFrames(pointer, frames, max_frames);
Colin Cross2d4721c2016-02-02 11:57:54 -08001092}
1093
Christopher Ferris63860cb2015-11-16 17:30:32 -08001094#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
1095void* debug_pvalloc(size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001096 Unreachable::CheckIfRequested(g_debug->config());
1097
Christopher Ferris63860cb2015-11-16 17:30:32 -08001098 if (DebugCallsDisabled()) {
1099 return g_dispatch->pvalloc(bytes);
1100 }
1101
1102 size_t pagesize = getpagesize();
Dan Alberta613d0d2017-10-05 16:39:33 -07001103 size_t size = __BIONIC_ALIGN(bytes, pagesize);
Christopher Ferris63860cb2015-11-16 17:30:32 -08001104 if (size < bytes) {
1105 // Overflow
1106 errno = ENOMEM;
1107 return nullptr;
1108 }
1109 return debug_memalign(pagesize, size);
1110}
1111
1112void* debug_valloc(size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001113 Unreachable::CheckIfRequested(g_debug->config());
1114
Christopher Ferris63860cb2015-11-16 17:30:32 -08001115 if (DebugCallsDisabled()) {
1116 return g_dispatch->valloc(size);
1117 }
1118 return debug_memalign(getpagesize(), size);
1119}
1120#endif
Christopher Ferris602b88c2017-08-04 13:04:04 -07001121
1122static std::mutex g_dump_lock;
1123
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001124static void write_dump(int fd) {
1125 dprintf(fd, "Android Native Heap Dump v1.2\n\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001126
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001127 std::string fingerprint = android::base::GetProperty("ro.build.fingerprint", "unknown");
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001128 dprintf(fd, "Build fingerprint: '%s'\n\n", fingerprint.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001129
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001130 PointerData::DumpLiveToFile(fd);
Christopher Ferris602b88c2017-08-04 13:04:04 -07001131
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001132 dprintf(fd, "MAPS\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001133 std::string content;
1134 if (!android::base::ReadFileToString("/proc/self/maps", &content)) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001135 dprintf(fd, "Could not open /proc/self/maps\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001136 } else {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001137 dprintf(fd, "%s", content.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001138 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001139 dprintf(fd, "END\n");
Christopher Ferrisaa3e5742023-01-31 01:31:52 +00001140
1141 // Purge the memory that was allocated and freed during this operation
1142 // since it can be large enough to expand the RSS significantly.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -07001143 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001144}
1145
1146bool debug_write_malloc_leak_info(FILE* fp) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001147 // Make sure any pending output is written to the file.
1148 fflush(fp);
1149
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001150 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001151 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001152 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001153
1154 std::lock_guard<std::mutex> guard(g_dump_lock);
1155
1156 if (!(g_debug->config().options() & BACKTRACE)) {
1157 return false;
1158 }
1159
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001160 write_dump(fileno(fp));
1161
Christopher Ferris602b88c2017-08-04 13:04:04 -07001162 return true;
1163}
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001164
1165void debug_dump_heap(const char* file_name) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001166 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001167 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001168 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001169
1170 std::lock_guard<std::mutex> guard(g_dump_lock);
1171
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001172 int fd = open(file_name, O_RDWR | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0644);
1173 if (fd == -1) {
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001174 error_log("Unable to create file: %s", file_name);
1175 return;
1176 }
1177
1178 error_log("Dumping to file: %s\n", file_name);
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001179 write_dump(fd);
1180 close(fd);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001181}