blob: 5ab2232f2825a55203335590c7741cbf82120a6f [file] [log] [blame]
Christopher Ferris4da25032018-03-07 13:38:48 -08001/*
2 * Copyright (C) 2015 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 <signal.h>
32#include <stdint.h>
33#include <stdlib.h>
34#include <string.h>
35#include <sys/types.h>
36#include <unistd.h>
37
Christopher Ferrisf78486f2022-05-04 14:08:54 -070038#include <functional>
Christopher Ferris4da25032018-03-07 13:38:48 -080039#include <mutex>
40#include <string>
41#include <unordered_map>
42#include <utility>
43#include <vector>
44
45#include <android-base/stringprintf.h>
46#include <android-base/thread_annotations.h>
Josh Gao4956c372019-12-19 16:35:51 -080047#include <platform/bionic/macros.h>
Christopher Ferris4da25032018-03-07 13:38:48 -080048
49#include "Config.h"
50#include "DebugData.h"
51#include "PointerData.h"
52#include "backtrace.h"
53#include "debug_log.h"
54#include "malloc_debug.h"
Christopher Ferris93bdd6a2018-04-05 11:12:38 -070055#include "UnwindBacktrace.h"
Christopher Ferris4da25032018-03-07 13:38:48 -080056
Christopher Ferris9782b872019-07-18 13:36:50 -070057extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
58
Christopher Ferris4da25032018-03-07 13:38:48 -080059std::atomic_uint8_t PointerData::backtrace_enabled_;
60std::atomic_bool PointerData::backtrace_dump_;
61
62std::mutex PointerData::pointer_mutex_;
63std::unordered_map<uintptr_t, PointerInfoType> PointerData::pointers_ GUARDED_BY(
64 PointerData::pointer_mutex_);
65
66std::mutex PointerData::frame_mutex_;
67std::unordered_map<FrameKeyType, size_t> PointerData::key_to_index_ GUARDED_BY(
68 PointerData::frame_mutex_);
69std::unordered_map<size_t, FrameInfoType> PointerData::frames_ GUARDED_BY(PointerData::frame_mutex_);
Christopher Ferris459eecb2022-01-07 13:38:10 -080070std::unordered_map<size_t, std::vector<unwindstack::FrameData>> PointerData::backtraces_info_
71 GUARDED_BY(PointerData::frame_mutex_);
Christopher Ferris4da25032018-03-07 13:38:48 -080072constexpr size_t kBacktraceEmptyIndex = 1;
73size_t PointerData::cur_hash_index_ GUARDED_BY(PointerData::frame_mutex_);
74
75std::mutex PointerData::free_pointer_mutex_;
76std::deque<FreePointerInfoType> PointerData::free_pointers_ GUARDED_BY(
77 PointerData::free_pointer_mutex_);
78
79// Buffer to use for comparison.
80static constexpr size_t kCompareBufferSize = 512 * 1024;
81static std::vector<uint8_t> g_cmp_mem(0);
82
83static void ToggleBacktraceEnable(int, siginfo_t*, void*) {
84 g_debug->pointer->ToggleBacktraceEnabled();
85}
86
87static void EnableDump(int, siginfo_t*, void*) {
88 g_debug->pointer->EnableDumping();
89}
90
91PointerData::PointerData(DebugData* debug_data) : OptionData(debug_data) {}
92
93bool PointerData::Initialize(const Config& config) NO_THREAD_SAFETY_ANALYSIS {
94 pointers_.clear();
95 key_to_index_.clear();
96 frames_.clear();
97 free_pointers_.clear();
98 // A hash index of kBacktraceEmptyIndex indicates that we tried to get
99 // a backtrace, but there was nothing recorded.
100 cur_hash_index_ = kBacktraceEmptyIndex + 1;
101
102 backtrace_enabled_ = config.backtrace_enabled();
103 if (config.backtrace_enable_on_signal()) {
104 struct sigaction64 enable_act = {};
105 enable_act.sa_sigaction = ToggleBacktraceEnable;
106 enable_act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
107 if (sigaction64(config.backtrace_signal(), &enable_act, nullptr) != 0) {
108 error_log("Unable to set up backtrace signal enable function: %s", strerror(errno));
109 return false;
110 }
Christopher Ferrisc328e442019-04-01 19:31:26 -0700111 if (config.options() & VERBOSE) {
112 info_log("%s: Run: 'kill -%d %d' to enable backtracing.", getprogname(),
113 config.backtrace_signal(), getpid());
114 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800115 }
116
117 if (config.options() & BACKTRACE) {
118 struct sigaction64 act = {};
119 act.sa_sigaction = EnableDump;
120 act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
121 if (sigaction64(config.backtrace_dump_signal(), &act, nullptr) != 0) {
122 error_log("Unable to set up backtrace dump signal function: %s", strerror(errno));
123 return false;
124 }
Christopher Ferrisc328e442019-04-01 19:31:26 -0700125 if (config.options() & VERBOSE) {
126 info_log("%s: Run: 'kill -%d %d' to dump the backtrace.", getprogname(),
127 config.backtrace_dump_signal(), getpid());
128 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800129 }
130
131 backtrace_dump_ = false;
132
133 if (config.options() & FREE_TRACK) {
134 g_cmp_mem.resize(kCompareBufferSize, config.fill_free_value());
135 }
136 return true;
137}
138
Christopher Ferrisa3836482022-05-13 12:09:39 -0700139static inline bool ShouldBacktraceAllocSize(size_t size_bytes) {
140 static bool only_backtrace_specific_sizes =
141 g_debug->config().options() & BACKTRACE_SPECIFIC_SIZES;
142 if (!only_backtrace_specific_sizes) {
143 return true;
144 }
145 static size_t min_size_bytes = g_debug->config().backtrace_min_size_bytes();
146 static size_t max_size_bytes = g_debug->config().backtrace_max_size_bytes();
147 return size_bytes >= min_size_bytes && size_bytes <= max_size_bytes;
148}
149
150size_t PointerData::AddBacktrace(size_t num_frames, size_t size_bytes) {
151 if (!ShouldBacktraceAllocSize(size_bytes)) {
152 return kBacktraceEmptyIndex;
153 }
154
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700155 std::vector<uintptr_t> frames;
Christopher Ferris459eecb2022-01-07 13:38:10 -0800156 std::vector<unwindstack::FrameData> frames_info;
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700157 if (g_debug->config().options() & BACKTRACE_FULL) {
158 if (!Unwind(&frames, &frames_info, num_frames)) {
159 return kBacktraceEmptyIndex;
160 }
161 } else {
162 frames.resize(num_frames);
163 num_frames = backtrace_get(frames.data(), frames.size());
164 if (num_frames == 0) {
165 return kBacktraceEmptyIndex;
166 }
Christopher Ferrisdfbc59a2022-03-23 12:22:36 -0700167 frames.resize(num_frames);
Christopher Ferris4da25032018-03-07 13:38:48 -0800168 }
169
Christopher Ferrisdfbc59a2022-03-23 12:22:36 -0700170 FrameKeyType key{.num_frames = frames.size(), .frames = frames.data()};
Christopher Ferris4da25032018-03-07 13:38:48 -0800171 size_t hash_index;
172 std::lock_guard<std::mutex> frame_guard(frame_mutex_);
173 auto entry = key_to_index_.find(key);
174 if (entry == key_to_index_.end()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800175 hash_index = cur_hash_index_++;
176 key.frames = frames.data();
177 key_to_index_.emplace(key, hash_index);
178
179 frames_.emplace(hash_index, FrameInfoType{.references = 1, .frames = std::move(frames)});
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700180 if (g_debug->config().options() & BACKTRACE_FULL) {
181 backtraces_info_.emplace(hash_index, std::move(frames_info));
182 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800183 } else {
184 hash_index = entry->second;
185 FrameInfoType* frame_info = &frames_[hash_index];
186 frame_info->references++;
187 }
188 return hash_index;
189}
190
191void PointerData::RemoveBacktrace(size_t hash_index) {
192 if (hash_index <= kBacktraceEmptyIndex) {
193 return;
194 }
195
196 std::lock_guard<std::mutex> frame_guard(frame_mutex_);
197 auto frame_entry = frames_.find(hash_index);
198 if (frame_entry == frames_.end()) {
199 error_log("hash_index %zu does not have matching frame data.", hash_index);
200 return;
201 }
202 FrameInfoType* frame_info = &frame_entry->second;
203 if (--frame_info->references == 0) {
204 FrameKeyType key{.num_frames = frame_info->frames.size(), .frames = frame_info->frames.data()};
205 key_to_index_.erase(key);
206 frames_.erase(hash_index);
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700207 if (g_debug->config().options() & BACKTRACE_FULL) {
208 backtraces_info_.erase(hash_index);
209 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800210 }
211}
212
213void PointerData::Add(const void* ptr, size_t pointer_size) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800214 size_t hash_index = 0;
215 if (backtrace_enabled_) {
Christopher Ferrisa3836482022-05-13 12:09:39 -0700216 hash_index = AddBacktrace(g_debug->config().backtrace_frames(), pointer_size);
Christopher Ferris4da25032018-03-07 13:38:48 -0800217 }
218
219 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700220 uintptr_t mangled_ptr = ManglePointer(reinterpret_cast<uintptr_t>(ptr));
221 pointers_[mangled_ptr] =
222 PointerInfoType{PointerInfoType::GetEncodedSize(pointer_size), hash_index};
Christopher Ferris4da25032018-03-07 13:38:48 -0800223}
224
225void PointerData::Remove(const void* ptr) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800226 size_t hash_index;
227 {
228 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700229 uintptr_t mangled_ptr = ManglePointer(reinterpret_cast<uintptr_t>(ptr));
230 auto entry = pointers_.find(mangled_ptr);
Christopher Ferris4da25032018-03-07 13:38:48 -0800231 if (entry == pointers_.end()) {
Iris Chang7f209a92019-01-16 11:17:15 +0800232 // Attempt to remove unknown pointer.
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700233 error_log("No tracked pointer found for 0x%" PRIxPTR, DemanglePointer(mangled_ptr));
Christopher Ferris4da25032018-03-07 13:38:48 -0800234 return;
235 }
236 hash_index = entry->second.hash_index;
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700237 pointers_.erase(mangled_ptr);
Christopher Ferris4da25032018-03-07 13:38:48 -0800238 }
239
240 RemoveBacktrace(hash_index);
241}
242
243size_t PointerData::GetFrames(const void* ptr, uintptr_t* frames, size_t max_frames) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800244 size_t hash_index;
245 {
246 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700247 uintptr_t mangled_ptr = ManglePointer(reinterpret_cast<uintptr_t>(ptr));
248 auto entry = pointers_.find(mangled_ptr);
Christopher Ferris4da25032018-03-07 13:38:48 -0800249 if (entry == pointers_.end()) {
250 return 0;
251 }
252 hash_index = entry->second.hash_index;
253 }
254
255 if (hash_index <= kBacktraceEmptyIndex) {
256 return 0;
257 }
258
259 std::lock_guard<std::mutex> frame_guard(frame_mutex_);
260 auto frame_entry = frames_.find(hash_index);
261 if (frame_entry == frames_.end()) {
262 return 0;
263 }
264 FrameInfoType* frame_info = &frame_entry->second;
265 if (max_frames > frame_info->frames.size()) {
266 max_frames = frame_info->frames.size();
267 }
268 memcpy(frames, &frame_info->frames[0], max_frames * sizeof(uintptr_t));
269
270 return max_frames;
271}
272
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700273void PointerData::LogBacktrace(size_t hash_index) {
274 std::lock_guard<std::mutex> frame_guard(frame_mutex_);
275 if (g_debug->config().options() & BACKTRACE_FULL) {
276 auto backtrace_info_entry = backtraces_info_.find(hash_index);
277 if (backtrace_info_entry != backtraces_info_.end()) {
278 UnwindLog(backtrace_info_entry->second);
279 return;
280 }
281 } else {
282 auto frame_entry = frames_.find(hash_index);
283 if (frame_entry != frames_.end()) {
284 FrameInfoType* frame_info = &frame_entry->second;
285 backtrace_log(frame_info->frames.data(), frame_info->frames.size());
286 return;
287 }
288 }
289 error_log(" hash_index %zu does not have matching frame data.", hash_index);
290}
291
Iris Changb3441502019-02-12 14:00:59 +0800292void PointerData::LogFreeError(const FreePointerInfoType& info, size_t max_cmp_bytes) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800293 error_log(LOG_DIVIDER);
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700294 uintptr_t pointer = DemanglePointer(info.mangled_ptr);
295 uint8_t* memory = reinterpret_cast<uint8_t*>(pointer);
Christopher Ferris4da25032018-03-07 13:38:48 -0800296 error_log("+++ ALLOCATION %p USED AFTER FREE", memory);
297 uint8_t fill_free_value = g_debug->config().fill_free_value();
Iris Changb3441502019-02-12 14:00:59 +0800298 for (size_t i = 0; i < max_cmp_bytes; i++) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800299 if (memory[i] != fill_free_value) {
300 error_log(" allocation[%zu] = 0x%02x (expected 0x%02x)", i, memory[i], fill_free_value);
301 }
302 }
303
304 if (info.hash_index > kBacktraceEmptyIndex) {
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700305 error_log("Backtrace at time of free:");
306 LogBacktrace(info.hash_index);
Christopher Ferris4da25032018-03-07 13:38:48 -0800307 }
308
309 error_log(LOG_DIVIDER);
Iris Chang7f209a92019-01-16 11:17:15 +0800310 if (g_debug->config().options() & ABORT_ON_ERROR) {
311 abort();
312 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800313}
314
315void PointerData::VerifyFreedPointer(const FreePointerInfoType& info) {
316 size_t usable_size;
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700317 uintptr_t pointer = DemanglePointer(info.mangled_ptr);
Christopher Ferris4da25032018-03-07 13:38:48 -0800318 if (g_debug->HeaderEnabled()) {
319 // Check to see if the tag data has been damaged.
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700320 Header* header = g_debug->GetHeader(reinterpret_cast<const void*>(pointer));
Christopher Ferris4da25032018-03-07 13:38:48 -0800321 if (header->tag != DEBUG_FREE_TAG) {
322 error_log(LOG_DIVIDER);
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700323 error_log("+++ ALLOCATION 0x%" PRIxPTR " HAS CORRUPTED HEADER TAG 0x%x AFTER FREE", pointer,
324 header->tag);
Christopher Ferris4da25032018-03-07 13:38:48 -0800325 error_log(LOG_DIVIDER);
Iris Chang7f209a92019-01-16 11:17:15 +0800326 if (g_debug->config().options() & ABORT_ON_ERROR) {
327 abort();
328 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800329
330 // Stop processing here, it is impossible to tell how the header
331 // may have been damaged.
332 return;
333 }
334 usable_size = header->usable_size;
335 } else {
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700336 usable_size = g_dispatch->malloc_usable_size(reinterpret_cast<const void*>(pointer));
Christopher Ferris4da25032018-03-07 13:38:48 -0800337 }
338
339 size_t bytes = (usable_size < g_debug->config().fill_on_free_bytes())
340 ? usable_size
341 : g_debug->config().fill_on_free_bytes();
Iris Changb3441502019-02-12 14:00:59 +0800342 size_t max_cmp_bytes = bytes;
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700343 const uint8_t* memory = reinterpret_cast<const uint8_t*>(pointer);
Christopher Ferris4da25032018-03-07 13:38:48 -0800344 while (bytes > 0) {
345 size_t bytes_to_cmp = (bytes < g_cmp_mem.size()) ? bytes : g_cmp_mem.size();
346 if (memcmp(memory, g_cmp_mem.data(), bytes_to_cmp) != 0) {
Iris Changb3441502019-02-12 14:00:59 +0800347 LogFreeError(info, max_cmp_bytes);
Christopher Ferris4da25032018-03-07 13:38:48 -0800348 }
349 bytes -= bytes_to_cmp;
350 memory = &memory[bytes_to_cmp];
351 }
352}
353
Christopher Ferrisa3836482022-05-13 12:09:39 -0700354void* PointerData::AddFreed(const void* ptr, size_t size_bytes) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800355 size_t hash_index = 0;
356 size_t num_frames = g_debug->config().free_track_backtrace_num_frames();
357 if (num_frames) {
Christopher Ferrisa3836482022-05-13 12:09:39 -0700358 hash_index = AddBacktrace(num_frames, size_bytes);
Christopher Ferris4da25032018-03-07 13:38:48 -0800359 }
360
361 void* last = nullptr;
362 std::lock_guard<std::mutex> freed_guard(free_pointer_mutex_);
363 if (free_pointers_.size() == g_debug->config().free_track_allocations()) {
364 FreePointerInfoType info(free_pointers_.front());
365 free_pointers_.pop_front();
366 VerifyFreedPointer(info);
367 RemoveBacktrace(info.hash_index);
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700368 last = reinterpret_cast<void*>(DemanglePointer(info.mangled_ptr));
Christopher Ferris4da25032018-03-07 13:38:48 -0800369 }
370
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700371 uintptr_t mangled_ptr = ManglePointer(reinterpret_cast<uintptr_t>(ptr));
372 free_pointers_.emplace_back(FreePointerInfoType{mangled_ptr, hash_index});
Christopher Ferris4da25032018-03-07 13:38:48 -0800373 return last;
374}
375
376void PointerData::LogFreeBacktrace(const void* ptr) {
377 size_t hash_index = 0;
378 {
379 uintptr_t pointer = reinterpret_cast<uintptr_t>(ptr);
380 std::lock_guard<std::mutex> freed_guard(free_pointer_mutex_);
381 for (const auto& info : free_pointers_) {
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700382 if (DemanglePointer(info.mangled_ptr) == pointer) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800383 hash_index = info.hash_index;
384 break;
385 }
386 }
387 }
388
389 if (hash_index <= kBacktraceEmptyIndex) {
390 return;
391 }
392
Christopher Ferris4da25032018-03-07 13:38:48 -0800393 error_log("Backtrace of original free:");
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700394 LogBacktrace(hash_index);
Christopher Ferris4da25032018-03-07 13:38:48 -0800395}
396
397void PointerData::VerifyAllFreed() {
398 std::lock_guard<std::mutex> freed_guard(free_pointer_mutex_);
399 for (auto& free_info : free_pointers_) {
400 VerifyFreedPointer(free_info);
401 }
402}
403
404void PointerData::GetList(std::vector<ListInfoType>* list, bool only_with_backtrace)
405 REQUIRES(pointer_mutex_, frame_mutex_) {
406 for (const auto& entry : pointers_) {
407 FrameInfoType* frame_info = nullptr;
Christopher Ferris459eecb2022-01-07 13:38:10 -0800408 std::vector<unwindstack::FrameData>* backtrace_info = nullptr;
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700409 uintptr_t pointer = DemanglePointer(entry.first);
Christopher Ferris4da25032018-03-07 13:38:48 -0800410 size_t hash_index = entry.second.hash_index;
411 if (hash_index > kBacktraceEmptyIndex) {
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700412 auto frame_entry = frames_.find(hash_index);
413 if (frame_entry == frames_.end()) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800414 // Somehow wound up with a pointer with a valid hash_index, but
415 // no frame data. This should not be possible since adding a pointer
416 // occurs after the hash_index and frame data have been added.
417 // When removing a pointer, the pointer is deleted before the frame
418 // data.
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700419 error_log("Pointer 0x%" PRIxPTR " hash_index %zu does not exist.", pointer, hash_index);
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700420 } else {
421 frame_info = &frame_entry->second;
422 }
423
424 if (g_debug->config().options() & BACKTRACE_FULL) {
425 auto backtrace_entry = backtraces_info_.find(hash_index);
426 if (backtrace_entry == backtraces_info_.end()) {
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700427 error_log("Pointer 0x%" PRIxPTR " hash_index %zu does not exist.", pointer, hash_index);
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700428 } else {
429 backtrace_info = &backtrace_entry->second;
430 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800431 }
432 }
433 if (hash_index == 0 && only_with_backtrace) {
434 continue;
435 }
436
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700437 list->emplace_back(ListInfoType{pointer, 1, entry.second.RealSize(),
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700438 entry.second.ZygoteChildAlloc(), frame_info, backtrace_info});
Christopher Ferris4da25032018-03-07 13:38:48 -0800439 }
440
441 // Sort by the size of the allocation.
442 std::sort(list->begin(), list->end(), [](const ListInfoType& a, const ListInfoType& b) {
443 // Put zygote child allocations first.
444 bool a_zygote_child_alloc = a.zygote_child_alloc;
445 bool b_zygote_child_alloc = b.zygote_child_alloc;
446 if (a_zygote_child_alloc && !b_zygote_child_alloc) {
447 return false;
448 }
449 if (!a_zygote_child_alloc && b_zygote_child_alloc) {
450 return true;
451 }
452
453 // Sort by size, descending order.
454 if (a.size != b.size) return a.size > b.size;
455
456 // Put pointers with no backtrace last.
457 FrameInfoType* a_frame = a.frame_info;
458 FrameInfoType* b_frame = b.frame_info;
459 if (a_frame == nullptr && b_frame != nullptr) {
460 return false;
Christopher Ferrisc151bc32018-05-01 12:59:37 -0700461 } else if (a_frame != nullptr && b_frame == nullptr) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800462 return true;
Christopher Ferrisc151bc32018-05-01 12:59:37 -0700463 } else if (a_frame == nullptr && b_frame == nullptr) {
464 return a.pointer < b.pointer;
Christopher Ferris4da25032018-03-07 13:38:48 -0800465 }
Christopher Ferrisc151bc32018-05-01 12:59:37 -0700466
Christopher Ferris4da25032018-03-07 13:38:48 -0800467 // Put the pointers with longest backtrace first.
468 if (a_frame->frames.size() != b_frame->frames.size()) {
469 return a_frame->frames.size() > b_frame->frames.size();
470 }
471
472 // Last sort by pointer.
473 return a.pointer < b.pointer;
474 });
475}
476
477void PointerData::GetUniqueList(std::vector<ListInfoType>* list, bool only_with_backtrace)
478 REQUIRES(pointer_mutex_, frame_mutex_) {
479 GetList(list, only_with_backtrace);
480
481 // Remove duplicates of size/backtraces.
482 for (auto iter = list->begin(); iter != list->end();) {
483 auto dup_iter = iter + 1;
484 bool zygote_child_alloc = iter->zygote_child_alloc;
485 size_t size = iter->size;
486 FrameInfoType* frame_info = iter->frame_info;
487 for (; dup_iter != list->end(); ++dup_iter) {
488 if (zygote_child_alloc != dup_iter->zygote_child_alloc || size != dup_iter->size ||
489 frame_info != dup_iter->frame_info) {
490 break;
491 }
492 iter->num_allocations++;
493 }
494 iter = list->erase(iter + 1, dup_iter);
495 }
496}
497
498void PointerData::LogLeaks() {
499 std::vector<ListInfoType> list;
500
501 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
502 std::lock_guard<std::mutex> frame_guard(frame_mutex_);
503 GetList(&list, false);
504
505 size_t track_count = 0;
506 for (const auto& list_info : list) {
507 error_log("+++ %s leaked block of size %zu at 0x%" PRIxPTR " (leak %zu of %zu)", getprogname(),
508 list_info.size, list_info.pointer, ++track_count, list.size());
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700509 if (list_info.backtrace_info != nullptr) {
510 error_log("Backtrace at time of allocation:");
511 UnwindLog(*list_info.backtrace_info);
512 } else if (list_info.frame_info != nullptr) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800513 error_log("Backtrace at time of allocation:");
514 backtrace_log(list_info.frame_info->frames.data(), list_info.frame_info->frames.size());
515 }
516 // Do not bother to free the pointers, we are about to exit any way.
517 }
518}
519
Christopher Ferris6c619a02019-03-01 17:59:51 -0800520void PointerData::GetAllocList(std::vector<ListInfoType>* list) {
521 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
522 std::lock_guard<std::mutex> frame_guard(frame_mutex_);
523
524 if (pointers_.empty()) {
525 return;
526 }
527
528 GetList(list, false);
529}
530
Christopher Ferris4da25032018-03-07 13:38:48 -0800531void PointerData::GetInfo(uint8_t** info, size_t* overall_size, size_t* info_size,
532 size_t* total_memory, size_t* backtrace_size) {
533 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
534 std::lock_guard<std::mutex> frame_guard(frame_mutex_);
535
536 if (pointers_.empty()) {
537 return;
538 }
539
540 std::vector<ListInfoType> list;
541 GetUniqueList(&list, true);
542 if (list.empty()) {
543 return;
544 }
545
546 *backtrace_size = g_debug->config().backtrace_frames();
547 *info_size = sizeof(size_t) * 2 + sizeof(uintptr_t) * *backtrace_size;
548 *overall_size = *info_size * list.size();
549 *info = reinterpret_cast<uint8_t*>(g_dispatch->calloc(*info_size, list.size()));
550 if (*info == nullptr) {
551 return;
552 }
553
554 uint8_t* data = *info;
555 *total_memory = 0;
556 for (const auto& list_info : list) {
557 FrameInfoType* frame_info = list_info.frame_info;
558 *total_memory += list_info.size * list_info.num_allocations;
559 size_t allocation_size =
560 PointerInfoType::GetEncodedSize(list_info.zygote_child_alloc, list_info.size);
561 memcpy(data, &allocation_size, sizeof(size_t));
562 memcpy(&data[sizeof(size_t)], &list_info.num_allocations, sizeof(size_t));
563 if (frame_info != nullptr) {
564 memcpy(&data[2 * sizeof(size_t)], frame_info->frames.data(),
565 frame_info->frames.size() * sizeof(uintptr_t));
566 }
567 data += *info_size;
568 }
569}
570
571bool PointerData::Exists(const void* ptr) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800572 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700573 uintptr_t mangled_ptr = ManglePointer(reinterpret_cast<uintptr_t>(ptr));
574 return pointers_.count(mangled_ptr) != 0;
Christopher Ferris4da25032018-03-07 13:38:48 -0800575}
576
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800577void PointerData::DumpLiveToFile(int fd) {
Christopher Ferris4da25032018-03-07 13:38:48 -0800578 std::vector<ListInfoType> list;
579
580 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
581 std::lock_guard<std::mutex> frame_guard(frame_mutex_);
582 GetUniqueList(&list, false);
583
584 size_t total_memory = 0;
585 for (const auto& info : list) {
586 total_memory += info.size * info.num_allocations;
587 }
588
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800589 dprintf(fd, "Total memory: %zu\n", total_memory);
590 dprintf(fd, "Allocation records: %zd\n", list.size());
591 dprintf(fd, "Backtrace size: %zu\n", g_debug->config().backtrace_frames());
592 dprintf(fd, "\n");
Christopher Ferris4da25032018-03-07 13:38:48 -0800593
594 for (const auto& info : list) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800595 dprintf(fd, "z %d sz %8zu num %zu bt", (info.zygote_child_alloc) ? 1 : 0, info.size,
Christopher Ferris4da25032018-03-07 13:38:48 -0800596 info.num_allocations);
597 FrameInfoType* frame_info = info.frame_info;
598 if (frame_info != nullptr) {
599 for (size_t i = 0; i < frame_info->frames.size(); i++) {
600 if (frame_info->frames[i] == 0) {
601 break;
602 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800603 dprintf(fd, " %" PRIxPTR, frame_info->frames[i]);
Christopher Ferris4da25032018-03-07 13:38:48 -0800604 }
605 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800606 dprintf(fd, "\n");
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700607 if (info.backtrace_info != nullptr) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800608 dprintf(fd, " bt_info");
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700609 for (const auto& frame : *info.backtrace_info) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800610 dprintf(fd, " {");
David Srbecky92b8d642021-05-13 00:03:26 +0100611 if (frame.map_info != nullptr && !frame.map_info->name().empty()) {
612 dprintf(fd, "\"%s\"", frame.map_info->name().c_str());
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700613 } else {
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800614 dprintf(fd, "\"\"");
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700615 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800616 dprintf(fd, " %" PRIx64, frame.rel_pc);
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700617 if (frame.function_name.empty()) {
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800618 dprintf(fd, " \"\" 0}");
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700619 } else {
Christopher Ferris9782b872019-07-18 13:36:50 -0700620 char* demangled_name = __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr,
621 nullptr);
622 const char* name;
623 if (demangled_name != nullptr) {
624 name = demangled_name;
625 } else {
626 name = frame.function_name.c_str();
627 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800628 dprintf(fd, " \"%s\" %" PRIx64 "}", name, frame.function_offset);
Christopher Ferris9782b872019-07-18 13:36:50 -0700629 free(demangled_name);
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700630 }
631 }
Christopher Ferrisff88fb02019-11-04 18:40:00 -0800632 dprintf(fd, "\n");
Christopher Ferris93bdd6a2018-04-05 11:12:38 -0700633 }
Christopher Ferris4da25032018-03-07 13:38:48 -0800634 }
635}
636
637void PointerData::PrepareFork() NO_THREAD_SAFETY_ANALYSIS {
Iris Chang76dcc472019-03-07 12:32:19 +0800638 free_pointer_mutex_.lock();
Christopher Ferris4da25032018-03-07 13:38:48 -0800639 pointer_mutex_.lock();
640 frame_mutex_.lock();
Christopher Ferris4da25032018-03-07 13:38:48 -0800641}
642
643void PointerData::PostForkParent() NO_THREAD_SAFETY_ANALYSIS {
644 frame_mutex_.unlock();
645 pointer_mutex_.unlock();
646 free_pointer_mutex_.unlock();
647}
648
649void PointerData::PostForkChild() __attribute__((no_thread_safety_analysis)) {
650 // Make sure that any potential mutexes have been released and are back
651 // to an initial state.
652 frame_mutex_.try_lock();
653 frame_mutex_.unlock();
654 pointer_mutex_.try_lock();
655 pointer_mutex_.unlock();
656 free_pointer_mutex_.try_lock();
657 free_pointer_mutex_.unlock();
658}
Christopher Ferrisf78486f2022-05-04 14:08:54 -0700659
660void PointerData::IteratePointers(std::function<void(uintptr_t pointer)> fn) {
661 std::lock_guard<std::mutex> pointer_guard(pointer_mutex_);
662 for (const auto entry : pointers_) {
663 fn(DemanglePointer(entry.first));
664 }
665}