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