blob: b06ec9eebcaaa1a86317c2573ed980d8dfeb2037 [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 Ferrisb42e8b42022-05-09 14:00:47 -070056#include "Unreachable.h"
57#include "UnwindBacktrace.h"
Christopher Ferris4da25032018-03-07 13:38:48 -080058#include "backtrace.h"
Christopher Ferris63860cb2015-11-16 17:30:32 -080059#include "debug_disable.h"
60#include "debug_log.h"
61#include "malloc_debug.h"
62
63// ------------------------------------------------------------------------
64// Global Data
65// ------------------------------------------------------------------------
66DebugData* g_debug;
67
Christopher Ferris8189e772019-04-09 16:37:23 -070068bool* g_zygote_child;
Christopher Ferris63860cb2015-11-16 17:30:32 -080069
70const MallocDispatch* g_dispatch;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +000071
72static __always_inline uint64_t Nanotime() {
73 struct timespec t = {};
74 clock_gettime(CLOCK_MONOTONIC, &t);
75 return static_cast<uint64_t>(t.tv_sec) * 1000000000LL + t.tv_nsec;
76}
77
78namespace {
79// A TimedResult contains the result of from malloc end_ns al. functions and the
80// start/end timestamps.
81struct TimedResult {
82 uint64_t start_ns = 0;
83 uint64_t end_ns = 0;
84 union {
85 size_t s;
86 int i;
87 void* p;
88 } v;
89
90 uint64_t GetStartTimeNS() const { return start_ns; }
91 uint64_t GetEndTimeNS() const { return end_ns; }
92 void SetStartTimeNS(uint64_t t) { start_ns = t; }
93 void SetEndTimeNS(uint64_t t) { end_ns = t; }
94
95 template <typename T>
96 void setValue(T);
97 template <>
98 void setValue(size_t s) {
99 v.s = s;
100 }
101 template <>
102 void setValue(int i) {
103 v.i = i;
104 }
105 template <>
106 void setValue(void* p) {
107 v.p = p;
108 }
109
110 template <typename T>
111 T getValue() const;
112 template <>
113 size_t getValue<size_t>() const {
114 return v.s;
115 }
116 template <>
117 int getValue<int>() const {
118 return v.i;
119 }
120 template <>
121 void* getValue<void*>() const {
122 return v.p;
123 }
124};
125
126class ScopedTimer {
127 public:
128 ScopedTimer(TimedResult& res) : res_(res) { res_.start_ns = Nanotime(); }
129
130 ~ScopedTimer() { res_.end_ns = Nanotime(); }
131
132 private:
133 TimedResult& res_;
134};
135
136} // namespace
137
138template <typename MallocFn, typename... Args>
139static TimedResult TimerCall(MallocFn fn, Args... args) {
140 TimedResult ret;
141 decltype((g_dispatch->*fn)(args...)) r;
142 if (g_debug->config().options() & RECORD_ALLOCS) {
143 ScopedTimer t(ret);
144 r = (g_dispatch->*fn)(args...);
145 } else {
146 r = (g_dispatch->*fn)(args...);
147 }
148 ret.setValue<decltype(r)>(r);
149 return ret;
150}
151
152template <typename MallocFn, typename... Args>
153static TimedResult TimerCallVoid(MallocFn fn, Args... args) {
154 TimedResult ret;
155 {
156 ScopedTimer t(ret);
157 (g_dispatch->*fn)(args...);
158 }
159 return ret;
160}
161
162#define TCALL(FUNC, ...) TimerCall(&MallocDispatch::FUNC, __VA_ARGS__);
163#define TCALLVOID(FUNC, ...) TimerCallVoid(&MallocDispatch::FUNC, __VA_ARGS__);
164
Christopher Ferris63860cb2015-11-16 17:30:32 -0800165// ------------------------------------------------------------------------
166
167// ------------------------------------------------------------------------
168// Use C style prototypes for all exported functions. This makes it easy
169// to do dlsym lookups during libc initialization when malloc debug
170// is enabled.
171// ------------------------------------------------------------------------
172__BEGIN_DECLS
173
Christopher Ferris8189e772019-04-09 16:37:23 -0700174bool debug_initialize(const MallocDispatch* malloc_dispatch, bool* malloc_zygote_child,
Christopher Ferris4da25032018-03-07 13:38:48 -0800175 const char* options);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800176void debug_finalize();
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700177void debug_dump_heap(const char* file_name);
Christopher Ferris4da25032018-03-07 13:38:48 -0800178void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
179 size_t* total_memory, size_t* backtrace_size);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -0700180bool debug_write_malloc_leak_info(FILE* fp);
Colin Cross2d4721c2016-02-02 11:57:54 -0800181ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t frame_count);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800182void debug_free_malloc_leak_info(uint8_t* info);
183size_t debug_malloc_usable_size(void* pointer);
184void* debug_malloc(size_t size);
185void debug_free(void* pointer);
Christopher Ferriscae21a92018-02-05 18:14:55 -0800186void* debug_aligned_alloc(size_t alignment, size_t size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800187void* debug_memalign(size_t alignment, size_t bytes);
188void* debug_realloc(void* pointer, size_t bytes);
189void* debug_calloc(size_t nmemb, size_t bytes);
190struct mallinfo debug_mallinfo();
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700191int debug_mallopt(int param, int value);
Christopher Ferris6c619a02019-03-01 17:59:51 -0800192int debug_malloc_info(int options, FILE* fp);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800193int debug_posix_memalign(void** memptr, size_t alignment, size_t size);
Christopher Ferris6f517cd2019-11-08 11:28:38 -0800194int debug_malloc_iterate(uintptr_t base, size_t size,
195 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg);
Colin Cross869691c2016-01-29 12:48:18 -0800196void debug_malloc_disable();
197void debug_malloc_enable();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800198
199#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
200void* debug_pvalloc(size_t bytes);
201void* debug_valloc(size_t size);
202#endif
203
204__END_DECLS
205// ------------------------------------------------------------------------
206
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700207class ScopedConcurrentLock {
208 public:
209 ScopedConcurrentLock() {
210 pthread_rwlock_rdlock(&lock_);
211 }
212 ~ScopedConcurrentLock() {
213 pthread_rwlock_unlock(&lock_);
214 }
215
216 static void Init() {
217 pthread_rwlockattr_t attr;
218 // Set the attribute so that when a write lock is pending, read locks are no
219 // longer granted.
220 pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
221 pthread_rwlock_init(&lock_, &attr);
222 }
223
224 static void BlockAllOperations() {
225 pthread_rwlock_wrlock(&lock_);
226 }
227
228 private:
229 static pthread_rwlock_t lock_;
230};
231pthread_rwlock_t ScopedConcurrentLock::lock_;
232
Christopher Ferris9bf78172020-05-20 15:37:30 -0700233// Use this because the sigprocmask* functions filter out the reserved bionic
234// signals including the signal this code blocks.
235static inline int __rt_sigprocmask(int how, const sigset64_t* new_set, sigset64_t* old_set,
236 size_t sigset_size) {
237 return syscall(SYS_rt_sigprocmask, how, new_set, old_set, sigset_size);
238}
239
240// Need to block the backtrace signal while in malloc debug routines
241// otherwise there is a chance of a deadlock and timeout when unwinding.
242// This can occur if a thread is paused while owning a malloc debug
243// internal lock.
244class ScopedBacktraceSignalBlocker {
245 public:
246 ScopedBacktraceSignalBlocker() {
247 sigemptyset64(&backtrace_set_);
248 sigaddset64(&backtrace_set_, BIONIC_SIGNAL_BACKTRACE);
249 sigset64_t old_set;
250 __rt_sigprocmask(SIG_BLOCK, &backtrace_set_, &old_set, sizeof(backtrace_set_));
251 if (sigismember64(&old_set, BIONIC_SIGNAL_BACKTRACE)) {
252 unblock_ = false;
253 }
254 }
255
256 ~ScopedBacktraceSignalBlocker() {
257 if (unblock_) {
258 __rt_sigprocmask(SIG_UNBLOCK, &backtrace_set_, nullptr, sizeof(backtrace_set_));
259 }
260 }
261
262 private:
263 bool unblock_ = true;
264 sigset64_t backtrace_set_;
265};
266
Colin Cross7a28a3c2016-02-07 22:51:15 -0800267static void InitAtfork() {
268 static pthread_once_t atfork_init = PTHREAD_ONCE_INIT;
Christopher Ferris4da25032018-03-07 13:38:48 -0800269 pthread_once(&atfork_init, []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800270 pthread_atfork(
Christopher Ferris4da25032018-03-07 13:38:48 -0800271 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800272 if (g_debug != nullptr) {
273 g_debug->PrepareFork();
274 }
275 },
Christopher Ferris4da25032018-03-07 13:38:48 -0800276 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800277 if (g_debug != nullptr) {
278 g_debug->PostForkParent();
279 }
280 },
Christopher Ferris4da25032018-03-07 13:38:48 -0800281 []() {
Colin Cross7a28a3c2016-02-07 22:51:15 -0800282 if (g_debug != nullptr) {
283 g_debug->PostForkChild();
284 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800285 });
Colin Cross7a28a3c2016-02-07 22:51:15 -0800286 });
287}
Christopher Ferrisd0919622016-03-15 22:39:39 -0700288
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700289void BacktraceAndLog() {
290 if (g_debug->config().options() & BACKTRACE_FULL) {
291 std::vector<uintptr_t> frames;
Christopher Ferris459eecb2022-01-07 13:38:10 -0800292 std::vector<unwindstack::FrameData> frames_info;
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700293 if (!Unwind(&frames, &frames_info, 256)) {
294 error_log(" Backtrace failed to get any frames.");
295 } else {
296 UnwindLog(frames_info);
297 }
298 } else {
299 std::vector<uintptr_t> frames(256);
300 size_t num_frames = backtrace_get(frames.data(), frames.size());
301 if (num_frames == 0) {
302 error_log(" Backtrace failed to get any frames.");
303 } else {
304 backtrace_log(frames.data(), num_frames);
305 }
306 }
307}
308
Christopher Ferris4da25032018-03-07 13:38:48 -0800309static void LogError(const void* pointer, const char* error_str) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800310 error_log(LOG_DIVIDER);
Christopher Ferris4da25032018-03-07 13:38:48 -0800311 error_log("+++ ALLOCATION %p %s", pointer, error_str);
312
313 // If we are tracking already freed pointers, check to see if this is
314 // one so we can print extra information.
315 if (g_debug->config().options() & FREE_TRACK) {
316 PointerData::LogFreeBacktrace(pointer);
Christopher Ferris7993b802016-01-28 18:35:05 -0800317 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800318
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700319 error_log("Backtrace at time of failure:");
320 BacktraceAndLog();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800321 error_log(LOG_DIVIDER);
Iris Chang7f209a92019-01-16 11:17:15 +0800322 if (g_debug->config().options() & ABORT_ON_ERROR) {
323 abort();
324 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800325}
326
Christopher Ferris4da25032018-03-07 13:38:48 -0800327static bool VerifyPointer(const void* pointer, const char* function_name) {
328 if (g_debug->HeaderEnabled()) {
329 Header* header = g_debug->GetHeader(pointer);
330 if (header->tag != DEBUG_TAG) {
331 std::string error_str;
332 if (header->tag == DEBUG_FREE_TAG) {
333 error_str = std::string("USED AFTER FREE (") + function_name + ")";
334 } else {
335 error_str = android::base::StringPrintf("HAS INVALID TAG %" PRIx32 " (%s)", header->tag,
336 function_name);
337 }
338 LogError(pointer, error_str.c_str());
339 return false;
340 }
341 }
342
343 if (g_debug->TrackPointers()) {
344 if (!PointerData::Exists(pointer)) {
345 std::string error_str(std::string("UNKNOWN POINTER (") + function_name + ")");
346 LogError(pointer, error_str.c_str());
347 return false;
348 }
349 }
350 return true;
351}
352
353static size_t InternalMallocUsableSize(void* pointer) {
354 if (g_debug->HeaderEnabled()) {
355 return g_debug->GetHeader(pointer)->usable_size;
356 } else {
357 return g_dispatch->malloc_usable_size(pointer);
358 }
359}
360
Christopher Ferris63860cb2015-11-16 17:30:32 -0800361static void* InitHeader(Header* header, void* orig_pointer, size_t size) {
362 header->tag = DEBUG_TAG;
363 header->orig_pointer = orig_pointer;
364 header->size = size;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800365 header->usable_size = g_dispatch->malloc_usable_size(orig_pointer);
366 if (header->usable_size == 0) {
367 g_dispatch->free(orig_pointer);
368 return nullptr;
369 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800370 header->usable_size -= g_debug->pointer_offset() + reinterpret_cast<uintptr_t>(header) -
371 reinterpret_cast<uintptr_t>(orig_pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800372
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700373 if (g_debug->config().options() & FRONT_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800374 uint8_t* guard = g_debug->GetFrontGuard(header);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700375 memset(guard, g_debug->config().front_guard_value(), g_debug->config().front_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800376 }
377
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700378 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800379 uint8_t* guard = g_debug->GetRearGuard(header);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700380 memset(guard, g_debug->config().rear_guard_value(), g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800381 // If the rear guard is enabled, set the usable size to the exact size
382 // of the allocation.
Christopher Ferris4da25032018-03-07 13:38:48 -0800383 header->usable_size = header->size;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800384 }
385
386 return g_debug->GetPointer(header);
387}
388
Christopher Ferris705de3c2019-05-22 13:39:57 -0700389extern "C" void __asan_init() __attribute__((weak));
390
Christopher Ferris8189e772019-04-09 16:37:23 -0700391bool debug_initialize(const MallocDispatch* malloc_dispatch, bool* zygote_child,
Christopher Ferris4da25032018-03-07 13:38:48 -0800392 const char* options) {
Christopher Ferris8189e772019-04-09 16:37:23 -0700393 if (zygote_child == nullptr || options == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800394 return false;
395 }
Colin Cross7a28a3c2016-02-07 22:51:15 -0800396
Christopher Ferris705de3c2019-05-22 13:39:57 -0700397 if (__asan_init != 0) {
398 error_log("malloc debug cannot be enabled alongside ASAN");
399 return false;
400 }
401
Colin Cross7a28a3c2016-02-07 22:51:15 -0800402 InitAtfork();
403
Christopher Ferris8189e772019-04-09 16:37:23 -0700404 g_zygote_child = zygote_child;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800405
406 g_dispatch = malloc_dispatch;
407
408 if (!DebugDisableInitialize()) {
409 return false;
410 }
411
412 DebugData* debug = new DebugData();
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700413 if (!debug->Initialize(options) || !Unreachable::Initialize(debug->config())) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800414 delete debug;
415 DebugDisableFinalize();
416 return false;
417 }
418 g_debug = debug;
419
420 // Always enable the backtrace code since we will use it in a number
421 // of different error cases.
422 backtrace_startup();
423
Christopher Ferrisc328e442019-04-01 19:31:26 -0700424 if (g_debug->config().options() & VERBOSE) {
425 info_log("%s: malloc debug enabled", getprogname());
426 }
427
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700428 ScopedConcurrentLock::Init();
429
Christopher Ferris63860cb2015-11-16 17:30:32 -0800430 return true;
431}
432
433void debug_finalize() {
434 if (g_debug == nullptr) {
435 return;
436 }
437
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700438 // Make sure that there are no other threads doing debug allocations
439 // before we kill everything.
440 ScopedConcurrentLock::BlockAllOperations();
441
Christopher Ferris97b47472018-07-10 14:45:24 -0700442 // Turn off capturing allocations calls.
443 DebugDisableSet(true);
444
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700445 if (g_debug->config().options() & FREE_TRACK) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800446 PointerData::VerifyAllFreed();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800447 }
448
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700449 if (g_debug->config().options() & LEAK_TRACK) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800450 PointerData::LogLeaks();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800451 }
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
Colin Cross2c759912016-02-05 16:17:39 -0800459 backtrace_shutdown();
460
Christopher Ferris33d73372021-07-02 15:46:18 -0700461 // In order to prevent any issues of threads freeing previous pointers
462 // after the main thread calls this code, simply leak the g_debug pointer
463 // and do not destroy the debug disable pthread key.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800464}
465
Christopher Ferris4da25032018-03-07 13:38:48 -0800466void debug_get_malloc_leak_info(uint8_t** info, size_t* overall_size, size_t* info_size,
467 size_t* total_memory, size_t* backtrace_size) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700468 ScopedConcurrentLock lock;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800469 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700470 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800471
472 // Verify the arguments.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700473 if (info == nullptr || overall_size == nullptr || info_size == nullptr || total_memory == nullptr ||
Christopher Ferris4da25032018-03-07 13:38:48 -0800474 backtrace_size == nullptr) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800475 error_log("get_malloc_leak_info: At least one invalid parameter.");
476 return;
477 }
478
479 *info = nullptr;
480 *overall_size = 0;
481 *info_size = 0;
482 *total_memory = 0;
483 *backtrace_size = 0;
484
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700485 if (!(g_debug->config().options() & BACKTRACE)) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800486 error_log(
487 "get_malloc_leak_info: Allocations not being tracked, to enable "
488 "set the option 'backtrace'.");
Christopher Ferris63860cb2015-11-16 17:30:32 -0800489 return;
490 }
491
Christopher Ferris4da25032018-03-07 13:38:48 -0800492 PointerData::GetInfo(info, overall_size, info_size, total_memory, backtrace_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800493}
494
495void debug_free_malloc_leak_info(uint8_t* info) {
496 g_dispatch->free(info);
Christopher Ferrisaa3e5742023-01-31 01:31:52 +0000497 // Purge the memory that was freed since a significant amount of
498 // memory could have been allocated and freed.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -0700499 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800500}
501
Christopher Ferris55a89a42016-04-07 17:14:53 -0700502size_t debug_malloc_usable_size(void* pointer) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700503 Unreachable::CheckIfRequested(g_debug->config());
504
Christopher Ferris55a89a42016-04-07 17:14:53 -0700505 if (DebugCallsDisabled() || pointer == nullptr) {
506 return g_dispatch->malloc_usable_size(pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800507 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700508 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700509 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700510 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800511
Christopher Ferris4da25032018-03-07 13:38:48 -0800512 if (!VerifyPointer(pointer, "malloc_usable_size")) {
513 return 0;
514 }
515
516 return InternalMallocUsableSize(pointer);
Christopher Ferris55a89a42016-04-07 17:14:53 -0700517}
518
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000519static TimedResult InternalMalloc(size_t size) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800520 if ((g_debug->config().options() & BACKTRACE) && g_debug->pointer->ShouldDumpAndReset()) {
521 debug_dump_heap(android::base::StringPrintf(
522 "%s.%d.txt", g_debug->config().backtrace_dump_prefix().c_str(), getpid())
523 .c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700524 }
525
Colin Cross9567c7b2016-03-09 17:56:14 -0800526 if (size == 0) {
527 size = 1;
528 }
529
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000530 TimedResult result;
531
Christopher Ferris63860cb2015-11-16 17:30:32 -0800532 size_t real_size = size + g_debug->extra_bytes();
533 if (real_size < size) {
534 // Overflow.
535 errno = ENOMEM;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000536 result.setValue<void*>(nullptr);
537 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800538 }
539
Christopher Ferris4da25032018-03-07 13:38:48 -0800540 if (size > PointerInfoType::MaxSize()) {
541 errno = ENOMEM;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000542 result.setValue<void*>(nullptr);
543 return result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800544 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800545
Christopher Ferris4da25032018-03-07 13:38:48 -0800546 if (g_debug->HeaderEnabled()) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000547 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
548 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800549 if (header == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000550 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800551 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000552 result.setValue<void*>(InitHeader(header, header, size));
Christopher Ferris63860cb2015-11-16 17:30:32 -0800553 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000554 result = TCALL(malloc, real_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800555 }
556
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000557 void* pointer = result.getValue<void*>();
558
Christopher Ferris4da25032018-03-07 13:38:48 -0800559 if (pointer != nullptr) {
560 if (g_debug->TrackPointers()) {
561 PointerData::Add(pointer, size);
562 }
563
564 if (g_debug->config().options() & FILL_ON_ALLOC) {
565 size_t bytes = InternalMallocUsableSize(pointer);
566 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
567 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
568 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
569 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800570 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000571
572 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800573}
574
Christopher Ferris55a89a42016-04-07 17:14:53 -0700575void* debug_malloc(size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700576 Unreachable::CheckIfRequested(g_debug->config());
577
Christopher Ferris55a89a42016-04-07 17:14:53 -0700578 if (DebugCallsDisabled()) {
579 return g_dispatch->malloc(size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800580 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700581 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700582 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700583 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800584
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000585 TimedResult result = InternalMalloc(size);
Christopher Ferris7bd01782016-04-20 12:30:58 -0700586
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700587 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000588 g_debug->record->AddEntry(new MallocEntry(result.getValue<void*>(), size,
589 result.GetStartTimeNS(), result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700590 }
591
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000592 return result.getValue<void*>();
Christopher Ferris55a89a42016-04-07 17:14:53 -0700593}
594
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000595static TimedResult InternalFree(void* pointer) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800596 if ((g_debug->config().options() & BACKTRACE) && g_debug->pointer->ShouldDumpAndReset()) {
597 debug_dump_heap(android::base::StringPrintf(
598 "%s.%d.txt", g_debug->config().backtrace_dump_prefix().c_str(), getpid())
599 .c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -0700600 }
601
Christopher Ferris63860cb2015-11-16 17:30:32 -0800602 void* free_pointer = pointer;
603 size_t bytes;
Christopher Ferrisd0919622016-03-15 22:39:39 -0700604 Header* header;
Christopher Ferris4da25032018-03-07 13:38:48 -0800605 if (g_debug->HeaderEnabled()) {
Christopher Ferrisd0919622016-03-15 22:39:39 -0700606 header = g_debug->GetHeader(pointer);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800607 free_pointer = header->orig_pointer;
608
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700609 if (g_debug->config().options() & FRONT_GUARD) {
Christopher Ferris55a89a42016-04-07 17:14:53 -0700610 if (!g_debug->front_guard->Valid(header)) {
611 g_debug->front_guard->LogFailure(header);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800612 }
613 }
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700614 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris55a89a42016-04-07 17:14:53 -0700615 if (!g_debug->rear_guard->Valid(header)) {
616 g_debug->rear_guard->LogFailure(header);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800617 }
618 }
619
Christopher Ferris7993b802016-01-28 18:35:05 -0800620 header->tag = DEBUG_FREE_TAG;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800621
622 bytes = header->usable_size;
623 } else {
624 bytes = g_dispatch->malloc_usable_size(pointer);
625 }
626
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700627 if (g_debug->config().options() & FILL_ON_FREE) {
628 size_t fill_bytes = g_debug->config().fill_on_free_bytes();
Christopher Ferrisa3836482022-05-13 12:09:39 -0700629 fill_bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
630 memset(pointer, g_debug->config().fill_free_value(), fill_bytes);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800631 }
632
Christopher Ferris4da25032018-03-07 13:38:48 -0800633 if (g_debug->TrackPointers()) {
634 PointerData::Remove(pointer);
635 }
636
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000637 TimedResult result;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700638 if (g_debug->config().options() & FREE_TRACK) {
Christopher Ferrisd0919622016-03-15 22:39:39 -0700639 // Do not add the allocation until we are done modifying the pointer
640 // itself. This avoids a race if a lot of threads are all doing
641 // frees at the same time and we wind up trying to really free this
642 // pointer from another thread, while still trying to free it in
643 // this function.
Christopher Ferrisa3836482022-05-13 12:09:39 -0700644 pointer = PointerData::AddFreed(pointer, bytes);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000645 if (pointer != nullptr && g_debug->HeaderEnabled()) {
646 pointer = g_debug->GetHeader(pointer)->orig_pointer;
Christopher Ferris4da25032018-03-07 13:38:48 -0800647 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000648 result = TCALLVOID(free, pointer);
Christopher Ferrisd0919622016-03-15 22:39:39 -0700649 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000650 result = TCALLVOID(free, free_pointer);
Christopher Ferrisd0919622016-03-15 22:39:39 -0700651 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000652
653 return result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800654}
655
Christopher Ferris55a89a42016-04-07 17:14:53 -0700656void debug_free(void* pointer) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700657 Unreachable::CheckIfRequested(g_debug->config());
658
Christopher Ferris55a89a42016-04-07 17:14:53 -0700659 if (DebugCallsDisabled() || pointer == nullptr) {
660 return g_dispatch->free(pointer);
661 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700662 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700663 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700664 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700665
Christopher Ferris4da25032018-03-07 13:38:48 -0800666 if (!VerifyPointer(pointer, "free")) {
667 return;
668 }
669
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000670 TimedResult result = InternalFree(pointer);
671
672 if (g_debug->config().options() & RECORD_ALLOCS) {
673 g_debug->record->AddEntry(
674 new FreeEntry(pointer, result.GetStartTimeNS(), result.GetEndTimeNS()));
675 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700676}
677
Christopher Ferris63860cb2015-11-16 17:30:32 -0800678void* debug_memalign(size_t alignment, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700679 Unreachable::CheckIfRequested(g_debug->config());
680
Christopher Ferris63860cb2015-11-16 17:30:32 -0800681 if (DebugCallsDisabled()) {
682 return g_dispatch->memalign(alignment, bytes);
683 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700684 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700685 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700686 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800687
Colin Cross9567c7b2016-03-09 17:56:14 -0800688 if (bytes == 0) {
689 bytes = 1;
690 }
691
Christopher Ferris4da25032018-03-07 13:38:48 -0800692 if (bytes > PointerInfoType::MaxSize()) {
693 errno = ENOMEM;
694 return nullptr;
695 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800696
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000697 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800698 void* pointer;
699 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800700 // Make the alignment a power of two.
701 if (!powerof2(alignment)) {
702 alignment = BIONIC_ROUND_UP_POWER_OF_2(alignment);
703 }
Christopher Ferris72df6702016-02-11 15:51:31 -0800704 // Force the alignment to at least MINIMUM_ALIGNMENT_BYTES to guarantee
Christopher Ferris63860cb2015-11-16 17:30:32 -0800705 // that the header is aligned properly.
Christopher Ferris72df6702016-02-11 15:51:31 -0800706 if (alignment < MINIMUM_ALIGNMENT_BYTES) {
707 alignment = MINIMUM_ALIGNMENT_BYTES;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800708 }
709
710 // We don't have any idea what the natural alignment of
711 // the underlying native allocator is, so we always need to
712 // over allocate.
713 size_t real_size = alignment + bytes + g_debug->extra_bytes();
714 if (real_size < bytes) {
715 // Overflow.
716 errno = ENOMEM;
717 return nullptr;
718 }
719
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000720 result = TCALL(malloc, real_size);
721 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800722 if (pointer == nullptr) {
723 return nullptr;
724 }
725
726 uintptr_t value = reinterpret_cast<uintptr_t>(pointer) + g_debug->pointer_offset();
727 // Now align the pointer.
728 value += (-value % alignment);
729
730 Header* header = g_debug->GetHeader(reinterpret_cast<void*>(value));
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000731 // Don't need to update `result` here because we only need the timestamps.
Christopher Ferris63860cb2015-11-16 17:30:32 -0800732 pointer = InitHeader(header, pointer, bytes);
733 } else {
734 size_t real_size = bytes + g_debug->extra_bytes();
735 if (real_size < bytes) {
736 // Overflow.
737 errno = ENOMEM;
738 return nullptr;
739 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000740 result = TCALL(memalign, alignment, real_size);
741 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800742 }
743
Christopher Ferris4da25032018-03-07 13:38:48 -0800744 if (pointer != nullptr) {
745 if (g_debug->TrackPointers()) {
746 PointerData::Add(pointer, bytes);
747 }
Christopher Ferris55a89a42016-04-07 17:14:53 -0700748
Christopher Ferris4da25032018-03-07 13:38:48 -0800749 if (g_debug->config().options() & FILL_ON_ALLOC) {
750 size_t bytes = InternalMallocUsableSize(pointer);
751 size_t fill_bytes = g_debug->config().fill_on_alloc_bytes();
752 bytes = (bytes < fill_bytes) ? bytes : fill_bytes;
753 memset(pointer, g_debug->config().fill_alloc_value(), bytes);
754 }
755
756 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000757 g_debug->record->AddEntry(new MemalignEntry(pointer, bytes, alignment,
758 result.GetStartTimeNS(), result.GetEndTimeNS()));
Christopher Ferris4da25032018-03-07 13:38:48 -0800759 }
Christopher Ferris7bd01782016-04-20 12:30:58 -0700760 }
761
Christopher Ferris63860cb2015-11-16 17:30:32 -0800762 return pointer;
763}
764
765void* debug_realloc(void* pointer, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700766 Unreachable::CheckIfRequested(g_debug->config());
767
Christopher Ferris63860cb2015-11-16 17:30:32 -0800768 if (DebugCallsDisabled()) {
769 return g_dispatch->realloc(pointer, bytes);
770 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700771 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700772 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700773 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800774
775 if (pointer == nullptr) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000776 TimedResult result = InternalMalloc(bytes);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700777 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000778 g_debug->record->AddEntry(new ReallocEntry(result.getValue<void*>(), bytes, nullptr,
779 result.GetStartTimeNS(), result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700780 }
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000781 pointer = result.getValue<void*>();
Christopher Ferris7bd01782016-04-20 12:30:58 -0700782 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800783 }
784
Christopher Ferris4da25032018-03-07 13:38:48 -0800785 if (!VerifyPointer(pointer, "realloc")) {
786 return nullptr;
787 }
788
Christopher Ferris63860cb2015-11-16 17:30:32 -0800789 if (bytes == 0) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000790 TimedResult result = InternalFree(pointer);
791
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700792 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000793 g_debug->record->AddEntry(new ReallocEntry(nullptr, bytes, pointer, result.GetStartTimeNS(),
794 result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700795 }
796
Christopher Ferris63860cb2015-11-16 17:30:32 -0800797 return nullptr;
798 }
799
800 size_t real_size = bytes;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700801 if (g_debug->config().options() & EXPAND_ALLOC) {
802 real_size += g_debug->config().expand_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800803 if (real_size < bytes) {
804 // Overflow.
805 errno = ENOMEM;
806 return nullptr;
807 }
808 }
809
Christopher Ferris4da25032018-03-07 13:38:48 -0800810 if (bytes > PointerInfoType::MaxSize()) {
811 errno = ENOMEM;
812 return nullptr;
813 }
814
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000815 TimedResult result;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800816 void* new_pointer;
817 size_t prev_size;
Christopher Ferris4da25032018-03-07 13:38:48 -0800818 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800819 // Same size, do nothing.
Christopher Ferris4da25032018-03-07 13:38:48 -0800820 Header* header = g_debug->GetHeader(pointer);
821 if (real_size == header->size) {
822 if (g_debug->TrackPointers()) {
823 // Remove and re-add so that the backtrace is updated.
824 PointerData::Remove(pointer);
825 PointerData::Add(pointer, real_size);
826 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800827 return pointer;
828 }
829
830 // Allocation is shrinking.
831 if (real_size < header->usable_size) {
832 header->size = real_size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700833 if (g_debug->config().options() & REAR_GUARD) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800834 // Don't bother allocating a smaller pointer in this case, simply
835 // change the header usable_size and reset the rear guard.
Christopher Ferris4da25032018-03-07 13:38:48 -0800836 header->usable_size = header->size;
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700837 memset(g_debug->GetRearGuard(header), g_debug->config().rear_guard_value(),
838 g_debug->config().rear_guard_bytes());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800839 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800840 if (g_debug->TrackPointers()) {
841 // Remove and re-add so that the backtrace is updated.
842 PointerData::Remove(pointer);
843 PointerData::Add(pointer, real_size);
844 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800845 return pointer;
846 }
847
848 // Allocate the new size.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000849 result = InternalMalloc(bytes);
850 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800851 if (new_pointer == nullptr) {
852 errno = ENOMEM;
853 return nullptr;
854 }
855
856 prev_size = header->usable_size;
857 memcpy(new_pointer, pointer, prev_size);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000858 TimedResult free_time = InternalFree(pointer);
859 // `realloc` is split into two steps, update the end time to the finish time
860 // of the second operation.
861 result.SetEndTimeNS(free_time.GetEndTimeNS());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800862 } else {
Christopher Ferris4da25032018-03-07 13:38:48 -0800863 if (g_debug->TrackPointers()) {
864 PointerData::Remove(pointer);
865 }
866
Christopher Ferris63860cb2015-11-16 17:30:32 -0800867 prev_size = g_dispatch->malloc_usable_size(pointer);
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000868 result = TCALL(realloc, pointer, real_size);
869 new_pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800870 if (new_pointer == nullptr) {
871 return nullptr;
872 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800873
874 if (g_debug->TrackPointers()) {
875 PointerData::Add(new_pointer, real_size);
876 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800877 }
878
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700879 if (g_debug->config().options() & FILL_ON_ALLOC) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800880 size_t bytes = InternalMallocUsableSize(new_pointer);
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700881 if (bytes > g_debug->config().fill_on_alloc_bytes()) {
882 bytes = g_debug->config().fill_on_alloc_bytes();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800883 }
884 if (bytes > prev_size) {
885 memset(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(new_pointer) + prev_size),
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700886 g_debug->config().fill_alloc_value(), bytes - prev_size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800887 }
888 }
889
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700890 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000891 g_debug->record->AddEntry(new ReallocEntry(new_pointer, bytes, pointer, result.GetStartTimeNS(),
892 result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700893 }
894
Christopher Ferris63860cb2015-11-16 17:30:32 -0800895 return new_pointer;
896}
897
898void* debug_calloc(size_t nmemb, size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -0700899 Unreachable::CheckIfRequested(g_debug->config());
900
Christopher Ferris63860cb2015-11-16 17:30:32 -0800901 if (DebugCallsDisabled()) {
902 return g_dispatch->calloc(nmemb, bytes);
903 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700904 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -0700905 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700906 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800907
Colin Cross7877df62016-03-10 13:01:27 -0800908 size_t size;
909 if (__builtin_mul_overflow(nmemb, bytes, &size)) {
910 // Overflow
911 errno = ENOMEM;
912 return nullptr;
913 }
914
Colin Cross9567c7b2016-03-09 17:56:14 -0800915 if (size == 0) {
916 size = 1;
917 }
918
Colin Cross7877df62016-03-10 13:01:27 -0800919 size_t real_size;
920 if (__builtin_add_overflow(size, g_debug->extra_bytes(), &real_size)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800921 // Overflow.
922 errno = ENOMEM;
923 return nullptr;
924 }
925
Christopher Ferris4da25032018-03-07 13:38:48 -0800926 if (real_size > PointerInfoType::MaxSize()) {
927 errno = ENOMEM;
928 return nullptr;
929 }
Christopher Ferris63860cb2015-11-16 17:30:32 -0800930
Christopher Ferris4da25032018-03-07 13:38:48 -0800931 void* pointer;
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000932 TimedResult result;
Christopher Ferris4da25032018-03-07 13:38:48 -0800933 if (g_debug->HeaderEnabled()) {
Christopher Ferris63860cb2015-11-16 17:30:32 -0800934 // Need to guarantee the alignment of the header.
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000935 result = TCALL(memalign, MINIMUM_ALIGNMENT_BYTES, real_size);
936 Header* header = reinterpret_cast<Header*>(result.getValue<void*>());
Christopher Ferris63860cb2015-11-16 17:30:32 -0800937 if (header == nullptr) {
938 return nullptr;
939 }
940 memset(header, 0, g_dispatch->malloc_usable_size(header));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700941 pointer = InitHeader(header, header, size);
Christopher Ferris63860cb2015-11-16 17:30:32 -0800942 } else {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000943 result = TCALL(calloc, 1, real_size);
944 pointer = result.getValue<void*>();
Christopher Ferris63860cb2015-11-16 17:30:32 -0800945 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800946
Christopher Ferris2b2b25b2017-04-05 19:13:03 -0700947 if (g_debug->config().options() & RECORD_ALLOCS) {
Chia-hung Duanf7e8b172022-11-01 21:37:56 +0000948 g_debug->record->AddEntry(
Greg Kaiser23352132023-01-09 17:53:07 +0000949 new CallocEntry(pointer, nmemb, bytes, result.GetStartTimeNS(), result.GetEndTimeNS()));
Christopher Ferris7bd01782016-04-20 12:30:58 -0700950 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800951
952 if (pointer != nullptr && g_debug->TrackPointers()) {
953 PointerData::Add(pointer, size);
954 }
Christopher Ferris7bd01782016-04-20 12:30:58 -0700955 return pointer;
Christopher Ferris63860cb2015-11-16 17:30:32 -0800956}
957
958struct mallinfo debug_mallinfo() {
959 return g_dispatch->mallinfo();
960}
961
Christopher Ferrisa1c0d2f2017-05-15 15:50:19 -0700962int debug_mallopt(int param, int value) {
963 return g_dispatch->mallopt(param, value);
964}
965
Christopher Ferris6c619a02019-03-01 17:59:51 -0800966int debug_malloc_info(int options, FILE* fp) {
967 if (DebugCallsDisabled() || !g_debug->TrackPointers()) {
968 return g_dispatch->malloc_info(options, fp);
969 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800970
971 // Make sure any pending output is written to the file.
972 fflush(fp);
973
Christopher Ferrisd269fcc2019-05-06 19:03:59 -0700974 ScopedConcurrentLock lock;
975 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -0700976 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris6c619a02019-03-01 17:59:51 -0800977
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800978 // Avoid any issues where allocations are made that will be freed
979 // in the fclose.
980 int fd = fileno(fp);
981 MallocXmlElem root(fd, "malloc", "version=\"debug-malloc-1\"");
Christopher Ferris6c619a02019-03-01 17:59:51 -0800982 std::vector<ListInfoType> list;
983 PointerData::GetAllocList(&list);
984
985 size_t alloc_num = 0;
986 for (size_t i = 0; i < list.size(); i++) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800987 MallocXmlElem alloc(fd, "allocation", "nr=\"%zu\"", alloc_num);
Christopher Ferris6c619a02019-03-01 17:59:51 -0800988
989 size_t total = 1;
990 size_t size = list[i].size;
991 while (i < list.size() - 1 && list[i + 1].size == size) {
992 i++;
993 total++;
994 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800995 MallocXmlElem(fd, "size").Contents("%zu", list[i].size);
996 MallocXmlElem(fd, "total").Contents("%zu", total);
Christopher Ferris6c619a02019-03-01 17:59:51 -0800997 alloc_num++;
998 }
999 return 0;
1000}
1001
Christopher Ferriscae21a92018-02-05 18:14:55 -08001002void* debug_aligned_alloc(size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001003 Unreachable::CheckIfRequested(g_debug->config());
1004
Christopher Ferriscae21a92018-02-05 18:14:55 -08001005 if (DebugCallsDisabled()) {
1006 return g_dispatch->aligned_alloc(alignment, size);
1007 }
Christopher Ferrisa22f5d52019-03-01 16:40:59 -08001008 if (!powerof2(alignment) || (size % alignment) != 0) {
Christopher Ferriscae21a92018-02-05 18:14:55 -08001009 errno = EINVAL;
1010 return nullptr;
1011 }
1012 return debug_memalign(alignment, size);
1013}
1014
Christopher Ferris63860cb2015-11-16 17:30:32 -08001015int debug_posix_memalign(void** memptr, size_t alignment, size_t size) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001016 Unreachable::CheckIfRequested(g_debug->config());
1017
Christopher Ferris63860cb2015-11-16 17:30:32 -08001018 if (DebugCallsDisabled()) {
1019 return g_dispatch->posix_memalign(memptr, alignment, size);
1020 }
1021
Christopher Ferris6c619a02019-03-01 17:59:51 -08001022 if (alignment < sizeof(void*) || !powerof2(alignment)) {
Christopher Ferris63860cb2015-11-16 17:30:32 -08001023 return EINVAL;
1024 }
1025 int saved_errno = errno;
1026 *memptr = debug_memalign(alignment, size);
1027 errno = saved_errno;
1028 return (*memptr != nullptr) ? 0 : ENOMEM;
1029}
1030
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001031int debug_malloc_iterate(uintptr_t base, size_t size, void (*callback)(uintptr_t, size_t, void*),
Christopher Ferris4da25032018-03-07 13:38:48 -08001032 void* arg) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001033 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001034 if (g_debug->TrackPointers()) {
Christopher Ferrisf78486f2022-05-04 14:08:54 -07001035 PointerData::IteratePointers([&callback, &arg](uintptr_t pointer) {
1036 callback(pointer, InternalMallocUsableSize(reinterpret_cast<void*>(pointer)), arg);
1037 });
Christopher Ferris4da25032018-03-07 13:38:48 -08001038 return 0;
1039 }
Colin Cross869691c2016-01-29 12:48:18 -08001040
Christopher Ferris4da25032018-03-07 13:38:48 -08001041 // An option that adds a header will add pointer tracking, so no need to
1042 // check if headers are enabled.
Christopher Ferris6f517cd2019-11-08 11:28:38 -08001043 return g_dispatch->malloc_iterate(base, size, callback, arg);
Colin Cross869691c2016-01-29 12:48:18 -08001044}
1045
1046void debug_malloc_disable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001047 ScopedConcurrentLock lock;
Colin Cross869691c2016-01-29 12:48:18 -08001048 g_dispatch->malloc_disable();
Christopher Ferris4da25032018-03-07 13:38:48 -08001049 if (g_debug->pointer) {
1050 g_debug->pointer->PrepareFork();
Colin Cross869691c2016-01-29 12:48:18 -08001051 }
1052}
1053
1054void debug_malloc_enable() {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001055 ScopedConcurrentLock lock;
Christopher Ferris4da25032018-03-07 13:38:48 -08001056 if (g_debug->pointer) {
1057 g_debug->pointer->PostForkParent();
Colin Cross869691c2016-01-29 12:48:18 -08001058 }
1059 g_dispatch->malloc_enable();
1060}
1061
Christopher Ferris4da25032018-03-07 13:38:48 -08001062ssize_t debug_malloc_backtrace(void* pointer, uintptr_t* frames, size_t max_frames) {
Colin Cross2d4721c2016-02-02 11:57:54 -08001063 if (DebugCallsDisabled() || pointer == nullptr) {
1064 return 0;
1065 }
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001066 ScopedConcurrentLock lock;
Christopher Ferris55a89a42016-04-07 17:14:53 -07001067 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001068 ScopedBacktraceSignalBlocker blocked;
Colin Cross2d4721c2016-02-02 11:57:54 -08001069
Christopher Ferris4da25032018-03-07 13:38:48 -08001070 if (!(g_debug->config().options() & BACKTRACE)) {
1071 return 0;
Colin Cross2d4721c2016-02-02 11:57:54 -08001072 }
Mitch Phillips3b21ada2020-01-07 15:47:47 -08001073 pointer = UntagPointer(pointer);
Christopher Ferris4da25032018-03-07 13:38:48 -08001074 return PointerData::GetFrames(pointer, frames, max_frames);
Colin Cross2d4721c2016-02-02 11:57:54 -08001075}
1076
Christopher Ferris63860cb2015-11-16 17:30:32 -08001077#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
1078void* debug_pvalloc(size_t bytes) {
Christopher Ferrisb42e8b42022-05-09 14:00:47 -07001079 Unreachable::CheckIfRequested(g_debug->config());
1080
Christopher Ferris63860cb2015-11-16 17:30:32 -08001081 if (DebugCallsDisabled()) {
1082 return g_dispatch->pvalloc(bytes);
1083 }
1084
1085 size_t pagesize = getpagesize();
Dan Alberta613d0d2017-10-05 16:39:33 -07001086 size_t size = __BIONIC_ALIGN(bytes, pagesize);
Christopher Ferris63860cb2015-11-16 17:30:32 -08001087 if (size < bytes) {
1088 // Overflow
1089 errno = ENOMEM;
1090 return nullptr;
1091 }
1092 return debug_memalign(pagesize, size);
1093}
1094
1095void* debug_valloc(size_t size) {
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->valloc(size);
1100 }
1101 return debug_memalign(getpagesize(), size);
1102}
1103#endif
Christopher Ferris602b88c2017-08-04 13:04:04 -07001104
1105static std::mutex g_dump_lock;
1106
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001107static void write_dump(int fd) {
1108 dprintf(fd, "Android Native Heap Dump v1.2\n\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001109
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001110 std::string fingerprint = android::base::GetProperty("ro.build.fingerprint", "unknown");
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001111 dprintf(fd, "Build fingerprint: '%s'\n\n", fingerprint.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001112
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001113 PointerData::DumpLiveToFile(fd);
Christopher Ferris602b88c2017-08-04 13:04:04 -07001114
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001115 dprintf(fd, "MAPS\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001116 std::string content;
1117 if (!android::base::ReadFileToString("/proc/self/maps", &content)) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001118 dprintf(fd, "Could not open /proc/self/maps\n");
Christopher Ferris602b88c2017-08-04 13:04:04 -07001119 } else {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001120 dprintf(fd, "%s", content.c_str());
Christopher Ferris602b88c2017-08-04 13:04:04 -07001121 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001122 dprintf(fd, "END\n");
Christopher Ferrisaa3e5742023-01-31 01:31:52 +00001123
1124 // Purge the memory that was allocated and freed during this operation
1125 // since it can be large enough to expand the RSS significantly.
Christopher Ferrisf1ab9c42023-03-22 13:47:27 -07001126 g_dispatch->mallopt(M_PURGE_ALL, 0);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001127}
1128
1129bool debug_write_malloc_leak_info(FILE* fp) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001130 // Make sure any pending output is written to the file.
1131 fflush(fp);
1132
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001133 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001134 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001135 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001136
1137 std::lock_guard<std::mutex> guard(g_dump_lock);
1138
1139 if (!(g_debug->config().options() & BACKTRACE)) {
1140 return false;
1141 }
1142
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001143 write_dump(fileno(fp));
1144
Christopher Ferris602b88c2017-08-04 13:04:04 -07001145 return true;
1146}
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001147
1148void debug_dump_heap(const char* file_name) {
Christopher Ferrisd269fcc2019-05-06 19:03:59 -07001149 ScopedConcurrentLock lock;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001150 ScopedDisableDebugCalls disable;
Christopher Ferris9bf78172020-05-20 15:37:30 -07001151 ScopedBacktraceSignalBlocker blocked;
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001152
1153 std::lock_guard<std::mutex> guard(g_dump_lock);
1154
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001155 int fd = open(file_name, O_RDWR | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0644);
1156 if (fd == -1) {
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001157 error_log("Unable to create file: %s", file_name);
1158 return;
1159 }
1160
1161 error_log("Dumping to file: %s\n", file_name);
Christopher Ferrisff88fb02019-11-04 18:40:00 -08001162 write_dump(fd);
1163 close(fd);
Christopher Ferris2e1a40a2018-06-13 10:46:34 -07001164}