blob: 641f7123e8123cd54776129e8a80f1418ca00698 [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.");
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 }
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);
227 } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);
228
229 unw_destroy_addr_space(addr_space);
230 context_ = nullptr;
231 return true;
232}
233
234bool BacktraceOffline::ReadWord(uintptr_t ptr, word_t* out_value) {
235 size_t bytes_read = Read(ptr, reinterpret_cast<uint8_t*>(out_value), sizeof(word_t));
236 return bytes_read == sizeof(word_t);
237}
238
239size_t BacktraceOffline::Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
240 // Normally, libunwind needs stack information and call frame information to do remote unwinding.
241 // If call frame information is stored in .debug_frame, libunwind can read it from file
242 // by itself. If call frame information is stored in .eh_frame, we need to provide data in
243 // .eh_frame/.eh_frame_hdr sections.
244 // The order of readings below doesn't matter, as the spaces don't overlap with each other.
245 size_t read_size = eh_frame_hdr_space_.Read(addr, buffer, bytes);
246 if (read_size != 0) {
247 return read_size;
248 }
249 read_size = eh_frame_space_.Read(addr, buffer, bytes);
250 if (read_size != 0) {
251 return read_size;
252 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800253 read_size = arm_exidx_space_.Read(addr, buffer, bytes);
254 if (read_size != 0) {
255 return read_size;
256 }
257 read_size = arm_extab_space_.Read(addr, buffer, bytes);
258 if (read_size != 0) {
259 return read_size;
260 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000261 read_size = stack_space_.Read(addr, buffer, bytes);
262 return read_size;
263}
264
Yabin Cui9e402bb2015-09-22 04:46:57 +0000265bool BacktraceOffline::FindProcInfo(unw_addr_space_t addr_space, uint64_t ip,
266 unw_proc_info_t* proc_info, int need_unwind_info) {
267 backtrace_map_t map;
268 FillInMap(ip, &map);
269 if (!BacktraceMap::IsValid(map)) {
270 return false;
271 }
272 const std::string& filename = map.name;
273 DebugFrameInfo* debug_frame = GetDebugFrameInFile(filename);
274 if (debug_frame == nullptr) {
275 return false;
276 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000277
278 eh_frame_hdr_space_.Clear();
279 eh_frame_space_.Clear();
Yabin Cui5d991bc2016-11-15 17:47:09 -0800280 arm_exidx_space_.Clear();
281 arm_extab_space_.Clear();
282
283 // vaddr in the elf file.
284 uint64_t ip_vaddr = ip - map.start + debug_frame->min_vaddr;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800285
Yabin Cuic4a480e2017-02-02 15:25:08 -0800286 // The unwind info can come from .ARM.exidx or .eh_frame, or .debug_frame/.gnu_debugdata.
287 // First check .eh_frame/.debug_frame, then check .ARM.exidx. Because .eh_frame/.debug_frame has
288 // function range for each entry, by matching ip address with the function range, we know exactly
289 // whether the ip address hits an entry. But .ARM.exidx doesn't have function range for each
290 // entry, it thinks that an ip address hits an entry when (entry.addr <= ip < next_entry.addr).
291 // To prevent ip addresses hit in .eh_frame/.debug_frame being regarded as addresses hit in
292 // .ARM.exidx, we need to check .eh_frame/.debug_frame first.
Yabin Cui5d991bc2016-11-15 17:47:09 -0800293 if (debug_frame->has_eh_frame) {
294 if (ip_vaddr >= debug_frame->eh_frame.min_func_vaddr &&
295 ip_vaddr < debug_frame->text_end_vaddr) {
296 // Prepare eh_frame_hdr space and eh_frame space.
297 eh_frame_hdr_space_.start = ip - ip_vaddr + debug_frame->eh_frame.hdr_vaddr;
298 eh_frame_hdr_space_.end =
299 eh_frame_hdr_space_.start + debug_frame->eh_frame.hdr_data.size();
300 eh_frame_hdr_space_.data = debug_frame->eh_frame.hdr_data.data();
Yabin Cui5d991bc2016-11-15 17:47:09 -0800301 eh_frame_space_.start = ip - ip_vaddr + debug_frame->eh_frame.vaddr;
302 eh_frame_space_.end = eh_frame_space_.start + debug_frame->eh_frame.data.size();
303 eh_frame_space_.data = debug_frame->eh_frame.data.data();
304
305 unw_dyn_info di;
306 memset(&di, '\0', sizeof(di));
307 di.start_ip = map.start;
308 di.end_ip = map.end;
309 di.format = UNW_INFO_FORMAT_REMOTE_TABLE;
310 di.u.rti.name_ptr = 0;
311 di.u.rti.segbase = eh_frame_hdr_space_.start;
312 di.u.rti.table_data =
313 eh_frame_hdr_space_.start + debug_frame->eh_frame.fde_table_offset;
314 di.u.rti.table_len = (eh_frame_hdr_space_.end - di.u.rti.table_data) / sizeof(unw_word_t);
315 // TODO: Do it ourselves is more efficient than calling this function.
316 int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
317 if (ret == 0) {
318 return true;
319 }
320 }
321 }
Yabin Cui0ca49b02017-12-10 17:55:12 -0800322 if (!is_debug_frame_used_ && (debug_frame->has_debug_frame || debug_frame->has_gnu_debugdata)) {
323 is_debug_frame_used_ = true;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800324 unw_dyn_info_t di;
Yabin Cui4a26eaf2017-12-05 17:40:48 -0800325 unw_word_t segbase = map.start - debug_frame->min_vaddr;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800326 // TODO: http://b/32916571
327 // TODO: Do it ourselves is more efficient than calling libunwind functions.
328 int found = dwarf_find_debug_frame(0, &di, ip, segbase, filename.c_str(), map.start, map.end);
329 if (found == 1) {
330 int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
331 if (ret == 0) {
332 return true;
333 }
334 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000335 }
Yabin Cuic4a480e2017-02-02 15:25:08 -0800336
337 if (debug_frame->has_arm_exidx) {
338 auto& func_vaddrs = debug_frame->arm_exidx.func_vaddr_array;
339 if (ip_vaddr >= func_vaddrs[0] && ip_vaddr < debug_frame->text_end_vaddr) {
340 // Use binary search to find the correct function.
341 auto it = std::upper_bound(func_vaddrs.begin(), func_vaddrs.end(),
342 static_cast<uint32_t>(ip_vaddr));
343 if (it != func_vaddrs.begin()) {
344 --it;
345 // Found the exidx entry.
346 size_t index = it - func_vaddrs.begin();
347 proc_info->start_ip = *it;
348 proc_info->format = UNW_INFO_FORMAT_ARM_EXIDX;
349 proc_info->unwind_info = reinterpret_cast<void*>(
350 static_cast<uintptr_t>(index * sizeof(ArmIdxEntry) +
351 debug_frame->arm_exidx.exidx_vaddr +
352 debug_frame->min_vaddr));
353 eh_frame_hdr_space_.Clear();
354 eh_frame_space_.Clear();
355 // Prepare arm_exidx space and arm_extab space.
356 arm_exidx_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.exidx_vaddr;
357 arm_exidx_space_.end = arm_exidx_space_.start +
358 debug_frame->arm_exidx.exidx_data.size() * sizeof(ArmIdxEntry);
359 arm_exidx_space_.data = reinterpret_cast<const uint8_t*>(
360 debug_frame->arm_exidx.exidx_data.data());
361
362 arm_extab_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.extab_vaddr;
363 arm_extab_space_.end = arm_extab_space_.start +
364 debug_frame->arm_exidx.extab_data.size();
365 arm_extab_space_.data = debug_frame->arm_exidx.extab_data.data();
366 return true;
367 }
368 }
369 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000370 return false;
371}
372
373bool BacktraceOffline::ReadReg(size_t reg, uint64_t* value) {
374 bool result = true;
375#if defined(__arm__)
376 switch (reg) {
377 case UNW_ARM_R0:
378 *value = context_->uc_mcontext.arm_r0;
379 break;
380 case UNW_ARM_R1:
381 *value = context_->uc_mcontext.arm_r1;
382 break;
383 case UNW_ARM_R2:
384 *value = context_->uc_mcontext.arm_r2;
385 break;
386 case UNW_ARM_R3:
387 *value = context_->uc_mcontext.arm_r3;
388 break;
389 case UNW_ARM_R4:
390 *value = context_->uc_mcontext.arm_r4;
391 break;
392 case UNW_ARM_R5:
393 *value = context_->uc_mcontext.arm_r5;
394 break;
395 case UNW_ARM_R6:
396 *value = context_->uc_mcontext.arm_r6;
397 break;
398 case UNW_ARM_R7:
399 *value = context_->uc_mcontext.arm_r7;
400 break;
401 case UNW_ARM_R8:
402 *value = context_->uc_mcontext.arm_r8;
403 break;
404 case UNW_ARM_R9:
405 *value = context_->uc_mcontext.arm_r9;
406 break;
407 case UNW_ARM_R10:
408 *value = context_->uc_mcontext.arm_r10;
409 break;
410 case UNW_ARM_R11:
411 *value = context_->uc_mcontext.arm_fp;
412 break;
413 case UNW_ARM_R12:
414 *value = context_->uc_mcontext.arm_ip;
415 break;
416 case UNW_ARM_R13:
417 *value = context_->uc_mcontext.arm_sp;
418 break;
419 case UNW_ARM_R14:
420 *value = context_->uc_mcontext.arm_lr;
421 break;
422 case UNW_ARM_R15:
423 *value = context_->uc_mcontext.arm_pc;
424 break;
425 default:
426 result = false;
427 }
428#elif defined(__aarch64__)
429 if (reg <= UNW_AARCH64_PC) {
430 *value = context_->uc_mcontext.regs[reg];
431 } else {
432 result = false;
433 }
434#elif defined(__x86_64__)
435 switch (reg) {
436 case UNW_X86_64_R8:
437 *value = context_->uc_mcontext.gregs[REG_R8];
438 break;
439 case UNW_X86_64_R9:
440 *value = context_->uc_mcontext.gregs[REG_R9];
441 break;
442 case UNW_X86_64_R10:
443 *value = context_->uc_mcontext.gregs[REG_R10];
444 break;
445 case UNW_X86_64_R11:
446 *value = context_->uc_mcontext.gregs[REG_R11];
447 break;
448 case UNW_X86_64_R12:
449 *value = context_->uc_mcontext.gregs[REG_R12];
450 break;
451 case UNW_X86_64_R13:
452 *value = context_->uc_mcontext.gregs[REG_R13];
453 break;
454 case UNW_X86_64_R14:
455 *value = context_->uc_mcontext.gregs[REG_R14];
456 break;
457 case UNW_X86_64_R15:
458 *value = context_->uc_mcontext.gregs[REG_R15];
459 break;
460 case UNW_X86_64_RDI:
461 *value = context_->uc_mcontext.gregs[REG_RDI];
462 break;
463 case UNW_X86_64_RSI:
464 *value = context_->uc_mcontext.gregs[REG_RSI];
465 break;
466 case UNW_X86_64_RBP:
467 *value = context_->uc_mcontext.gregs[REG_RBP];
468 break;
469 case UNW_X86_64_RBX:
470 *value = context_->uc_mcontext.gregs[REG_RBX];
471 break;
472 case UNW_X86_64_RDX:
473 *value = context_->uc_mcontext.gregs[REG_RDX];
474 break;
475 case UNW_X86_64_RAX:
476 *value = context_->uc_mcontext.gregs[REG_RAX];
477 break;
478 case UNW_X86_64_RCX:
479 *value = context_->uc_mcontext.gregs[REG_RCX];
480 break;
481 case UNW_X86_64_RSP:
482 *value = context_->uc_mcontext.gregs[REG_RSP];
483 break;
484 case UNW_X86_64_RIP:
485 *value = context_->uc_mcontext.gregs[REG_RIP];
486 break;
487 default:
488 result = false;
489 }
490#elif defined(__i386__)
491 switch (reg) {
492 case UNW_X86_GS:
493 *value = context_->uc_mcontext.gregs[REG_GS];
494 break;
495 case UNW_X86_FS:
496 *value = context_->uc_mcontext.gregs[REG_FS];
497 break;
498 case UNW_X86_ES:
499 *value = context_->uc_mcontext.gregs[REG_ES];
500 break;
501 case UNW_X86_DS:
502 *value = context_->uc_mcontext.gregs[REG_DS];
503 break;
504 case UNW_X86_EAX:
505 *value = context_->uc_mcontext.gregs[REG_EAX];
506 break;
507 case UNW_X86_EBX:
508 *value = context_->uc_mcontext.gregs[REG_EBX];
509 break;
510 case UNW_X86_ECX:
511 *value = context_->uc_mcontext.gregs[REG_ECX];
512 break;
513 case UNW_X86_EDX:
514 *value = context_->uc_mcontext.gregs[REG_EDX];
515 break;
516 case UNW_X86_ESI:
517 *value = context_->uc_mcontext.gregs[REG_ESI];
518 break;
519 case UNW_X86_EDI:
520 *value = context_->uc_mcontext.gregs[REG_EDI];
521 break;
522 case UNW_X86_EBP:
523 *value = context_->uc_mcontext.gregs[REG_EBP];
524 break;
525 case UNW_X86_EIP:
526 *value = context_->uc_mcontext.gregs[REG_EIP];
527 break;
528 case UNW_X86_ESP:
529 *value = context_->uc_mcontext.gregs[REG_ESP];
530 break;
531 case UNW_X86_TRAPNO:
532 *value = context_->uc_mcontext.gregs[REG_TRAPNO];
533 break;
534 case UNW_X86_CS:
535 *value = context_->uc_mcontext.gregs[REG_CS];
536 break;
537 case UNW_X86_EFLAGS:
538 *value = context_->uc_mcontext.gregs[REG_EFL];
539 break;
540 case UNW_X86_SS:
541 *value = context_->uc_mcontext.gregs[REG_SS];
542 break;
543 default:
544 result = false;
545 }
Colin Cross06d31492016-12-15 12:55:03 -0800546#else
547 UNUSED(reg);
548 UNUSED(value);
549 result = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000550#endif
551 return result;
552}
553
554std::string BacktraceOffline::GetFunctionNameRaw(uintptr_t, uintptr_t* offset) {
555 // We don't have enough information to support this. And it is expensive.
556 *offset = 0;
557 return "";
558}
559
Yabin Cui26369a32017-02-10 18:05:34 -0800560static std::mutex g_lock;
561static std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>* g_debug_frames = nullptr;
562
Yabin Cui9e402bb2015-09-22 04:46:57 +0000563static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename);
564
565DebugFrameInfo* BacktraceOffline::GetDebugFrameInFile(const std::string& filename) {
566 if (cache_file_) {
Yabin Cui26369a32017-02-10 18:05:34 -0800567 std::lock_guard<std::mutex> lock(g_lock);
568 if (g_debug_frames != nullptr) {
569 auto it = g_debug_frames->find(filename);
570 if (it != g_debug_frames->end()) {
571 return it->second.get();
572 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000573 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000574 }
575 DebugFrameInfo* debug_frame = ReadDebugFrameFromFile(filename);
576 if (cache_file_) {
Yabin Cui26369a32017-02-10 18:05:34 -0800577 std::lock_guard<std::mutex> lock(g_lock);
578 if (g_debug_frames == nullptr) {
579 g_debug_frames = new std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>;
580 }
581 auto pair = g_debug_frames->emplace(filename, std::unique_ptr<DebugFrameInfo>(debug_frame));
582 if (!pair.second) {
583 debug_frame = pair.first->second.get();
584 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000585 }
586 return debug_frame;
587}
588
589static bool OmitEncodedValue(uint8_t encode, const uint8_t*& p) {
590 if (encode == DW_EH_PE_omit) {
591 return 0;
592 }
593 uint8_t format = encode & 0x0f;
594 switch (format) {
595 case DW_EH_PE_ptr:
596 p += sizeof(unw_word_t);
597 break;
598 case DW_EH_PE_uleb128:
599 case DW_EH_PE_sleb128:
600 while ((*p & 0x80) != 0) {
601 ++p;
602 }
603 ++p;
604 break;
605 case DW_EH_PE_udata2:
606 case DW_EH_PE_sdata2:
607 p += 2;
608 break;
609 case DW_EH_PE_udata4:
610 case DW_EH_PE_sdata4:
611 p += 4;
612 break;
613 case DW_EH_PE_udata8:
614 case DW_EH_PE_sdata8:
615 p += 8;
616 break;
617 default:
618 return false;
619 }
620 return true;
621}
622
623static bool GetFdeTableOffsetInEhFrameHdr(const std::vector<uint8_t>& data,
624 uint64_t* table_offset_in_eh_frame_hdr) {
625 const uint8_t* p = data.data();
626 const uint8_t* end = p + data.size();
627 if (p + 4 > end) {
628 return false;
629 }
630 uint8_t version = *p++;
631 if (version != 1) {
632 return false;
633 }
634 uint8_t eh_frame_ptr_encode = *p++;
635 uint8_t fde_count_encode = *p++;
636 uint8_t fde_table_encode = *p++;
637
638 if (fde_table_encode != (DW_EH_PE_datarel | DW_EH_PE_sdata4)) {
639 return false;
640 }
641
642 if (!OmitEncodedValue(eh_frame_ptr_encode, p) || !OmitEncodedValue(fde_count_encode, p)) {
643 return false;
644 }
645 if (p >= end) {
646 return false;
647 }
648 *table_offset_in_eh_frame_hdr = p - data.data();
649 return true;
650}
651
Yabin Cui9e402bb2015-09-22 04:46:57 +0000652template <class ELFT>
653DebugFrameInfo* ReadDebugFrameFromELFFile(const llvm::object::ELFFile<ELFT>* elf) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800654 DebugFrameInfo* result = new DebugFrameInfo;
655 result->text_end_vaddr = std::numeric_limits<uint64_t>::max();
656
Yabin Cui9e402bb2015-09-22 04:46:57 +0000657 bool has_eh_frame_hdr = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000658 bool has_eh_frame = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000659
Stephen Hines19c30e92016-03-08 01:23:43 -0800660 for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000661 llvm::ErrorOr<llvm::StringRef> name = elf->getSectionName(&*it);
662 if (name) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800663 std::string s = name.get();
664 if (s == ".debug_frame") {
665 result->has_debug_frame = true;
666 } else if (s == ".gnu_debugdata") {
667 result->has_gnu_debugdata = true;
668 } else if (s == ".eh_frame_hdr") {
669 result->eh_frame.hdr_vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000670 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
671 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800672 result->eh_frame.hdr_data.insert(result->eh_frame.hdr_data.end(),
673 data->data(), data->data() + data->size());
674
675 uint64_t fde_table_offset;
676 if (GetFdeTableOffsetInEhFrameHdr(result->eh_frame.hdr_data,
677 &fde_table_offset)) {
678 result->eh_frame.fde_table_offset = fde_table_offset;
679 // Make sure we have at least one entry in fde_table.
680 if (fde_table_offset + 2 * sizeof(int32_t) <= data->size()) {
681 intptr_t eh_frame_hdr_vaddr = it->sh_addr;
682 int32_t sdata;
683 uint8_t* p = result->eh_frame.hdr_data.data() + fde_table_offset;
684 memcpy(&sdata, p, sizeof(sdata));
685 result->eh_frame.min_func_vaddr = eh_frame_hdr_vaddr + sdata;
686 has_eh_frame_hdr = true;
687 }
688 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000689 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800690 } else if (s == ".eh_frame") {
691 result->eh_frame.vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000692 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
693 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800694 result->eh_frame.data.insert(result->eh_frame.data.end(),
695 data->data(), data->data() + data->size());
696 has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000697 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800698 } else if (s == ".ARM.exidx") {
699 result->arm_exidx.exidx_vaddr = it->sh_addr;
700 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
701 if (data) {
702 size_t entry_count = data->size() / sizeof(ArmIdxEntry);
703 result->arm_exidx.exidx_data.resize(entry_count);
704 memcpy(result->arm_exidx.exidx_data.data(), data->data(),
705 entry_count * sizeof(ArmIdxEntry));
706 if (entry_count > 0u) {
707 // Change IdxEntry.func_offset into vaddr.
708 result->arm_exidx.func_vaddr_array.reserve(entry_count);
709 uint32_t vaddr = it->sh_addr;
710 for (auto& entry : result->arm_exidx.exidx_data) {
711 uint32_t func_offset = entry.func_offset + vaddr;
712 // Clear bit 31 for the prel31 offset.
713 // Arm sets bit 0 to mark it as thumb code, remove the flag.
714 result->arm_exidx.func_vaddr_array.push_back(
715 func_offset & 0x7ffffffe);
716 vaddr += 8;
717 }
718 result->has_arm_exidx = true;
719 }
720 }
721 } else if (s == ".ARM.extab") {
722 result->arm_exidx.extab_vaddr = it->sh_addr;
723 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
724 if (data) {
725 result->arm_exidx.extab_data.insert(result->arm_exidx.extab_data.end(),
726 data->data(), data->data() + data->size());
727 }
728 } else if (s == ".text") {
729 result->text_end_vaddr = it->sh_addr + it->sh_size;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000730 }
731 }
732 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800733
734 if (has_eh_frame_hdr && has_eh_frame) {
735 result->has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000736 }
737
Yabin Cui5d991bc2016-11-15 17:47:09 -0800738 result->min_vaddr = std::numeric_limits<uint64_t>::max();
Stephen Hines19c30e92016-03-08 01:23:43 -0800739 for (auto it = elf->program_header_begin(); it != elf->program_header_end(); ++it) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800740 if ((it->p_type == llvm::ELF::PT_LOAD) && (it->p_flags & llvm::ELF::PF_X)) {
741 if (it->p_vaddr < result->min_vaddr) {
742 result->min_vaddr = it->p_vaddr;
743 }
744 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000745 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800746 if (!result->has_eh_frame && !result->has_arm_exidx && !result->has_debug_frame &&
747 !result->has_gnu_debugdata) {
748 delete result;
749 return nullptr;
750 }
751 return result;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000752}
753
Yabin Cui2ad59db2015-12-08 18:43:00 -0800754static bool IsValidElfPath(const std::string& filename) {
755 static const char elf_magic[] = {0x7f, 'E', 'L', 'F'};
756
757 struct stat st;
758 if (stat(filename.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
759 return false;
760 }
761 FILE* fp = fopen(filename.c_str(), "reb");
762 if (fp == nullptr) {
763 return false;
764 }
765 char buf[4];
766 if (fread(buf, 4, 1, fp) != 1) {
767 fclose(fp);
768 return false;
769 }
770 fclose(fp);
771 return memcmp(buf, elf_magic, 4) == 0;
772}
773
Yabin Cuib791a762016-03-18 18:46:08 -0700774static bool IsValidApkPath(const std::string& apk_path) {
775 static const char zip_preamble[] = {0x50, 0x4b, 0x03, 0x04};
776 struct stat st;
777 if (stat(apk_path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
778 return false;
779 }
780 FILE* fp = fopen(apk_path.c_str(), "reb");
781 if (fp == nullptr) {
782 return false;
783 }
784 char buf[4];
785 if (fread(buf, 4, 1, fp) != 1) {
786 fclose(fp);
787 return false;
788 }
789 fclose(fp);
790 return memcmp(buf, zip_preamble, 4) == 0;
791}
792
793class ScopedZiparchiveHandle {
794 public:
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -0700795 explicit ScopedZiparchiveHandle(ZipArchiveHandle handle) : handle_(handle) {
Yabin Cuib791a762016-03-18 18:46:08 -0700796 }
797
798 ~ScopedZiparchiveHandle() {
799 CloseArchive(handle_);
800 }
801
802 private:
803 ZipArchiveHandle handle_;
804};
805
806llvm::object::OwningBinary<llvm::object::Binary> OpenEmbeddedElfFile(const std::string& filename) {
807 llvm::object::OwningBinary<llvm::object::Binary> nothing;
808 size_t pos = filename.find("!/");
809 if (pos == std::string::npos) {
810 return nothing;
811 }
812 std::string apk_file = filename.substr(0, pos);
813 std::string elf_file = filename.substr(pos + 2);
814 if (!IsValidApkPath(apk_file)) {
815 BACK_LOGW("%s is not a valid apk file", apk_file.c_str());
816 return nothing;
817 }
818 ZipArchiveHandle handle;
819 int32_t ret_code = OpenArchive(apk_file.c_str(), &handle);
820 if (ret_code != 0) {
821 CloseArchive(handle);
822 BACK_LOGW("failed to open archive %s: %s", apk_file.c_str(), ErrorCodeString(ret_code));
823 return nothing;
824 }
825 ScopedZiparchiveHandle scoped_handle(handle);
826 ZipEntry zentry;
827 ret_code = FindEntry(handle, ZipString(elf_file.c_str()), &zentry);
828 if (ret_code != 0) {
829 BACK_LOGW("failed to find %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
830 ErrorCodeString(ret_code));
831 return nothing;
832 }
833 if (zentry.method != kCompressStored || zentry.compressed_length != zentry.uncompressed_length) {
834 BACK_LOGW("%s is compressed in %s, which doesn't support running directly", elf_file.c_str(),
835 apk_file.c_str());
836 return nothing;
837 }
838 auto buffer_or_err = llvm::MemoryBuffer::getOpenFileSlice(GetFileDescriptor(handle), apk_file,
839 zentry.uncompressed_length,
840 zentry.offset);
841 if (!buffer_or_err) {
842 BACK_LOGW("failed to read %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
843 buffer_or_err.getError().message().c_str());
844 return nothing;
845 }
846 auto binary_or_err = llvm::object::createBinary(buffer_or_err.get()->getMemBufferRef());
847 if (!binary_or_err) {
848 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 -0700849 llvm::toString(binary_or_err.takeError()).c_str());
Yabin Cuib791a762016-03-18 18:46:08 -0700850 return nothing;
851 }
852 return llvm::object::OwningBinary<llvm::object::Binary>(std::move(binary_or_err.get()),
853 std::move(buffer_or_err.get()));
854}
855
Yabin Cui9e402bb2015-09-22 04:46:57 +0000856static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename) {
Yabin Cuib791a762016-03-18 18:46:08 -0700857 llvm::object::OwningBinary<llvm::object::Binary> owning_binary;
858 if (filename.find("!/") != std::string::npos) {
859 owning_binary = OpenEmbeddedElfFile(filename);
860 } else {
861 if (!IsValidElfPath(filename)) {
862 return nullptr;
863 }
864 auto binary_or_err = llvm::object::createBinary(llvm::StringRef(filename));
865 if (!binary_or_err) {
866 return nullptr;
867 }
868 owning_binary = std::move(binary_or_err.get());
Yabin Cui2ad59db2015-12-08 18:43:00 -0800869 }
Yabin Cuib791a762016-03-18 18:46:08 -0700870 llvm::object::Binary* binary = owning_binary.getBinary();
Yabin Cui9e402bb2015-09-22 04:46:57 +0000871 auto obj = llvm::dyn_cast<llvm::object::ObjectFile>(binary);
872 if (obj == nullptr) {
873 return nullptr;
874 }
875 if (auto elf = llvm::dyn_cast<llvm::object::ELF32LEObjectFile>(obj)) {
876 return ReadDebugFrameFromELFFile(elf->getELFFile());
877 }
878 if (auto elf = llvm::dyn_cast<llvm::object::ELF64LEObjectFile>(obj)) {
879 return ReadDebugFrameFromELFFile(elf->getELFFile());
880 }
881 return nullptr;
882}
Christopher Ferris85402162016-01-25 16:17:48 -0800883
884Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
885 const backtrace_stackinfo_t& stack, bool cache_file) {
886 return new BacktraceOffline(pid, tid, map, stack, cache_file);
887}