1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "libdebuggerd/gwp_asan.h"
18 #include "libdebuggerd/utility.h"
19 
20 #include "gwp_asan/common.h"
21 #include "gwp_asan/crash_handler.h"
22 
23 #include <unwindstack/Maps.h>
24 #include <unwindstack/Memory.h>
25 #include <unwindstack/Regs.h>
26 #include <unwindstack/Unwinder.h>
27 
28 // Retrieve GWP-ASan state from `state_addr` inside the process at
29 // `process_memory`. Place the state into `*state`.
retrieve_gwp_asan_state(unwindstack::Memory * process_memory,uintptr_t state_addr,gwp_asan::AllocatorState * state)30 static bool retrieve_gwp_asan_state(unwindstack::Memory* process_memory, uintptr_t state_addr,
31                                     gwp_asan::AllocatorState* state) {
32   return process_memory->ReadFully(state_addr, state, sizeof(*state));
33 }
34 
35 // Retrieve the GWP-ASan metadata pool from `metadata_addr` inside the process
36 // at `process_memory`. The number of metadata slots is retrieved from the
37 // allocator state provided. This function returns a heap-allocated copy of the
38 // metadata pool whose ownership should be managed by the caller. Returns
39 // nullptr on failure.
retrieve_gwp_asan_metadata(unwindstack::Memory * process_memory,const gwp_asan::AllocatorState & state,uintptr_t metadata_addr)40 static const gwp_asan::AllocationMetadata* retrieve_gwp_asan_metadata(
41     unwindstack::Memory* process_memory, const gwp_asan::AllocatorState& state,
42     uintptr_t metadata_addr) {
43   if (state.MaxSimultaneousAllocations > 1024) {
44     ALOGE(
45         "Error when retrieving GWP-ASan metadata, MSA from state (%zu) "
46         "exceeds maximum allowed (1024).",
47         state.MaxSimultaneousAllocations);
48     return nullptr;
49   }
50 
51   gwp_asan::AllocationMetadata* meta =
52       new gwp_asan::AllocationMetadata[state.MaxSimultaneousAllocations];
53   if (!process_memory->ReadFully(metadata_addr, meta,
54                                  sizeof(*meta) * state.MaxSimultaneousAllocations)) {
55     ALOGE(
56         "Error when retrieving GWP-ASan metadata, could not retrieve %zu "
57         "pieces of metadata.",
58         state.MaxSimultaneousAllocations);
59     delete[] meta;
60     meta = nullptr;
61   }
62   return meta;
63 }
64 
GwpAsanCrashData(unwindstack::Memory * process_memory,const ProcessInfo & process_info,const ThreadInfo & thread_info)65 GwpAsanCrashData::GwpAsanCrashData(unwindstack::Memory* process_memory,
66                                    const ProcessInfo& process_info, const ThreadInfo& thread_info) {
67   if (!process_memory || !process_info.gwp_asan_metadata || !process_info.gwp_asan_state) return;
68   // Extract the GWP-ASan regions from the dead process.
69   if (!retrieve_gwp_asan_state(process_memory, process_info.gwp_asan_state, &state_)) return;
70   metadata_.reset(retrieve_gwp_asan_metadata(process_memory, state_, process_info.gwp_asan_metadata));
71   if (!metadata_.get()) return;
72 
73   // Get the external crash address from the thread info.
74   crash_address_ = 0u;
75   if (signal_has_si_addr(thread_info.siginfo)) {
76     crash_address_ = reinterpret_cast<uintptr_t>(thread_info.siginfo->si_addr);
77   }
78 
79   // Ensure the error belongs to GWP-ASan.
80   if (!__gwp_asan_error_is_mine(&state_, crash_address_)) return;
81 
82   is_gwp_asan_responsible_ = true;
83   thread_id_ = thread_info.tid;
84 
85   // Grab the internal error address, if it exists.
86   uintptr_t internal_crash_address = __gwp_asan_get_internal_crash_address(&state_);
87   if (internal_crash_address) {
88     crash_address_ = internal_crash_address;
89   }
90 
91   // Get other information from the internal state.
92   error_ = __gwp_asan_diagnose_error(&state_, metadata_.get(), crash_address_);
93   error_string_ = gwp_asan::ErrorToString(error_);
94   responsible_allocation_ = __gwp_asan_get_metadata(&state_, metadata_.get(), crash_address_);
95 }
96 
CrashIsMine() const97 bool GwpAsanCrashData::CrashIsMine() const {
98   return is_gwp_asan_responsible_;
99 }
100 
DumpCause(log_t * log) const101 void GwpAsanCrashData::DumpCause(log_t* log) const {
102   if (!CrashIsMine()) {
103     ALOGE("Internal Error: DumpCause() on a non-GWP-ASan crash.");
104     return;
105   }
106 
107   if (error_ == gwp_asan::Error::UNKNOWN) {
108     _LOG(log, logtype::HEADER, "Cause: [GWP-ASan]: Unknown error occurred at 0x%" PRIxPTR ".\n",
109          crash_address_);
110     return;
111   }
112 
113   if (!responsible_allocation_) {
114     _LOG(log, logtype::HEADER, "Cause: [GWP-ASan]: %s at 0x%" PRIxPTR ".\n", error_string_,
115          crash_address_);
116     return;
117   }
118 
119   uintptr_t alloc_address = __gwp_asan_get_allocation_address(responsible_allocation_);
120   size_t alloc_size = __gwp_asan_get_allocation_size(responsible_allocation_);
121 
122   if (crash_address_ == alloc_address) {
123     // Use After Free on a 41-byte allocation at 0xdeadbeef.
124     _LOG(log, logtype::HEADER, "Cause: [GWP-ASan]: %s on a %zu-byte allocation at 0x%" PRIxPTR "\n",
125          error_string_, alloc_size, alloc_address);
126     return;
127   }
128 
129   uintptr_t diff;
130   const char* location_str;
131 
132   if (crash_address_ < alloc_address) {
133     // Buffer Underflow, 6 bytes left of a 41-byte allocation at 0xdeadbeef.
134     location_str = "left of";
135     diff = alloc_address - crash_address_;
136   } else if (crash_address_ - alloc_address < alloc_size) {
137     // Use After Free, 40 bytes into a 41-byte allocation at 0xdeadbeef.
138     location_str = "into";
139     diff = crash_address_ - alloc_address;
140   } else {
141     // Buffer Overflow, 6 bytes right of a 41-byte allocation at 0xdeadbeef, or
142     // Invalid Free, 47 bytes right of a 41-byte allocation at 0xdeadbeef.
143     location_str = "right of";
144     diff = crash_address_ - alloc_address;
145     if (error_ == gwp_asan::Error::BUFFER_OVERFLOW) {
146       diff -= alloc_size;
147     }
148   }
149 
150   // Suffix of 'bytes', i.e. 4 bytes' vs. '1 byte'.
151   const char* byte_suffix = "s";
152   if (diff == 1) {
153     byte_suffix = "";
154   }
155   _LOG(log, logtype::HEADER,
156        "Cause: [GWP-ASan]: %s, %" PRIuPTR " byte%s %s a %zu-byte allocation at 0x%" PRIxPTR "\n",
157        error_string_, diff, byte_suffix, location_str, alloc_size, alloc_address);
158 }
159 
160 constexpr size_t kMaxTraceLength = gwp_asan::AllocationMetadata::kMaxTraceLengthToCollect;
161 
HasDeallocationTrace() const162 bool GwpAsanCrashData::HasDeallocationTrace() const {
163   assert(CrashIsMine() && "HasDeallocationTrace(): Crash is not mine!");
164   if (!responsible_allocation_ || !__gwp_asan_is_deallocated(responsible_allocation_)) {
165     return false;
166   }
167   return true;
168 }
169 
DumpDeallocationTrace(log_t * log,unwindstack::Unwinder * unwinder) const170 void GwpAsanCrashData::DumpDeallocationTrace(log_t* log, unwindstack::Unwinder* unwinder) const {
171   assert(HasDeallocationTrace() && "DumpDeallocationTrace(): No dealloc trace!");
172   uint64_t thread_id = __gwp_asan_get_deallocation_thread_id(responsible_allocation_);
173 
174   std::unique_ptr<uintptr_t> frames(new uintptr_t[kMaxTraceLength]);
175   size_t num_frames =
176       __gwp_asan_get_deallocation_trace(responsible_allocation_, frames.get(), kMaxTraceLength);
177 
178   if (thread_id == gwp_asan::kInvalidThreadID) {
179     _LOG(log, logtype::BACKTRACE, "\ndeallocated by thread <unknown>:\n");
180   } else {
181     _LOG(log, logtype::BACKTRACE, "\ndeallocated by thread %" PRIu64 ":\n", thread_id);
182   }
183 
184   unwinder->SetDisplayBuildID(true);
185   for (size_t i = 0; i < num_frames; ++i) {
186     unwindstack::FrameData frame_data = unwinder->BuildFrameFromPcOnly(frames.get()[i]);
187     frame_data.num = i;
188     _LOG(log, logtype::BACKTRACE, "    %s\n", unwinder->FormatFrame(frame_data).c_str());
189   }
190 }
191 
HasAllocationTrace() const192 bool GwpAsanCrashData::HasAllocationTrace() const {
193   assert(CrashIsMine() && "HasAllocationTrace(): Crash is not mine!");
194   return responsible_allocation_ != nullptr;
195 }
196 
DumpAllocationTrace(log_t * log,unwindstack::Unwinder * unwinder) const197 void GwpAsanCrashData::DumpAllocationTrace(log_t* log, unwindstack::Unwinder* unwinder) const {
198   assert(HasAllocationTrace() && "DumpAllocationTrace(): No dealloc trace!");
199   uint64_t thread_id = __gwp_asan_get_allocation_thread_id(responsible_allocation_);
200 
201   std::unique_ptr<uintptr_t> frames(new uintptr_t[kMaxTraceLength]);
202   size_t num_frames =
203       __gwp_asan_get_allocation_trace(responsible_allocation_, frames.get(), kMaxTraceLength);
204 
205   if (thread_id == gwp_asan::kInvalidThreadID) {
206     _LOG(log, logtype::BACKTRACE, "\nallocated by thread <unknown>:\n");
207   } else {
208     _LOG(log, logtype::BACKTRACE, "\nallocated by thread %" PRIu64 ":\n", thread_id);
209   }
210 
211   unwinder->SetDisplayBuildID(true);
212   for (size_t i = 0; i < num_frames; ++i) {
213     unwindstack::FrameData frame_data = unwinder->BuildFrameFromPcOnly(frames.get()[i]);
214     frame_data.num = i;
215     _LOG(log, logtype::BACKTRACE, "    %s\n", unwinder->FormatFrame(frame_data).c_str());
216   }
217 }
218