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