• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 #include "stack.h"
18 #include <limits>
19 
20 #include "android-base/stringprintf.h"
21 
22 #include "arch/context.h"
23 #include "art_method-inl.h"
24 #include "base/callee_save_type.h"
25 #include "base/enums.h"
26 #include "base/hex_dump.h"
27 #include "dex/dex_file_types.h"
28 #include "entrypoints/entrypoint_utils-inl.h"
29 #include "entrypoints/quick/callee_save_frame.h"
30 #include "entrypoints/runtime_asm_entrypoints.h"
31 #include "gc/space/image_space.h"
32 #include "gc/space/space-inl.h"
33 #include "interpreter/mterp/nterp.h"
34 #include "interpreter/shadow_frame-inl.h"
35 #include "jit/jit.h"
36 #include "jit/jit_code_cache.h"
37 #include "linear_alloc.h"
38 #include "managed_stack.h"
39 #include "mirror/class-inl.h"
40 #include "mirror/object-inl.h"
41 #include "mirror/object_array-inl.h"
42 #include "nterp_helpers.h"
43 #include "oat_quick_method_header.h"
44 #include "obj_ptr-inl.h"
45 #include "quick/quick_method_frame_info.h"
46 #include "runtime.h"
47 #include "thread.h"
48 #include "thread_list.h"
49 
50 namespace art {
51 
52 using android::base::StringPrintf;
53 
54 static constexpr bool kDebugStackWalk = false;
55 
StackVisitor(Thread * thread,Context * context,StackWalkKind walk_kind,bool check_suspended)56 StackVisitor::StackVisitor(Thread* thread,
57                            Context* context,
58                            StackWalkKind walk_kind,
59                            bool check_suspended)
60     : StackVisitor(thread, context, walk_kind, 0, check_suspended) {}
61 
StackVisitor(Thread * thread,Context * context,StackWalkKind walk_kind,size_t num_frames,bool check_suspended)62 StackVisitor::StackVisitor(Thread* thread,
63                            Context* context,
64                            StackWalkKind walk_kind,
65                            size_t num_frames,
66                            bool check_suspended)
67     : thread_(thread),
68       walk_kind_(walk_kind),
69       cur_shadow_frame_(nullptr),
70       cur_quick_frame_(nullptr),
71       cur_quick_frame_pc_(0),
72       cur_oat_quick_method_header_(nullptr),
73       num_frames_(num_frames),
74       cur_depth_(0),
75       cur_inline_info_(nullptr, CodeInfo()),
76       cur_stack_map_(0, StackMap()),
77       context_(context),
78       check_suspended_(check_suspended) {
79   if (check_suspended_) {
80     DCHECK(thread == Thread::Current() || thread->IsSuspended()) << *thread;
81   }
82 }
83 
GetCurrentInlineInfo() const84 CodeInfo* StackVisitor::GetCurrentInlineInfo() const {
85   DCHECK(!(*cur_quick_frame_)->IsNative());
86   const OatQuickMethodHeader* header = GetCurrentOatQuickMethodHeader();
87   if (cur_inline_info_.first != header) {
88     cur_inline_info_ = std::make_pair(header, CodeInfo::DecodeInlineInfoOnly(header));
89   }
90   return &cur_inline_info_.second;
91 }
92 
GetCurrentStackMap() const93 StackMap* StackVisitor::GetCurrentStackMap() const {
94   DCHECK(!(*cur_quick_frame_)->IsNative());
95   const OatQuickMethodHeader* header = GetCurrentOatQuickMethodHeader();
96   if (cur_stack_map_.first != cur_quick_frame_pc_) {
97     uint32_t pc = header->NativeQuickPcOffset(cur_quick_frame_pc_);
98     cur_stack_map_ = std::make_pair(cur_quick_frame_pc_,
99                                     GetCurrentInlineInfo()->GetStackMapForNativePcOffset(pc));
100   }
101   return &cur_stack_map_.second;
102 }
103 
GetMethod() const104 ArtMethod* StackVisitor::GetMethod() const {
105   if (cur_shadow_frame_ != nullptr) {
106     return cur_shadow_frame_->GetMethod();
107   } else if (cur_quick_frame_ != nullptr) {
108     if (IsInInlinedFrame()) {
109       CodeInfo* code_info = GetCurrentInlineInfo();
110       DCHECK(walk_kind_ != StackWalkKind::kSkipInlinedFrames);
111       return GetResolvedMethod(*GetCurrentQuickFrame(), *code_info, current_inline_frames_);
112     } else {
113       return *cur_quick_frame_;
114     }
115   }
116   return nullptr;
117 }
118 
GetDexPc(bool abort_on_failure) const119 uint32_t StackVisitor::GetDexPc(bool abort_on_failure) const {
120   if (cur_shadow_frame_ != nullptr) {
121     return cur_shadow_frame_->GetDexPC();
122   } else if (cur_quick_frame_ != nullptr) {
123     if (IsInInlinedFrame()) {
124       return current_inline_frames_.back().GetDexPc();
125     } else if (cur_oat_quick_method_header_ == nullptr) {
126       return dex::kDexNoIndex;
127     } else if ((*GetCurrentQuickFrame())->IsNative()) {
128       return cur_oat_quick_method_header_->ToDexPc(
129           GetCurrentQuickFrame(), cur_quick_frame_pc_, abort_on_failure);
130     } else if (cur_oat_quick_method_header_->IsOptimized()) {
131       StackMap* stack_map = GetCurrentStackMap();
132       DCHECK(stack_map->IsValid());
133       return stack_map->GetDexPc();
134     } else {
135       DCHECK(cur_oat_quick_method_header_->IsNterpMethodHeader());
136       return NterpGetDexPC(cur_quick_frame_);
137     }
138   } else {
139     return 0;
140   }
141 }
142 
143 extern "C" mirror::Object* artQuickGetProxyThisObject(ArtMethod** sp)
144     REQUIRES_SHARED(Locks::mutator_lock_);
145 
GetThisObject() const146 ObjPtr<mirror::Object> StackVisitor::GetThisObject() const {
147   DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
148   ArtMethod* m = GetMethod();
149   if (m->IsStatic()) {
150     return nullptr;
151   } else if (m->IsNative()) {
152     if (cur_quick_frame_ != nullptr) {
153       // The `this` reference is stored in the first out vreg in the caller's frame.
154       const size_t frame_size = GetCurrentQuickFrameInfo().FrameSizeInBytes();
155       auto* stack_ref = reinterpret_cast<StackReference<mirror::Object>*>(
156           reinterpret_cast<uint8_t*>(cur_quick_frame_) + frame_size + sizeof(ArtMethod*));
157       return stack_ref->AsMirrorPtr();
158     } else {
159       return cur_shadow_frame_->GetVRegReference(0);
160     }
161   } else if (m->IsProxyMethod()) {
162     if (cur_quick_frame_ != nullptr) {
163       return artQuickGetProxyThisObject(cur_quick_frame_);
164     } else {
165       return cur_shadow_frame_->GetVRegReference(0);
166     }
167   } else {
168     CodeItemDataAccessor accessor(m->DexInstructionData());
169     if (!accessor.HasCodeItem()) {
170       UNIMPLEMENTED(ERROR) << "Failed to determine this object of abstract or proxy method: "
171           << ArtMethod::PrettyMethod(m);
172       return nullptr;
173     } else {
174       uint16_t reg = accessor.RegistersSize() - accessor.InsSize();
175       uint32_t value = 0;
176       if (!GetVReg(m, reg, kReferenceVReg, &value)) {
177         return nullptr;
178       }
179       return reinterpret_cast<mirror::Object*>(value);
180     }
181   }
182 }
183 
GetNativePcOffset() const184 size_t StackVisitor::GetNativePcOffset() const {
185   DCHECK(!IsShadowFrame());
186   return GetCurrentOatQuickMethodHeader()->NativeQuickPcOffset(cur_quick_frame_pc_);
187 }
188 
GetVRegFromDebuggerShadowFrame(uint16_t vreg,VRegKind kind,uint32_t * val) const189 bool StackVisitor::GetVRegFromDebuggerShadowFrame(uint16_t vreg,
190                                                   VRegKind kind,
191                                                   uint32_t* val) const {
192   size_t frame_id = const_cast<StackVisitor*>(this)->GetFrameId();
193   ShadowFrame* shadow_frame = thread_->FindDebuggerShadowFrame(frame_id);
194   if (shadow_frame != nullptr) {
195     bool* updated_vreg_flags = thread_->GetUpdatedVRegFlags(frame_id);
196     DCHECK(updated_vreg_flags != nullptr);
197     if (updated_vreg_flags[vreg]) {
198       // Value is set by the debugger.
199       if (kind == kReferenceVReg) {
200         *val = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(
201             shadow_frame->GetVRegReference(vreg)));
202       } else {
203         *val = shadow_frame->GetVReg(vreg);
204       }
205       return true;
206     }
207   }
208   // No value is set by the debugger.
209   return false;
210 }
211 
GetVReg(ArtMethod * m,uint16_t vreg,VRegKind kind,uint32_t * val,std::optional<DexRegisterLocation> location) const212 bool StackVisitor::GetVReg(ArtMethod* m,
213                            uint16_t vreg,
214                            VRegKind kind,
215                            uint32_t* val,
216                            std::optional<DexRegisterLocation> location) const {
217   if (cur_quick_frame_ != nullptr) {
218     DCHECK(context_ != nullptr);  // You can't reliably read registers without a context.
219     DCHECK(m == GetMethod());
220     // Check if there is value set by the debugger.
221     if (GetVRegFromDebuggerShadowFrame(vreg, kind, val)) {
222       return true;
223     }
224     bool result = false;
225     if (cur_oat_quick_method_header_->IsNterpMethodHeader()) {
226       result = true;
227       *val = (kind == kReferenceVReg)
228           ? NterpGetVRegReference(cur_quick_frame_, vreg)
229           : NterpGetVReg(cur_quick_frame_, vreg);
230     } else {
231       DCHECK(cur_oat_quick_method_header_->IsOptimized());
232       if (location.has_value() && kind != kReferenceVReg) {
233         uint32_t val2 = *val;
234         // The caller already known the register location, so we can use the faster overload
235         // which does not decode the stack maps.
236         result = GetVRegFromOptimizedCode(location.value(), val);
237         // Compare to the slower overload.
238         DCHECK_EQ(result, GetVRegFromOptimizedCode(m, vreg, kind, &val2));
239         DCHECK_EQ(*val, val2);
240       } else {
241         result = GetVRegFromOptimizedCode(m, vreg, kind, val);
242       }
243     }
244     if (kind == kReferenceVReg) {
245       // Perform a read barrier in case we are in a different thread and GC is ongoing.
246       mirror::Object* out = reinterpret_cast<mirror::Object*>(static_cast<uintptr_t>(*val));
247       uintptr_t ptr_out = reinterpret_cast<uintptr_t>(GcRoot<mirror::Object>(out).Read());
248       DCHECK_LT(ptr_out, std::numeric_limits<uint32_t>::max());
249       *val = static_cast<uint32_t>(ptr_out);
250     }
251     return result;
252   } else {
253     DCHECK(cur_shadow_frame_ != nullptr);
254     if (kind == kReferenceVReg) {
255       *val = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(
256           cur_shadow_frame_->GetVRegReference(vreg)));
257     } else {
258       *val = cur_shadow_frame_->GetVReg(vreg);
259     }
260     return true;
261   }
262 }
263 
GetVRegFromOptimizedCode(ArtMethod * m,uint16_t vreg,VRegKind kind,uint32_t * val) const264 bool StackVisitor::GetVRegFromOptimizedCode(ArtMethod* m,
265                                             uint16_t vreg,
266                                             VRegKind kind,
267                                             uint32_t* val) const {
268   DCHECK_EQ(m, GetMethod());
269   // Can't be null or how would we compile its instructions?
270   DCHECK(m->GetCodeItem() != nullptr) << m->PrettyMethod();
271   CodeItemDataAccessor accessor(m->DexInstructionData());
272   uint16_t number_of_dex_registers = accessor.RegistersSize();
273   DCHECK_LT(vreg, number_of_dex_registers);
274   const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
275   CodeInfo code_info(method_header);
276 
277   uint32_t native_pc_offset = method_header->NativeQuickPcOffset(cur_quick_frame_pc_);
278   StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
279   DCHECK(stack_map.IsValid());
280 
281   DexRegisterMap dex_register_map = IsInInlinedFrame()
282       ? code_info.GetInlineDexRegisterMapOf(stack_map, current_inline_frames_.back())
283       : code_info.GetDexRegisterMapOf(stack_map);
284   if (dex_register_map.empty()) {
285     return false;
286   }
287   DCHECK_EQ(dex_register_map.size(), number_of_dex_registers);
288   DexRegisterLocation::Kind location_kind = dex_register_map[vreg].GetKind();
289   switch (location_kind) {
290     case DexRegisterLocation::Kind::kInStack: {
291       const int32_t offset = dex_register_map[vreg].GetStackOffsetInBytes();
292       BitMemoryRegion stack_mask = code_info.GetStackMaskOf(stack_map);
293       if (kind == kReferenceVReg && !stack_mask.LoadBit(offset / kFrameSlotSize)) {
294         return false;
295       }
296       const uint8_t* addr = reinterpret_cast<const uint8_t*>(cur_quick_frame_) + offset;
297       *val = *reinterpret_cast<const uint32_t*>(addr);
298       return true;
299     }
300     case DexRegisterLocation::Kind::kInRegister: {
301       uint32_t register_mask = code_info.GetRegisterMaskOf(stack_map);
302       uint32_t reg = dex_register_map[vreg].GetMachineRegister();
303       if (kind == kReferenceVReg && !(register_mask & (1 << reg))) {
304         return false;
305       }
306       return GetRegisterIfAccessible(reg, location_kind, val);
307     }
308     case DexRegisterLocation::Kind::kInRegisterHigh:
309     case DexRegisterLocation::Kind::kInFpuRegister:
310     case DexRegisterLocation::Kind::kInFpuRegisterHigh: {
311       if (kind == kReferenceVReg) {
312         return false;
313       }
314       uint32_t reg = dex_register_map[vreg].GetMachineRegister();
315       return GetRegisterIfAccessible(reg, location_kind, val);
316     }
317     case DexRegisterLocation::Kind::kConstant: {
318       uint32_t result = dex_register_map[vreg].GetConstant();
319       if (kind == kReferenceVReg && result != 0) {
320         return false;
321       }
322       *val = result;
323       return true;
324     }
325     case DexRegisterLocation::Kind::kNone:
326       return false;
327     default:
328       LOG(FATAL) << "Unexpected location kind " << dex_register_map[vreg].GetKind();
329       UNREACHABLE();
330   }
331 }
332 
GetVRegFromOptimizedCode(DexRegisterLocation location,uint32_t * val) const333 bool StackVisitor::GetVRegFromOptimizedCode(DexRegisterLocation location, uint32_t* val) const {
334   switch (location.GetKind()) {
335     case DexRegisterLocation::Kind::kInvalid:
336       break;
337     case DexRegisterLocation::Kind::kInStack: {
338       const uint8_t* sp = reinterpret_cast<const uint8_t*>(cur_quick_frame_);
339       *val = *reinterpret_cast<const uint32_t*>(sp + location.GetStackOffsetInBytes());
340       return true;
341     }
342     case DexRegisterLocation::Kind::kInRegister:
343     case DexRegisterLocation::Kind::kInRegisterHigh:
344     case DexRegisterLocation::Kind::kInFpuRegister:
345     case DexRegisterLocation::Kind::kInFpuRegisterHigh:
346       return GetRegisterIfAccessible(location.GetMachineRegister(), location.GetKind(), val);
347     case DexRegisterLocation::Kind::kConstant:
348       *val = location.GetConstant();
349       return true;
350     case DexRegisterLocation::Kind::kNone:
351       return false;
352   }
353   LOG(FATAL) << "Unexpected location kind " << location.GetKind();
354   UNREACHABLE();
355 }
356 
GetRegisterIfAccessible(uint32_t reg,DexRegisterLocation::Kind location_kind,uint32_t * val) const357 bool StackVisitor::GetRegisterIfAccessible(uint32_t reg,
358                                            DexRegisterLocation::Kind location_kind,
359                                            uint32_t* val) const {
360   const bool is_float = (location_kind == DexRegisterLocation::Kind::kInFpuRegister) ||
361                         (location_kind == DexRegisterLocation::Kind::kInFpuRegisterHigh);
362 
363   if (kRuntimeISA == InstructionSet::kX86 && is_float) {
364     // X86 float registers are 64-bit and each XMM register is provided as two separate
365     // 32-bit registers by the context.
366     reg = (location_kind == DexRegisterLocation::Kind::kInFpuRegisterHigh)
367         ? (2 * reg + 1)
368         : (2 * reg);
369   }
370 
371   if (!IsAccessibleRegister(reg, is_float)) {
372     return false;
373   }
374   uintptr_t ptr_val = GetRegister(reg, is_float);
375   const bool target64 = Is64BitInstructionSet(kRuntimeISA);
376   if (target64) {
377     const bool is_high = (location_kind == DexRegisterLocation::Kind::kInRegisterHigh) ||
378                          (location_kind == DexRegisterLocation::Kind::kInFpuRegisterHigh);
379     int64_t value_long = static_cast<int64_t>(ptr_val);
380     ptr_val = static_cast<uintptr_t>(is_high ? High32Bits(value_long) : Low32Bits(value_long));
381   }
382   *val = ptr_val;
383   return true;
384 }
385 
GetVRegPairFromDebuggerShadowFrame(uint16_t vreg,VRegKind kind_lo,VRegKind kind_hi,uint64_t * val) const386 bool StackVisitor::GetVRegPairFromDebuggerShadowFrame(uint16_t vreg,
387                                                       VRegKind kind_lo,
388                                                       VRegKind kind_hi,
389                                                       uint64_t* val) const {
390   uint32_t low_32bits;
391   uint32_t high_32bits;
392   bool success = GetVRegFromDebuggerShadowFrame(vreg, kind_lo, &low_32bits);
393   success &= GetVRegFromDebuggerShadowFrame(vreg + 1, kind_hi, &high_32bits);
394   if (success) {
395     *val = (static_cast<uint64_t>(high_32bits) << 32) | static_cast<uint64_t>(low_32bits);
396   }
397   return success;
398 }
399 
GetVRegPair(ArtMethod * m,uint16_t vreg,VRegKind kind_lo,VRegKind kind_hi,uint64_t * val) const400 bool StackVisitor::GetVRegPair(ArtMethod* m, uint16_t vreg, VRegKind kind_lo,
401                                VRegKind kind_hi, uint64_t* val) const {
402   if (kind_lo == kLongLoVReg) {
403     DCHECK_EQ(kind_hi, kLongHiVReg);
404   } else if (kind_lo == kDoubleLoVReg) {
405     DCHECK_EQ(kind_hi, kDoubleHiVReg);
406   } else {
407     LOG(FATAL) << "Expected long or double: kind_lo=" << kind_lo << ", kind_hi=" << kind_hi;
408     UNREACHABLE();
409   }
410   // Check if there is value set by the debugger.
411   if (GetVRegPairFromDebuggerShadowFrame(vreg, kind_lo, kind_hi, val)) {
412     return true;
413   }
414   if (cur_quick_frame_ == nullptr) {
415     DCHECK(cur_shadow_frame_ != nullptr);
416     *val = cur_shadow_frame_->GetVRegLong(vreg);
417     return true;
418   }
419   if (cur_oat_quick_method_header_->IsNterpMethodHeader()) {
420     uint64_t val_lo = NterpGetVReg(cur_quick_frame_, vreg);
421     uint64_t val_hi = NterpGetVReg(cur_quick_frame_, vreg + 1);
422     *val = (val_hi << 32) + val_lo;
423     return true;
424   }
425 
426   DCHECK(context_ != nullptr);  // You can't reliably read registers without a context.
427   DCHECK(m == GetMethod());
428   DCHECK(cur_oat_quick_method_header_->IsOptimized());
429   return GetVRegPairFromOptimizedCode(m, vreg, kind_lo, kind_hi, val);
430 }
431 
GetVRegPairFromOptimizedCode(ArtMethod * m,uint16_t vreg,VRegKind kind_lo,VRegKind kind_hi,uint64_t * val) const432 bool StackVisitor::GetVRegPairFromOptimizedCode(ArtMethod* m, uint16_t vreg,
433                                                 VRegKind kind_lo, VRegKind kind_hi,
434                                                 uint64_t* val) const {
435   uint32_t low_32bits;
436   uint32_t high_32bits;
437   bool success = GetVRegFromOptimizedCode(m, vreg, kind_lo, &low_32bits);
438   success &= GetVRegFromOptimizedCode(m, vreg + 1, kind_hi, &high_32bits);
439   if (success) {
440     *val = (static_cast<uint64_t>(high_32bits) << 32) | static_cast<uint64_t>(low_32bits);
441   }
442   return success;
443 }
444 
PrepareSetVReg(ArtMethod * m,uint16_t vreg,bool wide)445 ShadowFrame* StackVisitor::PrepareSetVReg(ArtMethod* m, uint16_t vreg, bool wide) {
446   CodeItemDataAccessor accessor(m->DexInstructionData());
447   if (!accessor.HasCodeItem()) {
448     return nullptr;
449   }
450   ShadowFrame* shadow_frame = GetCurrentShadowFrame();
451   if (shadow_frame == nullptr) {
452     // This is a compiled frame: we must prepare and update a shadow frame that will
453     // be executed by the interpreter after deoptimization of the stack.
454     const size_t frame_id = GetFrameId();
455     const uint16_t num_regs = accessor.RegistersSize();
456     shadow_frame = thread_->FindOrCreateDebuggerShadowFrame(frame_id, num_regs, m, GetDexPc());
457     CHECK(shadow_frame != nullptr);
458     // Remember the vreg(s) has been set for debugging and must not be overwritten by the
459     // original value during deoptimization of the stack.
460     thread_->GetUpdatedVRegFlags(frame_id)[vreg] = true;
461     if (wide) {
462       thread_->GetUpdatedVRegFlags(frame_id)[vreg + 1] = true;
463     }
464   }
465   return shadow_frame;
466 }
467 
SetVReg(ArtMethod * m,uint16_t vreg,uint32_t new_value,VRegKind kind)468 bool StackVisitor::SetVReg(ArtMethod* m, uint16_t vreg, uint32_t new_value, VRegKind kind) {
469   DCHECK(kind == kIntVReg || kind == kFloatVReg);
470   ShadowFrame* shadow_frame = PrepareSetVReg(m, vreg, /* wide= */ false);
471   if (shadow_frame == nullptr) {
472     return false;
473   }
474   shadow_frame->SetVReg(vreg, new_value);
475   return true;
476 }
477 
SetVRegReference(ArtMethod * m,uint16_t vreg,ObjPtr<mirror::Object> new_value)478 bool StackVisitor::SetVRegReference(ArtMethod* m, uint16_t vreg, ObjPtr<mirror::Object> new_value) {
479   ShadowFrame* shadow_frame = PrepareSetVReg(m, vreg, /* wide= */ false);
480   if (shadow_frame == nullptr) {
481     return false;
482   }
483   shadow_frame->SetVRegReference(vreg, new_value);
484   return true;
485 }
486 
SetVRegPair(ArtMethod * m,uint16_t vreg,uint64_t new_value,VRegKind kind_lo,VRegKind kind_hi)487 bool StackVisitor::SetVRegPair(ArtMethod* m,
488                                uint16_t vreg,
489                                uint64_t new_value,
490                                VRegKind kind_lo,
491                                VRegKind kind_hi) {
492   if (kind_lo == kLongLoVReg) {
493     DCHECK_EQ(kind_hi, kLongHiVReg);
494   } else if (kind_lo == kDoubleLoVReg) {
495     DCHECK_EQ(kind_hi, kDoubleHiVReg);
496   } else {
497     LOG(FATAL) << "Expected long or double: kind_lo=" << kind_lo << ", kind_hi=" << kind_hi;
498     UNREACHABLE();
499   }
500   ShadowFrame* shadow_frame = PrepareSetVReg(m, vreg, /* wide= */ true);
501   if (shadow_frame == nullptr) {
502     return false;
503   }
504   shadow_frame->SetVRegLong(vreg, new_value);
505   return true;
506 }
507 
IsAccessibleGPR(uint32_t reg) const508 bool StackVisitor::IsAccessibleGPR(uint32_t reg) const {
509   DCHECK(context_ != nullptr);
510   return context_->IsAccessibleGPR(reg);
511 }
512 
GetGPRAddress(uint32_t reg) const513 uintptr_t* StackVisitor::GetGPRAddress(uint32_t reg) const {
514   DCHECK(cur_quick_frame_ != nullptr) << "This is a quick frame routine";
515   DCHECK(context_ != nullptr);
516   return context_->GetGPRAddress(reg);
517 }
518 
GetGPR(uint32_t reg) const519 uintptr_t StackVisitor::GetGPR(uint32_t reg) const {
520   DCHECK(cur_quick_frame_ != nullptr) << "This is a quick frame routine";
521   DCHECK(context_ != nullptr);
522   return context_->GetGPR(reg);
523 }
524 
IsAccessibleFPR(uint32_t reg) const525 bool StackVisitor::IsAccessibleFPR(uint32_t reg) const {
526   DCHECK(context_ != nullptr);
527   return context_->IsAccessibleFPR(reg);
528 }
529 
GetFPR(uint32_t reg) const530 uintptr_t StackVisitor::GetFPR(uint32_t reg) const {
531   DCHECK(cur_quick_frame_ != nullptr) << "This is a quick frame routine";
532   DCHECK(context_ != nullptr);
533   return context_->GetFPR(reg);
534 }
535 
GetReturnPcAddr() const536 uintptr_t StackVisitor::GetReturnPcAddr() const {
537   uintptr_t sp = reinterpret_cast<uintptr_t>(GetCurrentQuickFrame());
538   DCHECK_NE(sp, 0u);
539   return sp + GetCurrentQuickFrameInfo().GetReturnPcOffset();
540 }
541 
GetReturnPc() const542 uintptr_t StackVisitor::GetReturnPc() const {
543   return *reinterpret_cast<uintptr_t*>(GetReturnPcAddr());
544 }
545 
SetReturnPc(uintptr_t new_ret_pc)546 void StackVisitor::SetReturnPc(uintptr_t new_ret_pc) {
547   *reinterpret_cast<uintptr_t*>(GetReturnPcAddr()) = new_ret_pc;
548 }
549 
ComputeNumFrames(Thread * thread,StackWalkKind walk_kind)550 size_t StackVisitor::ComputeNumFrames(Thread* thread, StackWalkKind walk_kind) {
551   struct NumFramesVisitor : public StackVisitor {
552     NumFramesVisitor(Thread* thread_in, StackWalkKind walk_kind_in)
553         : StackVisitor(thread_in, nullptr, walk_kind_in), frames(0) {}
554 
555     bool VisitFrame() override {
556       frames++;
557       return true;
558     }
559 
560     size_t frames;
561   };
562   NumFramesVisitor visitor(thread, walk_kind);
563   visitor.WalkStack(true);
564   return visitor.frames;
565 }
566 
GetNextMethodAndDexPc(ArtMethod ** next_method,uint32_t * next_dex_pc)567 bool StackVisitor::GetNextMethodAndDexPc(ArtMethod** next_method, uint32_t* next_dex_pc) {
568   struct HasMoreFramesVisitor : public StackVisitor {
569     HasMoreFramesVisitor(Thread* thread,
570                          StackWalkKind walk_kind,
571                          size_t num_frames,
572                          size_t frame_height)
573         : StackVisitor(thread, nullptr, walk_kind, num_frames),
574           frame_height_(frame_height),
575           found_frame_(false),
576           has_more_frames_(false),
577           next_method_(nullptr),
578           next_dex_pc_(0) {
579     }
580 
581     bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
582       if (found_frame_) {
583         ArtMethod* method = GetMethod();
584         if (method != nullptr && !method->IsRuntimeMethod()) {
585           has_more_frames_ = true;
586           next_method_ = method;
587           next_dex_pc_ = GetDexPc();
588           return false;  // End stack walk once next method is found.
589         }
590       } else if (GetFrameHeight() == frame_height_) {
591         found_frame_ = true;
592       }
593       return true;
594     }
595 
596     size_t frame_height_;
597     bool found_frame_;
598     bool has_more_frames_;
599     ArtMethod* next_method_;
600     uint32_t next_dex_pc_;
601   };
602   HasMoreFramesVisitor visitor(thread_, walk_kind_, GetNumFrames(), GetFrameHeight());
603   visitor.WalkStack(true);
604   *next_method = visitor.next_method_;
605   *next_dex_pc = visitor.next_dex_pc_;
606   return visitor.has_more_frames_;
607 }
608 
DescribeStack(Thread * thread)609 void StackVisitor::DescribeStack(Thread* thread) {
610   struct DescribeStackVisitor : public StackVisitor {
611     explicit DescribeStackVisitor(Thread* thread_in)
612         : StackVisitor(thread_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames) {}
613 
614     bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
615       LOG(INFO) << "Frame Id=" << GetFrameId() << " " << DescribeLocation();
616       return true;
617     }
618   };
619   DescribeStackVisitor visitor(thread);
620   visitor.WalkStack(true);
621 }
622 
DescribeLocation() const623 std::string StackVisitor::DescribeLocation() const {
624   std::string result("Visiting method '");
625   ArtMethod* m = GetMethod();
626   if (m == nullptr) {
627     return "upcall";
628   }
629   result += m->PrettyMethod();
630   result += StringPrintf("' at dex PC 0x%04x", GetDexPc());
631   if (!IsShadowFrame()) {
632     result += StringPrintf(" (native PC %p)", reinterpret_cast<void*>(GetCurrentQuickFramePc()));
633   }
634   return result;
635 }
636 
SetMethod(ArtMethod * method)637 void StackVisitor::SetMethod(ArtMethod* method) {
638   DCHECK(GetMethod() != nullptr);
639   if (cur_shadow_frame_ != nullptr) {
640     cur_shadow_frame_->SetMethod(method);
641   } else {
642     DCHECK(cur_quick_frame_ != nullptr);
643     CHECK(!IsInInlinedFrame()) << "We do not support setting inlined method's ArtMethod: "
644                                << GetMethod()->PrettyMethod() << " is inlined into "
645                                << GetOuterMethod()->PrettyMethod();
646     *cur_quick_frame_ = method;
647   }
648 }
649 
ValidateFrame() const650 void StackVisitor::ValidateFrame() const {
651   if (!kIsDebugBuild) {
652     return;
653   }
654   ArtMethod* method = GetMethod();
655   ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
656   // Runtime methods have null declaring class.
657   if (!method->IsRuntimeMethod()) {
658     CHECK(declaring_class != nullptr);
659     CHECK_EQ(declaring_class->GetClass(), declaring_class->GetClass()->GetClass())
660         << declaring_class;
661   } else {
662     CHECK(declaring_class == nullptr);
663   }
664   Runtime* const runtime = Runtime::Current();
665   LinearAlloc* const linear_alloc = runtime->GetLinearAlloc();
666   if (!linear_alloc->Contains(method)) {
667     // Check class linker linear allocs.
668     // We get the canonical method as copied methods may have been allocated
669     // by a different class loader.
670     const PointerSize ptrSize = runtime->GetClassLinker()->GetImagePointerSize();
671     ArtMethod* canonical = method->GetCanonicalMethod(ptrSize);
672     ObjPtr<mirror::Class> klass = canonical->GetDeclaringClass();
673     LinearAlloc* const class_linear_alloc = (klass != nullptr)
674         ? runtime->GetClassLinker()->GetAllocatorForClassLoader(klass->GetClassLoader())
675         : linear_alloc;
676     if (!class_linear_alloc->Contains(canonical)) {
677       // Check image space.
678       bool in_image = false;
679       for (auto& space : runtime->GetHeap()->GetContinuousSpaces()) {
680         if (space->IsImageSpace()) {
681           auto* image_space = space->AsImageSpace();
682           const auto& header = image_space->GetImageHeader();
683           const ImageSection& methods = header.GetMethodsSection();
684           const ImageSection& runtime_methods = header.GetRuntimeMethodsSection();
685           const size_t offset =  reinterpret_cast<const uint8_t*>(canonical) - image_space->Begin();
686           if (methods.Contains(offset) || runtime_methods.Contains(offset)) {
687             in_image = true;
688             break;
689           }
690         }
691       }
692       CHECK(in_image) << canonical->PrettyMethod() << " not in linear alloc or image";
693     }
694   }
695   if (cur_quick_frame_ != nullptr) {
696     // Frame consistency checks.
697     size_t frame_size = GetCurrentQuickFrameInfo().FrameSizeInBytes();
698     CHECK_NE(frame_size, 0u);
699     // For compiled code, we could try to have a rough guess at an upper size we expect
700     // to see for a frame:
701     // 256 registers
702     // 2 words HandleScope overhead
703     // 3+3 register spills
704     // const size_t kMaxExpectedFrameSize = (256 + 2 + 3 + 3) * sizeof(word);
705     const size_t kMaxExpectedFrameSize = interpreter::kNterpMaxFrame;
706     CHECK_LE(frame_size, kMaxExpectedFrameSize) << method->PrettyMethod();
707     size_t return_pc_offset = GetCurrentQuickFrameInfo().GetReturnPcOffset();
708     CHECK_LT(return_pc_offset, frame_size);
709   }
710 }
711 
GetCurrentQuickFrameInfo() const712 QuickMethodFrameInfo StackVisitor::GetCurrentQuickFrameInfo() const {
713   if (cur_oat_quick_method_header_ != nullptr) {
714     if (cur_oat_quick_method_header_->IsOptimized()) {
715       return cur_oat_quick_method_header_->GetFrameInfo();
716     } else {
717       DCHECK(cur_oat_quick_method_header_->IsNterpMethodHeader());
718       return NterpFrameInfo(cur_quick_frame_);
719     }
720   }
721 
722   ArtMethod* method = GetMethod();
723   Runtime* runtime = Runtime::Current();
724 
725   if (method->IsAbstract()) {
726     return RuntimeCalleeSaveFrame::GetMethodFrameInfo(CalleeSaveType::kSaveRefsAndArgs);
727   }
728 
729   // This goes before IsProxyMethod since runtime methods have a null declaring class.
730   if (method->IsRuntimeMethod()) {
731     return runtime->GetRuntimeMethodFrameInfo(method);
732   }
733 
734   if (method->IsProxyMethod()) {
735     // There is only one direct method of a proxy class: the constructor. A direct method is
736     // cloned from the original java.lang.reflect.Proxy and is executed as usual quick
737     // compiled method without any stubs. Therefore the method must have a OatQuickMethodHeader.
738     DCHECK(!method->IsDirect() && !method->IsConstructor())
739         << "Constructors of proxy classes must have a OatQuickMethodHeader";
740     return RuntimeCalleeSaveFrame::GetMethodFrameInfo(CalleeSaveType::kSaveRefsAndArgs);
741   }
742 
743   // The only remaining cases are for native methods that either
744   //   - use the Generic JNI stub, called either directly or through some
745   //     (resolution, instrumentation) trampoline; or
746   //   - fake a Generic JNI frame in art_jni_dlsym_lookup_critical_stub.
747   DCHECK(method->IsNative());
748   if (kIsDebugBuild && !method->IsCriticalNative()) {
749     ClassLinker* class_linker = runtime->GetClassLinker();
750     const void* entry_point = runtime->GetInstrumentation()->GetCodeForInvoke(method);
751     CHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
752           // The current entrypoint (after filtering out trampolines) may have changed
753           // from GenericJNI to JIT-compiled stub since we have entered this frame.
754           (runtime->GetJit() != nullptr &&
755            runtime->GetJit()->GetCodeCache()->ContainsPc(entry_point))) << method->PrettyMethod();
756   }
757   // Generic JNI frame is just like the SaveRefsAndArgs frame.
758   // Note that HandleScope, if any, is below the frame.
759   return RuntimeCalleeSaveFrame::GetMethodFrameInfo(CalleeSaveType::kSaveRefsAndArgs);
760 }
761 
GetShouldDeoptimizeFlagAddr() const762 uint8_t* StackVisitor::GetShouldDeoptimizeFlagAddr() const REQUIRES_SHARED(Locks::mutator_lock_) {
763   DCHECK(GetCurrentOatQuickMethodHeader()->HasShouldDeoptimizeFlag());
764   QuickMethodFrameInfo frame_info = GetCurrentQuickFrameInfo();
765   size_t frame_size = frame_info.FrameSizeInBytes();
766   uint8_t* sp = reinterpret_cast<uint8_t*>(GetCurrentQuickFrame());
767   size_t core_spill_size =
768       POPCOUNT(frame_info.CoreSpillMask()) * GetBytesPerGprSpillLocation(kRuntimeISA);
769   size_t fpu_spill_size =
770       POPCOUNT(frame_info.FpSpillMask()) * GetBytesPerFprSpillLocation(kRuntimeISA);
771   size_t offset = frame_size - core_spill_size - fpu_spill_size - kShouldDeoptimizeFlagSize;
772   uint8_t* should_deoptimize_addr = sp + offset;
773   DCHECK_EQ(*should_deoptimize_addr & ~static_cast<uint8_t>(DeoptimizeFlagValue::kAll), 0);
774   return should_deoptimize_addr;
775 }
776 
777 template <StackVisitor::CountTransitions kCount>
WalkStack(bool include_transitions)778 void StackVisitor::WalkStack(bool include_transitions) {
779   if (check_suspended_) {
780     DCHECK(thread_ == Thread::Current() || thread_->IsSuspended());
781   }
782   CHECK_EQ(cur_depth_, 0U);
783   size_t inlined_frames_count = 0;
784 
785   for (const ManagedStack* current_fragment = thread_->GetManagedStack();
786        current_fragment != nullptr; current_fragment = current_fragment->GetLink()) {
787     cur_shadow_frame_ = current_fragment->GetTopShadowFrame();
788     cur_quick_frame_ = current_fragment->GetTopQuickFrame();
789     cur_quick_frame_pc_ = 0;
790     DCHECK(cur_oat_quick_method_header_ == nullptr);
791     if (cur_quick_frame_ != nullptr) {  // Handle quick stack frames.
792       // Can't be both a shadow and a quick fragment.
793       DCHECK(current_fragment->GetTopShadowFrame() == nullptr);
794       ArtMethod* method = *cur_quick_frame_;
795       DCHECK(method != nullptr);
796       bool header_retrieved = false;
797       if (method->IsNative()) {
798         // We do not have a PC for the first frame, so we cannot simply use
799         // ArtMethod::GetOatQuickMethodHeader() as we're unable to distinguish there
800         // between GenericJNI frame and JIT-compiled JNI stub; the entrypoint may have
801         // changed since the frame was entered. The top quick frame tag indicates
802         // GenericJNI here, otherwise it's either AOT-compiled or JNI-compiled JNI stub.
803         if (UNLIKELY(current_fragment->GetTopQuickFrameTag())) {
804           // The generic JNI does not have any method header.
805           cur_oat_quick_method_header_ = nullptr;
806         } else {
807           const void* existing_entry_point = method->GetEntryPointFromQuickCompiledCode();
808           CHECK(existing_entry_point != nullptr);
809           Runtime* runtime = Runtime::Current();
810           ClassLinker* class_linker = runtime->GetClassLinker();
811           // Check whether we can quickly get the header from the current entrypoint.
812           if (!class_linker->IsQuickGenericJniStub(existing_entry_point) &&
813               !class_linker->IsQuickResolutionStub(existing_entry_point) &&
814               existing_entry_point != GetQuickInstrumentationEntryPoint()) {
815             cur_oat_quick_method_header_ =
816                 OatQuickMethodHeader::FromEntryPoint(existing_entry_point);
817           } else {
818             const void* code = method->GetOatMethodQuickCode(class_linker->GetImagePointerSize());
819             if (code != nullptr) {
820               cur_oat_quick_method_header_ = OatQuickMethodHeader::FromEntryPoint(code);
821             } else {
822               // This must be a JITted JNI stub frame.
823               CHECK(runtime->GetJit() != nullptr);
824               code = runtime->GetJit()->GetCodeCache()->GetJniStubCode(method);
825               CHECK(code != nullptr) << method->PrettyMethod();
826               cur_oat_quick_method_header_ = OatQuickMethodHeader::FromCodePointer(code);
827             }
828           }
829         }
830         header_retrieved = true;
831       }
832       while (method != nullptr) {
833         if (!header_retrieved) {
834           cur_oat_quick_method_header_ = method->GetOatQuickMethodHeader(cur_quick_frame_pc_);
835         }
836         header_retrieved = false;  // Force header retrieval in next iteration.
837         ValidateFrame();
838 
839         if ((walk_kind_ == StackWalkKind::kIncludeInlinedFrames)
840             && (cur_oat_quick_method_header_ != nullptr)
841             && cur_oat_quick_method_header_->IsOptimized()
842             && !method->IsNative()  // JNI methods cannot have any inlined frames.
843             && CodeInfo::HasInlineInfo(cur_oat_quick_method_header_->GetOptimizedCodeInfoPtr())) {
844           DCHECK_NE(cur_quick_frame_pc_, 0u);
845           CodeInfo* code_info = GetCurrentInlineInfo();
846           StackMap* stack_map = GetCurrentStackMap();
847           if (stack_map->IsValid() && stack_map->HasInlineInfo()) {
848             DCHECK_EQ(current_inline_frames_.size(), 0u);
849             for (current_inline_frames_ = code_info->GetInlineInfosOf(*stack_map);
850                  !current_inline_frames_.empty();
851                  current_inline_frames_.pop_back()) {
852               bool should_continue = VisitFrame();
853               if (UNLIKELY(!should_continue)) {
854                 return;
855               }
856               cur_depth_++;
857               inlined_frames_count++;
858             }
859           }
860         }
861 
862         bool should_continue = VisitFrame();
863         if (UNLIKELY(!should_continue)) {
864           return;
865         }
866 
867         QuickMethodFrameInfo frame_info = GetCurrentQuickFrameInfo();
868         if (context_ != nullptr) {
869           context_->FillCalleeSaves(reinterpret_cast<uint8_t*>(cur_quick_frame_), frame_info);
870         }
871         // Compute PC for next stack frame from return PC.
872         size_t frame_size = frame_info.FrameSizeInBytes();
873         uintptr_t return_pc_addr = GetReturnPcAddr();
874         uintptr_t return_pc = *reinterpret_cast<uintptr_t*>(return_pc_addr);
875 
876         if (UNLIKELY(reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()) == return_pc)) {
877           // While profiling, the return pc is restored from the side stack, except when walking
878           // the stack for an exception where the side stack will be unwound in VisitFrame.
879           const std::map<uintptr_t, instrumentation::InstrumentationStackFrame>&
880               instrumentation_stack = *thread_->GetInstrumentationStack();
881           auto it = instrumentation_stack.find(return_pc_addr);
882           CHECK(it != instrumentation_stack.end());
883           const instrumentation::InstrumentationStackFrame& instrumentation_frame = it->second;
884           if (GetMethod() ==
885               Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves)) {
886             // Skip runtime save all callee frames which are used to deliver exceptions.
887           } else if (instrumentation_frame.interpreter_entry_) {
888             ArtMethod* callee =
889                 Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
890             CHECK_EQ(GetMethod(), callee) << "Expected: " << ArtMethod::PrettyMethod(callee)
891                                           << " Found: " << ArtMethod::PrettyMethod(GetMethod());
892           } else if (!instrumentation_frame.method_->IsRuntimeMethod()) {
893             // Trampolines get replaced with their actual method in the stack,
894             // so don't do the check below for runtime methods.
895             // Instrumentation generally doesn't distinguish between a method's obsolete and
896             // non-obsolete version.
897             CHECK_EQ(instrumentation_frame.method_->GetNonObsoleteMethod(),
898                      GetMethod()->GetNonObsoleteMethod())
899                 << "Expected: "
900                 << ArtMethod::PrettyMethod(instrumentation_frame.method_->GetNonObsoleteMethod())
901                 << " Found: " << ArtMethod::PrettyMethod(GetMethod()->GetNonObsoleteMethod());
902           }
903           return_pc = instrumentation_frame.return_pc_;
904         }
905 
906         cur_quick_frame_pc_ = return_pc;
907         uint8_t* next_frame = reinterpret_cast<uint8_t*>(cur_quick_frame_) + frame_size;
908         cur_quick_frame_ = reinterpret_cast<ArtMethod**>(next_frame);
909 
910         if (kDebugStackWalk) {
911           LOG(INFO) << ArtMethod::PrettyMethod(method) << "@" << method << " size=" << frame_size
912               << std::boolalpha
913               << " optimized=" << (cur_oat_quick_method_header_ != nullptr &&
914                                    cur_oat_quick_method_header_->IsOptimized())
915               << " native=" << method->IsNative()
916               << std::noboolalpha
917               << " entrypoints=" << method->GetEntryPointFromQuickCompiledCode()
918               << "," << (method->IsNative() ? method->GetEntryPointFromJni() : nullptr)
919               << " next=" << *cur_quick_frame_;
920         }
921 
922         if (kCount == CountTransitions::kYes || !method->IsRuntimeMethod()) {
923           cur_depth_++;
924         }
925         method = *cur_quick_frame_;
926       }
927       // We reached a transition frame, it doesn't have a method header.
928       cur_oat_quick_method_header_ = nullptr;
929     } else if (cur_shadow_frame_ != nullptr) {
930       do {
931         ValidateFrame();
932         bool should_continue = VisitFrame();
933         if (UNLIKELY(!should_continue)) {
934           return;
935         }
936         cur_depth_++;
937         cur_shadow_frame_ = cur_shadow_frame_->GetLink();
938       } while (cur_shadow_frame_ != nullptr);
939     }
940     if (include_transitions) {
941       bool should_continue = VisitFrame();
942       if (!should_continue) {
943         return;
944       }
945     }
946     if (kCount == CountTransitions::kYes) {
947       cur_depth_++;
948     }
949   }
950   if (num_frames_ != 0) {
951     CHECK_EQ(cur_depth_, num_frames_);
952   }
953 }
954 
955 template void StackVisitor::WalkStack<StackVisitor::CountTransitions::kYes>(bool);
956 template void StackVisitor::WalkStack<StackVisitor::CountTransitions::kNo>(bool);
957 
958 }  // namespace art
959