blob: a056716512db38d05e647ca90fdf354f5efd21e9 [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;
Christopher Ferris7937a362018-01-18 11:15:49 -080060 uint64_t min_func_vaddr;
Yabin Cui5d991bc2016-11-15 17:47:09 -080061 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;
Christopher Ferris7937a362018-01-18 11:15:49 -0800224 frame->pc = static_cast<uint64_t>(pc);
225 frame->sp = static_cast<uint64_t>(sp);
Yabin Cui9e402bb2015-09-22 04:46:57 +0000226 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
Christopher Ferris7937a362018-01-18 11:15:49 -0800256bool BacktraceOffline::ReadWord(uint64_t ptr, word_t* out_value) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000257 size_t bytes_read = Read(ptr, reinterpret_cast<uint8_t*>(out_value), sizeof(word_t));
258 return bytes_read == sizeof(word_t);
259}
260
Christopher Ferris7937a362018-01-18 11:15:49 -0800261size_t BacktraceOffline::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000262 // 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*>(
Christopher Ferris7937a362018-01-18 11:15:49 -0800389 static_cast<uint64_t>(index * sizeof(ArmIdxEntry) + debug_frame->arm_exidx.exidx_vaddr +
390 debug_frame->min_vaddr));
Yabin Cuic4a480e2017-02-02 15:25:08 -0800391 eh_frame_hdr_space_.Clear();
392 eh_frame_space_.Clear();
393 // Prepare arm_exidx space and arm_extab space.
394 arm_exidx_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.exidx_vaddr;
395 arm_exidx_space_.end = arm_exidx_space_.start +
396 debug_frame->arm_exidx.exidx_data.size() * sizeof(ArmIdxEntry);
397 arm_exidx_space_.data = reinterpret_cast<const uint8_t*>(
398 debug_frame->arm_exidx.exidx_data.data());
399
400 arm_extab_space_.start = debug_frame->min_vaddr + debug_frame->arm_exidx.extab_vaddr;
401 arm_extab_space_.end = arm_extab_space_.start +
402 debug_frame->arm_exidx.extab_data.size();
403 arm_extab_space_.data = debug_frame->arm_exidx.extab_data.data();
404 return true;
405 }
406 }
407 }
Yabin Cuif8808282017-12-12 18:04:10 -0800408 error_.error_code = BACKTRACE_UNWIND_ERROR_FIND_PROC_INFO_FAILED;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000409 return false;
410}
411
412bool BacktraceOffline::ReadReg(size_t reg, uint64_t* value) {
413 bool result = true;
414#if defined(__arm__)
415 switch (reg) {
416 case UNW_ARM_R0:
417 *value = context_->uc_mcontext.arm_r0;
418 break;
419 case UNW_ARM_R1:
420 *value = context_->uc_mcontext.arm_r1;
421 break;
422 case UNW_ARM_R2:
423 *value = context_->uc_mcontext.arm_r2;
424 break;
425 case UNW_ARM_R3:
426 *value = context_->uc_mcontext.arm_r3;
427 break;
428 case UNW_ARM_R4:
429 *value = context_->uc_mcontext.arm_r4;
430 break;
431 case UNW_ARM_R5:
432 *value = context_->uc_mcontext.arm_r5;
433 break;
434 case UNW_ARM_R6:
435 *value = context_->uc_mcontext.arm_r6;
436 break;
437 case UNW_ARM_R7:
438 *value = context_->uc_mcontext.arm_r7;
439 break;
440 case UNW_ARM_R8:
441 *value = context_->uc_mcontext.arm_r8;
442 break;
443 case UNW_ARM_R9:
444 *value = context_->uc_mcontext.arm_r9;
445 break;
446 case UNW_ARM_R10:
447 *value = context_->uc_mcontext.arm_r10;
448 break;
449 case UNW_ARM_R11:
450 *value = context_->uc_mcontext.arm_fp;
451 break;
452 case UNW_ARM_R12:
453 *value = context_->uc_mcontext.arm_ip;
454 break;
455 case UNW_ARM_R13:
456 *value = context_->uc_mcontext.arm_sp;
457 break;
458 case UNW_ARM_R14:
459 *value = context_->uc_mcontext.arm_lr;
460 break;
461 case UNW_ARM_R15:
462 *value = context_->uc_mcontext.arm_pc;
463 break;
464 default:
465 result = false;
466 }
467#elif defined(__aarch64__)
468 if (reg <= UNW_AARCH64_PC) {
469 *value = context_->uc_mcontext.regs[reg];
470 } else {
471 result = false;
472 }
473#elif defined(__x86_64__)
474 switch (reg) {
475 case UNW_X86_64_R8:
476 *value = context_->uc_mcontext.gregs[REG_R8];
477 break;
478 case UNW_X86_64_R9:
479 *value = context_->uc_mcontext.gregs[REG_R9];
480 break;
481 case UNW_X86_64_R10:
482 *value = context_->uc_mcontext.gregs[REG_R10];
483 break;
484 case UNW_X86_64_R11:
485 *value = context_->uc_mcontext.gregs[REG_R11];
486 break;
487 case UNW_X86_64_R12:
488 *value = context_->uc_mcontext.gregs[REG_R12];
489 break;
490 case UNW_X86_64_R13:
491 *value = context_->uc_mcontext.gregs[REG_R13];
492 break;
493 case UNW_X86_64_R14:
494 *value = context_->uc_mcontext.gregs[REG_R14];
495 break;
496 case UNW_X86_64_R15:
497 *value = context_->uc_mcontext.gregs[REG_R15];
498 break;
499 case UNW_X86_64_RDI:
500 *value = context_->uc_mcontext.gregs[REG_RDI];
501 break;
502 case UNW_X86_64_RSI:
503 *value = context_->uc_mcontext.gregs[REG_RSI];
504 break;
505 case UNW_X86_64_RBP:
506 *value = context_->uc_mcontext.gregs[REG_RBP];
507 break;
508 case UNW_X86_64_RBX:
509 *value = context_->uc_mcontext.gregs[REG_RBX];
510 break;
511 case UNW_X86_64_RDX:
512 *value = context_->uc_mcontext.gregs[REG_RDX];
513 break;
514 case UNW_X86_64_RAX:
515 *value = context_->uc_mcontext.gregs[REG_RAX];
516 break;
517 case UNW_X86_64_RCX:
518 *value = context_->uc_mcontext.gregs[REG_RCX];
519 break;
520 case UNW_X86_64_RSP:
521 *value = context_->uc_mcontext.gregs[REG_RSP];
522 break;
523 case UNW_X86_64_RIP:
524 *value = context_->uc_mcontext.gregs[REG_RIP];
525 break;
526 default:
527 result = false;
528 }
529#elif defined(__i386__)
530 switch (reg) {
531 case UNW_X86_GS:
532 *value = context_->uc_mcontext.gregs[REG_GS];
533 break;
534 case UNW_X86_FS:
535 *value = context_->uc_mcontext.gregs[REG_FS];
536 break;
537 case UNW_X86_ES:
538 *value = context_->uc_mcontext.gregs[REG_ES];
539 break;
540 case UNW_X86_DS:
541 *value = context_->uc_mcontext.gregs[REG_DS];
542 break;
543 case UNW_X86_EAX:
544 *value = context_->uc_mcontext.gregs[REG_EAX];
545 break;
546 case UNW_X86_EBX:
547 *value = context_->uc_mcontext.gregs[REG_EBX];
548 break;
549 case UNW_X86_ECX:
550 *value = context_->uc_mcontext.gregs[REG_ECX];
551 break;
552 case UNW_X86_EDX:
553 *value = context_->uc_mcontext.gregs[REG_EDX];
554 break;
555 case UNW_X86_ESI:
556 *value = context_->uc_mcontext.gregs[REG_ESI];
557 break;
558 case UNW_X86_EDI:
559 *value = context_->uc_mcontext.gregs[REG_EDI];
560 break;
561 case UNW_X86_EBP:
562 *value = context_->uc_mcontext.gregs[REG_EBP];
563 break;
564 case UNW_X86_EIP:
565 *value = context_->uc_mcontext.gregs[REG_EIP];
566 break;
567 case UNW_X86_ESP:
568 *value = context_->uc_mcontext.gregs[REG_ESP];
569 break;
570 case UNW_X86_TRAPNO:
571 *value = context_->uc_mcontext.gregs[REG_TRAPNO];
572 break;
573 case UNW_X86_CS:
574 *value = context_->uc_mcontext.gregs[REG_CS];
575 break;
576 case UNW_X86_EFLAGS:
577 *value = context_->uc_mcontext.gregs[REG_EFL];
578 break;
579 case UNW_X86_SS:
580 *value = context_->uc_mcontext.gregs[REG_SS];
581 break;
582 default:
583 result = false;
584 }
Colin Cross06d31492016-12-15 12:55:03 -0800585#else
586 UNUSED(reg);
587 UNUSED(value);
588 result = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000589#endif
Yabin Cuif8808282017-12-12 18:04:10 -0800590 if (!result) {
591 error_.error_code = BACKTRACE_UNWIND_ERROR_ACCESS_REG_FAILED;
592 error_.error_info.regno = reg;
593 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000594 return result;
595}
596
Christopher Ferris7937a362018-01-18 11:15:49 -0800597std::string BacktraceOffline::GetFunctionNameRaw(uint64_t, uint64_t* offset) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000598 // We don't have enough information to support this. And it is expensive.
599 *offset = 0;
600 return "";
601}
602
Yabin Cui26369a32017-02-10 18:05:34 -0800603static std::mutex g_lock;
604static std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>* g_debug_frames = nullptr;
605
Yabin Cui9e402bb2015-09-22 04:46:57 +0000606static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename);
607
608DebugFrameInfo* BacktraceOffline::GetDebugFrameInFile(const std::string& filename) {
609 if (cache_file_) {
Yabin Cui26369a32017-02-10 18:05:34 -0800610 std::lock_guard<std::mutex> lock(g_lock);
611 if (g_debug_frames != nullptr) {
612 auto it = g_debug_frames->find(filename);
613 if (it != g_debug_frames->end()) {
614 return it->second.get();
615 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000616 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000617 }
618 DebugFrameInfo* debug_frame = ReadDebugFrameFromFile(filename);
619 if (cache_file_) {
Yabin Cui26369a32017-02-10 18:05:34 -0800620 std::lock_guard<std::mutex> lock(g_lock);
621 if (g_debug_frames == nullptr) {
622 g_debug_frames = new std::unordered_map<std::string, std::unique_ptr<DebugFrameInfo>>;
623 }
624 auto pair = g_debug_frames->emplace(filename, std::unique_ptr<DebugFrameInfo>(debug_frame));
625 if (!pair.second) {
626 debug_frame = pair.first->second.get();
627 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000628 }
629 return debug_frame;
630}
631
Yabin Cui98791372017-12-18 14:37:54 -0800632static bool OmitEncodedValue(uint8_t encode, const uint8_t*& p, bool is_elf64) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000633 if (encode == DW_EH_PE_omit) {
634 return 0;
635 }
636 uint8_t format = encode & 0x0f;
637 switch (format) {
638 case DW_EH_PE_ptr:
Yabin Cui98791372017-12-18 14:37:54 -0800639 p += is_elf64 ? 8 : 4;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000640 break;
641 case DW_EH_PE_uleb128:
642 case DW_EH_PE_sleb128:
643 while ((*p & 0x80) != 0) {
644 ++p;
645 }
646 ++p;
647 break;
648 case DW_EH_PE_udata2:
649 case DW_EH_PE_sdata2:
650 p += 2;
651 break;
652 case DW_EH_PE_udata4:
653 case DW_EH_PE_sdata4:
654 p += 4;
655 break;
656 case DW_EH_PE_udata8:
657 case DW_EH_PE_sdata8:
658 p += 8;
659 break;
660 default:
661 return false;
662 }
663 return true;
664}
665
666static bool GetFdeTableOffsetInEhFrameHdr(const std::vector<uint8_t>& data,
Yabin Cui98791372017-12-18 14:37:54 -0800667 uint64_t* table_offset_in_eh_frame_hdr, bool is_elf64) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000668 const uint8_t* p = data.data();
669 const uint8_t* end = p + data.size();
670 if (p + 4 > end) {
671 return false;
672 }
673 uint8_t version = *p++;
674 if (version != 1) {
675 return false;
676 }
677 uint8_t eh_frame_ptr_encode = *p++;
678 uint8_t fde_count_encode = *p++;
679 uint8_t fde_table_encode = *p++;
680
681 if (fde_table_encode != (DW_EH_PE_datarel | DW_EH_PE_sdata4)) {
682 return false;
683 }
684
Yabin Cui98791372017-12-18 14:37:54 -0800685 if (!OmitEncodedValue(eh_frame_ptr_encode, p, is_elf64) ||
686 !OmitEncodedValue(fde_count_encode, p, is_elf64)) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000687 return false;
688 }
689 if (p >= end) {
690 return false;
691 }
692 *table_offset_in_eh_frame_hdr = p - data.data();
693 return true;
694}
695
Yabin Cui98791372017-12-18 14:37:54 -0800696static uint64_t ReadFromBuffer(const uint8_t*& p, size_t size) {
697 uint64_t result = 0;
698 int shift = 0;
699 while (size-- > 0) {
700 uint64_t tmp = *p++;
701 result |= tmp << shift;
702 shift += 8;
703 }
704 return result;
705}
706
707static uint64_t ReadSignValueFromBuffer(const uint8_t*& p, size_t size) {
708 uint64_t result = 0;
709 int shift = 0;
710 for (size_t i = 0; i < size; ++i) {
711 uint64_t tmp = *p++;
712 result |= tmp << shift;
713 shift += 8;
714 }
715 if (*(p - 1) & 0x80) {
716 result |= (-1ULL) << (size * 8);
717 }
718 return result;
719}
720
721static const char* ReadStrFromBuffer(const uint8_t*& p) {
722 const char* result = reinterpret_cast<const char*>(p);
723 p += strlen(result) + 1;
724 return result;
725}
726
727static int64_t ReadLEB128FromBuffer(const uint8_t*& p) {
728 int64_t result = 0;
729 int64_t tmp;
730 int shift = 0;
731 while (*p & 0x80) {
732 tmp = *p & 0x7f;
733 result |= tmp << shift;
734 shift += 7;
735 p++;
736 }
737 tmp = *p;
738 result |= tmp << shift;
739 if (*p & 0x40) {
740 result |= -((tmp & 0x40) << shift);
741 }
742 p++;
743 return result;
744}
745
746static uint64_t ReadULEB128FromBuffer(const uint8_t*& p) {
747 uint64_t result = 0;
748 uint64_t tmp;
749 int shift = 0;
750 while (*p & 0x80) {
751 tmp = *p & 0x7f;
752 result |= tmp << shift;
753 shift += 7;
754 p++;
755 }
756 tmp = *p;
757 result |= tmp << shift;
758 p++;
759 return result;
760}
761
762static uint64_t ReadEhEncoding(const uint8_t*& p, uint8_t encoding, bool is_elf64,
763 uint64_t section_vaddr, const uint8_t* section_begin) {
764 const uint8_t* init_addr = p;
765 uint64_t result = 0;
766 switch (encoding & 0x0f) {
767 case DW_EH_PE_absptr:
768 result = ReadFromBuffer(p, is_elf64 ? 8 : 4);
769 break;
770 case DW_EH_PE_omit:
771 result = 0;
772 break;
773 case DW_EH_PE_uleb128:
774 result = ReadULEB128FromBuffer(p);
775 break;
776 case DW_EH_PE_udata2:
777 result = ReadFromBuffer(p, 2);
778 break;
779 case DW_EH_PE_udata4:
780 result = ReadFromBuffer(p, 4);
781 break;
782 case DW_EH_PE_udata8:
783 result = ReadFromBuffer(p, 8);
784 break;
785 case DW_EH_PE_sleb128:
786 result = ReadLEB128FromBuffer(p);
787 break;
788 case DW_EH_PE_sdata2:
789 result = ReadSignValueFromBuffer(p, 2);
790 break;
791 case DW_EH_PE_sdata4:
792 result = ReadSignValueFromBuffer(p, 4);
793 break;
794 case DW_EH_PE_sdata8:
795 result = ReadSignValueFromBuffer(p, 8);
796 break;
797 }
798 switch (encoding & 0xf0) {
799 case DW_EH_PE_pcrel:
800 result += init_addr - section_begin + section_vaddr;
801 break;
802 case DW_EH_PE_datarel:
803 result += section_vaddr;
804 break;
805 }
806 return result;
807}
808
809static bool BuildEhFrameHdr(DebugFrameInfo* info, bool is_elf64) {
810 // For each fde entry, collect its (func_vaddr, fde_vaddr) pair.
811 std::vector<std::pair<uint64_t, uint64_t>> index_table;
812 // Map form cie_offset to fde encoding.
813 std::unordered_map<size_t, uint8_t> cie_map;
814 const uint8_t* eh_frame_begin = info->eh_frame.data.data();
815 const uint8_t* eh_frame_end = eh_frame_begin + info->eh_frame.data.size();
816 const uint8_t* p = eh_frame_begin;
817 uint64_t eh_frame_vaddr = info->eh_frame.vaddr;
818 while (p < eh_frame_end) {
819 const uint8_t* unit_begin = p;
820 uint64_t unit_len = ReadFromBuffer(p, 4);
821 size_t secbytes = 4;
822 if (unit_len == 0xffffffff) {
823 unit_len = ReadFromBuffer(p, 8);
824 secbytes = 8;
825 }
826 const uint8_t* unit_end = p + unit_len;
827 uint64_t cie_id = ReadFromBuffer(p, secbytes);
828 if (cie_id == 0) {
829 // This is a CIE.
830 // Read version
831 uint8_t version = *p++;
832 // Read augmentation
833 const char* augmentation = ReadStrFromBuffer(p);
834 if (version >= 4) {
835 // Read address size and segment size
836 p += 2;
837 }
838 // Read code alignment factor
839 ReadULEB128FromBuffer(p);
840 // Read data alignment factor
841 ReadLEB128FromBuffer(p);
842 // Read return address register
843 if (version == 1) {
844 p++;
845 } else {
846 ReadULEB128FromBuffer(p);
847 }
848 uint8_t fde_pointer_encoding = 0;
849 if (augmentation[0] == 'z') {
850 // Read augmentation length.
851 ReadULEB128FromBuffer(p);
852 for (int i = 1; augmentation[i] != '\0'; ++i) {
853 char c = augmentation[i];
854 if (c == 'R') {
855 fde_pointer_encoding = *p++;
856 } else if (c == 'P') {
857 // Read personality handler
858 uint8_t encoding = *p++;
859 OmitEncodedValue(encoding, p, is_elf64);
860 } else if (c == 'L') {
861 // Read lsda encoding
862 p++;
863 }
864 }
865 }
866 cie_map[unit_begin - eh_frame_begin] = fde_pointer_encoding;
867 } else {
868 // This is an FDE.
869 size_t cie_offset = p - secbytes - eh_frame_begin - cie_id;
870 auto it = cie_map.find(cie_offset);
871 if (it != cie_map.end()) {
872 uint8_t fde_pointer_encoding = it->second;
873 uint64_t initial_location =
874 ReadEhEncoding(p, fde_pointer_encoding, is_elf64, eh_frame_vaddr, eh_frame_begin);
875 uint64_t fde_vaddr = unit_begin - eh_frame_begin + eh_frame_vaddr;
876 index_table.push_back(std::make_pair(initial_location, fde_vaddr));
877 }
878 }
879 p = unit_end;
880 }
881 if (index_table.empty()) {
882 return false;
883 }
884 std::sort(index_table.begin(), index_table.end());
885 info->eh_frame.hdr_vaddr = 0;
886 info->eh_frame.hdr_data.resize(index_table.size() * 8);
887 uint32_t* ptr = reinterpret_cast<uint32_t*>(info->eh_frame.hdr_data.data());
888 for (auto& pair : index_table) {
889 *ptr++ = static_cast<uint32_t>(pair.first - info->eh_frame.hdr_vaddr);
890 *ptr++ = static_cast<uint32_t>(pair.second - info->eh_frame.hdr_vaddr);
891 }
892 info->eh_frame.fde_table_offset = 0;
893 info->eh_frame.min_func_vaddr = index_table[0].first;
894 return true;
895}
896
Yabin Cui9e402bb2015-09-22 04:46:57 +0000897template <class ELFT>
898DebugFrameInfo* ReadDebugFrameFromELFFile(const llvm::object::ELFFile<ELFT>* elf) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800899 DebugFrameInfo* result = new DebugFrameInfo;
Yabin Cui98791372017-12-18 14:37:54 -0800900 result->eh_frame.hdr_vaddr = 0;
Yabin Cui5d991bc2016-11-15 17:47:09 -0800901 result->text_end_vaddr = std::numeric_limits<uint64_t>::max();
902
Yabin Cui98791372017-12-18 14:37:54 -0800903 bool is_elf64 = (elf->getHeader()->getFileClass() == llvm::ELF::ELFCLASS64);
Yabin Cui9e402bb2015-09-22 04:46:57 +0000904 bool has_eh_frame_hdr = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000905 bool has_eh_frame = false;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000906
Stephen Hines19c30e92016-03-08 01:23:43 -0800907 for (auto it = elf->section_begin(); it != elf->section_end(); ++it) {
Yabin Cui9e402bb2015-09-22 04:46:57 +0000908 llvm::ErrorOr<llvm::StringRef> name = elf->getSectionName(&*it);
909 if (name) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800910 std::string s = name.get();
911 if (s == ".debug_frame") {
912 result->has_debug_frame = true;
913 } else if (s == ".gnu_debugdata") {
914 result->has_gnu_debugdata = true;
915 } else if (s == ".eh_frame_hdr") {
916 result->eh_frame.hdr_vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000917 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
918 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800919 result->eh_frame.hdr_data.insert(result->eh_frame.hdr_data.end(),
920 data->data(), data->data() + data->size());
921
922 uint64_t fde_table_offset;
Yabin Cui98791372017-12-18 14:37:54 -0800923 if (GetFdeTableOffsetInEhFrameHdr(result->eh_frame.hdr_data, &fde_table_offset, is_elf64)) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800924 result->eh_frame.fde_table_offset = fde_table_offset;
925 // Make sure we have at least one entry in fde_table.
926 if (fde_table_offset + 2 * sizeof(int32_t) <= data->size()) {
927 intptr_t eh_frame_hdr_vaddr = it->sh_addr;
928 int32_t sdata;
929 uint8_t* p = result->eh_frame.hdr_data.data() + fde_table_offset;
930 memcpy(&sdata, p, sizeof(sdata));
931 result->eh_frame.min_func_vaddr = eh_frame_hdr_vaddr + sdata;
932 has_eh_frame_hdr = true;
933 }
934 }
Yabin Cui9e402bb2015-09-22 04:46:57 +0000935 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800936 } else if (s == ".eh_frame") {
937 result->eh_frame.vaddr = it->sh_addr;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000938 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
939 if (data) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800940 result->eh_frame.data.insert(result->eh_frame.data.end(),
941 data->data(), data->data() + data->size());
942 has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000943 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800944 } else if (s == ".ARM.exidx") {
945 result->arm_exidx.exidx_vaddr = it->sh_addr;
946 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
947 if (data) {
948 size_t entry_count = data->size() / sizeof(ArmIdxEntry);
949 result->arm_exidx.exidx_data.resize(entry_count);
950 memcpy(result->arm_exidx.exidx_data.data(), data->data(),
951 entry_count * sizeof(ArmIdxEntry));
952 if (entry_count > 0u) {
953 // Change IdxEntry.func_offset into vaddr.
954 result->arm_exidx.func_vaddr_array.reserve(entry_count);
955 uint32_t vaddr = it->sh_addr;
956 for (auto& entry : result->arm_exidx.exidx_data) {
957 uint32_t func_offset = entry.func_offset + vaddr;
958 // Clear bit 31 for the prel31 offset.
959 // Arm sets bit 0 to mark it as thumb code, remove the flag.
960 result->arm_exidx.func_vaddr_array.push_back(
961 func_offset & 0x7ffffffe);
962 vaddr += 8;
963 }
964 result->has_arm_exidx = true;
965 }
966 }
967 } else if (s == ".ARM.extab") {
968 result->arm_exidx.extab_vaddr = it->sh_addr;
969 llvm::ErrorOr<llvm::ArrayRef<uint8_t>> data = elf->getSectionContents(&*it);
970 if (data) {
971 result->arm_exidx.extab_data.insert(result->arm_exidx.extab_data.end(),
972 data->data(), data->data() + data->size());
973 }
974 } else if (s == ".text") {
975 result->text_end_vaddr = it->sh_addr + it->sh_size;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000976 }
977 }
978 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800979
Yabin Cui98791372017-12-18 14:37:54 -0800980 if (has_eh_frame) {
981 if (!has_eh_frame_hdr) {
982 // Some libraries (like /vendor/lib64/egl/eglSubDriverAndroid.so) contain empty
983 // .eh_frame_hdr.
984 if (BuildEhFrameHdr(result, is_elf64)) {
985 has_eh_frame_hdr = true;
986 }
987 }
988 if (has_eh_frame_hdr) {
989 result->has_eh_frame = true;
990 }
991 }
Yabin Cui5d991bc2016-11-15 17:47:09 -0800992 if (has_eh_frame_hdr && has_eh_frame) {
993 result->has_eh_frame = true;
Yabin Cui9e402bb2015-09-22 04:46:57 +0000994 }
995
Yabin Cui5d991bc2016-11-15 17:47:09 -0800996 result->min_vaddr = std::numeric_limits<uint64_t>::max();
Stephen Hines19c30e92016-03-08 01:23:43 -0800997 for (auto it = elf->program_header_begin(); it != elf->program_header_end(); ++it) {
Yabin Cui5d991bc2016-11-15 17:47:09 -0800998 if ((it->p_type == llvm::ELF::PT_LOAD) && (it->p_flags & llvm::ELF::PF_X)) {
999 if (it->p_vaddr < result->min_vaddr) {
1000 result->min_vaddr = it->p_vaddr;
1001 }
1002 }
Yabin Cui9e402bb2015-09-22 04:46:57 +00001003 }
Yabin Cui5d991bc2016-11-15 17:47:09 -08001004 if (!result->has_eh_frame && !result->has_arm_exidx && !result->has_debug_frame &&
1005 !result->has_gnu_debugdata) {
1006 delete result;
1007 return nullptr;
1008 }
1009 return result;
Yabin Cui9e402bb2015-09-22 04:46:57 +00001010}
1011
Yabin Cui2ad59db2015-12-08 18:43:00 -08001012static bool IsValidElfPath(const std::string& filename) {
1013 static const char elf_magic[] = {0x7f, 'E', 'L', 'F'};
1014
1015 struct stat st;
1016 if (stat(filename.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
1017 return false;
1018 }
1019 FILE* fp = fopen(filename.c_str(), "reb");
1020 if (fp == nullptr) {
1021 return false;
1022 }
1023 char buf[4];
1024 if (fread(buf, 4, 1, fp) != 1) {
1025 fclose(fp);
1026 return false;
1027 }
1028 fclose(fp);
1029 return memcmp(buf, elf_magic, 4) == 0;
1030}
1031
Yabin Cuib791a762016-03-18 18:46:08 -07001032static bool IsValidApkPath(const std::string& apk_path) {
1033 static const char zip_preamble[] = {0x50, 0x4b, 0x03, 0x04};
1034 struct stat st;
1035 if (stat(apk_path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
1036 return false;
1037 }
1038 FILE* fp = fopen(apk_path.c_str(), "reb");
1039 if (fp == nullptr) {
1040 return false;
1041 }
1042 char buf[4];
1043 if (fread(buf, 4, 1, fp) != 1) {
1044 fclose(fp);
1045 return false;
1046 }
1047 fclose(fp);
1048 return memcmp(buf, zip_preamble, 4) == 0;
1049}
1050
1051class ScopedZiparchiveHandle {
1052 public:
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -07001053 explicit ScopedZiparchiveHandle(ZipArchiveHandle handle) : handle_(handle) {
Yabin Cuib791a762016-03-18 18:46:08 -07001054 }
1055
1056 ~ScopedZiparchiveHandle() {
1057 CloseArchive(handle_);
1058 }
1059
1060 private:
1061 ZipArchiveHandle handle_;
1062};
1063
1064llvm::object::OwningBinary<llvm::object::Binary> OpenEmbeddedElfFile(const std::string& filename) {
1065 llvm::object::OwningBinary<llvm::object::Binary> nothing;
1066 size_t pos = filename.find("!/");
1067 if (pos == std::string::npos) {
1068 return nothing;
1069 }
1070 std::string apk_file = filename.substr(0, pos);
1071 std::string elf_file = filename.substr(pos + 2);
1072 if (!IsValidApkPath(apk_file)) {
1073 BACK_LOGW("%s is not a valid apk file", apk_file.c_str());
1074 return nothing;
1075 }
1076 ZipArchiveHandle handle;
1077 int32_t ret_code = OpenArchive(apk_file.c_str(), &handle);
1078 if (ret_code != 0) {
1079 CloseArchive(handle);
1080 BACK_LOGW("failed to open archive %s: %s", apk_file.c_str(), ErrorCodeString(ret_code));
1081 return nothing;
1082 }
1083 ScopedZiparchiveHandle scoped_handle(handle);
1084 ZipEntry zentry;
1085 ret_code = FindEntry(handle, ZipString(elf_file.c_str()), &zentry);
1086 if (ret_code != 0) {
1087 BACK_LOGW("failed to find %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
1088 ErrorCodeString(ret_code));
1089 return nothing;
1090 }
1091 if (zentry.method != kCompressStored || zentry.compressed_length != zentry.uncompressed_length) {
1092 BACK_LOGW("%s is compressed in %s, which doesn't support running directly", elf_file.c_str(),
1093 apk_file.c_str());
1094 return nothing;
1095 }
1096 auto buffer_or_err = llvm::MemoryBuffer::getOpenFileSlice(GetFileDescriptor(handle), apk_file,
1097 zentry.uncompressed_length,
1098 zentry.offset);
1099 if (!buffer_or_err) {
1100 BACK_LOGW("failed to read %s in %s: %s", elf_file.c_str(), apk_file.c_str(),
1101 buffer_or_err.getError().message().c_str());
1102 return nothing;
1103 }
1104 auto binary_or_err = llvm::object::createBinary(buffer_or_err.get()->getMemBufferRef());
1105 if (!binary_or_err) {
1106 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 -07001107 llvm::toString(binary_or_err.takeError()).c_str());
Yabin Cuib791a762016-03-18 18:46:08 -07001108 return nothing;
1109 }
1110 return llvm::object::OwningBinary<llvm::object::Binary>(std::move(binary_or_err.get()),
1111 std::move(buffer_or_err.get()));
1112}
1113
Yabin Cui9e402bb2015-09-22 04:46:57 +00001114static DebugFrameInfo* ReadDebugFrameFromFile(const std::string& filename) {
Yabin Cuib791a762016-03-18 18:46:08 -07001115 llvm::object::OwningBinary<llvm::object::Binary> owning_binary;
1116 if (filename.find("!/") != std::string::npos) {
1117 owning_binary = OpenEmbeddedElfFile(filename);
1118 } else {
1119 if (!IsValidElfPath(filename)) {
1120 return nullptr;
1121 }
1122 auto binary_or_err = llvm::object::createBinary(llvm::StringRef(filename));
1123 if (!binary_or_err) {
1124 return nullptr;
1125 }
1126 owning_binary = std::move(binary_or_err.get());
Yabin Cui2ad59db2015-12-08 18:43:00 -08001127 }
Yabin Cuib791a762016-03-18 18:46:08 -07001128 llvm::object::Binary* binary = owning_binary.getBinary();
Yabin Cui9e402bb2015-09-22 04:46:57 +00001129 auto obj = llvm::dyn_cast<llvm::object::ObjectFile>(binary);
1130 if (obj == nullptr) {
1131 return nullptr;
1132 }
1133 if (auto elf = llvm::dyn_cast<llvm::object::ELF32LEObjectFile>(obj)) {
1134 return ReadDebugFrameFromELFFile(elf->getELFFile());
1135 }
1136 if (auto elf = llvm::dyn_cast<llvm::object::ELF64LEObjectFile>(obj)) {
1137 return ReadDebugFrameFromELFFile(elf->getELFFile());
1138 }
1139 return nullptr;
1140}
Christopher Ferris85402162016-01-25 16:17:48 -08001141
1142Backtrace* Backtrace::CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
1143 const backtrace_stackinfo_t& stack, bool cache_file) {
1144 return new BacktraceOffline(pid, tid, map, stack, cache_file);
1145}