stack.cc revision 4e30541a92381fb280cd0be9a1763b713ee4d64c
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 "mirror/art_method-inl.h"
20#include "mirror/class-inl.h"
21#include "mirror/object.h"
22#include "mirror/object-inl.h"
23#include "mirror/object_array-inl.h"
24#include "object_utils.h"
25#include "runtime.h"
26#include "thread_list.h"
27#include "throw_location.h"
28#include "verify_object-inl.h"
29#include "vmap_table.h"
30
31namespace art {
32
33mirror::Object* ShadowFrame::GetThisObject() const {
34  mirror::ArtMethod* m = GetMethod();
35  if (m->IsStatic()) {
36    return NULL;
37  } else if (m->IsNative()) {
38    return GetVRegReference(0);
39  } else {
40    const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
41    CHECK(code_item != NULL) << PrettyMethod(m);
42    uint16_t reg = code_item->registers_size_ - code_item->ins_size_;
43    return GetVRegReference(reg);
44  }
45}
46
47mirror::Object* ShadowFrame::GetThisObject(uint16_t num_ins) const {
48  mirror::ArtMethod* m = GetMethod();
49  if (m->IsStatic()) {
50    return NULL;
51  } else {
52    return GetVRegReference(NumberOfVRegs() - num_ins);
53  }
54}
55
56ThrowLocation ShadowFrame::GetCurrentLocationForThrow() const {
57  return ThrowLocation(GetThisObject(), GetMethod(), GetDexPC());
58}
59
60size_t ManagedStack::NumJniShadowFrameReferences() const {
61  size_t count = 0;
62  for (const ManagedStack* current_fragment = this; current_fragment != NULL;
63       current_fragment = current_fragment->GetLink()) {
64    for (ShadowFrame* current_frame = current_fragment->top_shadow_frame_; current_frame != NULL;
65         current_frame = current_frame->GetLink()) {
66      if (current_frame->GetMethod()->IsNative()) {
67        // The JNI ShadowFrame only contains references. (For indirect reference.)
68        count += current_frame->NumberOfVRegs();
69      }
70    }
71  }
72  return count;
73}
74
75bool ManagedStack::ShadowFramesContain(StackReference<mirror::Object>* shadow_frame_entry) const {
76  for (const ManagedStack* current_fragment = this; current_fragment != NULL;
77       current_fragment = current_fragment->GetLink()) {
78    for (ShadowFrame* current_frame = current_fragment->top_shadow_frame_; current_frame != NULL;
79         current_frame = current_frame->GetLink()) {
80      if (current_frame->Contains(shadow_frame_entry)) {
81        return true;
82      }
83    }
84  }
85  return false;
86}
87
88StackVisitor::StackVisitor(Thread* thread, Context* context)
89    : thread_(thread), cur_shadow_frame_(NULL),
90      cur_quick_frame_(NULL), cur_quick_frame_pc_(0), num_frames_(0), cur_depth_(0),
91      context_(context) {
92  DCHECK(thread == Thread::Current() || thread->IsSuspended()) << *thread;
93}
94
95uint32_t StackVisitor::GetDexPc() const {
96  if (cur_shadow_frame_ != NULL) {
97    return cur_shadow_frame_->GetDexPC();
98  } else if (cur_quick_frame_ != NULL) {
99    return GetMethod()->ToDexPc(cur_quick_frame_pc_);
100  } else {
101    return 0;
102  }
103}
104
105mirror::Object* StackVisitor::GetThisObject() const {
106  mirror::ArtMethod* m = GetMethod();
107  if (m->IsStatic()) {
108    return NULL;
109  } else if (m->IsNative()) {
110    if (cur_quick_frame_ != NULL) {
111      StackIndirectReferenceTable* sirt =
112          reinterpret_cast<StackIndirectReferenceTable*>(
113              reinterpret_cast<char*>(cur_quick_frame_) +
114              m->GetSirtOffsetInBytes());
115      return sirt->GetReference(0);
116    } else {
117      return cur_shadow_frame_->GetVRegReference(0);
118    }
119  } else {
120    const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
121    if (code_item == NULL) {
122      UNIMPLEMENTED(ERROR) << "Failed to determine this object of abstract or proxy method"
123          << PrettyMethod(m);
124      return NULL;
125    } else {
126      uint16_t reg = code_item->registers_size_ - code_item->ins_size_;
127      return reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
128    }
129  }
130}
131
132size_t StackVisitor::GetNativePcOffset() const {
133  DCHECK(!IsShadowFrame());
134  return GetMethod()->NativePcOffset(cur_quick_frame_pc_);
135}
136
137uint32_t StackVisitor::GetVReg(mirror::ArtMethod* m, uint16_t vreg, VRegKind kind) const {
138  if (cur_quick_frame_ != NULL) {
139    DCHECK(context_ != NULL);  // You can't reliably read registers without a context.
140    DCHECK(m == GetMethod());
141    const VmapTable vmap_table(m->GetVmapTable());
142    uint32_t vmap_offset;
143    // TODO: IsInContext stops before spotting floating point registers.
144    if (vmap_table.IsInContext(vreg, kind, &vmap_offset)) {
145      bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
146      uint32_t spill_mask = is_float ? m->GetFpSpillMask()
147                                     : m->GetCoreSpillMask();
148      return GetGPR(vmap_table.ComputeRegister(spill_mask, vmap_offset, kind));
149    } else {
150      const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
151      DCHECK(code_item != NULL) << PrettyMethod(m);  // Can't be NULL or how would we compile its instructions?
152      size_t frame_size = m->GetFrameSizeInBytes();
153      return *GetVRegAddr(cur_quick_frame_, code_item, m->GetCoreSpillMask(), m->GetFpSpillMask(),
154                          frame_size, vreg);
155    }
156  } else {
157    return cur_shadow_frame_->GetVReg(vreg);
158  }
159}
160
161void StackVisitor::SetVReg(mirror::ArtMethod* m, uint16_t vreg, uint32_t new_value,
162                           VRegKind kind) {
163  if (cur_quick_frame_ != NULL) {
164    DCHECK(context_ != NULL);  // You can't reliably write registers without a context.
165    DCHECK(m == GetMethod());
166    const VmapTable vmap_table(m->GetVmapTable());
167    uint32_t vmap_offset;
168    // TODO: IsInContext stops before spotting floating point registers.
169    if (vmap_table.IsInContext(vreg, kind, &vmap_offset)) {
170      bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
171      uint32_t spill_mask = is_float ? m->GetFpSpillMask() : m->GetCoreSpillMask();
172      const uint32_t reg = vmap_table.ComputeRegister(spill_mask, vmap_offset, kReferenceVReg);
173      SetGPR(reg, new_value);
174    } else {
175      const DexFile::CodeItem* code_item = MethodHelper(m).GetCodeItem();
176      DCHECK(code_item != NULL) << PrettyMethod(m);  // Can't be NULL or how would we compile its instructions?
177      uint32_t core_spills = m->GetCoreSpillMask();
178      uint32_t fp_spills = m->GetFpSpillMask();
179      size_t frame_size = m->GetFrameSizeInBytes();
180      int offset = GetVRegOffset(code_item, core_spills, fp_spills, frame_size, vreg);
181      byte* vreg_addr = reinterpret_cast<byte*>(GetCurrentQuickFrame()) + offset;
182      *reinterpret_cast<uint32_t*>(vreg_addr) = new_value;
183    }
184  } else {
185    return cur_shadow_frame_->SetVReg(vreg, new_value);
186  }
187}
188
189uintptr_t* StackVisitor::GetGPRAddress(uint32_t reg) const {
190  DCHECK(cur_quick_frame_ != NULL) << "This is a quick frame routine";
191  return context_->GetGPRAddress(reg);
192}
193
194uintptr_t StackVisitor::GetGPR(uint32_t reg) const {
195  DCHECK(cur_quick_frame_ != NULL) << "This is a quick frame routine";
196  return context_->GetGPR(reg);
197}
198
199void StackVisitor::SetGPR(uint32_t reg, uintptr_t value) {
200  DCHECK(cur_quick_frame_ != NULL) << "This is a quick frame routine";
201  context_->SetGPR(reg, value);
202}
203
204uintptr_t StackVisitor::GetReturnPc() const {
205  mirror::ArtMethod** sp = GetCurrentQuickFrame();
206  DCHECK(sp != NULL);
207  byte* pc_addr = reinterpret_cast<byte*>(sp) + GetMethod()->GetReturnPcOffsetInBytes();
208  return *reinterpret_cast<uintptr_t*>(pc_addr);
209}
210
211void StackVisitor::SetReturnPc(uintptr_t new_ret_pc) {
212  mirror::ArtMethod** sp = GetCurrentQuickFrame();
213  CHECK(sp != NULL);
214  byte* pc_addr = reinterpret_cast<byte*>(sp) + GetMethod()->GetReturnPcOffsetInBytes();
215  *reinterpret_cast<uintptr_t*>(pc_addr) = new_ret_pc;
216}
217
218size_t StackVisitor::ComputeNumFrames(Thread* thread) {
219  struct NumFramesVisitor : public StackVisitor {
220    explicit NumFramesVisitor(Thread* thread)
221        : StackVisitor(thread, NULL), frames(0) {}
222
223    virtual bool VisitFrame() {
224      frames++;
225      return true;
226    }
227
228    size_t frames;
229  };
230  NumFramesVisitor visitor(thread);
231  visitor.WalkStack(true);
232  return visitor.frames;
233}
234
235void StackVisitor::DescribeStack(Thread* thread) {
236  struct DescribeStackVisitor : public StackVisitor {
237    explicit DescribeStackVisitor(Thread* thread)
238        : StackVisitor(thread, NULL) {}
239
240    virtual bool VisitFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
241      LOG(INFO) << "Frame Id=" << GetFrameId() << " " << DescribeLocation();
242      return true;
243    }
244  };
245  DescribeStackVisitor visitor(thread);
246  visitor.WalkStack(true);
247}
248
249std::string StackVisitor::DescribeLocation() const {
250  std::string result("Visiting method '");
251  mirror::ArtMethod* m = GetMethod();
252  if (m == NULL) {
253    return "upcall";
254  }
255  result += PrettyMethod(m);
256  result += StringPrintf("' at dex PC 0x%04x", GetDexPc());
257  if (!IsShadowFrame()) {
258    result += StringPrintf(" (native PC %p)", reinterpret_cast<void*>(GetCurrentQuickFramePc()));
259  }
260  return result;
261}
262
263instrumentation::InstrumentationStackFrame& StackVisitor::GetInstrumentationStackFrame(uint32_t depth) const {
264  CHECK_LT(depth, thread_->GetInstrumentationStack()->size());
265  return thread_->GetInstrumentationStack()->at(depth);
266}
267
268void StackVisitor::SanityCheckFrame() const {
269  if (kIsDebugBuild) {
270    mirror::ArtMethod* method = GetMethod();
271    CHECK(method->GetClass() == mirror::ArtMethod::GetJavaLangReflectArtMethod());
272    if (cur_quick_frame_ != nullptr) {
273      method->AssertPcIsWithinQuickCode(cur_quick_frame_pc_);
274      // Frame sanity.
275      size_t frame_size = method->GetFrameSizeInBytes();
276      CHECK_NE(frame_size, 0u);
277      // A rough guess at an upper size we expect to see for a frame. The 256 is
278      // a dex register limit. The 16 incorporates callee save spills and
279      // outgoing argument set up.
280      const size_t kMaxExpectedFrameSize = 256 * sizeof(word) + 16;
281      CHECK_LE(frame_size, kMaxExpectedFrameSize);
282      size_t return_pc_offset = method->GetReturnPcOffsetInBytes();
283      CHECK_LT(return_pc_offset, frame_size);
284    }
285  }
286}
287
288void StackVisitor::WalkStack(bool include_transitions) {
289  DCHECK(thread_ == Thread::Current() || thread_->IsSuspended());
290  CHECK_EQ(cur_depth_, 0U);
291  bool exit_stubs_installed = Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled();
292  uint32_t instrumentation_stack_depth = 0;
293  for (const ManagedStack* current_fragment = thread_->GetManagedStack(); current_fragment != NULL;
294       current_fragment = current_fragment->GetLink()) {
295    cur_shadow_frame_ = current_fragment->GetTopShadowFrame();
296    cur_quick_frame_ = current_fragment->GetTopQuickFrame();
297    cur_quick_frame_pc_ = current_fragment->GetTopQuickFramePc();
298    if (cur_quick_frame_ != NULL) {  // Handle quick stack frames.
299      // Can't be both a shadow and a quick fragment.
300      DCHECK(current_fragment->GetTopShadowFrame() == NULL);
301      mirror::ArtMethod* method = *cur_quick_frame_;
302      while (method != NULL) {
303        SanityCheckFrame();
304        bool should_continue = VisitFrame();
305        if (UNLIKELY(!should_continue)) {
306          return;
307        }
308        if (context_ != NULL) {
309          context_->FillCalleeSaves(*this);
310        }
311        size_t frame_size = method->GetFrameSizeInBytes();
312        // Compute PC for next stack frame from return PC.
313        size_t return_pc_offset = method->GetReturnPcOffsetInBytes();
314        byte* return_pc_addr = reinterpret_cast<byte*>(cur_quick_frame_) + return_pc_offset;
315        uintptr_t return_pc = *reinterpret_cast<uintptr_t*>(return_pc_addr);
316        if (UNLIKELY(exit_stubs_installed)) {
317          // While profiling, the return pc is restored from the side stack, except when walking
318          // the stack for an exception where the side stack will be unwound in VisitFrame.
319          if (GetQuickInstrumentationExitPc() == return_pc) {
320            const instrumentation::InstrumentationStackFrame& instrumentation_frame =
321                GetInstrumentationStackFrame(instrumentation_stack_depth);
322            instrumentation_stack_depth++;
323            if (GetMethod() == Runtime::Current()->GetCalleeSaveMethod(Runtime::kSaveAll)) {
324              // Skip runtime save all callee frames which are used to deliver exceptions.
325            } else if (instrumentation_frame.interpreter_entry_) {
326              mirror::ArtMethod* callee = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
327              CHECK_EQ(GetMethod(), callee) << "Expected: " << PrettyMethod(callee) << " Found: "
328                                            << PrettyMethod(GetMethod());
329            } else if (instrumentation_frame.method_ != GetMethod()) {
330              LOG(FATAL)  << "Expected: " << PrettyMethod(instrumentation_frame.method_)
331                          << " Found: " << PrettyMethod(GetMethod());
332            }
333            if (num_frames_ != 0) {
334              // Check agreement of frame Ids only if num_frames_ is computed to avoid infinite
335              // recursion.
336              CHECK(instrumentation_frame.frame_id_ == GetFrameId())
337                    << "Expected: " << instrumentation_frame.frame_id_
338                    << " Found: " << GetFrameId();
339            }
340            return_pc = instrumentation_frame.return_pc_;
341          }
342        }
343        cur_quick_frame_pc_ = return_pc;
344        byte* next_frame = reinterpret_cast<byte*>(cur_quick_frame_) + frame_size;
345        cur_quick_frame_ = reinterpret_cast<mirror::ArtMethod**>(next_frame);
346        cur_depth_++;
347        method = *cur_quick_frame_;
348      }
349    } else if (cur_shadow_frame_ != NULL) {
350      do {
351        SanityCheckFrame();
352        bool should_continue = VisitFrame();
353        if (UNLIKELY(!should_continue)) {
354          return;
355        }
356        cur_depth_++;
357        cur_shadow_frame_ = cur_shadow_frame_->GetLink();
358      } while (cur_shadow_frame_ != NULL);
359    }
360    if (include_transitions) {
361      bool should_continue = VisitFrame();
362      if (!should_continue) {
363        return;
364      }
365    }
366    cur_depth_++;
367  }
368  if (num_frames_ != 0) {
369    CHECK_EQ(cur_depth_, num_frames_);
370  }
371}
372
373}  // namespace art
374