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/tombstone.h"
19 #include "libdebuggerd/utility.h"
20 
21 #include "gwp_asan/common.h"
22 #include "gwp_asan/crash_handler.h"
23 
24 #include <unwindstack/Maps.h>
25 #include <unwindstack/Memory.h>
26 #include <unwindstack/Regs.h>
27 #include <unwindstack/Unwinder.h>
28 
29 #include "tombstone.pb.h"
30 
31 // Retrieve GWP-ASan state from `state_addr` inside the process at
32 // `process_memory`. Place the state into `*state`.
33 static bool retrieve_gwp_asan_state(unwindstack::Memory* process_memory, uintptr_t state_addr,
34                                     gwp_asan::AllocatorState* state) {
35   return process_memory->ReadFully(state_addr, state, sizeof(*state));
36 }
37 
38 // Retrieve the GWP-ASan metadata pool from `metadata_addr` inside the process
39 // at `process_memory`. The number of metadata slots is retrieved from the
40 // allocator state provided. This function returns a heap-allocated copy of the
41 // metadata pool whose ownership should be managed by the caller. Returns
42 // nullptr on failure.
43 static const gwp_asan::AllocationMetadata* retrieve_gwp_asan_metadata(
44     unwindstack::Memory* process_memory, const gwp_asan::AllocatorState& state,
45     uintptr_t metadata_addr) {
46   if (state.MaxSimultaneousAllocations > 1024) {
47     ALOGE(
48         "Error when retrieving GWP-ASan metadata, MSA from state (%zu) "
49         "exceeds maximum allowed (1024).",
50         state.MaxSimultaneousAllocations);
51     return nullptr;
52   }
53 
54   gwp_asan::AllocationMetadata* meta =
55       new gwp_asan::AllocationMetadata[state.MaxSimultaneousAllocations];
56   if (!process_memory->ReadFully(metadata_addr, meta,
57                                  sizeof(*meta) * state.MaxSimultaneousAllocations)) {
58     ALOGE(
59         "Error when retrieving GWP-ASan metadata, could not retrieve %zu "
60         "pieces of metadata.",
61         state.MaxSimultaneousAllocations);
62     delete[] meta;
63     meta = nullptr;
64   }
65   return meta;
66 }
67 
68 GwpAsanCrashData::GwpAsanCrashData(unwindstack::Memory* process_memory,
69                                    const ProcessInfo& process_info, const ThreadInfo& thread_info) {
70   if (!process_memory || !process_info.gwp_asan_metadata || !process_info.gwp_asan_state) return;
71   // Extract the GWP-ASan regions from the dead process.
72   if (!retrieve_gwp_asan_state(process_memory, process_info.gwp_asan_state, &state_)) return;
73   metadata_.reset(retrieve_gwp_asan_metadata(process_memory, state_, process_info.gwp_asan_metadata));
74   if (!metadata_.get()) return;
75 
76   // Get the external crash address from the thread info.
77   crash_address_ = 0u;
78   if (process_info.has_fault_address) {
79     crash_address_ = process_info.untagged_fault_address;
80   }
81 
82   // Ensure the error belongs to GWP-ASan.
83   if (!__gwp_asan_error_is_mine(&state_, crash_address_)) return;
84 
85   is_gwp_asan_responsible_ = true;
86   thread_id_ = thread_info.tid;
87 
88   // Grab the internal error address, if it exists.
89   uintptr_t internal_crash_address = __gwp_asan_get_internal_crash_address(&state_);
90   if (internal_crash_address) {
91     crash_address_ = internal_crash_address;
92   }
93 
94   // Get other information from the internal state.
95   error_ = __gwp_asan_diagnose_error(&state_, metadata_.get(), crash_address_);
96   error_string_ = gwp_asan::ErrorToString(error_);
97   responsible_allocation_ = __gwp_asan_get_metadata(&state_, metadata_.get(), crash_address_);
98 }
99 
100 bool GwpAsanCrashData::CrashIsMine() const {
101   return is_gwp_asan_responsible_;
102 }
103 
104 constexpr size_t kMaxTraceLength = gwp_asan::AllocationMetadata::kMaxTraceLengthToCollect;
105 
106 void GwpAsanCrashData::AddCauseProtos(Tombstone* tombstone, unwindstack::Unwinder* unwinder) const {
107   if (!CrashIsMine()) {
108     ALOGE("Internal Error: AddCauseProtos() on a non-GWP-ASan crash.");
109     return;
110   }
111 
112   Cause* cause = tombstone->add_causes();
113   MemoryError* memory_error = cause->mutable_memory_error();
114   HeapObject* heap_object = memory_error->mutable_heap();
115 
116   memory_error->set_tool(MemoryError_Tool_GWP_ASAN);
117   switch (error_) {
118     case gwp_asan::Error::USE_AFTER_FREE:
119       memory_error->set_type(MemoryError_Type_USE_AFTER_FREE);
120       break;
121     case gwp_asan::Error::DOUBLE_FREE:
122       memory_error->set_type(MemoryError_Type_DOUBLE_FREE);
123       break;
124     case gwp_asan::Error::INVALID_FREE:
125       memory_error->set_type(MemoryError_Type_INVALID_FREE);
126       break;
127     case gwp_asan::Error::BUFFER_OVERFLOW:
128       memory_error->set_type(MemoryError_Type_BUFFER_OVERFLOW);
129       break;
130     case gwp_asan::Error::BUFFER_UNDERFLOW:
131       memory_error->set_type(MemoryError_Type_BUFFER_UNDERFLOW);
132       break;
133     default:
134       memory_error->set_type(MemoryError_Type_UNKNOWN);
135       break;
136   }
137 
138   heap_object->set_address(__gwp_asan_get_allocation_address(responsible_allocation_));
139   heap_object->set_size(__gwp_asan_get_allocation_size(responsible_allocation_));
140   unwinder->SetDisplayBuildID(true);
141 
142   std::unique_ptr<uintptr_t[]> frames(new uintptr_t[kMaxTraceLength]);
143 
144   heap_object->set_allocation_tid(__gwp_asan_get_allocation_thread_id(responsible_allocation_));
145   size_t num_frames =
146       __gwp_asan_get_allocation_trace(responsible_allocation_, frames.get(), kMaxTraceLength);
147   for (size_t i = 0; i != num_frames; ++i) {
148     unwindstack::FrameData frame_data = unwinder->BuildFrameFromPcOnly(frames[i]);
149     BacktraceFrame* f = heap_object->add_allocation_backtrace();
150     fill_in_backtrace_frame(f, frame_data, unwinder->GetMaps());
151   }
152 
153   heap_object->set_deallocation_tid(__gwp_asan_get_deallocation_thread_id(responsible_allocation_));
154   num_frames =
155       __gwp_asan_get_deallocation_trace(responsible_allocation_, frames.get(), kMaxTraceLength);
156   for (size_t i = 0; i != num_frames; ++i) {
157     unwindstack::FrameData frame_data = unwinder->BuildFrameFromPcOnly(frames[i]);
158     BacktraceFrame* f = heap_object->add_deallocation_backtrace();
159     fill_in_backtrace_frame(f, frame_data, unwinder->GetMaps());
160   }
161 
162   set_human_readable_cause(cause, crash_address_);
163 }
164 
165 void GwpAsanCrashData::DumpCause(log_t* log) const {
166   if (!CrashIsMine()) {
167     ALOGE("Internal Error: DumpCause() on a non-GWP-ASan crash.");
168     return;
169   }
170 
171   if (error_ == gwp_asan::Error::UNKNOWN) {
172     _LOG(log, logtype::HEADER, "Cause: [GWP-ASan]: Unknown error occurred at 0x%" PRIxPTR ".\n",
173          crash_address_);
174     return;
175   }
176 
177   if (!responsible_allocation_) {
178     _LOG(log, logtype::HEADER, "Cause: [GWP-ASan]: %s at 0x%" PRIxPTR ".\n", error_string_,
179          crash_address_);
180     return;
181   }
182 
183   uintptr_t alloc_address = __gwp_asan_get_allocation_address(responsible_allocation_);
184   size_t alloc_size = __gwp_asan_get_allocation_size(responsible_allocation_);
185 
186   uintptr_t diff;
187   const char* location_str;
188 
189   if (crash_address_ < alloc_address) {
190     // Buffer Underflow, 6 bytes left of a 41-byte allocation at 0xdeadbeef.
191     location_str = "left of";
192     diff = alloc_address - crash_address_;
193   } else if (crash_address_ - alloc_address < alloc_size) {
194     // Use After Free, 40 bytes into a 41-byte allocation at 0xdeadbeef.
195     location_str = "into";
196     diff = crash_address_ - alloc_address;
197   } else {
198     // Buffer Overflow, 6 bytes right of a 41-byte allocation at 0xdeadbeef, or
199     // Invalid Free, 47 bytes right of a 41-byte allocation at 0xdeadbeef.
200     location_str = "right of";
201     diff = crash_address_ - alloc_address;
202     if (error_ == gwp_asan::Error::BUFFER_OVERFLOW) {
203       diff -= alloc_size;
204     }
205   }
206 
207   // Suffix of 'bytes', i.e. 4 bytes' vs. '1 byte'.
208   const char* byte_suffix = "s";
209   if (diff == 1) {
210     byte_suffix = "";
211   }
212   _LOG(log, logtype::HEADER,
213        "Cause: [GWP-ASan]: %s, %" PRIuPTR " byte%s %s a %zu-byte allocation at 0x%" PRIxPTR "\n",
214        error_string_, diff, byte_suffix, location_str, alloc_size, alloc_address);
215 }
216 
217 bool GwpAsanCrashData::HasDeallocationTrace() const {
218   assert(CrashIsMine() && "HasDeallocationTrace(): Crash is not mine!");
219   if (!responsible_allocation_ || !__gwp_asan_is_deallocated(responsible_allocation_)) {
220     return false;
221   }
222   return true;
223 }
224 
225 void GwpAsanCrashData::DumpDeallocationTrace(log_t* log, unwindstack::Unwinder* unwinder) const {
226   assert(HasDeallocationTrace() && "DumpDeallocationTrace(): No dealloc trace!");
227   uint64_t thread_id = __gwp_asan_get_deallocation_thread_id(responsible_allocation_);
228 
229   std::unique_ptr<uintptr_t[]> frames(new uintptr_t[kMaxTraceLength]);
230   size_t num_frames =
231       __gwp_asan_get_deallocation_trace(responsible_allocation_, frames.get(), kMaxTraceLength);
232 
233   if (thread_id == gwp_asan::kInvalidThreadID) {
234     _LOG(log, logtype::BACKTRACE, "\ndeallocated by thread <unknown>:\n");
235   } else {
236     _LOG(log, logtype::BACKTRACE, "\ndeallocated by thread %" PRIu64 ":\n", thread_id);
237   }
238 
239   unwinder->SetDisplayBuildID(true);
240   for (size_t i = 0; i < num_frames; ++i) {
241     unwindstack::FrameData frame_data = unwinder->BuildFrameFromPcOnly(frames[i]);
242     frame_data.num = i;
243     _LOG(log, logtype::BACKTRACE, "    %s\n", unwinder->FormatFrame(frame_data).c_str());
244   }
245 }
246 
247 bool GwpAsanCrashData::HasAllocationTrace() const {
248   assert(CrashIsMine() && "HasAllocationTrace(): Crash is not mine!");
249   return responsible_allocation_ != nullptr;
250 }
251 
252 void GwpAsanCrashData::DumpAllocationTrace(log_t* log, unwindstack::Unwinder* unwinder) const {
253   assert(HasAllocationTrace() && "DumpAllocationTrace(): No dealloc trace!");
254   uint64_t thread_id = __gwp_asan_get_allocation_thread_id(responsible_allocation_);
255 
256   std::unique_ptr<uintptr_t[]> frames(new uintptr_t[kMaxTraceLength]);
257   size_t num_frames =
258       __gwp_asan_get_allocation_trace(responsible_allocation_, frames.get(), kMaxTraceLength);
259 
260   if (thread_id == gwp_asan::kInvalidThreadID) {
261     _LOG(log, logtype::BACKTRACE, "\nallocated by thread <unknown>:\n");
262   } else {
263     _LOG(log, logtype::BACKTRACE, "\nallocated by thread %" PRIu64 ":\n", thread_id);
264   }
265 
266   unwinder->SetDisplayBuildID(true);
267   for (size_t i = 0; i < num_frames; ++i) {
268     unwindstack::FrameData frame_data = unwinder->BuildFrameFromPcOnly(frames[i]);
269     frame_data.num = i;
270     _LOG(log, logtype::BACKTRACE, "    %s\n", unwinder->FormatFrame(frame_data).c_str());
271   }
272 }
273