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 <elf.h>
19 #include <inttypes.h>
20 #include <stdint.h>
21 #include <string.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 
25 #include <algorithm>
26 
27 #include <android-base/stringprintf.h>
28 #include <android-base/strings.h>
29 
30 #include <unwindstack/Elf.h>
31 #include <unwindstack/JitDebug.h>
32 #include <unwindstack/MapInfo.h>
33 #include <unwindstack/Maps.h>
34 #include <unwindstack/Memory.h>
35 #include <unwindstack/Unwinder.h>
36 
37 #include <unwindstack/DexFiles.h>
38 
39 // Use the demangler from libc++.
40 extern "C" char* __cxa_demangle(const char*, char*, size_t*, int* status);
41 
42 namespace unwindstack {
43 
44 // Inject extra 'virtual' frame that represents the dex pc data.
45 // The dex pc is a magic register defined in the Mterp interpreter,
46 // and thus it will be restored/observed in the frame after it.
47 // Adding the dex frame first here will create something like:
48 //   #7 pc 0015fa20 core.vdex   java.util.Arrays.binarySearch+8
49 //   #8 pc 006b1ba1 libartd.so  ExecuteMterpImpl+14625
50 //   #9 pc 0039a1ef libartd.so  art::interpreter::Execute+719
FillInDexFrame()51 void Unwinder::FillInDexFrame() {
52   size_t frame_num = frames_.size();
53   frames_.resize(frame_num + 1);
54   FrameData* frame = &frames_.at(frame_num);
55   frame->num = frame_num;
56 
57   uint64_t dex_pc = regs_->dex_pc();
58   frame->pc = dex_pc;
59   frame->sp = regs_->sp();
60 
61   MapInfo* info = maps_->Find(dex_pc);
62   if (info != nullptr) {
63     frame->map_start = info->start;
64     frame->map_end = info->end;
65     // Since this is a dex file frame, the elf_start_offset is not set
66     // by any of the normal code paths. Use the offset of the map since
67     // that matches the actual offset.
68     frame->map_elf_start_offset = info->offset;
69     frame->map_exact_offset = info->offset;
70     frame->map_load_bias = info->load_bias;
71     frame->map_flags = info->flags;
72     if (resolve_names_) {
73       frame->map_name = info->name;
74     }
75     frame->rel_pc = dex_pc - info->start;
76   } else {
77     frame->rel_pc = dex_pc;
78     return;
79   }
80 
81   if (!resolve_names_) {
82     return;
83   }
84 
85 #if defined(DEXFILE_SUPPORT)
86   if (dex_files_ == nullptr) {
87     return;
88   }
89 
90   dex_files_->GetMethodInformation(maps_, info, dex_pc, &frame->function_name,
91                                    &frame->function_offset);
92 #endif
93 }
94 
FillInFrame(MapInfo * map_info,Elf * elf,uint64_t rel_pc,uint64_t pc_adjustment)95 FrameData* Unwinder::FillInFrame(MapInfo* map_info, Elf* elf, uint64_t rel_pc,
96                                  uint64_t pc_adjustment) {
97   size_t frame_num = frames_.size();
98   frames_.resize(frame_num + 1);
99   FrameData* frame = &frames_.at(frame_num);
100   frame->num = frame_num;
101   frame->sp = regs_->sp();
102   frame->rel_pc = rel_pc - pc_adjustment;
103   frame->pc = regs_->pc() - pc_adjustment;
104 
105   if (map_info == nullptr) {
106     // Nothing else to update.
107     return nullptr;
108   }
109 
110   if (resolve_names_) {
111     frame->map_name = map_info->name;
112     if (embedded_soname_ && map_info->elf_start_offset != 0 && !frame->map_name.empty()) {
113       std::string soname = elf->GetSoname();
114       if (!soname.empty()) {
115         frame->map_name += '!' + soname;
116       }
117     }
118   }
119   frame->map_elf_start_offset = map_info->elf_start_offset;
120   frame->map_exact_offset = map_info->offset;
121   frame->map_start = map_info->start;
122   frame->map_end = map_info->end;
123   frame->map_flags = map_info->flags;
124   frame->map_load_bias = elf->GetLoadBias();
125   return frame;
126 }
127 
ShouldStop(const std::vector<std::string> * map_suffixes_to_ignore,std::string & map_name)128 static bool ShouldStop(const std::vector<std::string>* map_suffixes_to_ignore,
129                        std::string& map_name) {
130   if (map_suffixes_to_ignore == nullptr) {
131     return false;
132   }
133   auto pos = map_name.find_last_of('.');
134   if (pos == std::string::npos) {
135     return false;
136   }
137 
138   return std::find(map_suffixes_to_ignore->begin(), map_suffixes_to_ignore->end(),
139                    map_name.substr(pos + 1)) != map_suffixes_to_ignore->end();
140 }
141 
Unwind(const std::vector<std::string> * initial_map_names_to_skip,const std::vector<std::string> * map_suffixes_to_ignore)142 void Unwinder::Unwind(const std::vector<std::string>* initial_map_names_to_skip,
143                       const std::vector<std::string>* map_suffixes_to_ignore) {
144   frames_.clear();
145   last_error_.code = ERROR_NONE;
146   last_error_.address = 0;
147   elf_from_memory_not_file_ = false;
148 
149   ArchEnum arch = regs_->Arch();
150 
151   bool return_address_attempt = false;
152   bool adjust_pc = false;
153   for (; frames_.size() < max_frames_;) {
154     uint64_t cur_pc = regs_->pc();
155     uint64_t cur_sp = regs_->sp();
156 
157     MapInfo* map_info = maps_->Find(regs_->pc());
158     uint64_t pc_adjustment = 0;
159     uint64_t step_pc;
160     uint64_t rel_pc;
161     Elf* elf;
162     if (map_info == nullptr) {
163       step_pc = regs_->pc();
164       rel_pc = step_pc;
165       last_error_.code = ERROR_INVALID_MAP;
166     } else {
167       if (ShouldStop(map_suffixes_to_ignore, map_info->name)) {
168         break;
169       }
170       elf = map_info->GetElf(process_memory_, arch);
171       // If this elf is memory backed, and there is a valid file, then set
172       // an indicator that we couldn't open the file.
173       if (!elf_from_memory_not_file_ && map_info->memory_backed_elf && !map_info->name.empty() &&
174           map_info->name[0] != '[' && !android::base::StartsWith(map_info->name, "/memfd:")) {
175         elf_from_memory_not_file_ = true;
176       }
177       step_pc = regs_->pc();
178       rel_pc = elf->GetRelPc(step_pc, map_info);
179       // Everyone except elf data in gdb jit debug maps uses the relative pc.
180       if (!(map_info->flags & MAPS_FLAGS_JIT_SYMFILE_MAP)) {
181         step_pc = rel_pc;
182       }
183       if (adjust_pc) {
184         pc_adjustment = GetPcAdjustment(rel_pc, elf, arch);
185       } else {
186         pc_adjustment = 0;
187       }
188       step_pc -= pc_adjustment;
189 
190       // If the pc is in an invalid elf file, try and get an Elf object
191       // using the jit debug information.
192       if (!elf->valid() && jit_debug_ != nullptr) {
193         uint64_t adjusted_jit_pc = regs_->pc() - pc_adjustment;
194         Elf* jit_elf = jit_debug_->GetElf(maps_, adjusted_jit_pc);
195         if (jit_elf != nullptr) {
196           // The jit debug information requires a non relative adjusted pc.
197           step_pc = adjusted_jit_pc;
198           elf = jit_elf;
199         }
200       }
201     }
202 
203     FrameData* frame = nullptr;
204     if (map_info == nullptr || initial_map_names_to_skip == nullptr ||
205         std::find(initial_map_names_to_skip->begin(), initial_map_names_to_skip->end(),
206                   basename(map_info->name.c_str())) == initial_map_names_to_skip->end()) {
207       if (regs_->dex_pc() != 0) {
208         // Add a frame to represent the dex file.
209         FillInDexFrame();
210         // Clear the dex pc so that we don't repeat this frame later.
211         regs_->set_dex_pc(0);
212 
213         // Make sure there is enough room for the real frame.
214         if (frames_.size() == max_frames_) {
215           last_error_.code = ERROR_MAX_FRAMES_EXCEEDED;
216           break;
217         }
218       }
219 
220       frame = FillInFrame(map_info, elf, rel_pc, pc_adjustment);
221 
222       // Once a frame is added, stop skipping frames.
223       initial_map_names_to_skip = nullptr;
224     }
225     adjust_pc = true;
226 
227     bool stepped = false;
228     bool in_device_map = false;
229     bool finished = false;
230     if (map_info != nullptr) {
231       if (map_info->flags & MAPS_FLAGS_DEVICE_MAP) {
232         // Do not stop here, fall through in case we are
233         // in the speculative unwind path and need to remove
234         // some of the speculative frames.
235         in_device_map = true;
236       } else {
237         MapInfo* sp_info = maps_->Find(regs_->sp());
238         if (sp_info != nullptr && sp_info->flags & MAPS_FLAGS_DEVICE_MAP) {
239           // Do not stop here, fall through in case we are
240           // in the speculative unwind path and need to remove
241           // some of the speculative frames.
242           in_device_map = true;
243         } else {
244           if (elf->StepIfSignalHandler(rel_pc, regs_, process_memory_.get())) {
245             stepped = true;
246             if (frame != nullptr) {
247               // Need to adjust the relative pc because the signal handler
248               // pc should not be adjusted.
249               frame->rel_pc = rel_pc;
250               frame->pc += pc_adjustment;
251               step_pc = rel_pc;
252             }
253           } else if (elf->Step(step_pc, regs_, process_memory_.get(), &finished)) {
254             stepped = true;
255           }
256           elf->GetLastError(&last_error_);
257         }
258       }
259     }
260 
261     if (frame != nullptr) {
262       if (!resolve_names_ ||
263           !elf->GetFunctionName(step_pc, &frame->function_name, &frame->function_offset)) {
264         frame->function_name = "";
265         frame->function_offset = 0;
266       }
267     }
268 
269     if (finished) {
270       break;
271     }
272 
273     if (!stepped) {
274       if (return_address_attempt) {
275         // Only remove the speculative frame if there are more than two frames
276         // or the pc in the first frame is in a valid map.
277         // This allows for a case where the code jumps into the middle of
278         // nowhere, but there is no other unwind information after that.
279         if (frames_.size() > 2 || (frames_.size() > 0 && maps_->Find(frames_[0].pc) != nullptr)) {
280           // Remove the speculative frame.
281           frames_.pop_back();
282         }
283         break;
284       } else if (in_device_map) {
285         // Do not attempt any other unwinding, pc or sp is in a device
286         // map.
287         break;
288       } else {
289         // Steping didn't work, try this secondary method.
290         if (!regs_->SetPcFromReturnAddress(process_memory_.get())) {
291           break;
292         }
293         return_address_attempt = true;
294       }
295     } else {
296       return_address_attempt = false;
297       if (max_frames_ == frames_.size()) {
298         last_error_.code = ERROR_MAX_FRAMES_EXCEEDED;
299       }
300     }
301 
302     // If the pc and sp didn't change, then consider everything stopped.
303     if (cur_pc == regs_->pc() && cur_sp == regs_->sp()) {
304       last_error_.code = ERROR_REPEATED_FRAME;
305       break;
306     }
307   }
308 }
309 
FormatFrame(const FrameData & frame) const310 std::string Unwinder::FormatFrame(const FrameData& frame) const {
311   std::string data;
312   if (regs_->Is32Bit()) {
313     data += android::base::StringPrintf("  #%02zu pc %08" PRIx64, frame.num, frame.rel_pc);
314   } else {
315     data += android::base::StringPrintf("  #%02zu pc %016" PRIx64, frame.num, frame.rel_pc);
316   }
317 
318   if (frame.map_start == frame.map_end) {
319     // No valid map associated with this frame.
320     data += "  <unknown>";
321   } else if (!frame.map_name.empty()) {
322     data += "  " + frame.map_name;
323   } else {
324     data += android::base::StringPrintf("  <anonymous:%" PRIx64 ">", frame.map_start);
325   }
326 
327   if (frame.map_elf_start_offset != 0) {
328     data += android::base::StringPrintf(" (offset 0x%" PRIx64 ")", frame.map_elf_start_offset);
329   }
330 
331   if (!frame.function_name.empty()) {
332     char* demangled_name = __cxa_demangle(frame.function_name.c_str(), nullptr, nullptr, nullptr);
333     if (demangled_name == nullptr) {
334       data += " (" + frame.function_name;
335     } else {
336       data += " (";
337       data += demangled_name;
338       free(demangled_name);
339     }
340     if (frame.function_offset != 0) {
341       data += android::base::StringPrintf("+%" PRId64, frame.function_offset);
342     }
343     data += ')';
344   }
345 
346   MapInfo* map_info = maps_->Find(frame.map_start);
347   if (map_info != nullptr && display_build_id_) {
348     std::string build_id = map_info->GetPrintableBuildID();
349     if (!build_id.empty()) {
350       data += " (BuildId: " + build_id + ')';
351     }
352   }
353   return data;
354 }
355 
FormatFrame(size_t frame_num) const356 std::string Unwinder::FormatFrame(size_t frame_num) const {
357   if (frame_num >= frames_.size()) {
358     return "";
359   }
360   return FormatFrame(frames_[frame_num]);
361 }
362 
SetJitDebug(JitDebug * jit_debug,ArchEnum arch)363 void Unwinder::SetJitDebug(JitDebug* jit_debug, ArchEnum arch) {
364   jit_debug->SetArch(arch);
365   jit_debug_ = jit_debug;
366 }
367 
SetDexFiles(DexFiles * dex_files,ArchEnum arch)368 void Unwinder::SetDexFiles(DexFiles* dex_files, ArchEnum arch) {
369   dex_files->SetArch(arch);
370   dex_files_ = dex_files;
371 }
372 
Init(ArchEnum arch)373 bool UnwinderFromPid::Init(ArchEnum arch) {
374   if (pid_ == getpid()) {
375     maps_ptr_.reset(new LocalMaps());
376   } else {
377     maps_ptr_.reset(new RemoteMaps(pid_));
378   }
379   if (!maps_ptr_->Parse()) {
380     return false;
381   }
382   maps_ = maps_ptr_.get();
383 
384   process_memory_ = Memory::CreateProcessMemoryCached(pid_);
385 
386   jit_debug_ptr_.reset(new JitDebug(process_memory_));
387   jit_debug_ = jit_debug_ptr_.get();
388   SetJitDebug(jit_debug_, arch);
389 #if defined(DEXFILE_SUPPORT)
390   dex_files_ptr_.reset(new DexFiles(process_memory_));
391   dex_files_ = dex_files_ptr_.get();
392   SetDexFiles(dex_files_, arch);
393 #endif
394 
395   return true;
396 }
397 
BuildFrameFromPcOnly(uint64_t pc)398 FrameData Unwinder::BuildFrameFromPcOnly(uint64_t pc) {
399   FrameData frame;
400 
401   Maps* maps = GetMaps();
402   MapInfo* map_info = maps->Find(pc);
403   if (!map_info) {
404     frame.rel_pc = pc;
405     return frame;
406   }
407 
408   ArchEnum arch = Regs::CurrentArch();
409   Elf* elf = map_info->GetElf(GetProcessMemory(), arch);
410 
411   uint64_t relative_pc = elf->GetRelPc(pc, map_info);
412 
413   uint64_t pc_adjustment = GetPcAdjustment(relative_pc, elf, arch);
414   relative_pc -= pc_adjustment;
415   // The debug PC may be different if the PC comes from the JIT.
416   uint64_t debug_pc = relative_pc;
417 
418   // If we don't have a valid ELF file, check the JIT.
419   if (!elf->valid()) {
420     JitDebug jit_debug(GetProcessMemory());
421     uint64_t jit_pc = pc - pc_adjustment;
422     Elf* jit_elf = jit_debug.GetElf(maps, jit_pc);
423     if (jit_elf != nullptr) {
424       debug_pc = jit_pc;
425       elf = jit_elf;
426     }
427   }
428 
429   // Copy all the things we need into the frame for symbolization.
430   frame.rel_pc = relative_pc;
431   frame.pc = pc - pc_adjustment;
432   frame.map_name = map_info->name;
433   frame.map_elf_start_offset = map_info->elf_start_offset;
434   frame.map_exact_offset = map_info->offset;
435   frame.map_start = map_info->start;
436   frame.map_end = map_info->end;
437   frame.map_flags = map_info->flags;
438   frame.map_load_bias = elf->GetLoadBias();
439 
440   if (!resolve_names_ ||
441       !elf->GetFunctionName(relative_pc, &frame.function_name, &frame.function_offset)) {
442     frame.function_name = "";
443     frame.function_offset = 0;
444   }
445   return frame;
446 }
447 
448 }  // namespace unwindstack
449