stack.cc revision fead4e4f397455aa31905b2982d4d861126ab89d
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
19#include "arch/context.h"
20#include "base/hex_dump.h"
21#include "entrypoints/runtime_asm_entrypoints.h"
22#include "mirror/art_method-inl.h"
23#include "mirror/class-inl.h"
24#include "mirror/object.h"
25#include "mirror/object-inl.h"
26#include "mirror/object_array-inl.h"
27#include "quick/quick_method_frame_info.h"
28#include "runtime.h"
29#include "thread.h"
30#include "thread_list.h"
31#include "verify_object-inl.h"
32#include "vmap_table.h"
33
34namespace art {
35
36mirror::Object* ShadowFrame::GetThisObject() const {
37  mirror::ArtMethod* m = GetMethod();
38  if (m->IsStatic()) {
39    return NULL;
40  } else if (m->IsNative()) {
41    return GetVRegReference(0);
42  } else {
43    const DexFile::CodeItem* code_item = m->GetCodeItem();
44    CHECK(code_item != NULL) << PrettyMethod(m);
45    uint16_t reg = code_item->registers_size_ - code_item->ins_size_;
46    return GetVRegReference(reg);
47  }
48}
49
50mirror::Object* ShadowFrame::GetThisObject(uint16_t num_ins) const {
51  mirror::ArtMethod* m = GetMethod();
52  if (m->IsStatic()) {
53    return NULL;
54  } else {
55    return GetVRegReference(NumberOfVRegs() - num_ins);
56  }
57}
58
59size_t ManagedStack::NumJniShadowFrameReferences() const {
60  size_t count = 0;
61  for (const ManagedStack* current_fragment = this; current_fragment != NULL;
62       current_fragment = current_fragment->GetLink()) {
63    for (ShadowFrame* current_frame = current_fragment->top_shadow_frame_; current_frame != NULL;
64         current_frame = current_frame->GetLink()) {
65      if (current_frame->GetMethod()->IsNative()) {
66        // The JNI ShadowFrame only contains references. (For indirect reference.)
67        count += current_frame->NumberOfVRegs();
68      }
69    }
70  }
71  return count;
72}
73
74bool ManagedStack::ShadowFramesContain(StackReference<mirror::Object>* shadow_frame_entry) const {
75  for (const ManagedStack* current_fragment = this; current_fragment != NULL;
76       current_fragment = current_fragment->GetLink()) {
77    for (ShadowFrame* current_frame = current_fragment->top_shadow_frame_; current_frame != NULL;
78         current_frame = current_frame->GetLink()) {
79      if (current_frame->Contains(shadow_frame_entry)) {
80        return true;
81      }
82    }
83  }
84  return false;
85}
86
87StackVisitor::StackVisitor(Thread* thread, Context* context)
88    : thread_(thread), cur_shadow_frame_(NULL),
89      cur_quick_frame_(NULL), cur_quick_frame_pc_(0), num_frames_(0), cur_depth_(0),
90      context_(context) {
91  DCHECK(thread == Thread::Current() || thread->IsSuspended()) << *thread;
92}
93
94StackVisitor::StackVisitor(Thread* thread, Context* context, size_t num_frames)
95    : thread_(thread), cur_shadow_frame_(NULL),
96      cur_quick_frame_(NULL), cur_quick_frame_pc_(0), num_frames_(num_frames), cur_depth_(0),
97      context_(context) {
98  DCHECK(thread == Thread::Current() || thread->IsSuspended()) << *thread;
99}
100
101uint32_t StackVisitor::GetDexPc(bool abort_on_failure) const {
102  if (cur_shadow_frame_ != NULL) {
103    return cur_shadow_frame_->GetDexPC();
104  } else if (cur_quick_frame_ != NULL) {
105    return GetMethod()->ToDexPc(cur_quick_frame_pc_, abort_on_failure);
106  } else {
107    return 0;
108  }
109}
110
111extern "C" mirror::Object* artQuickGetProxyThisObject(StackReference<mirror::ArtMethod>* sp)
112    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
113
114mirror::Object* StackVisitor::GetThisObject() const {
115  mirror::ArtMethod* m = GetMethod();
116  if (m->IsStatic()) {
117    return nullptr;
118  } else if (m->IsNative()) {
119    if (cur_quick_frame_ != nullptr) {
120      HandleScope* hs = reinterpret_cast<HandleScope*>(
121          reinterpret_cast<char*>(cur_quick_frame_) + m->GetHandleScopeOffset().SizeValue());
122      return hs->GetReference(0);
123    } else {
124      return cur_shadow_frame_->GetVRegReference(0);
125    }
126  } else if (m->IsProxyMethod()) {
127    if (cur_quick_frame_ != nullptr) {
128      return artQuickGetProxyThisObject(cur_quick_frame_);
129    } else {
130      return cur_shadow_frame_->GetVRegReference(0);
131    }
132  } else {
133    const DexFile::CodeItem* code_item = m->GetCodeItem();
134    if (code_item == nullptr) {
135      UNIMPLEMENTED(ERROR) << "Failed to determine this object of abstract or proxy method: "
136          << PrettyMethod(m);
137      return nullptr;
138    } else {
139      uint16_t reg = code_item->registers_size_ - code_item->ins_size_;
140      uint32_t value = 0;
141      bool success = GetVReg(m, reg, kReferenceVReg, &value);
142      // We currently always guarantee the `this` object is live throughout the method.
143      CHECK(success) << "Failed to read the this object in " << PrettyMethod(m);
144      return reinterpret_cast<mirror::Object*>(value);
145    }
146  }
147}
148
149size_t StackVisitor::GetNativePcOffset() const {
150  DCHECK(!IsShadowFrame());
151  return GetMethod()->NativeQuickPcOffset(cur_quick_frame_pc_);
152}
153
154bool StackVisitor::GetVReg(mirror::ArtMethod* m, uint16_t vreg, VRegKind kind,
155                           uint32_t* val) const {
156  if (cur_quick_frame_ != nullptr) {
157    DCHECK(context_ != nullptr);  // You can't reliably read registers without a context.
158    DCHECK(m == GetMethod());
159    if (m->IsOptimized(sizeof(void*))) {
160      return GetVRegFromOptimizedCode(m, vreg, kind, val);
161    } else {
162      return GetVRegFromQuickCode(m, vreg, kind, val);
163    }
164  } else {
165    DCHECK(cur_shadow_frame_ != nullptr);
166    *val = cur_shadow_frame_->GetVReg(vreg);
167    return true;
168  }
169}
170
171bool StackVisitor::GetVRegFromQuickCode(mirror::ArtMethod* m, uint16_t vreg, VRegKind kind,
172                                        uint32_t* val) const {
173  const void* code_pointer = m->GetQuickOatCodePointer(sizeof(void*));
174  DCHECK(code_pointer != nullptr);
175  const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*)));
176  QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
177  uint32_t vmap_offset;
178  // TODO: IsInContext stops before spotting floating point registers.
179  if (vmap_table.IsInContext(vreg, kind, &vmap_offset)) {
180    bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
181    uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
182    uint32_t reg = vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
183    return GetRegisterIfAccessible(reg, kind, val);
184  } else {
185    const DexFile::CodeItem* code_item = m->GetCodeItem();
186    DCHECK(code_item != nullptr) << PrettyMethod(m);  // Can't be NULL or how would we compile
187                                                      // its instructions?
188    *val = *GetVRegAddrFromQuickCode(cur_quick_frame_, code_item, frame_info.CoreSpillMask(),
189                                     frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), vreg);
190    return true;
191  }
192}
193
194bool StackVisitor::GetVRegFromOptimizedCode(mirror::ArtMethod* m, uint16_t vreg, VRegKind kind,
195                                            uint32_t* val) const {
196  const void* code_pointer = m->GetQuickOatCodePointer(sizeof(void*));
197  DCHECK(code_pointer != nullptr);
198  uint32_t native_pc_offset = m->NativeQuickPcOffset(cur_quick_frame_pc_);
199  CodeInfo code_info = m->GetOptimizedCodeInfo();
200  StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
201  const DexFile::CodeItem* code_item = m->GetCodeItem();
202  DCHECK(code_item != nullptr) << PrettyMethod(m);  // Can't be NULL or how would we compile
203                                                    // its instructions?
204  DCHECK_LT(vreg, code_item->registers_size_);
205  uint16_t number_of_dex_registers = code_item->registers_size_;
206  DexRegisterMap dex_register_map =
207      code_info.GetDexRegisterMapOf(stack_map, number_of_dex_registers);
208  DexRegisterLocation::Kind location_kind =
209      dex_register_map.GetLocationKind(vreg, number_of_dex_registers);
210  switch (location_kind) {
211    case DexRegisterLocation::Kind::kInStack: {
212      const int32_t offset = dex_register_map.GetStackOffsetInBytes(vreg, number_of_dex_registers);
213      const uint8_t* addr = reinterpret_cast<const uint8_t*>(cur_quick_frame_) + offset;
214      *val = *reinterpret_cast<const uint32_t*>(addr);
215      return true;
216    }
217    case DexRegisterLocation::Kind::kInRegister:
218    case DexRegisterLocation::Kind::kInFpuRegister: {
219      uint32_t reg = dex_register_map.GetMachineRegister(vreg, number_of_dex_registers);
220      return GetRegisterIfAccessible(reg, kind, val);
221    }
222    case DexRegisterLocation::Kind::kConstant:
223      *val = dex_register_map.GetConstant(vreg, number_of_dex_registers);
224      return true;
225    case DexRegisterLocation::Kind::kNone:
226      return false;
227    default:
228      LOG(FATAL)
229          << "Unexpected location kind"
230          << DexRegisterLocation::PrettyDescriptor(
231                dex_register_map.GetLocationInternalKind(vreg, number_of_dex_registers));
232      UNREACHABLE();
233  }
234}
235
236bool StackVisitor::GetRegisterIfAccessible(uint32_t reg, VRegKind kind, uint32_t* val) const {
237  const bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
238  if (!IsAccessibleRegister(reg, is_float)) {
239    return false;
240  }
241  uintptr_t ptr_val = GetRegister(reg, is_float);
242  const bool target64 = Is64BitInstructionSet(kRuntimeISA);
243  if (target64) {
244    const bool wide_lo = (kind == kLongLoVReg) || (kind == kDoubleLoVReg);
245    const bool wide_hi = (kind == kLongHiVReg) || (kind == kDoubleHiVReg);
246    int64_t value_long = static_cast<int64_t>(ptr_val);
247    if (wide_lo) {
248      ptr_val = static_cast<uintptr_t>(Low32Bits(value_long));
249    } else if (wide_hi) {
250      ptr_val = static_cast<uintptr_t>(High32Bits(value_long));
251    }
252  }
253  *val = ptr_val;
254  return true;
255}
256
257bool StackVisitor::GetVRegPair(mirror::ArtMethod* m, uint16_t vreg, VRegKind kind_lo,
258                               VRegKind kind_hi, uint64_t* val) const {
259  if (kind_lo == kLongLoVReg) {
260    DCHECK_EQ(kind_hi, kLongHiVReg);
261  } else if (kind_lo == kDoubleLoVReg) {
262    DCHECK_EQ(kind_hi, kDoubleHiVReg);
263  } else {
264    LOG(FATAL) << "Expected long or double: kind_lo=" << kind_lo << ", kind_hi=" << kind_hi;
265    UNREACHABLE();
266  }
267  if (cur_quick_frame_ != nullptr) {
268    DCHECK(context_ != nullptr);  // You can't reliably read registers without a context.
269    DCHECK(m == GetMethod());
270    if (m->IsOptimized(sizeof(void*))) {
271      return GetVRegPairFromOptimizedCode(m, vreg, kind_lo, kind_hi, val);
272    } else {
273      return GetVRegPairFromQuickCode(m, vreg, kind_lo, kind_hi, val);
274    }
275  } else {
276    DCHECK(cur_shadow_frame_ != nullptr);
277    *val = cur_shadow_frame_->GetVRegLong(vreg);
278    return true;
279  }
280}
281
282bool StackVisitor::GetVRegPairFromQuickCode(mirror::ArtMethod* m, uint16_t vreg, VRegKind kind_lo,
283                                            VRegKind kind_hi, uint64_t* val) const {
284  const void* code_pointer = m->GetQuickOatCodePointer(sizeof(void*));
285  DCHECK(code_pointer != nullptr);
286  const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*)));
287  QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
288  uint32_t vmap_offset_lo, vmap_offset_hi;
289  // TODO: IsInContext stops before spotting floating point registers.
290  if (vmap_table.IsInContext(vreg, kind_lo, &vmap_offset_lo) &&
291      vmap_table.IsInContext(vreg + 1, kind_hi, &vmap_offset_hi)) {
292    bool is_float = (kind_lo == kDoubleLoVReg);
293    uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
294    uint32_t reg_lo = vmap_table.ComputeRegister(spill_mask, vmap_offset_lo, kind_lo);
295    uint32_t reg_hi = vmap_table.ComputeRegister(spill_mask, vmap_offset_hi, kind_hi);
296    return GetRegisterPairIfAccessible(reg_lo, reg_hi, kind_lo, val);
297  } else {
298    const DexFile::CodeItem* code_item = m->GetCodeItem();
299    DCHECK(code_item != nullptr) << PrettyMethod(m);  // Can't be NULL or how would we compile
300                                                      // its instructions?
301    uint32_t* addr = GetVRegAddrFromQuickCode(
302        cur_quick_frame_, code_item, frame_info.CoreSpillMask(),
303        frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), vreg);
304    *val = *reinterpret_cast<uint64_t*>(addr);
305    return true;
306  }
307}
308
309bool StackVisitor::GetVRegPairFromOptimizedCode(mirror::ArtMethod* m, uint16_t vreg,
310                                                VRegKind kind_lo, VRegKind kind_hi,
311                                                uint64_t* val) const {
312  uint32_t low_32bits;
313  uint32_t high_32bits;
314  bool success = GetVRegFromOptimizedCode(m, vreg, kind_lo, &low_32bits);
315  success &= GetVRegFromOptimizedCode(m, vreg + 1, kind_hi, &high_32bits);
316  if (success) {
317    *val = (static_cast<uint64_t>(high_32bits) << 32) | static_cast<uint64_t>(low_32bits);
318  }
319  return success;
320}
321
322bool StackVisitor::GetRegisterPairIfAccessible(uint32_t reg_lo, uint32_t reg_hi,
323                                               VRegKind kind_lo, uint64_t* val) const {
324  const bool is_float = (kind_lo == kDoubleLoVReg);
325  if (!IsAccessibleRegister(reg_lo, is_float) || !IsAccessibleRegister(reg_hi, is_float)) {
326    return false;
327  }
328  uintptr_t ptr_val_lo = GetRegister(reg_lo, is_float);
329  uintptr_t ptr_val_hi = GetRegister(reg_hi, is_float);
330  bool target64 = Is64BitInstructionSet(kRuntimeISA);
331  if (target64) {
332    int64_t value_long_lo = static_cast<int64_t>(ptr_val_lo);
333    int64_t value_long_hi = static_cast<int64_t>(ptr_val_hi);
334    ptr_val_lo = static_cast<uintptr_t>(Low32Bits(value_long_lo));
335    ptr_val_hi = static_cast<uintptr_t>(High32Bits(value_long_hi));
336  }
337  *val = (static_cast<uint64_t>(ptr_val_hi) << 32) | static_cast<uint32_t>(ptr_val_lo);
338  return true;
339}
340
341bool StackVisitor::SetVReg(mirror::ArtMethod* m, uint16_t vreg, uint32_t new_value,
342                           VRegKind kind) {
343  if (cur_quick_frame_ != nullptr) {
344      DCHECK(context_ != nullptr);  // You can't reliably write registers without a context.
345      DCHECK(m == GetMethod());
346      if (m->IsOptimized(sizeof(void*))) {
347        return SetVRegFromOptimizedCode(m, vreg, new_value, kind);
348      } else {
349        return SetVRegFromQuickCode(m, vreg, new_value, kind);
350      }
351    } else {
352      cur_shadow_frame_->SetVReg(vreg, new_value);
353      return true;
354    }
355}
356
357bool StackVisitor::SetVRegFromQuickCode(mirror::ArtMethod* m, uint16_t vreg, uint32_t new_value,
358                                        VRegKind kind) {
359  DCHECK(context_ != nullptr);  // You can't reliably write registers without a context.
360  DCHECK(m == GetMethod());
361  const void* code_pointer = m->GetQuickOatCodePointer(sizeof(void*));
362  DCHECK(code_pointer != nullptr);
363  const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*)));
364  QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
365  uint32_t vmap_offset;
366  // TODO: IsInContext stops before spotting floating point registers.
367  if (vmap_table.IsInContext(vreg, kind, &vmap_offset)) {
368    bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
369    uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
370    uint32_t reg = vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
371    return SetRegisterIfAccessible(reg, new_value, kind);
372  } else {
373    const DexFile::CodeItem* code_item = m->GetCodeItem();
374    DCHECK(code_item != nullptr) << PrettyMethod(m);  // Can't be NULL or how would we compile
375                                                      // its instructions?
376    uint32_t* addr = GetVRegAddrFromQuickCode(
377        cur_quick_frame_, code_item, frame_info.CoreSpillMask(),
378        frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), vreg);
379    *addr = new_value;
380    return true;
381  }
382}
383
384bool StackVisitor::SetVRegFromOptimizedCode(mirror::ArtMethod* m, uint16_t vreg, uint32_t new_value,
385                                            VRegKind kind) {
386  const void* code_pointer = m->GetQuickOatCodePointer(sizeof(void*));
387  DCHECK(code_pointer != nullptr);
388  uint32_t native_pc_offset = m->NativeQuickPcOffset(cur_quick_frame_pc_);
389  CodeInfo code_info = m->GetOptimizedCodeInfo();
390  StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
391  const DexFile::CodeItem* code_item = m->GetCodeItem();
392  DCHECK(code_item != nullptr) << PrettyMethod(m);  // Can't be NULL or how would we compile
393                                                    // its instructions?
394  uint16_t number_of_dex_registers = code_item->registers_size_;
395  DCHECK_LT(vreg, number_of_dex_registers);
396  DexRegisterMap dex_register_map =
397      code_info.GetDexRegisterMapOf(stack_map, number_of_dex_registers);
398  DexRegisterLocation::Kind location_kind =
399      dex_register_map.GetLocationKind(vreg, number_of_dex_registers);
400  uint32_t dex_pc = m->ToDexPc(cur_quick_frame_pc_, false);
401  switch (location_kind) {
402    case DexRegisterLocation::Kind::kInStack: {
403      const int32_t offset = dex_register_map.GetStackOffsetInBytes(vreg, number_of_dex_registers);
404      uint8_t* addr = reinterpret_cast<uint8_t*>(cur_quick_frame_) + offset;
405      *reinterpret_cast<uint32_t*>(addr) = new_value;
406      return true;
407    }
408    case DexRegisterLocation::Kind::kInRegister:
409    case DexRegisterLocation::Kind::kInFpuRegister: {
410      uint32_t reg = dex_register_map.GetMachineRegister(vreg, number_of_dex_registers);
411      return SetRegisterIfAccessible(reg, new_value, kind);
412    }
413    case DexRegisterLocation::Kind::kConstant:
414      LOG(ERROR) << StringPrintf("Cannot change value of DEX register v%u used as a constant at "
415                                 "DEX pc 0x%x (native pc 0x%x) of method %s",
416                                 vreg, dex_pc, native_pc_offset,
417                                 PrettyMethod(cur_quick_frame_->AsMirrorPtr()).c_str());
418      return false;
419    case DexRegisterLocation::Kind::kNone:
420      LOG(ERROR) << StringPrintf("No location for DEX register v%u at DEX pc 0x%x "
421                                 "(native pc 0x%x) of method %s",
422                                 vreg, dex_pc, native_pc_offset,
423                                 PrettyMethod(cur_quick_frame_->AsMirrorPtr()).c_str());
424      return false;
425    default:
426      LOG(FATAL) << StringPrintf("Unknown location for DEX register v%u at DEX pc 0x%x "
427                                 "(native pc 0x%x) of method %s",
428                                 vreg, dex_pc, native_pc_offset,
429                                 PrettyMethod(cur_quick_frame_->AsMirrorPtr()).c_str());
430      UNREACHABLE();
431  }
432}
433
434bool StackVisitor::SetRegisterIfAccessible(uint32_t reg, uint32_t new_value, VRegKind kind) {
435  const bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
436  if (!IsAccessibleRegister(reg, is_float)) {
437    return false;
438  }
439  const bool target64 = Is64BitInstructionSet(kRuntimeISA);
440
441  // Create a new value that can hold both low 32 and high 32 bits, in
442  // case we are running 64 bits.
443  uintptr_t full_new_value = new_value;
444  // Deal with 32 or 64-bit wide registers in a way that builds on all targets.
445  if (target64) {
446    bool wide_lo = (kind == kLongLoVReg) || (kind == kDoubleLoVReg);
447    bool wide_hi = (kind == kLongHiVReg) || (kind == kDoubleHiVReg);
448    if (wide_lo || wide_hi) {
449      uintptr_t old_reg_val = GetRegister(reg, is_float);
450      uint64_t new_vreg_portion = static_cast<uint64_t>(new_value);
451      uint64_t old_reg_val_as_wide = static_cast<uint64_t>(old_reg_val);
452      uint64_t mask = 0xffffffff;
453      if (wide_lo) {
454        mask = mask << 32;
455      } else {
456        new_vreg_portion = new_vreg_portion << 32;
457      }
458      full_new_value = static_cast<uintptr_t>((old_reg_val_as_wide & mask) | new_vreg_portion);
459    }
460  }
461  SetRegister(reg, full_new_value, is_float);
462  return true;
463}
464
465bool StackVisitor::SetVRegPair(mirror::ArtMethod* m, uint16_t vreg, uint64_t new_value,
466                               VRegKind kind_lo, VRegKind kind_hi) {
467  if (kind_lo == kLongLoVReg) {
468    DCHECK_EQ(kind_hi, kLongHiVReg);
469  } else if (kind_lo == kDoubleLoVReg) {
470    DCHECK_EQ(kind_hi, kDoubleHiVReg);
471  } else {
472    LOG(FATAL) << "Expected long or double: kind_lo=" << kind_lo << ", kind_hi=" << kind_hi;
473  }
474  if (cur_quick_frame_ != nullptr) {
475    DCHECK(context_ != nullptr);  // You can't reliably write registers without a context.
476    DCHECK(m == GetMethod());
477    if (m->IsOptimized(sizeof(void*))) {
478      return SetVRegPairFromOptimizedCode(m, vreg, new_value, kind_lo, kind_hi);
479    } else {
480      return SetVRegPairFromQuickCode(m, vreg, new_value, kind_lo, kind_hi);
481    }
482  } else {
483    DCHECK(cur_shadow_frame_ != nullptr);
484    cur_shadow_frame_->SetVRegLong(vreg, new_value);
485    return true;
486  }
487}
488
489bool StackVisitor::SetVRegPairFromQuickCode(mirror::ArtMethod* m, uint16_t vreg, uint64_t new_value,
490                                            VRegKind kind_lo, VRegKind kind_hi) {
491  const void* code_pointer = m->GetQuickOatCodePointer(sizeof(void*));
492  DCHECK(code_pointer != nullptr);
493  const VmapTable vmap_table(m->GetVmapTable(code_pointer, sizeof(void*)));
494  QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
495  uint32_t vmap_offset_lo, vmap_offset_hi;
496  // TODO: IsInContext stops before spotting floating point registers.
497  if (vmap_table.IsInContext(vreg, kind_lo, &vmap_offset_lo) &&
498      vmap_table.IsInContext(vreg + 1, kind_hi, &vmap_offset_hi)) {
499    bool is_float = (kind_lo == kDoubleLoVReg);
500    uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
501    uint32_t reg_lo = vmap_table.ComputeRegister(spill_mask, vmap_offset_lo, kind_lo);
502    uint32_t reg_hi = vmap_table.ComputeRegister(spill_mask, vmap_offset_hi, kind_hi);
503    return SetRegisterPairIfAccessible(reg_lo, reg_hi, new_value, is_float);
504  } else {
505    const DexFile::CodeItem* code_item = m->GetCodeItem();
506    DCHECK(code_item != nullptr) << PrettyMethod(m);  // Can't be NULL or how would we compile
507                                                      // its instructions?
508    uint32_t* addr = GetVRegAddrFromQuickCode(
509        cur_quick_frame_, code_item, frame_info.CoreSpillMask(),
510        frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), vreg);
511    *reinterpret_cast<uint64_t*>(addr) = new_value;
512    return true;
513  }
514}
515
516bool StackVisitor::SetVRegPairFromOptimizedCode(mirror::ArtMethod* m, uint16_t vreg, uint64_t new_value,
517                                                VRegKind kind_lo, VRegKind kind_hi) {
518  uint32_t low_32bits = Low32Bits(new_value);
519  uint32_t high_32bits = High32Bits(new_value);
520  bool success = SetVRegFromOptimizedCode(m, vreg, low_32bits, kind_lo);
521  success &= SetVRegFromOptimizedCode(m, vreg + 1, high_32bits, kind_hi);
522  return success;
523}
524
525bool StackVisitor::SetRegisterPairIfAccessible(uint32_t reg_lo, uint32_t reg_hi,
526                                               uint64_t new_value, bool is_float) {
527  if (!IsAccessibleRegister(reg_lo, is_float) || !IsAccessibleRegister(reg_hi, is_float)) {
528    return false;
529  }
530  uintptr_t new_value_lo = static_cast<uintptr_t>(new_value & 0xFFFFFFFF);
531  uintptr_t new_value_hi = static_cast<uintptr_t>(new_value >> 32);
532  bool target64 = Is64BitInstructionSet(kRuntimeISA);
533  // Deal with 32 or 64-bit wide registers in a way that builds on all targets.
534  if (target64) {
535    DCHECK_EQ(reg_lo, reg_hi);
536    SetRegister(reg_lo, new_value, is_float);
537  } else {
538    SetRegister(reg_lo, new_value_lo, is_float);
539    SetRegister(reg_hi, new_value_hi, is_float);
540  }
541  return true;
542}
543
544bool StackVisitor::IsAccessibleGPR(uint32_t reg) const {
545  DCHECK(context_ != nullptr);
546  return context_->IsAccessibleGPR(reg);
547}
548
549uintptr_t* StackVisitor::GetGPRAddress(uint32_t reg) const {
550  DCHECK(cur_quick_frame_ != nullptr) << "This is a quick frame routine";
551  DCHECK(context_ != nullptr);
552  return context_->GetGPRAddress(reg);
553}
554
555uintptr_t StackVisitor::GetGPR(uint32_t reg) const {
556  DCHECK(cur_quick_frame_ != nullptr) << "This is a quick frame routine";
557  DCHECK(context_ != nullptr);
558  return context_->GetGPR(reg);
559}
560
561void StackVisitor::SetGPR(uint32_t reg, uintptr_t value) {
562  DCHECK(cur_quick_frame_ != nullptr) << "This is a quick frame routine";
563  DCHECK(context_ != nullptr);
564  context_->SetGPR(reg, value);
565}
566
567bool StackVisitor::IsAccessibleFPR(uint32_t reg) const {
568  DCHECK(context_ != nullptr);
569  return context_->IsAccessibleFPR(reg);
570}
571
572uintptr_t StackVisitor::GetFPR(uint32_t reg) const {
573  DCHECK(cur_quick_frame_ != nullptr) << "This is a quick frame routine";
574  DCHECK(context_ != nullptr);
575  return context_->GetFPR(reg);
576}
577
578void StackVisitor::SetFPR(uint32_t reg, uintptr_t value) {
579  DCHECK(cur_quick_frame_ != nullptr) << "This is a quick frame routine";
580  DCHECK(context_ != nullptr);
581  context_->SetFPR(reg, value);
582}
583
584uintptr_t StackVisitor::GetReturnPc() const {
585  uint8_t* sp = reinterpret_cast<uint8_t*>(GetCurrentQuickFrame());
586  DCHECK(sp != NULL);
587  uint8_t* pc_addr = sp + GetMethod()->GetReturnPcOffset().SizeValue();
588  return *reinterpret_cast<uintptr_t*>(pc_addr);
589}
590
591void StackVisitor::SetReturnPc(uintptr_t new_ret_pc) {
592  uint8_t* sp = reinterpret_cast<uint8_t*>(GetCurrentQuickFrame());
593  CHECK(sp != NULL);
594  uint8_t* pc_addr = sp + GetMethod()->GetReturnPcOffset().SizeValue();
595  *reinterpret_cast<uintptr_t*>(pc_addr) = new_ret_pc;
596}
597
598size_t StackVisitor::ComputeNumFrames(Thread* thread) {
599  struct NumFramesVisitor : public StackVisitor {
600    explicit NumFramesVisitor(Thread* thread_in)
601        : StackVisitor(thread_in, NULL), frames(0) {}
602
603    bool VisitFrame() OVERRIDE {
604      frames++;
605      return true;
606    }
607
608    size_t frames;
609  };
610  NumFramesVisitor visitor(thread);
611  visitor.WalkStack(true);
612  return visitor.frames;
613}
614
615bool StackVisitor::GetNextMethodAndDexPc(mirror::ArtMethod** next_method, uint32_t* next_dex_pc) {
616  struct HasMoreFramesVisitor : public StackVisitor {
617    explicit HasMoreFramesVisitor(Thread* thread, size_t num_frames, size_t frame_height)
618        : StackVisitor(thread, nullptr, num_frames), frame_height_(frame_height),
619          found_frame_(false), has_more_frames_(false), next_method_(nullptr), next_dex_pc_(0) {
620    }
621
622    bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
623      if (found_frame_) {
624        mirror::ArtMethod* method = GetMethod();
625        if (method != nullptr && !method->IsRuntimeMethod()) {
626          has_more_frames_ = true;
627          next_method_ = method;
628          next_dex_pc_ = GetDexPc();
629          return false;  // End stack walk once next method is found.
630        }
631      } else if (GetFrameHeight() == frame_height_) {
632        found_frame_ = true;
633      }
634      return true;
635    }
636
637    size_t frame_height_;
638    bool found_frame_;
639    bool has_more_frames_;
640    mirror::ArtMethod* next_method_;
641    uint32_t next_dex_pc_;
642  };
643  HasMoreFramesVisitor visitor(thread_, GetNumFrames(), GetFrameHeight());
644  visitor.WalkStack(true);
645  *next_method = visitor.next_method_;
646  *next_dex_pc = visitor.next_dex_pc_;
647  return visitor.has_more_frames_;
648}
649
650void StackVisitor::DescribeStack(Thread* thread) {
651  struct DescribeStackVisitor : public StackVisitor {
652    explicit DescribeStackVisitor(Thread* thread_in)
653        : StackVisitor(thread_in, NULL) {}
654
655    bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
656      LOG(INFO) << "Frame Id=" << GetFrameId() << " " << DescribeLocation();
657      return true;
658    }
659  };
660  DescribeStackVisitor visitor(thread);
661  visitor.WalkStack(true);
662}
663
664std::string StackVisitor::DescribeLocation() const {
665  std::string result("Visiting method '");
666  mirror::ArtMethod* m = GetMethod();
667  if (m == NULL) {
668    return "upcall";
669  }
670  result += PrettyMethod(m);
671  result += StringPrintf("' at dex PC 0x%04x", GetDexPc());
672  if (!IsShadowFrame()) {
673    result += StringPrintf(" (native PC %p)", reinterpret_cast<void*>(GetCurrentQuickFramePc()));
674  }
675  return result;
676}
677
678static instrumentation::InstrumentationStackFrame& GetInstrumentationStackFrame(Thread* thread,
679                                                                                uint32_t depth) {
680  CHECK_LT(depth, thread->GetInstrumentationStack()->size());
681  return thread->GetInstrumentationStack()->at(depth);
682}
683
684void StackVisitor::SanityCheckFrame() const {
685  if (kIsDebugBuild) {
686    mirror::ArtMethod* method = GetMethod();
687    CHECK_EQ(method->GetClass(), mirror::ArtMethod::GetJavaLangReflectArtMethod());
688    if (cur_quick_frame_ != nullptr) {
689      method->AssertPcIsWithinQuickCode(cur_quick_frame_pc_);
690      // Frame sanity.
691      size_t frame_size = method->GetFrameSizeInBytes();
692      CHECK_NE(frame_size, 0u);
693      // A rough guess at an upper size we expect to see for a frame.
694      // 256 registers
695      // 2 words HandleScope overhead
696      // 3+3 register spills
697      // TODO: this seems architecture specific for the case of JNI frames.
698      // TODO: 083-compiler-regressions ManyFloatArgs shows this estimate is wrong.
699      // const size_t kMaxExpectedFrameSize = (256 + 2 + 3 + 3) * sizeof(word);
700      const size_t kMaxExpectedFrameSize = 2 * KB;
701      CHECK_LE(frame_size, kMaxExpectedFrameSize);
702      size_t return_pc_offset = method->GetReturnPcOffset().SizeValue();
703      CHECK_LT(return_pc_offset, frame_size);
704    }
705  }
706}
707
708void StackVisitor::WalkStack(bool include_transitions) {
709  DCHECK(thread_ == Thread::Current() || thread_->IsSuspended());
710  CHECK_EQ(cur_depth_, 0U);
711  bool exit_stubs_installed = Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled();
712  uint32_t instrumentation_stack_depth = 0;
713
714  for (const ManagedStack* current_fragment = thread_->GetManagedStack(); current_fragment != NULL;
715       current_fragment = current_fragment->GetLink()) {
716    cur_shadow_frame_ = current_fragment->GetTopShadowFrame();
717    cur_quick_frame_ = current_fragment->GetTopQuickFrame();
718    cur_quick_frame_pc_ = 0;
719
720    if (cur_quick_frame_ != NULL) {  // Handle quick stack frames.
721      // Can't be both a shadow and a quick fragment.
722      DCHECK(current_fragment->GetTopShadowFrame() == NULL);
723      mirror::ArtMethod* method = cur_quick_frame_->AsMirrorPtr();
724      while (method != NULL) {
725        SanityCheckFrame();
726        bool should_continue = VisitFrame();
727        if (UNLIKELY(!should_continue)) {
728          return;
729        }
730
731        if (context_ != NULL) {
732          context_->FillCalleeSaves(*this);
733        }
734        size_t frame_size = method->GetFrameSizeInBytes();
735        // Compute PC for next stack frame from return PC.
736        size_t return_pc_offset = method->GetReturnPcOffset(frame_size).SizeValue();
737        uint8_t* return_pc_addr = reinterpret_cast<uint8_t*>(cur_quick_frame_) + return_pc_offset;
738        uintptr_t return_pc = *reinterpret_cast<uintptr_t*>(return_pc_addr);
739        if (UNLIKELY(exit_stubs_installed)) {
740          // While profiling, the return pc is restored from the side stack, except when walking
741          // the stack for an exception where the side stack will be unwound in VisitFrame.
742          if (reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()) == return_pc) {
743            const instrumentation::InstrumentationStackFrame& instrumentation_frame =
744                GetInstrumentationStackFrame(thread_, instrumentation_stack_depth);
745            instrumentation_stack_depth++;
746            if (GetMethod() == Runtime::Current()->GetCalleeSaveMethod(Runtime::kSaveAll)) {
747              // Skip runtime save all callee frames which are used to deliver exceptions.
748            } else if (instrumentation_frame.interpreter_entry_) {
749              mirror::ArtMethod* callee = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
750              CHECK_EQ(GetMethod(), callee) << "Expected: " << PrettyMethod(callee) << " Found: "
751                                            << PrettyMethod(GetMethod());
752            } else if (instrumentation_frame.method_ != GetMethod()) {
753              LOG(FATAL)  << "Expected: " << PrettyMethod(instrumentation_frame.method_)
754                          << " Found: " << PrettyMethod(GetMethod());
755            }
756            if (num_frames_ != 0) {
757              // Check agreement of frame Ids only if num_frames_ is computed to avoid infinite
758              // recursion.
759              CHECK(instrumentation_frame.frame_id_ == GetFrameId())
760                    << "Expected: " << instrumentation_frame.frame_id_
761                    << " Found: " << GetFrameId();
762            }
763            return_pc = instrumentation_frame.return_pc_;
764          }
765        }
766        cur_quick_frame_pc_ = return_pc;
767        uint8_t* next_frame = reinterpret_cast<uint8_t*>(cur_quick_frame_) + frame_size;
768        cur_quick_frame_ = reinterpret_cast<StackReference<mirror::ArtMethod>*>(next_frame);
769        cur_depth_++;
770        method = cur_quick_frame_->AsMirrorPtr();
771      }
772    } else if (cur_shadow_frame_ != NULL) {
773      do {
774        SanityCheckFrame();
775        bool should_continue = VisitFrame();
776        if (UNLIKELY(!should_continue)) {
777          return;
778        }
779        cur_depth_++;
780        cur_shadow_frame_ = cur_shadow_frame_->GetLink();
781      } while (cur_shadow_frame_ != NULL);
782    }
783    if (include_transitions) {
784      bool should_continue = VisitFrame();
785      if (!should_continue) {
786        return;
787      }
788    }
789    cur_depth_++;
790  }
791  if (num_frames_ != 0) {
792    CHECK_EQ(cur_depth_, num_frames_);
793  }
794}
795
796void JavaFrameRootInfo::Describe(std::ostream& os) const {
797  const StackVisitor* visitor = stack_visitor_;
798  CHECK(visitor != nullptr);
799  os << "Type=" << GetType() << " thread_id=" << GetThreadId() << " location=" <<
800      visitor->DescribeLocation() << " vreg=" << vreg_;
801}
802
803}  // namespace art
804