stack.cc revision 0bcb2902ec21393d71c94e63aa6733cb5311a0cc
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 "base/hex_dump.h"
20#include "mirror/art_method-inl.h"
21#include "mirror/class-inl.h"
22#include "mirror/object.h"
23#include "mirror/object-inl.h"
24#include "mirror/object_array-inl.h"
25#include "object_utils.h"
26#include "quick/quick_method_frame_info.h"
27#include "runtime.h"
28#include "thread.h"
29#include "thread_list.h"
30#include "throw_location.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
59ThrowLocation ShadowFrame::GetCurrentLocationForThrow() const {
60  return ThrowLocation(GetThisObject(), GetMethod(), GetDexPC());
61}
62
63size_t ManagedStack::NumJniShadowFrameReferences() const {
64  size_t count = 0;
65  for (const ManagedStack* current_fragment = this; current_fragment != NULL;
66       current_fragment = current_fragment->GetLink()) {
67    for (ShadowFrame* current_frame = current_fragment->top_shadow_frame_; current_frame != NULL;
68         current_frame = current_frame->GetLink()) {
69      if (current_frame->GetMethod()->IsNative()) {
70        // The JNI ShadowFrame only contains references. (For indirect reference.)
71        count += current_frame->NumberOfVRegs();
72      }
73    }
74  }
75  return count;
76}
77
78bool ManagedStack::ShadowFramesContain(StackReference<mirror::Object>* shadow_frame_entry) const {
79  for (const ManagedStack* current_fragment = this; current_fragment != NULL;
80       current_fragment = current_fragment->GetLink()) {
81    for (ShadowFrame* current_frame = current_fragment->top_shadow_frame_; current_frame != NULL;
82         current_frame = current_frame->GetLink()) {
83      if (current_frame->Contains(shadow_frame_entry)) {
84        return true;
85      }
86    }
87  }
88  return false;
89}
90
91StackVisitor::StackVisitor(Thread* thread, Context* context)
92    : thread_(thread), cur_shadow_frame_(NULL),
93      cur_quick_frame_(NULL), cur_quick_frame_pc_(0), num_frames_(0), cur_depth_(0),
94      context_(context) {
95  DCHECK(thread == Thread::Current() || thread->IsSuspended()) << *thread;
96}
97
98StackVisitor::StackVisitor(Thread* thread, Context* context, size_t num_frames)
99    : thread_(thread), cur_shadow_frame_(NULL),
100      cur_quick_frame_(NULL), cur_quick_frame_pc_(0), num_frames_(num_frames), cur_depth_(0),
101      context_(context) {
102  DCHECK(thread == Thread::Current() || thread->IsSuspended()) << *thread;
103}
104
105uint32_t StackVisitor::GetDexPc(bool abort_on_failure) const {
106  if (cur_shadow_frame_ != NULL) {
107    return cur_shadow_frame_->GetDexPC();
108  } else if (cur_quick_frame_ != NULL) {
109    return GetMethod()->ToDexPc(cur_quick_frame_pc_, abort_on_failure);
110  } else {
111    return 0;
112  }
113}
114
115mirror::Object* StackVisitor::GetThisObject() const {
116  mirror::ArtMethod* m = GetMethod();
117  if (m->IsStatic()) {
118    return NULL;
119  } else if (m->IsNative()) {
120    if (cur_quick_frame_ != NULL) {
121      HandleScope* hs = reinterpret_cast<HandleScope*>(
122          reinterpret_cast<char*>(cur_quick_frame_) + m->GetHandleScopeOffsetInBytes());
123      return hs->GetReference(0);
124    } else {
125      return cur_shadow_frame_->GetVRegReference(0);
126    }
127  } else {
128    const DexFile::CodeItem* code_item = m->GetCodeItem();
129    if (code_item == NULL) {
130      UNIMPLEMENTED(ERROR) << "Failed to determine this object of abstract or proxy method: "
131          << PrettyMethod(m);
132      return nullptr;
133    } else {
134      uint16_t reg = code_item->registers_size_ - code_item->ins_size_;
135      return reinterpret_cast<mirror::Object*>(GetVReg(m, reg, kReferenceVReg));
136    }
137  }
138}
139
140size_t StackVisitor::GetNativePcOffset() const {
141  DCHECK(!IsShadowFrame());
142  return GetMethod()->NativePcOffset(cur_quick_frame_pc_);
143}
144
145bool StackVisitor::GetVReg(mirror::ArtMethod* m, uint16_t vreg, VRegKind kind,
146                           uint32_t* val) const {
147  if (cur_quick_frame_ != NULL) {
148    DCHECK(context_ != NULL);  // You can't reliably read registers without a context.
149    DCHECK(m == GetMethod());
150    const void* code_pointer = m->GetQuickOatCodePointer();
151    DCHECK(code_pointer != nullptr);
152    const VmapTable vmap_table(m->GetVmapTable(code_pointer));
153    QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
154    uint32_t vmap_offset;
155    // TODO: IsInContext stops before spotting floating point registers.
156    if (vmap_table.IsInContext(vreg, kind, &vmap_offset)) {
157      bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
158      uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
159      uint32_t reg = vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
160      uintptr_t ptr_val;
161      bool success = false;
162      if (is_float) {
163        success = GetFPR(reg, &ptr_val);
164      } else {
165        success = GetGPR(reg, &ptr_val);
166      }
167      *val = ptr_val;
168      return success;
169    } else {
170      const DexFile::CodeItem* code_item = m->GetCodeItem();
171      DCHECK(code_item != NULL) << PrettyMethod(m);  // Can't be NULL or how would we compile its instructions?
172      *val = *GetVRegAddr(cur_quick_frame_, code_item, frame_info.CoreSpillMask(),
173                          frame_info.FpSpillMask(), frame_info.FrameSizeInBytes(), vreg);
174      return true;
175    }
176  } else {
177    *val = cur_shadow_frame_->GetVReg(vreg);
178    return true;
179  }
180}
181
182bool StackVisitor::SetVReg(mirror::ArtMethod* m, uint16_t vreg, uint32_t new_value,
183                           VRegKind kind) {
184  if (cur_quick_frame_ != NULL) {
185    DCHECK(context_ != NULL);  // You can't reliably write registers without a context.
186    DCHECK(m == GetMethod());
187    const void* code_pointer = m->GetQuickOatCodePointer();
188    DCHECK(code_pointer != nullptr);
189    const VmapTable vmap_table(m->GetVmapTable(code_pointer));
190    QuickMethodFrameInfo frame_info = m->GetQuickFrameInfo(code_pointer);
191    uint32_t vmap_offset;
192    // TODO: IsInContext stops before spotting floating point registers.
193    if (vmap_table.IsInContext(vreg, kind, &vmap_offset)) {
194      bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
195      uint32_t spill_mask = is_float ? frame_info.FpSpillMask() : frame_info.CoreSpillMask();
196      const uint32_t reg = vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
197      if (is_float) {
198        return SetFPR(reg, new_value);
199      } else {
200        return SetGPR(reg, new_value);
201      }
202    } else {
203      const DexFile::CodeItem* code_item = m->GetCodeItem();
204      DCHECK(code_item != NULL) << PrettyMethod(m);  // Can't be NULL or how would we compile its instructions?
205      int offset = GetVRegOffset(code_item, frame_info.CoreSpillMask(), frame_info.FpSpillMask(),
206                                 frame_info.FrameSizeInBytes(), vreg, kRuntimeISA);
207      byte* vreg_addr = reinterpret_cast<byte*>(GetCurrentQuickFrame()) + offset;
208      *reinterpret_cast<uint32_t*>(vreg_addr) = new_value;
209      return true;
210    }
211  } else {
212    cur_shadow_frame_->SetVReg(vreg, new_value);
213    return true;
214  }
215}
216
217uintptr_t* StackVisitor::GetGPRAddress(uint32_t reg) const {
218  DCHECK(cur_quick_frame_ != NULL) << "This is a quick frame routine";
219  return context_->GetGPRAddress(reg);
220}
221
222bool StackVisitor::GetGPR(uint32_t reg, uintptr_t* val) const {
223  DCHECK(cur_quick_frame_ != NULL) << "This is a quick frame routine";
224  return context_->GetGPR(reg, val);
225}
226
227bool StackVisitor::SetGPR(uint32_t reg, uintptr_t value) {
228  DCHECK(cur_quick_frame_ != NULL) << "This is a quick frame routine";
229  return context_->SetGPR(reg, value);
230}
231
232bool StackVisitor::GetFPR(uint32_t reg, uintptr_t* val) const {
233  DCHECK(cur_quick_frame_ != NULL) << "This is a quick frame routine";
234  return context_->GetFPR(reg, val);
235}
236
237bool StackVisitor::SetFPR(uint32_t reg, uintptr_t value) {
238  DCHECK(cur_quick_frame_ != NULL) << "This is a quick frame routine";
239  return context_->SetFPR(reg, value);
240}
241
242uintptr_t StackVisitor::GetReturnPc() const {
243  byte* sp = reinterpret_cast<byte*>(GetCurrentQuickFrame());
244  DCHECK(sp != NULL);
245  byte* pc_addr = sp + GetMethod()->GetReturnPcOffsetInBytes();
246  return *reinterpret_cast<uintptr_t*>(pc_addr);
247}
248
249void StackVisitor::SetReturnPc(uintptr_t new_ret_pc) {
250  byte* sp = reinterpret_cast<byte*>(GetCurrentQuickFrame());
251  CHECK(sp != NULL);
252  byte* pc_addr = sp + GetMethod()->GetReturnPcOffsetInBytes();
253  *reinterpret_cast<uintptr_t*>(pc_addr) = new_ret_pc;
254}
255
256size_t StackVisitor::ComputeNumFrames(Thread* thread) {
257  struct NumFramesVisitor : public StackVisitor {
258    explicit NumFramesVisitor(Thread* thread)
259        : StackVisitor(thread, NULL), frames(0) {}
260
261    bool VisitFrame() OVERRIDE {
262      frames++;
263      return true;
264    }
265
266    size_t frames;
267  };
268  NumFramesVisitor visitor(thread);
269  visitor.WalkStack(true);
270  return visitor.frames;
271}
272
273bool StackVisitor::GetNextMethodAndDexPc(mirror::ArtMethod** next_method, uint32_t* next_dex_pc) {
274  struct HasMoreFramesVisitor : public StackVisitor {
275    explicit HasMoreFramesVisitor(Thread* thread, size_t num_frames, size_t frame_height)
276        : StackVisitor(thread, nullptr, num_frames), frame_height_(frame_height),
277          found_frame_(false), has_more_frames_(false), next_method_(nullptr), next_dex_pc_(0) {
278    }
279
280    bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
281      if (found_frame_) {
282        mirror::ArtMethod* method = GetMethod();
283        if (method != nullptr && !method->IsRuntimeMethod()) {
284          has_more_frames_ = true;
285          next_method_ = method;
286          next_dex_pc_ = GetDexPc();
287          return false;  // End stack walk once next method is found.
288        }
289      } else if (GetFrameHeight() == frame_height_) {
290        found_frame_ = true;
291      }
292      return true;
293    }
294
295    size_t frame_height_;
296    bool found_frame_;
297    bool has_more_frames_;
298    mirror::ArtMethod* next_method_;
299    uint32_t next_dex_pc_;
300  };
301  HasMoreFramesVisitor visitor(thread_, GetNumFrames(), GetFrameHeight());
302  visitor.WalkStack(true);
303  *next_method = visitor.next_method_;
304  *next_dex_pc = visitor.next_dex_pc_;
305  return visitor.has_more_frames_;
306}
307
308void StackVisitor::DescribeStack(Thread* thread) {
309  struct DescribeStackVisitor : public StackVisitor {
310    explicit DescribeStackVisitor(Thread* thread)
311        : StackVisitor(thread, NULL) {}
312
313    bool VisitFrame() OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
314      LOG(INFO) << "Frame Id=" << GetFrameId() << " " << DescribeLocation();
315      return true;
316    }
317  };
318  DescribeStackVisitor visitor(thread);
319  visitor.WalkStack(true);
320}
321
322std::string StackVisitor::DescribeLocation() const {
323  std::string result("Visiting method '");
324  mirror::ArtMethod* m = GetMethod();
325  if (m == NULL) {
326    return "upcall";
327  }
328  result += PrettyMethod(m);
329  result += StringPrintf("' at dex PC 0x%04x", GetDexPc());
330  if (!IsShadowFrame()) {
331    result += StringPrintf(" (native PC %p)", reinterpret_cast<void*>(GetCurrentQuickFramePc()));
332  }
333  return result;
334}
335
336instrumentation::InstrumentationStackFrame& StackVisitor::GetInstrumentationStackFrame(uint32_t depth) const {
337  CHECK_LT(depth, thread_->GetInstrumentationStack()->size());
338  return thread_->GetInstrumentationStack()->at(depth);
339}
340
341void StackVisitor::SanityCheckFrame() const {
342  if (kIsDebugBuild) {
343    mirror::ArtMethod* method = GetMethod();
344    CHECK_EQ(method->GetClass(), mirror::ArtMethod::GetJavaLangReflectArtMethod());
345    if (cur_quick_frame_ != nullptr) {
346      method->AssertPcIsWithinQuickCode(cur_quick_frame_pc_);
347      // Frame sanity.
348      size_t frame_size = method->GetFrameSizeInBytes();
349      CHECK_NE(frame_size, 0u);
350      // A rough guess at an upper size we expect to see for a frame.
351      // 256 registers
352      // 2 words HandleScope overhead
353      // 3+3 register spills
354      // TODO: this seems architecture specific for the case of JNI frames.
355      // TODO: 083-compiler-regressions ManyFloatArgs shows this estimate is wrong.
356      // const size_t kMaxExpectedFrameSize = (256 + 2 + 3 + 3) * sizeof(word);
357      const size_t kMaxExpectedFrameSize = 2 * KB;
358      CHECK_LE(frame_size, kMaxExpectedFrameSize);
359      size_t return_pc_offset = method->GetReturnPcOffsetInBytes();
360      CHECK_LT(return_pc_offset, frame_size);
361    }
362  }
363}
364
365void StackVisitor::WalkStack(bool include_transitions) {
366  DCHECK(thread_ == Thread::Current() || thread_->IsSuspended());
367  CHECK_EQ(cur_depth_, 0U);
368  bool exit_stubs_installed = Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled();
369  uint32_t instrumentation_stack_depth = 0;
370
371  for (const ManagedStack* current_fragment = thread_->GetManagedStack(); current_fragment != NULL;
372       current_fragment = current_fragment->GetLink()) {
373    cur_shadow_frame_ = current_fragment->GetTopShadowFrame();
374    cur_quick_frame_ = current_fragment->GetTopQuickFrame();
375    cur_quick_frame_pc_ = current_fragment->GetTopQuickFramePc();
376
377    if (cur_quick_frame_ != NULL) {  // Handle quick stack frames.
378      // Can't be both a shadow and a quick fragment.
379      DCHECK(current_fragment->GetTopShadowFrame() == NULL);
380      mirror::ArtMethod* method = cur_quick_frame_->AsMirrorPtr();
381      while (method != NULL) {
382        SanityCheckFrame();
383        bool should_continue = VisitFrame();
384        if (UNLIKELY(!should_continue)) {
385          return;
386        }
387
388        if (context_ != NULL) {
389          context_->FillCalleeSaves(*this);
390        }
391        size_t frame_size = method->GetFrameSizeInBytes();
392        // Compute PC for next stack frame from return PC.
393        size_t return_pc_offset = method->GetReturnPcOffsetInBytes(frame_size);
394        byte* return_pc_addr = reinterpret_cast<byte*>(cur_quick_frame_) + return_pc_offset;
395        uintptr_t return_pc = *reinterpret_cast<uintptr_t*>(return_pc_addr);
396        if (UNLIKELY(exit_stubs_installed)) {
397          // While profiling, the return pc is restored from the side stack, except when walking
398          // the stack for an exception where the side stack will be unwound in VisitFrame.
399          if (GetQuickInstrumentationExitPc() == return_pc) {
400            const instrumentation::InstrumentationStackFrame& instrumentation_frame =
401                GetInstrumentationStackFrame(instrumentation_stack_depth);
402            instrumentation_stack_depth++;
403            if (GetMethod() == Runtime::Current()->GetCalleeSaveMethod(Runtime::kSaveAll)) {
404              // Skip runtime save all callee frames which are used to deliver exceptions.
405            } else if (instrumentation_frame.interpreter_entry_) {
406              mirror::ArtMethod* callee = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
407              CHECK_EQ(GetMethod(), callee) << "Expected: " << PrettyMethod(callee) << " Found: "
408                                            << PrettyMethod(GetMethod());
409            } else if (instrumentation_frame.method_ != GetMethod()) {
410              LOG(FATAL)  << "Expected: " << PrettyMethod(instrumentation_frame.method_)
411                          << " Found: " << PrettyMethod(GetMethod());
412            }
413            if (num_frames_ != 0) {
414              // Check agreement of frame Ids only if num_frames_ is computed to avoid infinite
415              // recursion.
416              CHECK(instrumentation_frame.frame_id_ == GetFrameId())
417                    << "Expected: " << instrumentation_frame.frame_id_
418                    << " Found: " << GetFrameId();
419            }
420            return_pc = instrumentation_frame.return_pc_;
421          }
422        }
423        cur_quick_frame_pc_ = return_pc;
424        byte* next_frame = reinterpret_cast<byte*>(cur_quick_frame_) + frame_size;
425        cur_quick_frame_ = reinterpret_cast<StackReference<mirror::ArtMethod>*>(next_frame);
426        cur_depth_++;
427        method = cur_quick_frame_->AsMirrorPtr();
428      }
429    } else if (cur_shadow_frame_ != NULL) {
430      do {
431        SanityCheckFrame();
432        bool should_continue = VisitFrame();
433        if (UNLIKELY(!should_continue)) {
434          return;
435        }
436        cur_depth_++;
437        cur_shadow_frame_ = cur_shadow_frame_->GetLink();
438      } while (cur_shadow_frame_ != NULL);
439    }
440    if (include_transitions) {
441      bool should_continue = VisitFrame();
442      if (!should_continue) {
443        return;
444      }
445    }
446    cur_depth_++;
447  }
448  if (num_frames_ != 0) {
449    CHECK_EQ(cur_depth_, num_frames_);
450  }
451}
452
453}  // namespace art
454