1 /*
2  * Copyright (C) 2017 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 #define _GNU_SOURCE 1
18 #include <stdint.h>
19 #include <stdlib.h>
20 #include <string.h>
21 
22 #include <memory>
23 #include <set>
24 #include <string>
25 
26 #include <backtrace/Backtrace.h>
27 #include <unwindstack/Elf.h>
28 #include <unwindstack/MapInfo.h>
29 #include <unwindstack/Maps.h>
30 #include <unwindstack/Memory.h>
31 #include <unwindstack/Regs.h>
32 #include <unwindstack/RegsGetLocal.h>
33 
34 #if !defined(NO_LIBDEXFILE_SUPPORT)
35 #include <unwindstack/DexFiles.h>
36 #endif
37 #include <unwindstack/Unwinder.h>
38 
39 #include "BacktraceLog.h"
40 #include "UnwindStack.h"
41 #include "UnwindStackMap.h"
42 
43 extern "C" char* __cxa_demangle(const char*, char*, size_t*, int*);
44 
Unwind(unwindstack::Regs * regs,BacktraceMap * back_map,std::vector<backtrace_frame_data_t> * frames,size_t num_ignore_frames,std::vector<std::string> * skip_names,BacktraceUnwindError * error)45 bool Backtrace::Unwind(unwindstack::Regs* regs, BacktraceMap* back_map,
46                        std::vector<backtrace_frame_data_t>* frames, size_t num_ignore_frames,
47                        std::vector<std::string>* skip_names, BacktraceUnwindError* error) {
48   UnwindStackMap* stack_map = reinterpret_cast<UnwindStackMap*>(back_map);
49   auto process_memory = stack_map->process_memory();
50   unwindstack::Unwinder unwinder(MAX_BACKTRACE_FRAMES + num_ignore_frames, stack_map->stack_maps(),
51                                  regs, stack_map->process_memory());
52   unwinder.SetResolveNames(stack_map->ResolveNames());
53   stack_map->SetArch(regs->Arch());
54   if (stack_map->GetJitDebug() != nullptr) {
55     unwinder.SetJitDebug(stack_map->GetJitDebug());
56   }
57 #if !defined(NO_LIBDEXFILE_SUPPORT)
58   if (stack_map->GetDexFiles() != nullptr) {
59     unwinder.SetDexFiles(stack_map->GetDexFiles());
60   }
61 #endif
62   unwinder.Unwind(skip_names, &stack_map->GetSuffixesToIgnore());
63   if (error != nullptr) {
64     switch (unwinder.LastErrorCode()) {
65       case unwindstack::ERROR_NONE:
66         error->error_code = BACKTRACE_UNWIND_NO_ERROR;
67         break;
68 
69       case unwindstack::ERROR_MEMORY_INVALID:
70         error->error_code = BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED;
71         error->error_info.addr = unwinder.LastErrorAddress();
72         break;
73 
74       case unwindstack::ERROR_UNWIND_INFO:
75         error->error_code = BACKTRACE_UNWIND_ERROR_UNWIND_INFO;
76         break;
77 
78       case unwindstack::ERROR_UNSUPPORTED:
79         error->error_code = BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION;
80         break;
81 
82       case unwindstack::ERROR_INVALID_MAP:
83         error->error_code = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
84         break;
85 
86       case unwindstack::ERROR_MAX_FRAMES_EXCEEDED:
87         error->error_code = BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT;
88         break;
89 
90       case unwindstack::ERROR_REPEATED_FRAME:
91         error->error_code = BACKTRACE_UNWIND_ERROR_REPEATED_FRAME;
92         break;
93 
94       case unwindstack::ERROR_INVALID_ELF:
95         error->error_code = BACKTRACE_UNWIND_ERROR_INVALID_ELF;
96         break;
97 
98       case unwindstack::ERROR_SYSTEM_CALL:
99         error->error_code = BACKTRACE_UNWIND_ERROR_INTERNAL;
100         break;
101 
102       case unwindstack::ERROR_THREAD_DOES_NOT_EXIST:
103         error->error_code = BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST;
104         break;
105 
106       case unwindstack::ERROR_THREAD_TIMEOUT:
107         error->error_code = BACKTRACE_UNWIND_ERROR_THREAD_TIMEOUT;
108         break;
109     }
110   }
111 
112   if (num_ignore_frames >= unwinder.NumFrames()) {
113     frames->resize(0);
114     return true;
115   }
116 
117   auto unwinder_frames = unwinder.frames();
118   frames->resize(unwinder.NumFrames() - num_ignore_frames);
119   size_t cur_frame = 0;
120   for (size_t i = num_ignore_frames; i < unwinder.NumFrames(); i++) {
121     auto frame = &unwinder_frames[i];
122 
123     backtrace_frame_data_t* back_frame = &frames->at(cur_frame);
124 
125     back_frame->num = cur_frame++;
126 
127     back_frame->rel_pc = frame->rel_pc;
128     back_frame->pc = frame->pc;
129     back_frame->sp = frame->sp;
130 
131     char* demangled_name = __cxa_demangle(frame->function_name.c_str(), nullptr, nullptr, nullptr);
132     if (demangled_name != nullptr) {
133       back_frame->func_name = demangled_name;
134       free(demangled_name);
135     } else {
136       back_frame->func_name = frame->function_name;
137     }
138     back_frame->func_offset = frame->function_offset;
139 
140     back_frame->map.name = frame->map_name;
141     back_frame->map.start = frame->map_start;
142     back_frame->map.end = frame->map_end;
143     back_frame->map.offset = frame->map_elf_start_offset;
144     back_frame->map.load_bias = frame->map_load_bias;
145     back_frame->map.flags = frame->map_flags;
146   }
147 
148   return true;
149 }
150 
UnwindStackCurrent(pid_t pid,pid_t tid,BacktraceMap * map)151 UnwindStackCurrent::UnwindStackCurrent(pid_t pid, pid_t tid, BacktraceMap* map)
152     : BacktraceCurrent(pid, tid, map) {}
153 
GetFunctionNameRaw(uint64_t pc,uint64_t * offset)154 std::string UnwindStackCurrent::GetFunctionNameRaw(uint64_t pc, uint64_t* offset) {
155   return GetMap()->GetFunctionName(pc, offset);
156 }
157 
UnwindFromContext(size_t num_ignore_frames,void * ucontext)158 bool UnwindStackCurrent::UnwindFromContext(size_t num_ignore_frames, void* ucontext) {
159   std::unique_ptr<unwindstack::Regs> regs;
160   if (ucontext == nullptr) {
161     regs.reset(unwindstack::Regs::CreateFromLocal());
162     // Fill in the registers from this function. Do it here to avoid
163     // one extra function call appearing in the unwind.
164     unwindstack::RegsGetLocal(regs.get());
165   } else {
166     regs.reset(unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(), ucontext));
167   }
168 
169   std::vector<std::string> skip_names{"libunwindstack.so", "libbacktrace.so"};
170   if (!skip_frames_) {
171     skip_names.clear();
172   }
173   return Backtrace::Unwind(regs.get(), GetMap(), &frames_, num_ignore_frames, &skip_names, &error_);
174 }
175 
UnwindStackPtrace(pid_t pid,pid_t tid,BacktraceMap * map)176 UnwindStackPtrace::UnwindStackPtrace(pid_t pid, pid_t tid, BacktraceMap* map)
177     : BacktracePtrace(pid, tid, map), memory_(unwindstack::Memory::CreateProcessMemory(pid)) {}
178 
GetFunctionNameRaw(uint64_t pc,uint64_t * offset)179 std::string UnwindStackPtrace::GetFunctionNameRaw(uint64_t pc, uint64_t* offset) {
180   return GetMap()->GetFunctionName(pc, offset);
181 }
182 
Unwind(size_t num_ignore_frames,void * context)183 bool UnwindStackPtrace::Unwind(size_t num_ignore_frames, void* context) {
184   std::unique_ptr<unwindstack::Regs> regs;
185   if (context == nullptr) {
186     regs.reset(unwindstack::Regs::RemoteGet(Tid()));
187   } else {
188     regs.reset(unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(), context));
189   }
190 
191   return Backtrace::Unwind(regs.get(), GetMap(), &frames_, num_ignore_frames, nullptr, &error_);
192 }
193 
Read(uint64_t addr,uint8_t * buffer,size_t bytes)194 size_t UnwindStackPtrace::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
195 #if defined(__aarch64__)
196   // Tagged pointer after Android R would lead top byte to have random values
197   // https://source.android.com/devices/tech/debug/tagged-pointers
198   addr &= (1ULL << 56) - 1;
199 #endif
200   return memory_->Read(addr, buffer, bytes);
201 }
202