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