1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/trace_event/cfi_backtrace_android.h"
6
7 #include <sys/mman.h>
8 #include <sys/types.h>
9
10 #include "base/android/apk_assets.h"
11 #include "base/android/library_loader/anchor_functions.h"
12 #include "build/build_config.h"
13 #include "third_party/abseil-cpp/absl/base/attributes.h"
14
15 #if !defined(ARCH_CPU_ARMEL)
16 #error This file should not be built for this architecture.
17 #endif
18
19 /*
20 Basics of unwinding:
21 For each instruction in a function we need to know what is the offset of SP
22 (Stack Pointer) to reach the previous function's stack frame. To know which
23 function is being invoked, we need the return address of the next function. The
24 CFI information for an instruction is made up of 2 offsets, CFA (Call Frame
25 Address) offset and RA (Return Address) offset. The CFA offset is the change in
26 SP made by the function till the current instruction. This depends on amount of
27 memory allocated on stack by the function plus some registers that the function
28 stores that needs to be restored at the end of function. So, at each instruction
29 the CFA offset tells the offset from original SP before the function call. The
30 RA offset tells us the offset from the previous SP into the current function
31 where the return address is stored.
32
33 The unwind table file has 2 tables UNW_INDEX and UNW_DATA, inspired from ARM
34 EHABI format. The first table contains function addresses and an index into the
35 UNW_DATA table. The second table contains one or more rows for the function
36 unwind information.
37
38 UNW_INDEX contains two columns of N rows each, where N is the number of
39 functions.
40 1. First column 4 byte rows of all the function start address as offset from
41 start of the binary, in sorted order.
42 2. For each function addr, the second column contains 2 byte indices in order.
43 The indices are offsets (in count of 2 bytes) of the CFI data from start of
44 UNW_DATA.
45 The last entry in the table always contains CANT_UNWIND index to specify the
46 end address of the last function.
47
48 UNW_DATA contains data of all the functions. Each function data contains N rows.
49 The data found at the address pointed from UNW_INDEX will be:
50 2 bytes: N - number of rows that belong to current function.
51 N * 4 bytes: N rows of data. 16 bits : Address offset from function start.
52 14 bits : CFA offset / 4.
53 2 bits : RA offset / 4.
54 If the RA offset of a row is 0, then use the offset of the previous rows in the
55 same function.
56 TODO(ssid): Make sure RA offset is always present.
57
58 See extract_unwind_tables.py for details about how this data is extracted from
59 breakpad symbol files.
60 */
61
62 extern "C" {
63
64 // The address of |__executable_start| gives the start address of the
65 // executable or shared library. This value is used to find the offset address
66 // of the instruction in binary from PC.
67 extern char __executable_start;
68
69 }
70
71 namespace base {
72 namespace trace_event {
73
74 namespace {
75
76 // The value of index when the function does not have unwind information.
77 constexpr uint32_t kCantUnwind = 0xFFFF;
78
79 // The mask on the CFI row data that is used to get the high 14 bits and
80 // multiply it by 4 to get CFA offset. Since the last 2 bits are masked out, a
81 // shift is not necessary.
82 constexpr uint16_t kCFAMask = 0xfffc;
83
84 // The mask on the CFI row data that is used to get the low 2 bits and multiply
85 // it by 4 to get the RA offset.
86 constexpr uint16_t kRAMask = 0x3;
87 constexpr uint16_t kRAShift = 2;
88
89 // The code in this file assumes we are running in 32-bit builds since all the
90 // addresses in the unwind table are specified in 32 bits.
91 static_assert(sizeof(uintptr_t) == 4,
92 "The unwind table format is only valid for 32 bit builds.");
93
94 // The CFI data in UNW_DATA table starts with number of rows (N) and then
95 // followed by N rows of 4 bytes long. The CFIUnwindDataRow represents a single
96 // row of CFI data of a function in the table. Since we cast the memory at the
97 // address after the address of number of rows, into an array of
98 // CFIUnwindDataRow, the size of the struct should be 4 bytes and the order of
99 // the members is fixed according to the given format. The first 2 bytes tell
100 // the address of function and last 2 bytes give the CFI data for the offset.
101 struct CFIUnwindDataRow {
102 // The address of the instruction in terms of offset from the start of the
103 // function.
104 uint16_t addr_offset;
105 // Represents the CFA and RA offsets to get information about next stack
106 // frame. This is the CFI data at the point before executing the instruction
107 // at |addr_offset| from the start of the function.
108 uint16_t cfi_data;
109
110 // Return the RA offset for the current unwind row.
ra_offsetbase::trace_event::__anon42cf62ef0111::CFIUnwindDataRow111 uint16_t ra_offset() const {
112 return static_cast<uint16_t>((cfi_data & kRAMask) << kRAShift);
113 }
114
115 // Returns the CFA offset for the current unwind row.
cfa_offsetbase::trace_event::__anon42cf62ef0111::CFIUnwindDataRow116 uint16_t cfa_offset() const { return cfi_data & kCFAMask; }
117 };
118
119 static_assert(
120 sizeof(CFIUnwindDataRow) == 4,
121 "The CFIUnwindDataRow struct must be exactly 4 bytes for searching.");
122
123 ABSL_CONST_INIT thread_local CFIBacktraceAndroid::CFICache cfi_cache;
124
125 } // namespace
126
127 // static
GetInitializedInstance()128 CFIBacktraceAndroid* CFIBacktraceAndroid::GetInitializedInstance() {
129 static CFIBacktraceAndroid* instance = new CFIBacktraceAndroid();
130 return instance;
131 }
132
133 // static
is_chrome_address(uintptr_t pc)134 bool CFIBacktraceAndroid::is_chrome_address(uintptr_t pc) {
135 return pc >= base::android::kStartOfText && pc < executable_end_addr();
136 }
137
138 // static
executable_start_addr()139 uintptr_t CFIBacktraceAndroid::executable_start_addr() {
140 return reinterpret_cast<uintptr_t>(&__executable_start);
141 }
142
143 // static
executable_end_addr()144 uintptr_t CFIBacktraceAndroid::executable_end_addr() {
145 return base::android::kEndOfText;
146 }
147
CFIBacktraceAndroid()148 CFIBacktraceAndroid::CFIBacktraceAndroid() {
149 // This file name is defined by extract_unwind_tables.gni.
150 static constexpr char kCfiFileName[] = "assets/unwind_cfi_32";
151 static constexpr char kSplitName[] = "stack_unwinder";
152
153 MemoryMappedFile::Region cfi_region;
154 int fd = base::android::OpenApkAsset(kCfiFileName, kSplitName, &cfi_region);
155 if (fd < 0) {
156 return;
157 }
158 cfi_mmap_ = std::make_unique<MemoryMappedFile>();
159 // The CFI region starts at |cfi_region.offset|.
160 if (!cfi_mmap_->Initialize(base::File(fd), cfi_region)) {
161 return;
162 }
163
164 ParseCFITables();
165 can_unwind_stack_frames_ = true;
166 }
167
168 CFIBacktraceAndroid::~CFIBacktraceAndroid() = default;
169
ParseCFITables()170 void CFIBacktraceAndroid::ParseCFITables() {
171 // The first 4 bytes in the file is the number of entries in UNW_INDEX table.
172 size_t unw_index_size = 0;
173 memcpy(&unw_index_size, cfi_mmap_->data(), sizeof(unw_index_size));
174 // UNW_INDEX table starts after 4 bytes.
175 unw_index_function_col_ =
176 reinterpret_cast<const uintptr_t*>(cfi_mmap_->data()) + 1;
177 unw_index_row_count_ = unw_index_size;
178 unw_index_indices_col_ = reinterpret_cast<const uint16_t*>(
179 (unw_index_function_col_ + unw_index_row_count_).get());
180
181 // The UNW_DATA table data is right after the end of UNW_INDEX table.
182 // Interpret the UNW_DATA table as an array of 2 byte numbers since the
183 // indexes we have from the UNW_INDEX table are in terms of 2 bytes.
184 unw_data_start_addr_ = unw_index_indices_col_ + unw_index_row_count_;
185 }
186
Unwind(const void ** out_trace,size_t max_depth)187 size_t CFIBacktraceAndroid::Unwind(const void** out_trace, size_t max_depth) {
188 // This function walks the stack using the call frame information to find the
189 // return addresses of all the functions that belong to current binary in call
190 // stack. For each function the CFI table defines the offset of the previous
191 // call frame and offset where the return address is stored.
192 if (!can_unwind_stack_frames())
193 return 0;
194
195 // Get the current register state. This register state can be taken at any
196 // point in the function and the unwind information would be for this point.
197 // Define local variables before trying to get the current PC and SP to make
198 // sure the register state obtained is consistent with each other.
199 uintptr_t pc = 0, sp = 0;
200 asm volatile("mov %0, pc" : "=r"(pc));
201 asm volatile("mov %0, sp" : "=r"(sp));
202
203 return Unwind(pc, sp, /*lr=*/0, out_trace, max_depth);
204 }
205
Unwind(uintptr_t pc,uintptr_t sp,uintptr_t lr,const void ** out_trace,size_t max_depth)206 size_t CFIBacktraceAndroid::Unwind(uintptr_t pc,
207 uintptr_t sp,
208 uintptr_t lr,
209 const void** out_trace,
210 size_t max_depth) {
211 if (!can_unwind_stack_frames())
212 return 0;
213
214 // We can only unwind as long as the pc is within the chrome.so.
215 size_t depth = 0;
216 while (is_chrome_address(pc) && depth < max_depth) {
217 out_trace[depth++] = reinterpret_cast<void*>(pc);
218 // The offset of function from the start of the chrome.so binary:
219 uintptr_t func_addr = pc - executable_start_addr();
220 CFIRow cfi{};
221 if (!FindCFIRowForPC(func_addr, &cfi)) {
222 if (depth == 1 && lr != 0 && pc != lr) {
223 // If CFI data is not found for the frame, then we stopped in prolog of
224 // a function. The return address is stored in LR when in function
225 // prolog. So, update the PC with address in LR and do not update SP
226 // since SP was not updated by the prolog yet.
227 // TODO(ssid): Write tests / add info to detect if we are actually in
228 // function prolog. https://crbug.com/898276
229 pc = lr;
230 continue;
231 }
232 break;
233 }
234
235 // The rules for unwinding using the CFI information are:
236 // SP_prev = SP_cur + cfa_offset and
237 // PC_prev = * (SP_prev - ra_offset).
238 sp = sp + cfi.cfa_offset;
239 memcpy(&pc, reinterpret_cast<uintptr_t*>(sp - cfi.ra_offset),
240 sizeof(uintptr_t));
241 }
242 return depth;
243 }
244
FindCFIRowForPC(uintptr_t func_addr,CFIBacktraceAndroid::CFIRow * cfi)245 bool CFIBacktraceAndroid::FindCFIRowForPC(uintptr_t func_addr,
246 CFIBacktraceAndroid::CFIRow* cfi) {
247 if (!can_unwind_stack_frames())
248 return false;
249
250 *cfi = {0};
251 if (cfi_cache.Find(func_addr, cfi)) {
252 return true;
253 }
254
255 // Consider each column of UNW_INDEX table as arrays of uintptr_t (function
256 // addresses) and uint16_t (indices). Define start and end iterator on the
257 // first column array (addresses) and use std::lower_bound() to binary search
258 // on this array to find the required function address.
259 static const uintptr_t* const unw_index_fn_end =
260 unw_index_function_col_ + unw_index_row_count_;
261 const uintptr_t* found = std::lower_bound(unw_index_function_col_.get(),
262 unw_index_fn_end, func_addr);
263
264 // If found is start, then the given function is not in the table. If the
265 // given pc is start of a function then we cannot unwind.
266 if (found == unw_index_function_col_ || *found == func_addr)
267 return false;
268
269 // std::lower_bound() returns the iter that corresponds to the first address
270 // that is greater than the given address. So, the required iter is always one
271 // less than the value returned by std::lower_bound().
272 --found;
273 uintptr_t func_start_addr = *found;
274 size_t row_num = static_cast<size_t>(found - unw_index_function_col_);
275 uint16_t index = unw_index_indices_col_[row_num];
276 DCHECK_LE(func_start_addr, func_addr);
277 // If the index is CANT_UNWIND then we do not have unwind infomation for the
278 // function.
279 if (index == kCantUnwind)
280 return false;
281
282 // The unwind data for the current function is at an offsset of the index
283 // found in UNW_INDEX table.
284 const uint16_t* unwind_data = unw_data_start_addr_ + index;
285 // The value of first 2 bytes is the CFI data row count for the function.
286 uint16_t row_count = 0;
287 memcpy(&row_count, unwind_data, sizeof(row_count));
288 // And the actual CFI rows start after 2 bytes from the |unwind_data|. Cast
289 // the data into an array of CFIUnwindDataRow since the struct is designed to
290 // represent each row. We should be careful to read only |row_count| number of
291 // elements in the array.
292 const CFIUnwindDataRow* function_data =
293 reinterpret_cast<const CFIUnwindDataRow*>(unwind_data + 1);
294
295 // Iterate through the CFI rows of the function to find the row that gives
296 // offset for the given instruction address.
297 CFIUnwindDataRow cfi_row = {0, 0};
298 uint16_t ra_offset = 0;
299 for (uint16_t i = 0; i < row_count; ++i) {
300 CFIUnwindDataRow row;
301 memcpy(&row, function_data + i, sizeof(CFIUnwindDataRow));
302 // The return address of the function is the instruction that is not yet
303 // been executed. The cfi row specifies the unwind info before executing the
304 // given instruction. If the given address is equal to the instruction
305 // offset, then use the current row. Or use the row with highest address
306 // less than the given address.
307 if (row.addr_offset + func_start_addr > func_addr)
308 break;
309
310 cfi_row = row;
311 // The ra offset of the last specified row should be used, if unspecified.
312 // So, keep updating the RA offset till we reach the correct CFI row.
313 // TODO(ssid): This should be fixed in the format and we should always
314 // output ra offset.
315 if (cfi_row.ra_offset())
316 ra_offset = cfi_row.ra_offset();
317 }
318 DCHECK_NE(0u, cfi_row.addr_offset);
319 *cfi = {cfi_row.cfa_offset(), ra_offset};
320 DCHECK(cfi->cfa_offset);
321 DCHECK(cfi->ra_offset);
322
323 // safe to update since the cache is thread local.
324 cfi_cache.Add(func_addr, *cfi);
325 return true;
326 }
327
Add(uintptr_t address,CFIRow cfi)328 void CFIBacktraceAndroid::CFICache::Add(uintptr_t address, CFIRow cfi) {
329 cache_[address % kLimit] = {address, cfi};
330 }
331
Find(uintptr_t address,CFIRow * cfi)332 bool CFIBacktraceAndroid::CFICache::Find(uintptr_t address, CFIRow* cfi) {
333 if (cache_[address % kLimit].address == address) {
334 *cfi = cache_[address % kLimit].cfi;
335 return true;
336 }
337 return false;
338 }
339
340 } // namespace trace_event
341 } // namespace base
342