blob: e290b849675981b901e1945325707813add73dec [file] [log] [blame]
Yabin Cui9e402bb2015-09-22 04:46:57 +00001/*
2 * Copyright (C) 2015 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 "BacktraceOffline.h"
18
19extern "C" {
20#define UNW_REMOTE_ONLY
21#include <dwarf.h>
22}
23
Yabin Cuic4a480e2017-02-02 15:25:08 -080024#include <pthread.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000025#include <stdint.h>
Yabin Cui2ad59db2015-12-08 18:43:00 -080026#include <stdio.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000027#include <string.h>
Yabin Cui2ad59db2015-12-08 18:43:00 -080028#include <sys/stat.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000029#include <sys/types.h>
30#include <ucontext.h>
31#include <unistd.h>
32
Yabin Cuib791a762016-03-18 18:46:08 -070033#include <memory>
Yabin Cui26369a32017-02-10 18:05:34 -080034#include <mutex>
Yabin Cui9e402bb2015-09-22 04:46:57 +000035#include <string>
36#include <vector>
37
Yabin Cuib791a762016-03-18 18:46:08 -070038#include <android-base/file.h>
Colin Cross06d31492016-12-15 12:55:03 -080039#include <android-base/macros.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000040#include <backtrace/Backtrace.h>
41#include <backtrace/BacktraceMap.h>
Yabin Cuib791a762016-03-18 18:46:08 -070042#include <ziparchive/zip_archive.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000043
44#pragma clang diagnostic push
45#pragma clang diagnostic ignored "-Wunused-parameter"
46
47#include <llvm/ADT/StringRef.h>
48#include <llvm/Object/Binary.h>
49#include <llvm/Object/ELFObjectFile.h>
50#include <llvm/Object/ObjectFile.h>
51
52#pragma clang diagnostic pop
53
54#include "BacktraceLog.h"
55
Yabin Cui5d991bc2016-11-15 17:47:09 -080056struct EhFrame {
57 uint64_t hdr_vaddr;
58 uint64_t vaddr;
59 uint64_t fde_table_offset;
60 uintptr_t min_func_vaddr;
61 std::vector<uint8_t> hdr_data;
62 std::vector<uint8_t> data;
63};
64
65struct ArmIdxEntry {
66 uint32_t func_offset;
67 uint32_t value;
68};
69
70struct ArmExidx {
71 uint64_t exidx_vaddr;
72 uint64_t extab_vaddr;
73 std::vector<ArmIdxEntry> exidx_data;
74 std::vector<uint8_t> extab_data;
75 // There is a one-to-one map from exidx_data.func_offset to func_vaddr_array.
76 std::vector<uint32_t> func_vaddr_array;
77};
78
79struct DebugFrameInfo {
80 bool has_arm_exidx;
81 bool has_eh_frame;
82 bool has_debug_frame;
83 bool has_gnu_debugdata;
84
85 EhFrame eh_frame;
86 ArmExidx arm_exidx;
87
88 uint64_t min_vaddr;
89 uint64_t text_end_vaddr;
90
91 DebugFrameInfo() : has_arm_exidx(false), has_eh_frame(false),
92 has_debug_frame(false), has_gnu_debugdata(false) { }
93};
94
Yabin Cui9e402bb2015-09-22 04:46:57 +000095void Space::Clear() {
96 start = 0;
97 end = 0;
98 data = nullptr;
99}
100
101size_t Space::Read(uint64_t addr, uint8_t* buffer, size_t size) {
102 if (addr >= start && addr < end) {
103 size_t read_size = std::min(size, static_cast<size_t>(end - addr));
104 memcpy(buffer, data + (addr - start), read_size);
105 return read_size;
106 }
107 return 0;
108}
109
110static int FindProcInfo(unw_addr_space_t addr_space, unw_word_t ip, unw_proc_info* proc_info,
111 int need_unwind_info, void* arg) {
112 BacktraceOffline* backtrace = reinterpret_cast<BacktraceOffline*>(arg);
113 bool result = backtrace->FindProcInfo(addr_space, ip, proc_info, need_unwind_info);
114 return result ? 0 : -UNW_EINVAL;
115}
116
117static void PutUnwindInfo(unw_addr_space_t, unw_proc_info_t*, void*) {
118}
119
120static int GetDynInfoListAddr(unw_addr_space_t, unw_word_t*, void*) {
121 return -UNW_ENOINFO;
122}
123
124static int AccessMem(unw_addr_space_t, unw_word_t addr, unw_word_t* value, int write, void* arg) {
125 if (write == 1) {
126 return -UNW_EINVAL;
127 }
128 BacktraceOffline* backtrace = reinterpret_cast<BacktraceOffline*>(arg);
129 *value = 0;
130 size_t read_size = backtrace->Read(addr, reinterpret_cast<uint8_t*>(value), sizeof(unw_word_t));
131 // Strictly we should check if read_size matches sizeof(unw_word_t), but it is possible in
132 // .eh_frame_hdr that the section can end at a position not aligned in sizeof(unw_word_t), and
133 // we should permit the read at the end of the section.
134 return (read_size > 0u ? 0 : -UNW_EINVAL);
135}
136
137static int AccessReg(unw_addr_space_t, unw_regnum_t unwind_reg, unw_word_t* value, int write,
138 void* arg) {
139 if (write == 1) {
140 return -UNW_EINVAL;
141 }
142 BacktraceOffline* backtrace = reinterpret_cast<BacktraceOffline*>(arg);
143 uint64_t reg_value;
144 bool result = backtrace->ReadReg(unwind_reg, &reg_value);
145 if (result) {
146 *value = static_cast<unw_word_t>(reg_value);
147 }
148 return result ? 0 : -UNW_EINVAL;
149}
150
151static int AccessFpReg(unw_addr_space_t, unw_regnum_t, unw_fpreg_t*, int, void*) {
152 return -UNW_EINVAL;
153}
154
155static int Resume(unw_addr_space_t, unw_cursor_t*, void*) {
156 return -UNW_EINVAL;
157}
158
159static int GetProcName(unw_addr_space_t, unw_word_t, char*, size_t, unw_word_t*, void*) {
160 return -UNW_EINVAL;
161}
162
163static unw_accessors_t accessors = {
164 .find_proc_info = FindProcInfo,
165 .put_unwind_info = PutUnwindInfo,
166 .get_dyn_info_list_addr = GetDynInfoListAddr,
167 .access_mem = AccessMem,
168 .access_reg = AccessReg,
169 .access_fpreg = AccessFpReg,
170 .resume = Resume,
171 .get_proc_name = GetProcName,
172};
173
174bool BacktraceOffline::Unwind(size_t num_ignore_frames, ucontext_t* context) {
175 if (context == nullptr) {
176 BACK_LOGW("The context is needed for offline backtracing.");
Yabin Cuif8808282017-12-12 18:04:10 -0800177 error_.error_code = BACKTRACE_UNWIND_ERROR_NO_CONTEXT;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000178 return false;
179 }
180 context_ = context;
Yabin Cuif8808282017-12-12 18:04:10 -0800181 error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000182
183 unw_addr_space_t addr_space = unw_create_addr_space(&accessors, 0);
184 unw_cursor_t cursor;
185 int ret = unw_init_remote(&cursor, addr_space, this);
186 if (ret != 0) {
187 BACK_LOGW("unw_init_remote failed %d", ret);
188 unw_destroy_addr_space(addr_space);
Yabin Cuif8808282017-12-12 18:04:10 -0800189 error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000190 return false;
191 }
192 size_t num_frames = 0;
Yabin Cuif8808282017-12-12 18:04:10 -0800193 while (true) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000194 unw_word_t pc;
195 ret = unw_get_reg(&cursor, UNW_REG_IP, &pc);
196 if (ret < 0) {
197 BACK_LOGW("Failed to read IP %d", ret);
198 break;
199 }
200 unw_word_t sp;
201 ret = unw_get_reg(&cursor, UNW_REG_SP, &sp);
202 if (ret < 0) {
203 BACK_LOGW("Failed to read SP %d", ret);
204 break;
205 }
206
207 if (num_ignore_frames == 0) {
208 frames_.resize(num_frames + 1);
209 backtrace_frame_data_t* frame = &frames_[num_frames];
210 frame->num = num_frames;
211 frame->pc = static_cast<uintptr_t>(pc);
212 frame->sp = static_cast<uintptr_t>(sp);
213 frame->stack_size = 0;
214
215 if (num_frames > 0) {
216 backtrace_frame_data_t* prev = &frames_[num_frames - 1];
217 prev->stack_size = frame->sp - prev->sp;
218 }
219 frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);
220 FillInMap(frame->pc, &frame->map);
221 num_frames++;
222 } else {
223 num_ignore_frames--;
224 }
Yabin Cui0ca49b02017-12-10 17:55:12 -0800225 is_debug_frame_used_ = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000226 ret = unw_step(&cursor);
Yabin Cuif8808282017-12-12 18:04:10 -0800227 if (ret <= 0) {
228 if (error_.error_code == BACKTRACE_UNWIND_NO_ERROR) {
229 error_.error_code = BACKTRACE_UNWIND_ERROR_EXECUTE_DWARF_INSTRUCTION_FAILED;
230 }
231 break;
232 }
233 if (num_frames == MAX_BACKTRACE_FRAMES) {
234 error_.error_code = BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT;
235 break;
236 }
237 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000238
239 unw_destroy_addr_space(addr_space);
240 context_ = nullptr;
241 return true;
242}
243
244bool BacktraceOffline::ReadWord(uintptr_t ptr, word_t* out_value) {
245 size_t bytes_read = Read(ptr, reinterpret_cast<uint8_t*>(out_value), sizeof(word_t));
246 return bytes_read == sizeof(word_t);
247}
248
249size_t BacktraceOffline::Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
250 // Normally, libunwind needs stack information and call frame information to do remote unwinding.
251 // If call frame information is stored in .debug_frame, libunwind can read it from file
252 // by itself. If call frame information is stored in .eh_frame, we need to provide data in
253 // .eh_frame/.eh_frame_hdr sections.
254 // The order of readings below doesn't matter, as the spaces don't overlap with each other.
255 size_t read_size = eh_frame_hdr_space_.Read(addr, buffer, bytes);
256 if (read_size != 0) {
257 return read_size;
258 }
259 read_size = eh_frame_space_.Read(addr, buffer, bytes);
260 if (read_size != 0) {
261 return read_size;
262 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800263 read_size = arm_exidx_space_.Read(addr, buffer, bytes);
264 if (read_size != 0) {
265 return read_size;
266 }
267 read_size = arm_extab_space_.Read(addr, buffer, bytes);
268 if (read_size != 0) {
269 return read_size;
270 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000271 read_size = stack_space_.Read(addr, buffer, bytes);
Yabin Cuif8808282017-12-12 18:04:10 -0800272 if (read_size != 0) {
273 return read_size;
274 }
275 error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED;
276 error_.error_info.addr = addr;
277 return 0;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000278}
279
Yabin Cui9e402bb2015-09-22 04:46:57 +0000280bool BacktraceOffline::FindProcInfo(unw_addr_space_t addr_space, uint64_t ip,
281 unw_proc_info_t* proc_info, int need_unwind_info) {
282 backtrace_map_t map;
283 FillInMap(ip, &map);
284 if (!BacktraceMap::IsValid(map)) {
Yabin Cuif8808282017-12-12 18:04:10 -0800285 error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000286 return false;
287 }
288 const std::string& filename = map.name;
289 DebugFrameInfo* debug_frame = GetDebugFrameInFile(filename);
290 if (debug_frame == nullptr) {
Yabin Cuif8808282017-12-12 18:04:10 -0800291 error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000292 return false;
293 }
Yabin Cuif8808282017-12-12 18:04:10 -0800294 // Each FindProcInfo() is a new attempt to unwind, so reset the reason.
295 error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000296
297 eh_frame_hdr_space_.Clear();
298 eh_frame_space_.Clear();
Yabin Cui5d991bc2016-11-15 17:47:09 -0800299 arm_exidx_space_.Clear();
300 arm_extab_space_.Clear();
301
302 // vaddr in the elf file.
303 uint64_t ip_vaddr = ip - map.start + debug_frame->min_vaddr;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800304
Yabin Cuic4a480e2017-02-02 15:25:08 -0800305 // The unwind info can come from .ARM.exidx or .eh_frame, or .debug_frame/.gnu_debugdata.
306 // First check .eh_frame/.debug_frame, then check .ARM.exidx. Because .eh_frame/.debug_frame has
307 // function range for each entry, by matching ip address with the function range, we know exactly
308 // whether the ip address hits an entry. But .ARM.exidx doesn't have function range for each
309 // entry, it thinks that an ip address hits an entry when (entry.addr <= ip < next_entry.addr).
310 // To prevent ip addresses hit in .eh_frame/.debug_frame being regarded as addresses hit in
311 // .ARM.exidx, we need to check .eh_frame/.debug_frame first.
Yabin Cui5d991bc2016-11-15 17:47:09 -0800312 if (debug_frame->has_eh_frame) {
313 if (ip_vaddr >= debug_frame->eh_frame.min_func_vaddr &&
314 ip_vaddr < debug_frame->text_end_vaddr) {
315 // Prepare eh_frame_hdr space and eh_frame space.
316 eh_frame_hdr_space_.start = ip - ip_vaddr + debug_frame->eh_frame.hdr_vaddr;
317 eh_frame_hdr_space_.end =
318 eh_frame_hdr_space_.start + debug_frame->eh_frame.hdr_data.size();
319 eh_frame_hdr_space_.data = debug_frame->eh_frame.hdr_data.data();
Yabin Cui5d991bc2016-11-15 17:47:09 -0800320 eh_frame_space_.start = ip - ip_vaddr + debug_frame->eh_frame.vaddr;
321 eh_frame_space_.end = eh_frame_space_.start + debug_frame->eh_frame.data.size();
322 eh_frame_space_.data = debug_frame->eh_frame.data.data();
323
324 unw_dyn_info di;
325 memset(&di, '\0', sizeof(di));
326 di.start_ip = map.start;
327 di.end_ip = map.end;
328 di.format = UNW_INFO_FORMAT_REMOTE_TABLE;
329 di.u.rti.name_ptr = 0;
330 di.u.rti.segbase = eh_frame_hdr_space_.start;
331 di.u.rti.table_data =
332 eh_frame_hdr_space_.start + debug_frame->eh_frame.fde_table_offset;
333 di.u.rti.table_len = (eh_frame_hdr_space_.end - di.u.rti.table_data) / sizeof(unw_word_t);
334 // TODO: Do it ourselves is more efficient than calling this function.
335 int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
336 if (ret == 0) {
337 return true;
338 }
339 }
340 }
Yabin Cui0ca49b02017-12-10 17:55:12 -0800341 if (!is_debug_frame_used_ && (debug_frame->has_debug_frame || debug_frame->has_gnu_debugdata)) {
342 is_debug_frame_used_ = true;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800343 unw_dyn_info_t di;
Yabin Cui4a26eaf2017-12-05 17:40:48 -0800344 unw_word_t segbase = map.start - debug_frame->min_vaddr;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800345 // TODO: http://b/32916571
346 // TODO: Do it ourselves is more efficient than calling libunwind functions.
347 int found = dwarf_find_debug_frame(0, &di, ip, segbase, filename.c_str(), map.start, map.end);
348 if (found == 1) {
349 int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
350 if (ret == 0) {
351 return true;
352 }
353 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000354 }
Yabin Cuic4a480e2017-02-02 15:25:08 -0800355
356 if (debug_frame->has_arm_exidx) {
357 auto& func_vaddrs = debug_frame->arm_exidx.func_vaddr_array;
358 if (ip_vaddr >= func_vaddrs[0] && ip_vaddr < debug_frame->text_end_vaddr) {
359 // Use binary search to find the correct function.
360 auto it = std::upper_bound(func_vaddrs.begin(), func_vaddrs.end(),
361 static_cast<uint32_t>(ip_vaddr));
362 if (it != func_vaddrs.begin()) {
363 --it;
364 // Found the exidx entry.
365 size_t index = it - func_vaddrs.begin();
366 proc_info->start_ip = *it;
367 proc_info->format = UNW_INFO_FORMAT_ARM_EXIDX;
368 proc_info->unwind_info = reinterpret_cast<void*>(
369 static_cast<uintptr_t>(index * sizeof(ArmIdxEntry) +
370 debug_frame->arm_exidx.exidx_vaddr +
371 debug_frame->min_vaddr));
372 eh_frame_hdr_space_.Clear();
373 eh_frame_space_.Clear();
374 // Prepare arm_exidx space and arm_extab space.
375 arm_exidx_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.exidx_vaddr;
376 arm_exidx_space_.end = arm_exidx_space_.start +
377 debug_frame->arm_exidx.exidx_data.size() * sizeof(ArmIdxEntry);
378 arm_exidx_space_.data = reinterpret_cast<const uint8_t*>(
379 debug_frame->arm_exidx.exidx_data.data());
380
381 arm_extab_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.extab_vaddr;
382 arm_extab_space_.end = arm_extab_space_.start +
383 debug_frame->arm_exidx.extab_data.size();
384 arm_extab_space_.data = debug_frame->arm_exidx.extab_data.data();
385 return true;
386 }
387 }
388 }
Yabin Cuif8808282017-12-12 18:04:10 -0800389 error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000390 return false;
391}
392
393bool BacktraceOffline::ReadReg(size_t reg, uint64_t* value) {
394 bool result = true;
395#if defined(__arm__)
396 switch (reg) {
397 case UNW_ARM_R0:
398 *value = context_->uc_mcontext.arm_r0;
399 break;
400 case UNW_ARM_R1:
401 *value = context_->uc_mcontext.arm_r1;
402 break;
403 case UNW_ARM_R2:
404 *value = context_->uc_mcontext.arm_r2;
405 break;
406 case UNW_ARM_R3:
407 *value = context_->uc_mcontext.arm_r3;
408 break;
409 case UNW_ARM_R4:
410 *value = context_->uc_mcontext.arm_r4;
411 break;
412 case UNW_ARM_R5:
413 *value = context_->uc_mcontext.arm_r5;
414 break;
415 case UNW_ARM_R6:
416 *value = context_->uc_mcontext.arm_r6;
417 break;
418 case UNW_ARM_R7:
419 *value = context_->uc_mcontext.arm_r7;
420 break;
421 case UNW_ARM_R8:
422 *value = context_->uc_mcontext.arm_r8;
423 break;
424 case UNW_ARM_R9:
425 *value = context_->uc_mcontext.arm_r9;
426 break;
427 case UNW_ARM_R10:
428 *value = context_->uc_mcontext.arm_r10;
429 break;
430 case UNW_ARM_R11:
431 *value = context_->uc_mcontext.arm_fp;
432 break;
433 case UNW_ARM_R12:
434 *value = context_->uc_mcontext.arm_ip;
435 break;
436 case UNW_ARM_R13:
437 *value = context_->uc_mcontext.arm_sp;
438 break;
439 case UNW_ARM_R14:
440 *value = context_->uc_mcontext.arm_lr;
441 break;
442 case UNW_ARM_R15:
443 *value = context_->uc_mcontext.arm_pc;
444 break;
445 default:
446 result = false;
447 }
448#elif defined(__aarch64__)
449 if (reg <= UNW_AARCH64_PC) {
450 *value = context_->uc_mcontext.regs[reg];
451 } else {
452 result = false;
453 }
454#elif defined(__x86_64__)
455 switch (reg) {
456 case UNW_X86_64_R8:
457 *value = context_->uc_mcontext.gregs[REG_R8];
458 break;
459 case UNW_X86_64_R9:
460 *value = context_->uc_mcontext.gregs[REG_R9];
461 break;
462 case UNW_X86_64_R10:
463 *value = context_->uc_mcontext.gregs[REG_R10];
464 break;
465 case UNW_X86_64_R11:
466 *value = context_->uc_mcontext.gregs[REG_R11];
467 break;
468 case UNW_X86_64_R12:
469 *value = context_->uc_mcontext.gregs[REG_R12];
470 break;
471 case UNW_X86_64_R13:
472 *value = context_->uc_mcontext.gregs[REG_R13];
473 break;
474 case UNW_X86_64_R14:
475 *value = context_->uc_mcontext.gregs[REG_R14];
476 break;
477 case UNW_X86_64_R15:
478 *value = context_->uc_mcontext.gregs[REG_R15];
479 break;
480 case UNW_X86_64_RDI:
481 *value = context_->uc_mcontext.gregs[REG_RDI];
482 break;
483 case UNW_X86_64_RSI:
484 *value = context_->uc_mcontext.gregs[REG_RSI];
485 break;
486 case UNW_X86_64_RBP:
487 *value = context_->uc_mcontext.gregs[REG_RBP];
488 break;
489 case UNW_X86_64_RBX:
490 *value = context_->uc_mcontext.gregs[REG_RBX];
491 break;
492 case UNW_X86_64_RDX:
493 *value = context_->uc_mcontext.gregs[REG_RDX];
494 break;
495 case UNW_X86_64_RAX:
496 *value = context_->uc_mcontext.gregs[REG_RAX];
497 break;
498 case UNW_X86_64_RCX:
499 *value = context_->uc_mcontext.gregs[REG_RCX];
500 break;
501 case UNW_X86_64_RSP:
502 *value = context_->uc_mcontext.gregs[REG_RSP];
503 break;
504 case UNW_X86_64_RIP:
505 *value = context_->uc_mcontext.gregs[REG_RIP];
506 break;
507 default:
508 result = false;
509 }
510#elif defined(__i386__)
511 switch (reg) {
512 case UNW_X86_GS:
513 *value = context_->uc_mcontext.gregs[REG_GS];
514 break;
515 case UNW_X86_FS:
516 *value = context_->uc_mcontext.gregs[REG_FS];
517 break;
518 case UNW_X86_ES:
519 *value = context_->uc_mcontext.gregs[REG_ES];
520 break;
521 case UNW_X86_DS:
522 *value = context_->uc_mcontext.gregs[REG_DS];
523 break;
524 case UNW_X86_EAX:
525 *value = context_->uc_mcontext.gregs[REG_EAX];
526 break;
527 case UNW_X86_EBX:
528 *value = context_->uc_mcontext.gregs[REG_EBX];
529 break;
530 case UNW_X86_ECX:
531 *value = context_->uc_mcontext.gregs[REG_ECX];
532 break;
533 case UNW_X86_EDX:
534 *value = context_->uc_mcontext.gregs[REG_EDX];
535 break;
536 case UNW_X86_ESI:
537 *value = context_->uc_mcontext.gregs[REG_ESI];
538 break;
539 case UNW_X86_EDI:
540 *value = context_->uc_mcontext.gregs[REG_EDI];
541 break;
542 case UNW_X86_EBP:
543 *value = context_->uc_mcontext.gregs[REG_EBP];
544 break;
545 case UNW_X86_EIP:
546 *value = context_->uc_mcontext.gregs[REG_EIP];
547 break;
548 case UNW_X86_ESP:
549 *value = context_->uc_mcontext.gregs[REG_ESP];
550 break;
551 case UNW_X86_TRAPNO:
552 *value = context_->uc_mcontext.gregs[REG_TRAPNO];
553 break;
554 case UNW_X86_CS:
555 *value = context_->uc_mcontext.gregs[REG_CS];
556 break;
557 case UNW_X86_EFLAGS:
558 *value = context_->uc_mcontext.gregs[REG_EFL];
559 break;
560 case UNW_X86_SS:
561 *value = context_->uc_mcontext.gregs[REG_SS];
562 break;
563 default:
564 result = false;
565 }
Colin Cross06d31492016-12-15 12:55:03 -0800566#else
567 UNUSED(reg);
568 UNUSED(value);
569 result = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000570#endif
Yabin Cuif8808282017-12-12 18:04:10 -0800571 if (!result) {
572 error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED;
573 error_.error_info.regno = reg;
574 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000575 return result;
576}
577
578std::string BacktraceOffline::GetFunctionNameRaw(uintptr_t, uintptr_t* offset) {
579 // We don't have enough information to support this. And it is expensive.
580 *offset = 0;
581 return "";
582}
583
Yabin Cui26369a32017-02-10 18:05:34 -0800584static std::mutex g_lock;
585static std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>* g_debug_frames = nullptr;
586
Yabin Cui9e402bb2015-09-22 04:46:57 +0000587static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename);
588
589DebugFrameInfo* BacktraceOffline::GetDebugFrameInFile(const std::string& filename) {
590 if (cache_file_) {
Yabin Cui26369a32017-02-10 18:05:34 -0800591 std::lock_guard<std::mutex> lock(g_lock);
592 if (g_debug_frames != nullptr) {
593 auto it = g_debug_frames->find(filename);
594 if (it != g_debug_frames->end()) {
595 return it->second.get();
596 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000597 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000598 }
599 DebugFrameInfo* debug_frame = ReadDebugFrameFromFile(filename);
600 if (cache_file_) {
Yabin Cui26369a32017-02-10 18:05:34 -0800601 std::lock_guard<std::mutex> lock(g_lock);
602 if (g_debug_frames == nullptr) {
603 g_debug_frames = new std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>;
604 }
605 auto pair = g_debug_frames->emplace(filename, std::unique_ptr<DebugFrameInfo>(debug_frame));
606 if (!pair.second) {
607 debug_frame = pair.first->second.get();
608 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000609 }
610 return debug_frame;
611}
612
613static bool OmitEncodedValue(uint8_t encode, const uint8_t*& p) {
614 if (encode == DW_EH_PE_omit) {
615 return 0;
616 }
617 uint8_t format = encode & 0x0f;
618 switch (format) {
619 case DW_EH_PE_ptr:
620 p += sizeof(unw_word_t);
621 break;
622 case DW_EH_PE_uleb128:
623 case DW_EH_PE_sleb128:
624 while ((*p & 0x80) != 0) {
625 ++p;
626 }
627 ++p;
628 break;
629 case DW_EH_PE_udata2:
630 case DW_EH_PE_sdata2:
631 p += 2;
632 break;
633 case DW_EH_PE_udata4:
634 case DW_EH_PE_sdata4:
635 p += 4;
636 break;
637 case DW_EH_PE_udata8:
638 case DW_EH_PE_sdata8:
639 p += 8;
640 break;
641 default:
642 return false;
643 }
644 return true;
645}
646
647static bool GetFdeTableOffsetInEhFrameHdr(const std::vector<uint8_t>& data,
648 uint64_t* table_offset_in_eh_frame_hdr) {
649 const uint8_t* p = data.data();
650 const uint8_t* end = p + data.size();
651 if (p + 4 > end) {
652 return false;
653 }
654 uint8_t version = *p++;
655 if (version != 1) {
656 return false;
657 }
658 uint8_t eh_frame_ptr_encode = *p++;
659 uint8_t fde_count_encode = *p++;
660 uint8_t fde_table_encode = *p++;
661
662 if (fde_table_encode != (DW_EH_PE_datarel | DW_EH_PE_sdata4)) {
663 return false;
664 }
665
666 if (!OmitEncodedValue(eh_frame_ptr_encode, p) || !OmitEncodedValue(fde_count_encode, p)) {
667 return false;
668 }
669 if (p >= end) {
670 return false;
671 }
672 *table_offset_in_eh_frame_hdr = p - data.data();
673 return true;
674}
675
Yabin Cui9e402bb2015-09-22 04:46:57 +0000676template <class ELFT>
677DebugFrameInfo* ReadDebugFrameFromELFFile(const llvm::object::ELFFile<ELFT>* elf) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800678 DebugFrameInfo* result = new DebugFrameInfo;
679 result->text_end_vaddr = std::numeric_limits<uint64_t>::max();
680
Yabin Cui9e402bb2015-09-22 04:46:57 +0000681 bool has_eh_frame_hdr = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000682 bool has_eh_frame = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000683
Stephen Hines19c30e92016-03-08 01:23:43 -0800684 for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000685 llvm::ErrorOr<llvm::StringRef> name = elf->getSectionName(&*it);
686 if (name) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800687 std::string s = name.get();
688 if (s == ".debug_frame") {
689 result->has_debug_frame = true;
690 } else if (s == ".gnu_debugdata") {
691 result->has_gnu_debugdata = true;
692 } else if (s == ".eh_frame_hdr") {
693 result->eh_frame.hdr_vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000694 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
695 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800696 result->eh_frame.hdr_data.insert(result->eh_frame.hdr_data.end(),
697 data->data(), data->data() + data->size());
698
699 uint64_t fde_table_offset;
700 if (GetFdeTableOffsetInEhFrameHdr(result->eh_frame.hdr_data,
701 &fde_table_offset)) {
702 result->eh_frame.fde_table_offset = fde_table_offset;
703 // Make sure we have at least one entry in fde_table.
704 if (fde_table_offset + 2 * sizeof(int32_t) <= data->size()) {
705 intptr_t eh_frame_hdr_vaddr = it->sh_addr;
706 int32_t sdata;
707 uint8_t* p = result->eh_frame.hdr_data.data() + fde_table_offset;
708 memcpy(&sdata, p, sizeof(sdata));
709 result->eh_frame.min_func_vaddr = eh_frame_hdr_vaddr + sdata;
710 has_eh_frame_hdr = true;
711 }
712 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000713 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800714 } else if (s == ".eh_frame") {
715 result->eh_frame.vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000716 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
717 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800718 result->eh_frame.data.insert(result->eh_frame.data.end(),
719 data->data(), data->data() + data->size());
720 has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000721 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800722 } else if (s == ".ARM.exidx") {
723 result->arm_exidx.exidx_vaddr = it->sh_addr;
724 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
725 if (data) {
726 size_t entry_count = data->size() / sizeof(ArmIdxEntry);
727 result->arm_exidx.exidx_data.resize(entry_count);
728 memcpy(result->arm_exidx.exidx_data.data(), data->data(),
729 entry_count * sizeof(ArmIdxEntry));
730 if (entry_count > 0u) {
731 // Change IdxEntry.func_offset into vaddr.
732 result->arm_exidx.func_vaddr_array.reserve(entry_count);
733 uint32_t vaddr = it->sh_addr;
734 for (auto& entry : result->arm_exidx.exidx_data) {
735 uint32_t func_offset = entry.func_offset + vaddr;
736 // Clear bit 31 for the prel31 offset.
737 // Arm sets bit 0 to mark it as thumb code, remove the flag.
738 result->arm_exidx.func_vaddr_array.push_back(
739 func_offset & 0x7ffffffe);
740 vaddr += 8;
741 }
742 result->has_arm_exidx = true;
743 }
744 }
745 } else if (s == ".ARM.extab") {
746 result->arm_exidx.extab_vaddr = it->sh_addr;
747 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
748 if (data) {
749 result->arm_exidx.extab_data.insert(result->arm_exidx.extab_data.end(),
750 data->data(), data->data() + data->size());
751 }
752 } else if (s == ".text") {
753 result->text_end_vaddr = it->sh_addr + it->sh_size;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000754 }
755 }
756 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800757
758 if (has_eh_frame_hdr && has_eh_frame) {
759 result->has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000760 }
761
Yabin Cui5d991bc2016-11-15 17:47:09 -0800762 result->min_vaddr = std::numeric_limits<uint64_t>::max();
Stephen Hines19c30e92016-03-08 01:23:43 -0800763 for (auto it = elf->program_header_begin(); it != elf->program_header_end(); ++it) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800764 if ((it->p_type == llvm::ELF::PT_LOAD) && (it->p_flags & llvm::ELF::PF_X)) {
765 if (it->p_vaddr < result->min_vaddr) {
766 result->min_vaddr = it->p_vaddr;
767 }
768 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000769 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800770 if (!result->has_eh_frame && !result->has_arm_exidx && !result->has_debug_frame &&
771 !result->has_gnu_debugdata) {
772 delete result;
773 return nullptr;
774 }
775 return result;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000776}
777
Yabin Cui2ad59db2015-12-08 18:43:00 -0800778static bool IsValidElfPath(const std::string& filename) {
779 static const char elf_magic[] = {0x7f, 'E', 'L', 'F'};
780
781 struct stat st;
782 if (stat(filename.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
783 return false;
784 }
785 FILE* fp = fopen(filename.c_str(), "reb");
786 if (fp == nullptr) {
787 return false;
788 }
789 char buf[4];
790 if (fread(buf, 4, 1, fp) != 1) {
791 fclose(fp);
792 return false;
793 }
794 fclose(fp);
795 return memcmp(buf, elf_magic, 4) == 0;
796}
797
Yabin Cuib791a762016-03-18 18:46:08 -0700798static bool IsValidApkPath(const std::string& apk_path) {
799 static const char zip_preamble[] = {0x50, 0x4b, 0x03, 0x04};
800 struct stat st;
801 if (stat(apk_path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
802 return false;
803 }
804 FILE* fp = fopen(apk_path.c_str(), "reb");
805 if (fp == nullptr) {
806 return false;
807 }
808 char buf[4];
809 if (fread(buf, 4, 1, fp) != 1) {
810 fclose(fp);
811 return false;
812 }
813 fclose(fp);
814 return memcmp(buf, zip_preamble, 4) == 0;
815}
816
817class ScopedZiparchiveHandle {
818 public:
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700819 explicit ScopedZiparchiveHandle(ZipArchiveHandle handle) : handle_(handle) {
Yabin Cuib791a762016-03-18 18:46:08 -0700820 }
821
822 ~ScopedZiparchiveHandle() {
823 CloseArchive(handle_);
824 }
825
826 private:
827 ZipArchiveHandle handle_;
828};
829
830llvm::object::OwningBinary<llvm::object::Binary> OpenEmbeddedElfFile(const std::string& filename) {
831 llvm::object::OwningBinary<llvm::object::Binary> nothing;
832 size_t pos = filename.find("!/");
833 if (pos == std::string::npos) {
834 return nothing;
835 }
836 std::string apk_file = filename.substr(0, pos);
837 std::string elf_file = filename.substr(pos + 2);
838 if (!IsValidApkPath(apk_file)) {
839 BACK_LOGW("%s is not a valid apk file", apk_file.c_str());
840 return nothing;
841 }
842 ZipArchiveHandle handle;
843 int32_t ret_code = OpenArchive(apk_file.c_str(), &handle);
844 if (ret_code != 0) {
845 CloseArchive(handle);
846 BACK_LOGW("failed to open archive %s: %s", apk_file.c_str(), ErrorCodeString(ret_code));
847 return nothing;
848 }
849 ScopedZiparchiveHandle scoped_handle(handle);
850 ZipEntry zentry;
851 ret_code = FindEntry(handle, ZipString(elf_file.c_str()), &zentry);
852 if (ret_code != 0) {
853 BACK_LOGW("failed to find %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
854 ErrorCodeString(ret_code));
855 return nothing;
856 }
857 if (zentry.method != kCompressStored || zentry.compressed_length != zentry.uncompressed_length) {
858 BACK_LOGW("%s is compressed in %s, which doesn't support running directly", elf_file.c_str(),
859 apk_file.c_str());
860 return nothing;
861 }
862 auto buffer_or_err = llvm::MemoryBuffer::getOpenFileSlice(GetFileDescriptor(handle), apk_file,
863 zentry.uncompressed_length,
864 zentry.offset);
865 if (!buffer_or_err) {
866 BACK_LOGW("failed to read %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
867 buffer_or_err.getError().message().c_str());
868 return nothing;
869 }
870 auto binary_or_err = llvm::object::createBinary(buffer_or_err.get()->getMemBufferRef());
871 if (!binary_or_err) {
872 BACK_LOGW("failed to create binary for %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
Pirama Arumuga Nainar80fb4b02016-09-16 16:51:13 -0700873 llvm::toString(binary_or_err.takeError()).c_str());
Yabin Cuib791a762016-03-18 18:46:08 -0700874 return nothing;
875 }
876 return llvm::object::OwningBinary<llvm::object::Binary>(std::move(binary_or_err.get()),
877 std::move(buffer_or_err.get()));
878}
879
Yabin Cui9e402bb2015-09-22 04:46:57 +0000880static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename) {
Yabin Cuib791a762016-03-18 18:46:08 -0700881 llvm::object::OwningBinary<llvm::object::Binary> owning_binary;
882 if (filename.find("!/") != std::string::npos) {
883 owning_binary = OpenEmbeddedElfFile(filename);
884 } else {
885 if (!IsValidElfPath(filename)) {
886 return nullptr;
887 }
888 auto binary_or_err = llvm::object::createBinary(llvm::StringRef(filename));
889 if (!binary_or_err) {
890 return nullptr;
891 }
892 owning_binary = std::move(binary_or_err.get());
Yabin Cui2ad59db2015-12-08 18:43:00 -0800893 }
Yabin Cuib791a762016-03-18 18:46:08 -0700894 llvm::object::Binary* binary = owning_binary.getBinary();
Yabin Cui9e402bb2015-09-22 04:46:57 +0000895 auto obj = llvm::dyn_cast<llvm::object::ObjectFile>(binary);
896 if (obj == nullptr) {
897 return nullptr;
898 }
899 if (auto elf = llvm::dyn_cast<llvm::object::ELF32LEObjectFile>(obj)) {
900 return ReadDebugFrameFromELFFile(elf->getELFFile());
901 }
902 if (auto elf = llvm::dyn_cast<llvm::object::ELF64LEObjectFile>(obj)) {
903 return ReadDebugFrameFromELFFile(elf->getELFFile());
904 }
905 return nullptr;
906}
Christopher Ferris85402162016-01-25 16:17:48 -0800907
908Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
909 const backtrace_stackinfo_t& stack, bool cache_file) {
910 return new BacktraceOffline(pid, tid, map, stack, cache_file);
911}