blob: 9e95563b00ed42be4cc110662f4627fe1840b683 [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
24#include <stdint.h>
Yabin Cui2ad59db2015-12-08 18:43:00 -080025#include <stdio.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000026#include <string.h>
Yabin Cui2ad59db2015-12-08 18:43:00 -080027#include <sys/stat.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000028#include <sys/types.h>
29#include <ucontext.h>
30#include <unistd.h>
31
Yabin Cuib791a762016-03-18 18:46:08 -070032#include <memory>
Yabin Cui9e402bb2015-09-22 04:46:57 +000033#include <string>
34#include <vector>
35
Yabin Cuib791a762016-03-18 18:46:08 -070036#include <android-base/file.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000037#include <backtrace/Backtrace.h>
38#include <backtrace/BacktraceMap.h>
Yabin Cuib791a762016-03-18 18:46:08 -070039#include <ziparchive/zip_archive.h>
Yabin Cui9e402bb2015-09-22 04:46:57 +000040
41#pragma clang diagnostic push
42#pragma clang diagnostic ignored "-Wunused-parameter"
43
44#include <llvm/ADT/StringRef.h>
45#include <llvm/Object/Binary.h>
46#include <llvm/Object/ELFObjectFile.h>
47#include <llvm/Object/ObjectFile.h>
48
49#pragma clang diagnostic pop
50
51#include "BacktraceLog.h"
52
Yabin Cui5d991bc2016-11-15 17:47:09 -080053struct EhFrame {
54 uint64_t hdr_vaddr;
55 uint64_t vaddr;
56 uint64_t fde_table_offset;
57 uintptr_t min_func_vaddr;
58 std::vector<uint8_t> hdr_data;
59 std::vector<uint8_t> data;
60};
61
62struct ArmIdxEntry {
63 uint32_t func_offset;
64 uint32_t value;
65};
66
67struct ArmExidx {
68 uint64_t exidx_vaddr;
69 uint64_t extab_vaddr;
70 std::vector<ArmIdxEntry> exidx_data;
71 std::vector<uint8_t> extab_data;
72 // There is a one-to-one map from exidx_data.func_offset to func_vaddr_array.
73 std::vector<uint32_t> func_vaddr_array;
74};
75
76struct DebugFrameInfo {
77 bool has_arm_exidx;
78 bool has_eh_frame;
79 bool has_debug_frame;
80 bool has_gnu_debugdata;
81
82 EhFrame eh_frame;
83 ArmExidx arm_exidx;
84
85 uint64_t min_vaddr;
86 uint64_t text_end_vaddr;
87
88 DebugFrameInfo() : has_arm_exidx(false), has_eh_frame(false),
89 has_debug_frame(false), has_gnu_debugdata(false) { }
90};
91
92static std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>& g_debug_frames =
93 *new std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>;
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.");
Christopher Ferris206a3b92016-03-09 14:35:54 -0800177 error_ = BACKTRACE_UNWIND_ERROR_NO_CONTEXT;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000178 return false;
179 }
180 context_ = context;
Christopher Ferris206a3b92016-03-09 14:35:54 -0800181 error_ = 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);
Christopher Ferris206a3b92016-03-09 14:35:54 -0800189 error_ = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000190 return false;
191 }
192 size_t num_frames = 0;
193 do {
194 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 }
225 ret = unw_step(&cursor);
226 } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);
227
228 unw_destroy_addr_space(addr_space);
229 context_ = nullptr;
230 return true;
231}
232
233bool BacktraceOffline::ReadWord(uintptr_t ptr, word_t* out_value) {
234 size_t bytes_read = Read(ptr, reinterpret_cast<uint8_t*>(out_value), sizeof(word_t));
235 return bytes_read == sizeof(word_t);
236}
237
238size_t BacktraceOffline::Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
239 // Normally, libunwind needs stack information and call frame information to do remote unwinding.
240 // If call frame information is stored in .debug_frame, libunwind can read it from file
241 // by itself. If call frame information is stored in .eh_frame, we need to provide data in
242 // .eh_frame/.eh_frame_hdr sections.
243 // The order of readings below doesn't matter, as the spaces don't overlap with each other.
244 size_t read_size = eh_frame_hdr_space_.Read(addr, buffer, bytes);
245 if (read_size != 0) {
246 return read_size;
247 }
248 read_size = eh_frame_space_.Read(addr, buffer, bytes);
249 if (read_size != 0) {
250 return read_size;
251 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800252 read_size = arm_exidx_space_.Read(addr, buffer, bytes);
253 if (read_size != 0) {
254 return read_size;
255 }
256 read_size = arm_extab_space_.Read(addr, buffer, bytes);
257 if (read_size != 0) {
258 return read_size;
259 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000260 read_size = stack_space_.Read(addr, buffer, bytes);
261 return read_size;
262}
263
Yabin Cui9e402bb2015-09-22 04:46:57 +0000264bool BacktraceOffline::FindProcInfo(unw_addr_space_t addr_space, uint64_t ip,
265 unw_proc_info_t* proc_info, int need_unwind_info) {
266 backtrace_map_t map;
267 FillInMap(ip, &map);
268 if (!BacktraceMap::IsValid(map)) {
269 return false;
270 }
271 const std::string& filename = map.name;
272 DebugFrameInfo* debug_frame = GetDebugFrameInFile(filename);
273 if (debug_frame == nullptr) {
274 return false;
275 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000276
277 eh_frame_hdr_space_.Clear();
278 eh_frame_space_.Clear();
Yabin Cui5d991bc2016-11-15 17:47:09 -0800279 arm_exidx_space_.Clear();
280 arm_extab_space_.Clear();
281
282 // vaddr in the elf file.
283 uint64_t ip_vaddr = ip - map.start + debug_frame->min_vaddr;
284 if (debug_frame->has_arm_exidx) {
285 auto& func_vaddrs = debug_frame->arm_exidx.func_vaddr_array;
286 if (ip_vaddr >= func_vaddrs[0] && ip_vaddr < debug_frame->text_end_vaddr) {
287 // Use binary search to find the correct function.
288 auto it = std::upper_bound(func_vaddrs.begin(), func_vaddrs.end(),
289 static_cast<uint32_t>(ip_vaddr));
290 if (it != func_vaddrs.begin()) {
291 --it;
292 // Found the exidx entry.
293 size_t index = it - func_vaddrs.begin();
294
295 proc_info->format = UNW_INFO_FORMAT_ARM_EXIDX;
296 proc_info->unwind_info = reinterpret_cast<void*>(
297 static_cast<uintptr_t>(index * sizeof(ArmIdxEntry) +
298 debug_frame->arm_exidx.exidx_vaddr +
299 debug_frame->min_vaddr));
300
301 // Prepare arm_exidx space and arm_extab space.
302 arm_exidx_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.exidx_vaddr;
303 arm_exidx_space_.end = arm_exidx_space_.start +
304 debug_frame->arm_exidx.exidx_data.size() * sizeof(ArmIdxEntry);
305 arm_exidx_space_.data = reinterpret_cast<const uint8_t*>(
306 debug_frame->arm_exidx.exidx_data.data());
307
308 arm_extab_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.extab_vaddr;
309 arm_extab_space_.end = arm_extab_space_.start +
310 debug_frame->arm_exidx.extab_data.size();
311 arm_extab_space_.data = debug_frame->arm_exidx.extab_data.data();
312 return true;
313 }
314 }
315 }
316
317 if (debug_frame->has_eh_frame) {
318 if (ip_vaddr >= debug_frame->eh_frame.min_func_vaddr &&
319 ip_vaddr < debug_frame->text_end_vaddr) {
320 // Prepare eh_frame_hdr space and eh_frame space.
321 eh_frame_hdr_space_.start = ip - ip_vaddr + debug_frame->eh_frame.hdr_vaddr;
322 eh_frame_hdr_space_.end =
323 eh_frame_hdr_space_.start + debug_frame->eh_frame.hdr_data.size();
324 eh_frame_hdr_space_.data = debug_frame->eh_frame.hdr_data.data();
325
326 eh_frame_space_.start = ip - ip_vaddr + debug_frame->eh_frame.vaddr;
327 eh_frame_space_.end = eh_frame_space_.start + debug_frame->eh_frame.data.size();
328 eh_frame_space_.data = debug_frame->eh_frame.data.data();
329
330 unw_dyn_info di;
331 memset(&di, '\0', sizeof(di));
332 di.start_ip = map.start;
333 di.end_ip = map.end;
334 di.format = UNW_INFO_FORMAT_REMOTE_TABLE;
335 di.u.rti.name_ptr = 0;
336 di.u.rti.segbase = eh_frame_hdr_space_.start;
337 di.u.rti.table_data =
338 eh_frame_hdr_space_.start + debug_frame->eh_frame.fde_table_offset;
339 di.u.rti.table_len = (eh_frame_hdr_space_.end - di.u.rti.table_data) / sizeof(unw_word_t);
340 // TODO: Do it ourselves is more efficient than calling this function.
341 int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
342 if (ret == 0) {
343 return true;
344 }
345 }
346 }
347
348 if (debug_frame->has_debug_frame || debug_frame->has_gnu_debugdata) {
349 unw_dyn_info_t di;
350 unw_word_t segbase = map.start - map.offset;
351 // TODO: http://b/32916571
352 // TODO: Do it ourselves is more efficient than calling libunwind functions.
353 int found = dwarf_find_debug_frame(0, &di, ip, segbase, filename.c_str(), map.start, map.end);
354 if (found == 1) {
355 int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
356 if (ret == 0) {
357 return true;
358 }
359 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000360 }
361 return false;
362}
363
364bool BacktraceOffline::ReadReg(size_t reg, uint64_t* value) {
365 bool result = true;
366#if defined(__arm__)
367 switch (reg) {
368 case UNW_ARM_R0:
369 *value = context_->uc_mcontext.arm_r0;
370 break;
371 case UNW_ARM_R1:
372 *value = context_->uc_mcontext.arm_r1;
373 break;
374 case UNW_ARM_R2:
375 *value = context_->uc_mcontext.arm_r2;
376 break;
377 case UNW_ARM_R3:
378 *value = context_->uc_mcontext.arm_r3;
379 break;
380 case UNW_ARM_R4:
381 *value = context_->uc_mcontext.arm_r4;
382 break;
383 case UNW_ARM_R5:
384 *value = context_->uc_mcontext.arm_r5;
385 break;
386 case UNW_ARM_R6:
387 *value = context_->uc_mcontext.arm_r6;
388 break;
389 case UNW_ARM_R7:
390 *value = context_->uc_mcontext.arm_r7;
391 break;
392 case UNW_ARM_R8:
393 *value = context_->uc_mcontext.arm_r8;
394 break;
395 case UNW_ARM_R9:
396 *value = context_->uc_mcontext.arm_r9;
397 break;
398 case UNW_ARM_R10:
399 *value = context_->uc_mcontext.arm_r10;
400 break;
401 case UNW_ARM_R11:
402 *value = context_->uc_mcontext.arm_fp;
403 break;
404 case UNW_ARM_R12:
405 *value = context_->uc_mcontext.arm_ip;
406 break;
407 case UNW_ARM_R13:
408 *value = context_->uc_mcontext.arm_sp;
409 break;
410 case UNW_ARM_R14:
411 *value = context_->uc_mcontext.arm_lr;
412 break;
413 case UNW_ARM_R15:
414 *value = context_->uc_mcontext.arm_pc;
415 break;
416 default:
417 result = false;
418 }
419#elif defined(__aarch64__)
420 if (reg <= UNW_AARCH64_PC) {
421 *value = context_->uc_mcontext.regs[reg];
422 } else {
423 result = false;
424 }
425#elif defined(__x86_64__)
426 switch (reg) {
427 case UNW_X86_64_R8:
428 *value = context_->uc_mcontext.gregs[REG_R8];
429 break;
430 case UNW_X86_64_R9:
431 *value = context_->uc_mcontext.gregs[REG_R9];
432 break;
433 case UNW_X86_64_R10:
434 *value = context_->uc_mcontext.gregs[REG_R10];
435 break;
436 case UNW_X86_64_R11:
437 *value = context_->uc_mcontext.gregs[REG_R11];
438 break;
439 case UNW_X86_64_R12:
440 *value = context_->uc_mcontext.gregs[REG_R12];
441 break;
442 case UNW_X86_64_R13:
443 *value = context_->uc_mcontext.gregs[REG_R13];
444 break;
445 case UNW_X86_64_R14:
446 *value = context_->uc_mcontext.gregs[REG_R14];
447 break;
448 case UNW_X86_64_R15:
449 *value = context_->uc_mcontext.gregs[REG_R15];
450 break;
451 case UNW_X86_64_RDI:
452 *value = context_->uc_mcontext.gregs[REG_RDI];
453 break;
454 case UNW_X86_64_RSI:
455 *value = context_->uc_mcontext.gregs[REG_RSI];
456 break;
457 case UNW_X86_64_RBP:
458 *value = context_->uc_mcontext.gregs[REG_RBP];
459 break;
460 case UNW_X86_64_RBX:
461 *value = context_->uc_mcontext.gregs[REG_RBX];
462 break;
463 case UNW_X86_64_RDX:
464 *value = context_->uc_mcontext.gregs[REG_RDX];
465 break;
466 case UNW_X86_64_RAX:
467 *value = context_->uc_mcontext.gregs[REG_RAX];
468 break;
469 case UNW_X86_64_RCX:
470 *value = context_->uc_mcontext.gregs[REG_RCX];
471 break;
472 case UNW_X86_64_RSP:
473 *value = context_->uc_mcontext.gregs[REG_RSP];
474 break;
475 case UNW_X86_64_RIP:
476 *value = context_->uc_mcontext.gregs[REG_RIP];
477 break;
478 default:
479 result = false;
480 }
481#elif defined(__i386__)
482 switch (reg) {
483 case UNW_X86_GS:
484 *value = context_->uc_mcontext.gregs[REG_GS];
485 break;
486 case UNW_X86_FS:
487 *value = context_->uc_mcontext.gregs[REG_FS];
488 break;
489 case UNW_X86_ES:
490 *value = context_->uc_mcontext.gregs[REG_ES];
491 break;
492 case UNW_X86_DS:
493 *value = context_->uc_mcontext.gregs[REG_DS];
494 break;
495 case UNW_X86_EAX:
496 *value = context_->uc_mcontext.gregs[REG_EAX];
497 break;
498 case UNW_X86_EBX:
499 *value = context_->uc_mcontext.gregs[REG_EBX];
500 break;
501 case UNW_X86_ECX:
502 *value = context_->uc_mcontext.gregs[REG_ECX];
503 break;
504 case UNW_X86_EDX:
505 *value = context_->uc_mcontext.gregs[REG_EDX];
506 break;
507 case UNW_X86_ESI:
508 *value = context_->uc_mcontext.gregs[REG_ESI];
509 break;
510 case UNW_X86_EDI:
511 *value = context_->uc_mcontext.gregs[REG_EDI];
512 break;
513 case UNW_X86_EBP:
514 *value = context_->uc_mcontext.gregs[REG_EBP];
515 break;
516 case UNW_X86_EIP:
517 *value = context_->uc_mcontext.gregs[REG_EIP];
518 break;
519 case UNW_X86_ESP:
520 *value = context_->uc_mcontext.gregs[REG_ESP];
521 break;
522 case UNW_X86_TRAPNO:
523 *value = context_->uc_mcontext.gregs[REG_TRAPNO];
524 break;
525 case UNW_X86_CS:
526 *value = context_->uc_mcontext.gregs[REG_CS];
527 break;
528 case UNW_X86_EFLAGS:
529 *value = context_->uc_mcontext.gregs[REG_EFL];
530 break;
531 case UNW_X86_SS:
532 *value = context_->uc_mcontext.gregs[REG_SS];
533 break;
534 default:
535 result = false;
536 }
537#endif
538 return result;
539}
540
541std::string BacktraceOffline::GetFunctionNameRaw(uintptr_t, uintptr_t* offset) {
542 // We don't have enough information to support this. And it is expensive.
543 *offset = 0;
544 return "";
545}
546
Yabin Cui9e402bb2015-09-22 04:46:57 +0000547static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename);
548
549DebugFrameInfo* BacktraceOffline::GetDebugFrameInFile(const std::string& filename) {
550 if (cache_file_) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800551 auto it = g_debug_frames.find(filename);
552 if (it != g_debug_frames.end()) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000553 return it->second.get();
554 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000555 }
556 DebugFrameInfo* debug_frame = ReadDebugFrameFromFile(filename);
557 if (cache_file_) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800558 g_debug_frames.emplace(filename, std::unique_ptr<DebugFrameInfo>(debug_frame));
Yabin Cui9e402bb2015-09-22 04:46:57 +0000559 }
560 return debug_frame;
561}
562
563static bool OmitEncodedValue(uint8_t encode, const uint8_t*& p) {
564 if (encode == DW_EH_PE_omit) {
565 return 0;
566 }
567 uint8_t format = encode & 0x0f;
568 switch (format) {
569 case DW_EH_PE_ptr:
570 p += sizeof(unw_word_t);
571 break;
572 case DW_EH_PE_uleb128:
573 case DW_EH_PE_sleb128:
574 while ((*p & 0x80) != 0) {
575 ++p;
576 }
577 ++p;
578 break;
579 case DW_EH_PE_udata2:
580 case DW_EH_PE_sdata2:
581 p += 2;
582 break;
583 case DW_EH_PE_udata4:
584 case DW_EH_PE_sdata4:
585 p += 4;
586 break;
587 case DW_EH_PE_udata8:
588 case DW_EH_PE_sdata8:
589 p += 8;
590 break;
591 default:
592 return false;
593 }
594 return true;
595}
596
597static bool GetFdeTableOffsetInEhFrameHdr(const std::vector<uint8_t>& data,
598 uint64_t* table_offset_in_eh_frame_hdr) {
599 const uint8_t* p = data.data();
600 const uint8_t* end = p + data.size();
601 if (p + 4 > end) {
602 return false;
603 }
604 uint8_t version = *p++;
605 if (version != 1) {
606 return false;
607 }
608 uint8_t eh_frame_ptr_encode = *p++;
609 uint8_t fde_count_encode = *p++;
610 uint8_t fde_table_encode = *p++;
611
612 if (fde_table_encode != (DW_EH_PE_datarel | DW_EH_PE_sdata4)) {
613 return false;
614 }
615
616 if (!OmitEncodedValue(eh_frame_ptr_encode, p) || !OmitEncodedValue(fde_count_encode, p)) {
617 return false;
618 }
619 if (p >= end) {
620 return false;
621 }
622 *table_offset_in_eh_frame_hdr = p - data.data();
623 return true;
624}
625
Yabin Cui9e402bb2015-09-22 04:46:57 +0000626template <class ELFT>
627DebugFrameInfo* ReadDebugFrameFromELFFile(const llvm::object::ELFFile<ELFT>* elf) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800628 DebugFrameInfo* result = new DebugFrameInfo;
629 result->text_end_vaddr = std::numeric_limits<uint64_t>::max();
630
Yabin Cui9e402bb2015-09-22 04:46:57 +0000631 bool has_eh_frame_hdr = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000632 bool has_eh_frame = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000633
Stephen Hines19c30e92016-03-08 01:23:43 -0800634 for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000635 llvm::ErrorOr<llvm::StringRef> name = elf->getSectionName(&*it);
636 if (name) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800637 std::string s = name.get();
638 if (s == ".debug_frame") {
639 result->has_debug_frame = true;
640 } else if (s == ".gnu_debugdata") {
641 result->has_gnu_debugdata = true;
642 } else if (s == ".eh_frame_hdr") {
643 result->eh_frame.hdr_vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000644 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
645 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800646 result->eh_frame.hdr_data.insert(result->eh_frame.hdr_data.end(),
647 data->data(), data->data() + data->size());
648
649 uint64_t fde_table_offset;
650 if (GetFdeTableOffsetInEhFrameHdr(result->eh_frame.hdr_data,
651 &fde_table_offset)) {
652 result->eh_frame.fde_table_offset = fde_table_offset;
653 // Make sure we have at least one entry in fde_table.
654 if (fde_table_offset + 2 * sizeof(int32_t) <= data->size()) {
655 intptr_t eh_frame_hdr_vaddr = it->sh_addr;
656 int32_t sdata;
657 uint8_t* p = result->eh_frame.hdr_data.data() + fde_table_offset;
658 memcpy(&sdata, p, sizeof(sdata));
659 result->eh_frame.min_func_vaddr = eh_frame_hdr_vaddr + sdata;
660 has_eh_frame_hdr = true;
661 }
662 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000663 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800664 } else if (s == ".eh_frame") {
665 result->eh_frame.vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000666 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
667 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800668 result->eh_frame.data.insert(result->eh_frame.data.end(),
669 data->data(), data->data() + data->size());
670 has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000671 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800672 } else if (s == ".ARM.exidx") {
673 result->arm_exidx.exidx_vaddr = it->sh_addr;
674 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
675 if (data) {
676 size_t entry_count = data->size() / sizeof(ArmIdxEntry);
677 result->arm_exidx.exidx_data.resize(entry_count);
678 memcpy(result->arm_exidx.exidx_data.data(), data->data(),
679 entry_count * sizeof(ArmIdxEntry));
680 if (entry_count > 0u) {
681 // Change IdxEntry.func_offset into vaddr.
682 result->arm_exidx.func_vaddr_array.reserve(entry_count);
683 uint32_t vaddr = it->sh_addr;
684 for (auto& entry : result->arm_exidx.exidx_data) {
685 uint32_t func_offset = entry.func_offset + vaddr;
686 // Clear bit 31 for the prel31 offset.
687 // Arm sets bit 0 to mark it as thumb code, remove the flag.
688 result->arm_exidx.func_vaddr_array.push_back(
689 func_offset & 0x7ffffffe);
690 vaddr += 8;
691 }
692 result->has_arm_exidx = true;
693 }
694 }
695 } else if (s == ".ARM.extab") {
696 result->arm_exidx.extab_vaddr = it->sh_addr;
697 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
698 if (data) {
699 result->arm_exidx.extab_data.insert(result->arm_exidx.extab_data.end(),
700 data->data(), data->data() + data->size());
701 }
702 } else if (s == ".text") {
703 result->text_end_vaddr = it->sh_addr + it->sh_size;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000704 }
705 }
706 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800707
708 if (has_eh_frame_hdr && has_eh_frame) {
709 result->has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000710 }
711
Yabin Cui5d991bc2016-11-15 17:47:09 -0800712 result->min_vaddr = std::numeric_limits<uint64_t>::max();
Stephen Hines19c30e92016-03-08 01:23:43 -0800713 for (auto it = elf->program_header_begin(); it != elf->program_header_end(); ++it) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800714 if ((it->p_type == llvm::ELF::PT_LOAD) && (it->p_flags & llvm::ELF::PF_X)) {
715 if (it->p_vaddr < result->min_vaddr) {
716 result->min_vaddr = it->p_vaddr;
717 }
718 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000719 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800720 if (!result->has_eh_frame && !result->has_arm_exidx && !result->has_debug_frame &&
721 !result->has_gnu_debugdata) {
722 delete result;
723 return nullptr;
724 }
725 return result;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000726}
727
Yabin Cui2ad59db2015-12-08 18:43:00 -0800728static bool IsValidElfPath(const std::string& filename) {
729 static const char elf_magic[] = {0x7f, 'E', 'L', 'F'};
730
731 struct stat st;
732 if (stat(filename.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
733 return false;
734 }
735 FILE* fp = fopen(filename.c_str(), "reb");
736 if (fp == nullptr) {
737 return false;
738 }
739 char buf[4];
740 if (fread(buf, 4, 1, fp) != 1) {
741 fclose(fp);
742 return false;
743 }
744 fclose(fp);
745 return memcmp(buf, elf_magic, 4) == 0;
746}
747
Yabin Cuib791a762016-03-18 18:46:08 -0700748static bool IsValidApkPath(const std::string& apk_path) {
749 static const char zip_preamble[] = {0x50, 0x4b, 0x03, 0x04};
750 struct stat st;
751 if (stat(apk_path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
752 return false;
753 }
754 FILE* fp = fopen(apk_path.c_str(), "reb");
755 if (fp == nullptr) {
756 return false;
757 }
758 char buf[4];
759 if (fread(buf, 4, 1, fp) != 1) {
760 fclose(fp);
761 return false;
762 }
763 fclose(fp);
764 return memcmp(buf, zip_preamble, 4) == 0;
765}
766
767class ScopedZiparchiveHandle {
768 public:
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700769 explicit ScopedZiparchiveHandle(ZipArchiveHandle handle) : handle_(handle) {
Yabin Cuib791a762016-03-18 18:46:08 -0700770 }
771
772 ~ScopedZiparchiveHandle() {
773 CloseArchive(handle_);
774 }
775
776 private:
777 ZipArchiveHandle handle_;
778};
779
780llvm::object::OwningBinary<llvm::object::Binary> OpenEmbeddedElfFile(const std::string& filename) {
781 llvm::object::OwningBinary<llvm::object::Binary> nothing;
782 size_t pos = filename.find("!/");
783 if (pos == std::string::npos) {
784 return nothing;
785 }
786 std::string apk_file = filename.substr(0, pos);
787 std::string elf_file = filename.substr(pos + 2);
788 if (!IsValidApkPath(apk_file)) {
789 BACK_LOGW("%s is not a valid apk file", apk_file.c_str());
790 return nothing;
791 }
792 ZipArchiveHandle handle;
793 int32_t ret_code = OpenArchive(apk_file.c_str(), &handle);
794 if (ret_code != 0) {
795 CloseArchive(handle);
796 BACK_LOGW("failed to open archive %s: %s", apk_file.c_str(), ErrorCodeString(ret_code));
797 return nothing;
798 }
799 ScopedZiparchiveHandle scoped_handle(handle);
800 ZipEntry zentry;
801 ret_code = FindEntry(handle, ZipString(elf_file.c_str()), &zentry);
802 if (ret_code != 0) {
803 BACK_LOGW("failed to find %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
804 ErrorCodeString(ret_code));
805 return nothing;
806 }
807 if (zentry.method != kCompressStored || zentry.compressed_length != zentry.uncompressed_length) {
808 BACK_LOGW("%s is compressed in %s, which doesn't support running directly", elf_file.c_str(),
809 apk_file.c_str());
810 return nothing;
811 }
812 auto buffer_or_err = llvm::MemoryBuffer::getOpenFileSlice(GetFileDescriptor(handle), apk_file,
813 zentry.uncompressed_length,
814 zentry.offset);
815 if (!buffer_or_err) {
816 BACK_LOGW("failed to read %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
817 buffer_or_err.getError().message().c_str());
818 return nothing;
819 }
820 auto binary_or_err = llvm::object::createBinary(buffer_or_err.get()->getMemBufferRef());
821 if (!binary_or_err) {
822 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 -0700823 llvm::toString(binary_or_err.takeError()).c_str());
Yabin Cuib791a762016-03-18 18:46:08 -0700824 return nothing;
825 }
826 return llvm::object::OwningBinary<llvm::object::Binary>(std::move(binary_or_err.get()),
827 std::move(buffer_or_err.get()));
828}
829
Yabin Cui9e402bb2015-09-22 04:46:57 +0000830static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename) {
Yabin Cuib791a762016-03-18 18:46:08 -0700831 llvm::object::OwningBinary<llvm::object::Binary> owning_binary;
832 if (filename.find("!/") != std::string::npos) {
833 owning_binary = OpenEmbeddedElfFile(filename);
834 } else {
835 if (!IsValidElfPath(filename)) {
836 return nullptr;
837 }
838 auto binary_or_err = llvm::object::createBinary(llvm::StringRef(filename));
839 if (!binary_or_err) {
840 return nullptr;
841 }
842 owning_binary = std::move(binary_or_err.get());
Yabin Cui2ad59db2015-12-08 18:43:00 -0800843 }
Yabin Cuib791a762016-03-18 18:46:08 -0700844 llvm::object::Binary* binary = owning_binary.getBinary();
Yabin Cui9e402bb2015-09-22 04:46:57 +0000845 auto obj = llvm::dyn_cast<llvm::object::ObjectFile>(binary);
846 if (obj == nullptr) {
847 return nullptr;
848 }
849 if (auto elf = llvm::dyn_cast<llvm::object::ELF32LEObjectFile>(obj)) {
850 return ReadDebugFrameFromELFFile(elf->getELFFile());
851 }
852 if (auto elf = llvm::dyn_cast<llvm::object::ELF64LEObjectFile>(obj)) {
853 return ReadDebugFrameFromELFFile(elf->getELFFile());
854 }
855 return nullptr;
856}
Christopher Ferris85402162016-01-25 16:17:48 -0800857
858Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
859 const backtrace_stackinfo_t& stack, bool cache_file) {
860 return new BacktraceOffline(pid, tid, map, stack, cache_file);
861}