1 /*
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 "OfflineUnwinder.h"
18 
19 #include <inttypes.h>
20 #include <sys/mman.h>
21 
22 #include <unordered_map>
23 
24 #include <android-base/logging.h>
25 #include <android-base/parseint.h>
26 #include <unwindstack/MachineArm.h>
27 #include <unwindstack/MachineArm64.h>
28 #include <unwindstack/MachineX86.h>
29 #include <unwindstack/MachineX86_64.h>
30 #include <unwindstack/Maps.h>
31 #include <unwindstack/RegsArm.h>
32 #include <unwindstack/RegsArm64.h>
33 #include <unwindstack/RegsX86.h>
34 #include <unwindstack/RegsX86_64.h>
35 #include <unwindstack/Unwinder.h>
36 #include <unwindstack/UserArm.h>
37 #include <unwindstack/UserArm64.h>
38 #include <unwindstack/UserX86.h>
39 #include <unwindstack/UserX86_64.h>
40 
41 #include "JITDebugReader.h"
42 #include "OfflineUnwinder_impl.h"
43 #include "environment.h"
44 #include "perf_regs.h"
45 #include "read_apk.h"
46 #include "thread_tree.h"
47 
48 namespace simpleperf {
49 
50 // unwindstack only builds on linux. So simpleperf redefines flags in unwindstack, to use them on
51 // darwin/windows. Use static_assert to make sure they are on the same page.
52 static_assert(map_flags::PROT_JIT_SYMFILE_MAP == unwindstack::MAPS_FLAGS_JIT_SYMFILE_MAP);
53 
54 #define CHECK_ERROR_CODE(error_code_name) \
55   static_assert(UnwindStackErrorCode::error_code_name == unwindstack::ErrorCode::error_code_name)
56 
57 CHECK_ERROR_CODE(ERROR_NONE);
58 CHECK_ERROR_CODE(ERROR_MEMORY_INVALID);
59 CHECK_ERROR_CODE(ERROR_UNWIND_INFO);
60 CHECK_ERROR_CODE(ERROR_UNSUPPORTED);
61 CHECK_ERROR_CODE(ERROR_INVALID_MAP);
62 CHECK_ERROR_CODE(ERROR_MAX_FRAMES_EXCEEDED);
63 CHECK_ERROR_CODE(ERROR_REPEATED_FRAME);
64 CHECK_ERROR_CODE(ERROR_INVALID_ELF);
65 CHECK_ERROR_CODE(ERROR_THREAD_DOES_NOT_EXIST);
66 CHECK_ERROR_CODE(ERROR_THREAD_TIMEOUT);
67 CHECK_ERROR_CODE(ERROR_SYSTEM_CALL);
68 CHECK_ERROR_CODE(ERROR_MAX);
69 
70 // Max frames seen so far is 463, in http://b/110923759.
71 static constexpr size_t MAX_UNWINDING_FRAMES = 512;
72 
GetBacktraceRegs(const RegSet & regs)73 unwindstack::Regs* OfflineUnwinderImpl::GetBacktraceRegs(const RegSet& regs) {
74   switch (regs.arch) {
75     case ARCH_ARM: {
76       unwindstack::arm_user_regs arm_user_regs;
77       memset(&arm_user_regs, 0, sizeof(arm_user_regs));
78       static_assert(static_cast<int>(unwindstack::ARM_REG_R0) == static_cast<int>(PERF_REG_ARM_R0),
79                     "");
80       static_assert(
81           static_cast<int>(unwindstack::ARM_REG_LAST) == static_cast<int>(PERF_REG_ARM_MAX), "");
82       for (size_t i = unwindstack::ARM_REG_R0; i < unwindstack::ARM_REG_LAST; ++i) {
83         arm_user_regs.regs[i] = static_cast<uint32_t>(regs.data[i]);
84       }
85       return unwindstack::RegsArm::Read(&arm_user_regs);
86     }
87     case ARCH_ARM64: {
88       unwindstack::arm64_user_regs arm64_user_regs;
89       memset(&arm64_user_regs, 0, sizeof(arm64_user_regs));
90       static_assert(
91           static_cast<int>(unwindstack::ARM64_REG_R0) == static_cast<int>(PERF_REG_ARM64_X0), "");
92       static_assert(
93           static_cast<int>(unwindstack::ARM64_REG_R30) == static_cast<int>(PERF_REG_ARM64_LR), "");
94       memcpy(&arm64_user_regs.regs[unwindstack::ARM64_REG_R0], &regs.data[PERF_REG_ARM64_X0],
95              sizeof(uint64_t) * (PERF_REG_ARM64_LR - PERF_REG_ARM64_X0 + 1));
96       arm64_user_regs.sp = regs.data[PERF_REG_ARM64_SP];
97       arm64_user_regs.pc = regs.data[PERF_REG_ARM64_PC];
98       auto regs =
99           static_cast<unwindstack::RegsArm64*>(unwindstack::RegsArm64::Read(&arm64_user_regs));
100       regs->SetPACMask(arm64_pac_mask_);
101       return regs;
102     }
103     case ARCH_X86_32: {
104       unwindstack::x86_user_regs x86_user_regs;
105       memset(&x86_user_regs, 0, sizeof(x86_user_regs));
106       x86_user_regs.eax = static_cast<uint32_t>(regs.data[PERF_REG_X86_AX]);
107       x86_user_regs.ebx = static_cast<uint32_t>(regs.data[PERF_REG_X86_BX]);
108       x86_user_regs.ecx = static_cast<uint32_t>(regs.data[PERF_REG_X86_CX]);
109       x86_user_regs.edx = static_cast<uint32_t>(regs.data[PERF_REG_X86_DX]);
110       x86_user_regs.ebp = static_cast<uint32_t>(regs.data[PERF_REG_X86_BP]);
111       x86_user_regs.edi = static_cast<uint32_t>(regs.data[PERF_REG_X86_DI]);
112       x86_user_regs.esi = static_cast<uint32_t>(regs.data[PERF_REG_X86_SI]);
113       x86_user_regs.esp = static_cast<uint32_t>(regs.data[PERF_REG_X86_SP]);
114       x86_user_regs.eip = static_cast<uint32_t>(regs.data[PERF_REG_X86_IP]);
115       return unwindstack::RegsX86::Read(&x86_user_regs);
116     }
117     case ARCH_X86_64: {
118       unwindstack::x86_64_user_regs x86_64_user_regs;
119       memset(&x86_64_user_regs, 0, sizeof(x86_64_user_regs));
120       x86_64_user_regs.rax = regs.data[PERF_REG_X86_AX];
121       x86_64_user_regs.rbx = regs.data[PERF_REG_X86_BX];
122       x86_64_user_regs.rcx = regs.data[PERF_REG_X86_CX];
123       x86_64_user_regs.rdx = regs.data[PERF_REG_X86_DX];
124       x86_64_user_regs.r8 = regs.data[PERF_REG_X86_R8];
125       x86_64_user_regs.r9 = regs.data[PERF_REG_X86_R9];
126       x86_64_user_regs.r10 = regs.data[PERF_REG_X86_R10];
127       x86_64_user_regs.r11 = regs.data[PERF_REG_X86_R11];
128       x86_64_user_regs.r12 = regs.data[PERF_REG_X86_R12];
129       x86_64_user_regs.r13 = regs.data[PERF_REG_X86_R13];
130       x86_64_user_regs.r14 = regs.data[PERF_REG_X86_R14];
131       x86_64_user_regs.r15 = regs.data[PERF_REG_X86_R15];
132       x86_64_user_regs.rdi = regs.data[PERF_REG_X86_DI];
133       x86_64_user_regs.rsi = regs.data[PERF_REG_X86_SI];
134       x86_64_user_regs.rbp = regs.data[PERF_REG_X86_BP];
135       x86_64_user_regs.rsp = regs.data[PERF_REG_X86_SP];
136       x86_64_user_regs.rip = regs.data[PERF_REG_X86_IP];
137       return unwindstack::RegsX86_64::Read(&x86_64_user_regs);
138     }
139     default:
140       return nullptr;
141   }
142 }
143 
CreateMapInfo(const MapEntry * entry)144 static unwindstack::MapInfo* CreateMapInfo(const MapEntry* entry) {
145   std::string name_holder;
146   const char* name = entry->dso->GetDebugFilePath().data();
147   uint64_t pgoff = entry->pgoff;
148   auto tuple = SplitUrlInApk(entry->dso->GetDebugFilePath());
149   if (std::get<0>(tuple)) {
150     // The unwinder does not understand the ! format, so change back to
151     // the previous format (apk, offset).
152     EmbeddedElf* elf = ApkInspector::FindElfInApkByName(std::get<1>(tuple), std::get<2>(tuple));
153     if (elf != nullptr) {
154       name = elf->filepath().data();
155       pgoff += elf->entry_offset();
156     }
157   } else if (entry->flags & map_flags::PROT_JIT_SYMFILE_MAP) {
158     // Remove location_in_file suffix, which isn't recognized by libunwindstack.
159     const std::string& path = entry->dso->GetDebugFilePath();
160     if (JITDebugReader::IsPathInJITSymFile(path)) {
161       size_t colon_pos = path.rfind(':');
162       CHECK_NE(colon_pos, std::string::npos);
163       name_holder = path.substr(0, colon_pos);
164       name = name_holder.data();
165     }
166   }
167   return new unwindstack::MapInfo(nullptr, nullptr, entry->start_addr, entry->get_end_addr(), pgoff,
168                                   PROT_READ | entry->flags, name);
169 }
170 
UpdateMaps(const MapSet & map_set)171 void UnwindMaps::UpdateMaps(const MapSet& map_set) {
172   if (version_ == map_set.version) {
173     return;
174   }
175   version_ = map_set.version;
176   size_t i = 0;
177   size_t old_size = entries_.size();
178   bool has_removed_entry = false;
179   for (auto it = map_set.maps.begin(); it != map_set.maps.end();) {
180     const MapEntry* entry = it->second;
181     if (i < old_size && entry == entries_[i]) {
182       i++;
183       ++it;
184     } else if (i == old_size || entry->start_addr <= entries_[i]->start_addr) {
185       // Add an entry.
186       entries_.push_back(entry);
187       maps_.emplace_back(CreateMapInfo(entry));
188       ++it;
189     } else {
190       // Remove an entry.
191       has_removed_entry = true;
192       entries_[i] = nullptr;
193       maps_[i++] = nullptr;
194     }
195   }
196   while (i < old_size) {
197     has_removed_entry = true;
198     entries_[i] = nullptr;
199     maps_[i++] = nullptr;
200   }
201 
202   if (has_removed_entry) {
203     entries_.resize(std::remove(entries_.begin(), entries_.end(), nullptr) - entries_.begin());
204     maps_.resize(std::remove(maps_.begin(), maps_.end(), std::unique_ptr<unwindstack::MapInfo>()) -
205                  maps_.begin());
206   }
207 
208   std::sort(entries_.begin(), entries_.end(),
209             [](const auto& e1, const auto& e2) { return e1->start_addr < e2->start_addr; });
210   // Use Sort() to sort maps_ and create prev_real_map links.
211   // prev_real_map is needed by libunwindstack to find the start of an embedded lib in an apk.
212   // See http://b/120981155.
213   Sort();
214 }
215 
CollectMetaInfo(std::unordered_map<std::string,std::string> * info_map)216 void OfflineUnwinder::CollectMetaInfo(std::unordered_map<std::string, std::string>* info_map
217                                       __attribute__((unused))) {
218 #if defined(__aarch64__)
219   // Find pac_mask for ARMv8.3-A Pointer Authentication by below steps:
220   // 1. Create a 64 bit value with every bit set, but clear bit 55. Because linux user space uses
221   //    TTBR0.
222   // 2. Use XPACLRI to clear auth code bits.
223   // 3. Flip every bit to get pac_mask, excluding bit 55.
224   // We can also use ptrace(PTRACE_GETREGSET, pid, NT_ARM_PAC_MASK). But it needs a tracee.
225   register uint64_t x30 __asm("x30") = ~(1ULL << 55);
226   // This is XPACLRI on ARMv8.3-A, and nop on prev ARMv8.3-A.
227   asm("hint 0x7" : "+r"(x30));
228   uint64_t pac_mask = ~x30 & ~(1ULL << 55);
229   if (pac_mask != 0) {
230     (*info_map)[META_KEY_ARM64_PAC_MASK] = android::base::StringPrintf("0x%" PRIx64, pac_mask);
231   }
232 #endif
233 }
234 
LoadMetaInfo(const std::unordered_map<std::string,std::string> & info_map)235 void OfflineUnwinderImpl::LoadMetaInfo(
236     const std::unordered_map<std::string, std::string>& info_map) {
237   if (auto it = info_map.find(META_KEY_ARM64_PAC_MASK); it != info_map.end()) {
238     CHECK(android::base::ParseUint(it->second, &arm64_pac_mask_));
239   }
240 }
241 
UnwindCallChain(const ThreadEntry & thread,const RegSet & regs,const char * stack,size_t stack_size,std::vector<uint64_t> * ips,std::vector<uint64_t> * sps)242 bool OfflineUnwinderImpl::UnwindCallChain(const ThreadEntry& thread, const RegSet& regs,
243                                           const char* stack, size_t stack_size,
244                                           std::vector<uint64_t>* ips, std::vector<uint64_t>* sps) {
245   uint64_t start_time;
246   if (collect_stat_) {
247     start_time = GetSystemClock();
248   }
249   is_callchain_broken_for_incomplete_jit_debug_info_ = false;
250   ips->clear();
251   sps->clear();
252   std::vector<uint64_t> result;
253   uint64_t sp_reg_value;
254   if (!regs.GetSpRegValue(&sp_reg_value)) {
255     LOG(ERROR) << "can't get sp reg value";
256     return false;
257   }
258   uint64_t stack_addr = sp_reg_value;
259 
260   UnwindMaps& cached_map = cached_maps_[thread.pid];
261   cached_map.UpdateMaps(*thread.maps);
262   std::unique_ptr<unwindstack::Regs> unwind_regs(GetBacktraceRegs(regs));
263   if (!unwind_regs) {
264     return false;
265   }
266   unwindstack::Unwinder unwinder(
267       MAX_UNWINDING_FRAMES, &cached_map, unwind_regs.get(),
268       unwindstack::Memory::CreateOfflineMemory(reinterpret_cast<const uint8_t*>(stack), stack_addr,
269                                                stack_addr + stack_size));
270   unwinder.SetResolveNames(false);
271   unwinder.Unwind();
272   size_t last_jit_method_frame = UINT_MAX;
273   for (auto& frame : unwinder.frames()) {
274     // Unwinding in arm architecture can return 0 pc address.
275 
276     // If frame.map.start == 0, this frame doesn't hit any map, it could be:
277     // 1. In an executable map not backed by a file. Note that RecordCommand::ShouldOmitRecord()
278     //    may omit maps only exist memory.
279     // 2. An incorrectly unwound frame. Like caused by invalid stack data, as in
280     //    SampleRecord::GetValidStackSize(). Or caused by incomplete JIT debug info.
281     // We want to remove this frame and callchains following it in either case.
282     if (frame.pc == 0 || frame.map_start == 0) {
283       is_callchain_broken_for_incomplete_jit_debug_info_ = true;
284       break;
285     }
286     if (frame.map_flags & unwindstack::MAPS_FLAGS_JIT_SYMFILE_MAP) {
287       last_jit_method_frame = ips->size();
288     }
289     ips->push_back(frame.pc);
290     sps->push_back(frame.sp);
291   }
292   // If the unwound frames stop near to a JITed method, it may be caused by incomplete JIT debug
293   // info.
294   if (last_jit_method_frame != UINT_MAX && last_jit_method_frame + 3 > ips->size()) {
295     is_callchain_broken_for_incomplete_jit_debug_info_ = true;
296   }
297 
298   uint64_t ip_reg_value;
299   if (!regs.GetIpRegValue(&ip_reg_value)) {
300     LOG(ERROR) << "can't get ip reg value";
301     return false;
302   }
303   if (ips->empty()) {
304     ips->push_back(ip_reg_value);
305     sps->push_back(sp_reg_value);
306   } else {
307     // Check if the unwinder returns ip reg value as the first ip address in callstack.
308     CHECK_EQ((*ips)[0], ip_reg_value);
309   }
310   if (collect_stat_) {
311     unwinding_result_.used_time = GetSystemClock() - start_time;
312     unwinding_result_.error_code = unwinder.LastErrorCode();
313     unwinding_result_.error_addr = unwinder.LastErrorAddress();
314     unwinding_result_.stack_start = stack_addr;
315     unwinding_result_.stack_end = stack_addr + stack_size;
316   }
317   return true;
318 }
319 
Create(bool collect_stat)320 std::unique_ptr<OfflineUnwinder> OfflineUnwinder::Create(bool collect_stat) {
321   return std::unique_ptr<OfflineUnwinder>(new OfflineUnwinderImpl(collect_stat));
322 }
323 
324 }  // namespace simpleperf
325