blob: 30845a2d0004c014b42e190c570ba0e1df26e33b [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);
Yabin Cui98791372017-12-18 14:37:54 -0800198 error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED;
199 error_.error_info.regno = UNW_REG_IP;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000200 break;
201 }
202 unw_word_t sp;
203 ret = unw_get_reg(&cursor, UNW_REG_SP, &sp);
204 if (ret < 0) {
205 BACK_LOGW("Failed to read SP %d", ret);
Yabin Cui98791372017-12-18 14:37:54 -0800206 error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED;
207 error_.error_info.regno = UNW_REG_SP;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000208 break;
209 }
210
211 if (num_ignore_frames == 0) {
Yabin Cui98791372017-12-18 14:37:54 -0800212 backtrace_map_t map;
213 FillInMap(pc, &map);
214 if (map.start == 0 || (map.flags & PROT_EXEC) == 0) {
215 // .eh_frame and .ARM.exidx doesn't know how to unwind from instructions setting up or
216 // destroying stack frames. It can lead to wrong callchains, which may contain pcs outside
217 // executable mapping areas. Stop unwinding once this is detected.
218 error_.error_code = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
219 break;
220 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000221 frames_.resize(num_frames + 1);
222 backtrace_frame_data_t* frame = &frames_[num_frames];
223 frame->num = num_frames;
224 frame->pc = static_cast<uintptr_t>(pc);
225 frame->sp = static_cast<uintptr_t>(sp);
226 frame->stack_size = 0;
227
228 if (num_frames > 0) {
229 backtrace_frame_data_t* prev = &frames_[num_frames - 1];
230 prev->stack_size = frame->sp - prev->sp;
231 }
232 frame->func_name = GetFunctionName(frame->pc, &frame->func_offset);
Yabin Cui98791372017-12-18 14:37:54 -0800233 frame->map = map;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000234 num_frames++;
235 } else {
236 num_ignore_frames--;
237 }
Yabin Cui0ca49b02017-12-10 17:55:12 -0800238 is_debug_frame_used_ = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000239 ret = unw_step(&cursor);
Yabin Cuif8808282017-12-12 18:04:10 -0800240 if (ret <= 0) {
241 if (error_.error_code == BACKTRACE_UNWIND_NO_ERROR) {
242 error_.error_code = BACKTRACE_UNWIND_ERROR_EXECUTE_DWARF_INSTRUCTION_FAILED;
243 }
244 break;
245 }
246 if (num_frames == MAX_BACKTRACE_FRAMES) {
247 error_.error_code = BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT;
248 break;
249 }
250 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000251 unw_destroy_addr_space(addr_space);
252 context_ = nullptr;
253 return true;
254}
255
256bool BacktraceOffline::ReadWord(uintptr_t ptr, word_t* out_value) {
257 size_t bytes_read = Read(ptr, reinterpret_cast<uint8_t*>(out_value), sizeof(word_t));
258 return bytes_read == sizeof(word_t);
259}
260
261size_t BacktraceOffline::Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
262 // Normally, libunwind needs stack information and call frame information to do remote unwinding.
263 // If call frame information is stored in .debug_frame, libunwind can read it from file
264 // by itself. If call frame information is stored in .eh_frame, we need to provide data in
265 // .eh_frame/.eh_frame_hdr sections.
266 // The order of readings below doesn't matter, as the spaces don't overlap with each other.
267 size_t read_size = eh_frame_hdr_space_.Read(addr, buffer, bytes);
268 if (read_size != 0) {
269 return read_size;
270 }
271 read_size = eh_frame_space_.Read(addr, buffer, bytes);
272 if (read_size != 0) {
273 return read_size;
274 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800275 read_size = arm_exidx_space_.Read(addr, buffer, bytes);
276 if (read_size != 0) {
277 return read_size;
278 }
279 read_size = arm_extab_space_.Read(addr, buffer, bytes);
280 if (read_size != 0) {
281 return read_size;
282 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000283 read_size = stack_space_.Read(addr, buffer, bytes);
Yabin Cuif8808282017-12-12 18:04:10 -0800284 if (read_size != 0) {
285 return read_size;
286 }
Yabin Cui98791372017-12-18 14:37:54 -0800287 // In some libraries (like /system/lib64/libskia.so), some CIE entries in .eh_frame use
288 // augmentation "P", which makes libunwind/libunwindstack try to read personality routine in
289 // memory. However, that is not available in offline unwinding. Work around this by returning
290 // all zero data.
Yabin Cuif8808282017-12-12 18:04:10 -0800291 error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED;
292 error_.error_info.addr = addr;
Yabin Cui98791372017-12-18 14:37:54 -0800293 memset(buffer, 0, bytes);
294 return bytes;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000295}
296
Yabin Cui9e402bb2015-09-22 04:46:57 +0000297bool BacktraceOffline::FindProcInfo(unw_addr_space_t addr_space, uint64_t ip,
298 unw_proc_info_t* proc_info, int need_unwind_info) {
299 backtrace_map_t map;
300 FillInMap(ip, &map);
301 if (!BacktraceMap::IsValid(map)) {
Yabin Cuif8808282017-12-12 18:04:10 -0800302 error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000303 return false;
304 }
305 const std::string& filename = map.name;
306 DebugFrameInfo* debug_frame = GetDebugFrameInFile(filename);
307 if (debug_frame == nullptr) {
Yabin Cuif8808282017-12-12 18:04:10 -0800308 error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000309 return false;
310 }
Yabin Cuif8808282017-12-12 18:04:10 -0800311 // Each FindProcInfo() is a new attempt to unwind, so reset the reason.
312 error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000313
314 eh_frame_hdr_space_.Clear();
315 eh_frame_space_.Clear();
Yabin Cui5d991bc2016-11-15 17:47:09 -0800316 arm_exidx_space_.Clear();
317 arm_extab_space_.Clear();
318
319 // vaddr in the elf file.
320 uint64_t ip_vaddr = ip - map.start + debug_frame->min_vaddr;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800321
Yabin Cuic4a480e2017-02-02 15:25:08 -0800322 // The unwind info can come from .ARM.exidx or .eh_frame, or .debug_frame/.gnu_debugdata.
323 // First check .eh_frame/.debug_frame, then check .ARM.exidx. Because .eh_frame/.debug_frame has
324 // function range for each entry, by matching ip address with the function range, we know exactly
325 // whether the ip address hits an entry. But .ARM.exidx doesn't have function range for each
326 // entry, it thinks that an ip address hits an entry when (entry.addr <= ip < next_entry.addr).
327 // To prevent ip addresses hit in .eh_frame/.debug_frame being regarded as addresses hit in
328 // .ARM.exidx, we need to check .eh_frame/.debug_frame first.
Yabin Cui98791372017-12-18 14:37:54 -0800329
330 // Check .debug_frame/.gnu_debugdata before .eh_frame, because .debug_frame can unwind from
331 // instructions setting up or destroying stack frames, while .eh_frame can't.
332 if (!is_debug_frame_used_ && (debug_frame->has_debug_frame || debug_frame->has_gnu_debugdata)) {
333 is_debug_frame_used_ = true;
334 unw_dyn_info_t di;
335 unw_word_t segbase = map.start - debug_frame->min_vaddr;
336 // TODO: http://b/32916571
337 // TODO: Do it ourselves is more efficient than calling libunwind functions.
338 int found = dwarf_find_debug_frame(0, &di, ip, segbase, filename.c_str(), map.start, map.end);
339 if (found == 1) {
340 int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
341 if (ret == 0) {
342 return true;
343 }
344 }
345 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800346 if (debug_frame->has_eh_frame) {
347 if (ip_vaddr >= debug_frame->eh_frame.min_func_vaddr &&
348 ip_vaddr < debug_frame->text_end_vaddr) {
349 // Prepare eh_frame_hdr space and eh_frame space.
350 eh_frame_hdr_space_.start = ip - ip_vaddr + debug_frame->eh_frame.hdr_vaddr;
351 eh_frame_hdr_space_.end =
352 eh_frame_hdr_space_.start + debug_frame->eh_frame.hdr_data.size();
353 eh_frame_hdr_space_.data = debug_frame->eh_frame.hdr_data.data();
Yabin Cui5d991bc2016-11-15 17:47:09 -0800354 eh_frame_space_.start = ip - ip_vaddr + debug_frame->eh_frame.vaddr;
355 eh_frame_space_.end = eh_frame_space_.start + debug_frame->eh_frame.data.size();
356 eh_frame_space_.data = debug_frame->eh_frame.data.data();
357
358 unw_dyn_info di;
359 memset(&di, '\0', sizeof(di));
360 di.start_ip = map.start;
361 di.end_ip = map.end;
362 di.format = UNW_INFO_FORMAT_REMOTE_TABLE;
363 di.u.rti.name_ptr = 0;
364 di.u.rti.segbase = eh_frame_hdr_space_.start;
365 di.u.rti.table_data =
366 eh_frame_hdr_space_.start + debug_frame->eh_frame.fde_table_offset;
367 di.u.rti.table_len = (eh_frame_hdr_space_.end - di.u.rti.table_data) / sizeof(unw_word_t);
368 // TODO: Do it ourselves is more efficient than calling this function.
369 int ret = dwarf_search_unwind_table(addr_space, ip, &di, proc_info, need_unwind_info, this);
370 if (ret == 0) {
371 return true;
372 }
373 }
374 }
Yabin Cuic4a480e2017-02-02 15:25:08 -0800375
376 if (debug_frame->has_arm_exidx) {
377 auto& func_vaddrs = debug_frame->arm_exidx.func_vaddr_array;
378 if (ip_vaddr >= func_vaddrs[0] && ip_vaddr < debug_frame->text_end_vaddr) {
379 // Use binary search to find the correct function.
380 auto it = std::upper_bound(func_vaddrs.begin(), func_vaddrs.end(),
381 static_cast<uint32_t>(ip_vaddr));
382 if (it != func_vaddrs.begin()) {
383 --it;
384 // Found the exidx entry.
385 size_t index = it - func_vaddrs.begin();
386 proc_info->start_ip = *it;
387 proc_info->format = UNW_INFO_FORMAT_ARM_EXIDX;
388 proc_info->unwind_info = reinterpret_cast<void*>(
389 static_cast<uintptr_t>(index * sizeof(ArmIdxEntry) +
390 debug_frame->arm_exidx.exidx_vaddr +
391 debug_frame->min_vaddr));
392 eh_frame_hdr_space_.Clear();
393 eh_frame_space_.Clear();
394 // Prepare arm_exidx space and arm_extab space.
395 arm_exidx_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.exidx_vaddr;
396 arm_exidx_space_.end = arm_exidx_space_.start +
397 debug_frame->arm_exidx.exidx_data.size() * sizeof(ArmIdxEntry);
398 arm_exidx_space_.data = reinterpret_cast<const uint8_t*>(
399 debug_frame->arm_exidx.exidx_data.data());
400
401 arm_extab_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.extab_vaddr;
402 arm_extab_space_.end = arm_extab_space_.start +
403 debug_frame->arm_exidx.extab_data.size();
404 arm_extab_space_.data = debug_frame->arm_exidx.extab_data.data();
405 return true;
406 }
407 }
408 }
Yabin Cuif8808282017-12-12 18:04:10 -0800409 error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000410 return false;
411}
412
413bool BacktraceOffline::ReadReg(size_t reg, uint64_t* value) {
414 bool result = true;
415#if defined(__arm__)
416 switch (reg) {
417 case UNW_ARM_R0:
418 *value = context_->uc_mcontext.arm_r0;
419 break;
420 case UNW_ARM_R1:
421 *value = context_->uc_mcontext.arm_r1;
422 break;
423 case UNW_ARM_R2:
424 *value = context_->uc_mcontext.arm_r2;
425 break;
426 case UNW_ARM_R3:
427 *value = context_->uc_mcontext.arm_r3;
428 break;
429 case UNW_ARM_R4:
430 *value = context_->uc_mcontext.arm_r4;
431 break;
432 case UNW_ARM_R5:
433 *value = context_->uc_mcontext.arm_r5;
434 break;
435 case UNW_ARM_R6:
436 *value = context_->uc_mcontext.arm_r6;
437 break;
438 case UNW_ARM_R7:
439 *value = context_->uc_mcontext.arm_r7;
440 break;
441 case UNW_ARM_R8:
442 *value = context_->uc_mcontext.arm_r8;
443 break;
444 case UNW_ARM_R9:
445 *value = context_->uc_mcontext.arm_r9;
446 break;
447 case UNW_ARM_R10:
448 *value = context_->uc_mcontext.arm_r10;
449 break;
450 case UNW_ARM_R11:
451 *value = context_->uc_mcontext.arm_fp;
452 break;
453 case UNW_ARM_R12:
454 *value = context_->uc_mcontext.arm_ip;
455 break;
456 case UNW_ARM_R13:
457 *value = context_->uc_mcontext.arm_sp;
458 break;
459 case UNW_ARM_R14:
460 *value = context_->uc_mcontext.arm_lr;
461 break;
462 case UNW_ARM_R15:
463 *value = context_->uc_mcontext.arm_pc;
464 break;
465 default:
466 result = false;
467 }
468#elif defined(__aarch64__)
469 if (reg <= UNW_AARCH64_PC) {
470 *value = context_->uc_mcontext.regs[reg];
471 } else {
472 result = false;
473 }
474#elif defined(__x86_64__)
475 switch (reg) {
476 case UNW_X86_64_R8:
477 *value = context_->uc_mcontext.gregs[REG_R8];
478 break;
479 case UNW_X86_64_R9:
480 *value = context_->uc_mcontext.gregs[REG_R9];
481 break;
482 case UNW_X86_64_R10:
483 *value = context_->uc_mcontext.gregs[REG_R10];
484 break;
485 case UNW_X86_64_R11:
486 *value = context_->uc_mcontext.gregs[REG_R11];
487 break;
488 case UNW_X86_64_R12:
489 *value = context_->uc_mcontext.gregs[REG_R12];
490 break;
491 case UNW_X86_64_R13:
492 *value = context_->uc_mcontext.gregs[REG_R13];
493 break;
494 case UNW_X86_64_R14:
495 *value = context_->uc_mcontext.gregs[REG_R14];
496 break;
497 case UNW_X86_64_R15:
498 *value = context_->uc_mcontext.gregs[REG_R15];
499 break;
500 case UNW_X86_64_RDI:
501 *value = context_->uc_mcontext.gregs[REG_RDI];
502 break;
503 case UNW_X86_64_RSI:
504 *value = context_->uc_mcontext.gregs[REG_RSI];
505 break;
506 case UNW_X86_64_RBP:
507 *value = context_->uc_mcontext.gregs[REG_RBP];
508 break;
509 case UNW_X86_64_RBX:
510 *value = context_->uc_mcontext.gregs[REG_RBX];
511 break;
512 case UNW_X86_64_RDX:
513 *value = context_->uc_mcontext.gregs[REG_RDX];
514 break;
515 case UNW_X86_64_RAX:
516 *value = context_->uc_mcontext.gregs[REG_RAX];
517 break;
518 case UNW_X86_64_RCX:
519 *value = context_->uc_mcontext.gregs[REG_RCX];
520 break;
521 case UNW_X86_64_RSP:
522 *value = context_->uc_mcontext.gregs[REG_RSP];
523 break;
524 case UNW_X86_64_RIP:
525 *value = context_->uc_mcontext.gregs[REG_RIP];
526 break;
527 default:
528 result = false;
529 }
530#elif defined(__i386__)
531 switch (reg) {
532 case UNW_X86_GS:
533 *value = context_->uc_mcontext.gregs[REG_GS];
534 break;
535 case UNW_X86_FS:
536 *value = context_->uc_mcontext.gregs[REG_FS];
537 break;
538 case UNW_X86_ES:
539 *value = context_->uc_mcontext.gregs[REG_ES];
540 break;
541 case UNW_X86_DS:
542 *value = context_->uc_mcontext.gregs[REG_DS];
543 break;
544 case UNW_X86_EAX:
545 *value = context_->uc_mcontext.gregs[REG_EAX];
546 break;
547 case UNW_X86_EBX:
548 *value = context_->uc_mcontext.gregs[REG_EBX];
549 break;
550 case UNW_X86_ECX:
551 *value = context_->uc_mcontext.gregs[REG_ECX];
552 break;
553 case UNW_X86_EDX:
554 *value = context_->uc_mcontext.gregs[REG_EDX];
555 break;
556 case UNW_X86_ESI:
557 *value = context_->uc_mcontext.gregs[REG_ESI];
558 break;
559 case UNW_X86_EDI:
560 *value = context_->uc_mcontext.gregs[REG_EDI];
561 break;
562 case UNW_X86_EBP:
563 *value = context_->uc_mcontext.gregs[REG_EBP];
564 break;
565 case UNW_X86_EIP:
566 *value = context_->uc_mcontext.gregs[REG_EIP];
567 break;
568 case UNW_X86_ESP:
569 *value = context_->uc_mcontext.gregs[REG_ESP];
570 break;
571 case UNW_X86_TRAPNO:
572 *value = context_->uc_mcontext.gregs[REG_TRAPNO];
573 break;
574 case UNW_X86_CS:
575 *value = context_->uc_mcontext.gregs[REG_CS];
576 break;
577 case UNW_X86_EFLAGS:
578 *value = context_->uc_mcontext.gregs[REG_EFL];
579 break;
580 case UNW_X86_SS:
581 *value = context_->uc_mcontext.gregs[REG_SS];
582 break;
583 default:
584 result = false;
585 }
Colin Cross06d31492016-12-15 12:55:03 -0800586#else
587 UNUSED(reg);
588 UNUSED(value);
589 result = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000590#endif
Yabin Cuif8808282017-12-12 18:04:10 -0800591 if (!result) {
592 error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED;
593 error_.error_info.regno = reg;
594 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000595 return result;
596}
597
598std::string BacktraceOffline::GetFunctionNameRaw(uintptr_t, uintptr_t* offset) {
599 // We don't have enough information to support this. And it is expensive.
600 *offset = 0;
601 return "";
602}
603
Yabin Cui26369a32017-02-10 18:05:34 -0800604static std::mutex g_lock;
605static std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>* g_debug_frames = nullptr;
606
Yabin Cui9e402bb2015-09-22 04:46:57 +0000607static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename);
608
609DebugFrameInfo* BacktraceOffline::GetDebugFrameInFile(const std::string& filename) {
610 if (cache_file_) {
Yabin Cui26369a32017-02-10 18:05:34 -0800611 std::lock_guard<std::mutex> lock(g_lock);
612 if (g_debug_frames != nullptr) {
613 auto it = g_debug_frames->find(filename);
614 if (it != g_debug_frames->end()) {
615 return it->second.get();
616 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000617 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000618 }
619 DebugFrameInfo* debug_frame = ReadDebugFrameFromFile(filename);
620 if (cache_file_) {
Yabin Cui26369a32017-02-10 18:05:34 -0800621 std::lock_guard<std::mutex> lock(g_lock);
622 if (g_debug_frames == nullptr) {
623 g_debug_frames = new std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>;
624 }
625 auto pair = g_debug_frames->emplace(filename, std::unique_ptr<DebugFrameInfo>(debug_frame));
626 if (!pair.second) {
627 debug_frame = pair.first->second.get();
628 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000629 }
630 return debug_frame;
631}
632
Yabin Cui98791372017-12-18 14:37:54 -0800633static bool OmitEncodedValue(uint8_t encode, const uint8_t*& p, bool is_elf64) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000634 if (encode == DW_EH_PE_omit) {
635 return 0;
636 }
637 uint8_t format = encode & 0x0f;
638 switch (format) {
639 case DW_EH_PE_ptr:
Yabin Cui98791372017-12-18 14:37:54 -0800640 p += is_elf64 ? 8 : 4;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000641 break;
642 case DW_EH_PE_uleb128:
643 case DW_EH_PE_sleb128:
644 while ((*p & 0x80) != 0) {
645 ++p;
646 }
647 ++p;
648 break;
649 case DW_EH_PE_udata2:
650 case DW_EH_PE_sdata2:
651 p += 2;
652 break;
653 case DW_EH_PE_udata4:
654 case DW_EH_PE_sdata4:
655 p += 4;
656 break;
657 case DW_EH_PE_udata8:
658 case DW_EH_PE_sdata8:
659 p += 8;
660 break;
661 default:
662 return false;
663 }
664 return true;
665}
666
667static bool GetFdeTableOffsetInEhFrameHdr(const std::vector<uint8_t>& data,
Yabin Cui98791372017-12-18 14:37:54 -0800668 uint64_t* table_offset_in_eh_frame_hdr, bool is_elf64) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000669 const uint8_t* p = data.data();
670 const uint8_t* end = p + data.size();
671 if (p + 4 > end) {
672 return false;
673 }
674 uint8_t version = *p++;
675 if (version != 1) {
676 return false;
677 }
678 uint8_t eh_frame_ptr_encode = *p++;
679 uint8_t fde_count_encode = *p++;
680 uint8_t fde_table_encode = *p++;
681
682 if (fde_table_encode != (DW_EH_PE_datarel | DW_EH_PE_sdata4)) {
683 return false;
684 }
685
Yabin Cui98791372017-12-18 14:37:54 -0800686 if (!OmitEncodedValue(eh_frame_ptr_encode, p, is_elf64) ||
687 !OmitEncodedValue(fde_count_encode, p, is_elf64)) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000688 return false;
689 }
690 if (p >= end) {
691 return false;
692 }
693 *table_offset_in_eh_frame_hdr = p - data.data();
694 return true;
695}
696
Yabin Cui98791372017-12-18 14:37:54 -0800697static uint64_t ReadFromBuffer(const uint8_t*& p, size_t size) {
698 uint64_t result = 0;
699 int shift = 0;
700 while (size-- > 0) {
701 uint64_t tmp = *p++;
702 result |= tmp << shift;
703 shift += 8;
704 }
705 return result;
706}
707
708static uint64_t ReadSignValueFromBuffer(const uint8_t*& p, size_t size) {
709 uint64_t result = 0;
710 int shift = 0;
711 for (size_t i = 0; i < size; ++i) {
712 uint64_t tmp = *p++;
713 result |= tmp << shift;
714 shift += 8;
715 }
716 if (*(p - 1) & 0x80) {
717 result |= (-1ULL) << (size * 8);
718 }
719 return result;
720}
721
722static const char* ReadStrFromBuffer(const uint8_t*& p) {
723 const char* result = reinterpret_cast<const char*>(p);
724 p += strlen(result) + 1;
725 return result;
726}
727
728static int64_t ReadLEB128FromBuffer(const uint8_t*& p) {
729 int64_t result = 0;
730 int64_t tmp;
731 int shift = 0;
732 while (*p & 0x80) {
733 tmp = *p & 0x7f;
734 result |= tmp << shift;
735 shift += 7;
736 p++;
737 }
738 tmp = *p;
739 result |= tmp << shift;
740 if (*p & 0x40) {
741 result |= -((tmp & 0x40) << shift);
742 }
743 p++;
744 return result;
745}
746
747static uint64_t ReadULEB128FromBuffer(const uint8_t*& p) {
748 uint64_t result = 0;
749 uint64_t tmp;
750 int shift = 0;
751 while (*p & 0x80) {
752 tmp = *p & 0x7f;
753 result |= tmp << shift;
754 shift += 7;
755 p++;
756 }
757 tmp = *p;
758 result |= tmp << shift;
759 p++;
760 return result;
761}
762
763static uint64_t ReadEhEncoding(const uint8_t*& p, uint8_t encoding, bool is_elf64,
764 uint64_t section_vaddr, const uint8_t* section_begin) {
765 const uint8_t* init_addr = p;
766 uint64_t result = 0;
767 switch (encoding & 0x0f) {
768 case DW_EH_PE_absptr:
769 result = ReadFromBuffer(p, is_elf64 ? 8 : 4);
770 break;
771 case DW_EH_PE_omit:
772 result = 0;
773 break;
774 case DW_EH_PE_uleb128:
775 result = ReadULEB128FromBuffer(p);
776 break;
777 case DW_EH_PE_udata2:
778 result = ReadFromBuffer(p, 2);
779 break;
780 case DW_EH_PE_udata4:
781 result = ReadFromBuffer(p, 4);
782 break;
783 case DW_EH_PE_udata8:
784 result = ReadFromBuffer(p, 8);
785 break;
786 case DW_EH_PE_sleb128:
787 result = ReadLEB128FromBuffer(p);
788 break;
789 case DW_EH_PE_sdata2:
790 result = ReadSignValueFromBuffer(p, 2);
791 break;
792 case DW_EH_PE_sdata4:
793 result = ReadSignValueFromBuffer(p, 4);
794 break;
795 case DW_EH_PE_sdata8:
796 result = ReadSignValueFromBuffer(p, 8);
797 break;
798 }
799 switch (encoding & 0xf0) {
800 case DW_EH_PE_pcrel:
801 result += init_addr - section_begin + section_vaddr;
802 break;
803 case DW_EH_PE_datarel:
804 result += section_vaddr;
805 break;
806 }
807 return result;
808}
809
810static bool BuildEhFrameHdr(DebugFrameInfo* info, bool is_elf64) {
811 // For each fde entry, collect its (func_vaddr, fde_vaddr) pair.
812 std::vector<std::pair<uint64_t, uint64_t>> index_table;
813 // Map form cie_offset to fde encoding.
814 std::unordered_map<size_t, uint8_t> cie_map;
815 const uint8_t* eh_frame_begin = info->eh_frame.data.data();
816 const uint8_t* eh_frame_end = eh_frame_begin + info->eh_frame.data.size();
817 const uint8_t* p = eh_frame_begin;
818 uint64_t eh_frame_vaddr = info->eh_frame.vaddr;
819 while (p < eh_frame_end) {
820 const uint8_t* unit_begin = p;
821 uint64_t unit_len = ReadFromBuffer(p, 4);
822 size_t secbytes = 4;
823 if (unit_len == 0xffffffff) {
824 unit_len = ReadFromBuffer(p, 8);
825 secbytes = 8;
826 }
827 const uint8_t* unit_end = p + unit_len;
828 uint64_t cie_id = ReadFromBuffer(p, secbytes);
829 if (cie_id == 0) {
830 // This is a CIE.
831 // Read version
832 uint8_t version = *p++;
833 // Read augmentation
834 const char* augmentation = ReadStrFromBuffer(p);
835 if (version >= 4) {
836 // Read address size and segment size
837 p += 2;
838 }
839 // Read code alignment factor
840 ReadULEB128FromBuffer(p);
841 // Read data alignment factor
842 ReadLEB128FromBuffer(p);
843 // Read return address register
844 if (version == 1) {
845 p++;
846 } else {
847 ReadULEB128FromBuffer(p);
848 }
849 uint8_t fde_pointer_encoding = 0;
850 if (augmentation[0] == 'z') {
851 // Read augmentation length.
852 ReadULEB128FromBuffer(p);
853 for (int i = 1; augmentation[i] != '\0'; ++i) {
854 char c = augmentation[i];
855 if (c == 'R') {
856 fde_pointer_encoding = *p++;
857 } else if (c == 'P') {
858 // Read personality handler
859 uint8_t encoding = *p++;
860 OmitEncodedValue(encoding, p, is_elf64);
861 } else if (c == 'L') {
862 // Read lsda encoding
863 p++;
864 }
865 }
866 }
867 cie_map[unit_begin - eh_frame_begin] = fde_pointer_encoding;
868 } else {
869 // This is an FDE.
870 size_t cie_offset = p - secbytes - eh_frame_begin - cie_id;
871 auto it = cie_map.find(cie_offset);
872 if (it != cie_map.end()) {
873 uint8_t fde_pointer_encoding = it->second;
874 uint64_t initial_location =
875 ReadEhEncoding(p, fde_pointer_encoding, is_elf64, eh_frame_vaddr, eh_frame_begin);
876 uint64_t fde_vaddr = unit_begin - eh_frame_begin + eh_frame_vaddr;
877 index_table.push_back(std::make_pair(initial_location, fde_vaddr));
878 }
879 }
880 p = unit_end;
881 }
882 if (index_table.empty()) {
883 return false;
884 }
885 std::sort(index_table.begin(), index_table.end());
886 info->eh_frame.hdr_vaddr = 0;
887 info->eh_frame.hdr_data.resize(index_table.size() * 8);
888 uint32_t* ptr = reinterpret_cast<uint32_t*>(info->eh_frame.hdr_data.data());
889 for (auto& pair : index_table) {
890 *ptr++ = static_cast<uint32_t>(pair.first - info->eh_frame.hdr_vaddr);
891 *ptr++ = static_cast<uint32_t>(pair.second - info->eh_frame.hdr_vaddr);
892 }
893 info->eh_frame.fde_table_offset = 0;
894 info->eh_frame.min_func_vaddr = index_table[0].first;
895 return true;
896}
897
Yabin Cui9e402bb2015-09-22 04:46:57 +0000898template <class ELFT>
899DebugFrameInfo* ReadDebugFrameFromELFFile(const llvm::object::ELFFile<ELFT>* elf) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800900 DebugFrameInfo* result = new DebugFrameInfo;
Yabin Cui98791372017-12-18 14:37:54 -0800901 result->eh_frame.hdr_vaddr = 0;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800902 result->text_end_vaddr = std::numeric_limits<uint64_t>::max();
903
Yabin Cui98791372017-12-18 14:37:54 -0800904 bool is_elf64 = (elf->getHeader()->getFileClass() == llvm::ELF::ELFCLASS64);
Yabin Cui9e402bb2015-09-22 04:46:57 +0000905 bool has_eh_frame_hdr = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000906 bool has_eh_frame = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000907
Stephen Hines19c30e92016-03-08 01:23:43 -0800908 for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000909 llvm::ErrorOr<llvm::StringRef> name = elf->getSectionName(&*it);
910 if (name) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800911 std::string s = name.get();
912 if (s == ".debug_frame") {
913 result->has_debug_frame = true;
914 } else if (s == ".gnu_debugdata") {
915 result->has_gnu_debugdata = true;
916 } else if (s == ".eh_frame_hdr") {
917 result->eh_frame.hdr_vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000918 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
919 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800920 result->eh_frame.hdr_data.insert(result->eh_frame.hdr_data.end(),
921 data->data(), data->data() + data->size());
922
923 uint64_t fde_table_offset;
Yabin Cui98791372017-12-18 14:37:54 -0800924 if (GetFdeTableOffsetInEhFrameHdr(result->eh_frame.hdr_data, &fde_table_offset, is_elf64)) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800925 result->eh_frame.fde_table_offset = fde_table_offset;
926 // Make sure we have at least one entry in fde_table.
927 if (fde_table_offset + 2 * sizeof(int32_t) <= data->size()) {
928 intptr_t eh_frame_hdr_vaddr = it->sh_addr;
929 int32_t sdata;
930 uint8_t* p = result->eh_frame.hdr_data.data() + fde_table_offset;
931 memcpy(&sdata, p, sizeof(sdata));
932 result->eh_frame.min_func_vaddr = eh_frame_hdr_vaddr + sdata;
933 has_eh_frame_hdr = true;
934 }
935 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000936 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800937 } else if (s == ".eh_frame") {
938 result->eh_frame.vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000939 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
940 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800941 result->eh_frame.data.insert(result->eh_frame.data.end(),
942 data->data(), data->data() + data->size());
943 has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000944 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800945 } else if (s == ".ARM.exidx") {
946 result->arm_exidx.exidx_vaddr = it->sh_addr;
947 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
948 if (data) {
949 size_t entry_count = data->size() / sizeof(ArmIdxEntry);
950 result->arm_exidx.exidx_data.resize(entry_count);
951 memcpy(result->arm_exidx.exidx_data.data(), data->data(),
952 entry_count * sizeof(ArmIdxEntry));
953 if (entry_count > 0u) {
954 // Change IdxEntry.func_offset into vaddr.
955 result->arm_exidx.func_vaddr_array.reserve(entry_count);
956 uint32_t vaddr = it->sh_addr;
957 for (auto& entry : result->arm_exidx.exidx_data) {
958 uint32_t func_offset = entry.func_offset + vaddr;
959 // Clear bit 31 for the prel31 offset.
960 // Arm sets bit 0 to mark it as thumb code, remove the flag.
961 result->arm_exidx.func_vaddr_array.push_back(
962 func_offset & 0x7ffffffe);
963 vaddr += 8;
964 }
965 result->has_arm_exidx = true;
966 }
967 }
968 } else if (s == ".ARM.extab") {
969 result->arm_exidx.extab_vaddr = it->sh_addr;
970 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
971 if (data) {
972 result->arm_exidx.extab_data.insert(result->arm_exidx.extab_data.end(),
973 data->data(), data->data() + data->size());
974 }
975 } else if (s == ".text") {
976 result->text_end_vaddr = it->sh_addr + it->sh_size;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000977 }
978 }
979 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800980
Yabin Cui98791372017-12-18 14:37:54 -0800981 if (has_eh_frame) {
982 if (!has_eh_frame_hdr) {
983 // Some libraries (like /vendor/lib64/egl/eglSubDriverAndroid.so) contain empty
984 // .eh_frame_hdr.
985 if (BuildEhFrameHdr(result, is_elf64)) {
986 has_eh_frame_hdr = true;
987 }
988 }
989 if (has_eh_frame_hdr) {
990 result->has_eh_frame = true;
991 }
992 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800993 if (has_eh_frame_hdr && has_eh_frame) {
994 result->has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000995 }
996
Yabin Cui5d991bc2016-11-15 17:47:09 -0800997 result->min_vaddr = std::numeric_limits<uint64_t>::max();
Stephen Hines19c30e92016-03-08 01:23:43 -0800998 for (auto it = elf->program_header_begin(); it != elf->program_header_end(); ++it) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800999 if ((it->p_type == llvm::ELF::PT_LOAD) && (it->p_flags & llvm::ELF::PF_X)) {
1000 if (it->p_vaddr < result->min_vaddr) {
1001 result->min_vaddr = it->p_vaddr;
1002 }
1003 }
Yabin Cui9e402bb2015-09-22 04:46:57 +00001004 }
Yabin Cui5d991bc2016-11-15 17:47:09 -08001005 if (!result->has_eh_frame && !result->has_arm_exidx && !result->has_debug_frame &&
1006 !result->has_gnu_debugdata) {
1007 delete result;
1008 return nullptr;
1009 }
1010 return result;
Yabin Cui9e402bb2015-09-22 04:46:57 +00001011}
1012
Yabin Cui2ad59db2015-12-08 18:43:00 -08001013static bool IsValidElfPath(const std::string& filename) {
1014 static const char elf_magic[] = {0x7f, 'E', 'L', 'F'};
1015
1016 struct stat st;
1017 if (stat(filename.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
1018 return false;
1019 }
1020 FILE* fp = fopen(filename.c_str(), "reb");
1021 if (fp == nullptr) {
1022 return false;
1023 }
1024 char buf[4];
1025 if (fread(buf, 4, 1, fp) != 1) {
1026 fclose(fp);
1027 return false;
1028 }
1029 fclose(fp);
1030 return memcmp(buf, elf_magic, 4) == 0;
1031}
1032
Yabin Cuib791a762016-03-18 18:46:08 -07001033static bool IsValidApkPath(const std::string& apk_path) {
1034 static const char zip_preamble[] = {0x50, 0x4b, 0x03, 0x04};
1035 struct stat st;
1036 if (stat(apk_path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
1037 return false;
1038 }
1039 FILE* fp = fopen(apk_path.c_str(), "reb");
1040 if (fp == nullptr) {
1041 return false;
1042 }
1043 char buf[4];
1044 if (fread(buf, 4, 1, fp) != 1) {
1045 fclose(fp);
1046 return false;
1047 }
1048 fclose(fp);
1049 return memcmp(buf, zip_preamble, 4) == 0;
1050}
1051
1052class ScopedZiparchiveHandle {
1053 public:
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -07001054 explicit ScopedZiparchiveHandle(ZipArchiveHandle handle) : handle_(handle) {
Yabin Cuib791a762016-03-18 18:46:08 -07001055 }
1056
1057 ~ScopedZiparchiveHandle() {
1058 CloseArchive(handle_);
1059 }
1060
1061 private:
1062 ZipArchiveHandle handle_;
1063};
1064
1065llvm::object::OwningBinary<llvm::object::Binary> OpenEmbeddedElfFile(const std::string& filename) {
1066 llvm::object::OwningBinary<llvm::object::Binary> nothing;
1067 size_t pos = filename.find("!/");
1068 if (pos == std::string::npos) {
1069 return nothing;
1070 }
1071 std::string apk_file = filename.substr(0, pos);
1072 std::string elf_file = filename.substr(pos + 2);
1073 if (!IsValidApkPath(apk_file)) {
1074 BACK_LOGW("%s is not a valid apk file", apk_file.c_str());
1075 return nothing;
1076 }
1077 ZipArchiveHandle handle;
1078 int32_t ret_code = OpenArchive(apk_file.c_str(), &handle);
1079 if (ret_code != 0) {
1080 CloseArchive(handle);
1081 BACK_LOGW("failed to open archive %s: %s", apk_file.c_str(), ErrorCodeString(ret_code));
1082 return nothing;
1083 }
1084 ScopedZiparchiveHandle scoped_handle(handle);
1085 ZipEntry zentry;
1086 ret_code = FindEntry(handle, ZipString(elf_file.c_str()), &zentry);
1087 if (ret_code != 0) {
1088 BACK_LOGW("failed to find %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
1089 ErrorCodeString(ret_code));
1090 return nothing;
1091 }
1092 if (zentry.method != kCompressStored || zentry.compressed_length != zentry.uncompressed_length) {
1093 BACK_LOGW("%s is compressed in %s, which doesn't support running directly", elf_file.c_str(),
1094 apk_file.c_str());
1095 return nothing;
1096 }
1097 auto buffer_or_err = llvm::MemoryBuffer::getOpenFileSlice(GetFileDescriptor(handle), apk_file,
1098 zentry.uncompressed_length,
1099 zentry.offset);
1100 if (!buffer_or_err) {
1101 BACK_LOGW("failed to read %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
1102 buffer_or_err.getError().message().c_str());
1103 return nothing;
1104 }
1105 auto binary_or_err = llvm::object::createBinary(buffer_or_err.get()->getMemBufferRef());
1106 if (!binary_or_err) {
1107 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 -07001108 llvm::toString(binary_or_err.takeError()).c_str());
Yabin Cuib791a762016-03-18 18:46:08 -07001109 return nothing;
1110 }
1111 return llvm::object::OwningBinary<llvm::object::Binary>(std::move(binary_or_err.get()),
1112 std::move(buffer_or_err.get()));
1113}
1114
Yabin Cui9e402bb2015-09-22 04:46:57 +00001115static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename) {
Yabin Cuib791a762016-03-18 18:46:08 -07001116 llvm::object::OwningBinary<llvm::object::Binary> owning_binary;
1117 if (filename.find("!/") != std::string::npos) {
1118 owning_binary = OpenEmbeddedElfFile(filename);
1119 } else {
1120 if (!IsValidElfPath(filename)) {
1121 return nullptr;
1122 }
1123 auto binary_or_err = llvm::object::createBinary(llvm::StringRef(filename));
1124 if (!binary_or_err) {
1125 return nullptr;
1126 }
1127 owning_binary = std::move(binary_or_err.get());
Yabin Cui2ad59db2015-12-08 18:43:00 -08001128 }
Yabin Cuib791a762016-03-18 18:46:08 -07001129 llvm::object::Binary* binary = owning_binary.getBinary();
Yabin Cui9e402bb2015-09-22 04:46:57 +00001130 auto obj = llvm::dyn_cast<llvm::object::ObjectFile>(binary);
1131 if (obj == nullptr) {
1132 return nullptr;
1133 }
1134 if (auto elf = llvm::dyn_cast<llvm::object::ELF32LEObjectFile>(obj)) {
1135 return ReadDebugFrameFromELFFile(elf->getELFFile());
1136 }
1137 if (auto elf = llvm::dyn_cast<llvm::object::ELF64LEObjectFile>(obj)) {
1138 return ReadDebugFrameFromELFFile(elf->getELFFile());
1139 }
1140 return nullptr;
1141}
Christopher Ferris85402162016-01-25 16:17:48 -08001142
1143Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
1144 const backtrace_stackinfo_t& stack, bool cache_file) {
1145 return new BacktraceOffline(pid, tid, map, stack, cache_file);
1146}