emulated_stack_frame.cc revision 2cb856c47b884a08485e2f08e6a3ef6a5bbf773a
1/*
2 * Copyright (C) 2016 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 "emulated_stack_frame.h"
18
19#include "class-inl.h"
20#include "gc_root-inl.h"
21#include "jvalue-inl.h"
22#include "method_handles.h"
23#include "method_handles-inl.h"
24#include "reflection-inl.h"
25
26namespace art {
27namespace mirror {
28
29GcRoot<mirror::Class> EmulatedStackFrame::static_class_;
30
31// Calculates the size of a stack frame based on the size of its argument
32// types and return types.
33static void CalculateFrameAndReferencesSize(ObjPtr<mirror::ObjectArray<mirror::Class>> p_types,
34                                            ObjPtr<mirror::Class> r_type,
35                                            size_t* frame_size_out,
36                                            size_t* references_size_out)
37    REQUIRES_SHARED(Locks::mutator_lock_) {
38  const size_t length = p_types->GetLength();
39  size_t frame_size = 0;
40  size_t references_size = 0;
41  for (size_t i = 0; i < length; ++i) {
42    ObjPtr<mirror::Class> type = p_types->GetWithoutChecks(i);
43    const Primitive::Type primitive_type = type->GetPrimitiveType();
44    if (primitive_type == Primitive::kPrimNot) {
45      references_size++;
46    } else if (Primitive::Is64BitType(primitive_type)) {
47      frame_size += 8;
48    } else {
49      frame_size += 4;
50    }
51  }
52
53  const Primitive::Type return_type = r_type->GetPrimitiveType();
54  if (return_type == Primitive::kPrimNot) {
55    references_size++;
56  } else if (Primitive::Is64BitType(return_type)) {
57    frame_size += 8;
58  } else {
59    frame_size += 4;
60  }
61
62  (*frame_size_out) = frame_size;
63  (*references_size_out) = references_size;
64}
65
66// Allows for read or write access to an emulated stack frame. Each
67// accessor index has an associated index into the references / stack frame
68// arrays which is incremented on every read or write to the frame.
69//
70// This class is used in conjunction with PerformConversions, either as a setter
71// or as a getter.
72class EmulatedStackFrameAccessor {
73 public:
74  EmulatedStackFrameAccessor(Handle<mirror::ObjectArray<mirror::Object>> references,
75                             Handle<mirror::ByteArray> stack_frame,
76                             size_t stack_frame_size) :
77    references_(references),
78    stack_frame_(stack_frame),
79    stack_frame_size_(stack_frame_size),
80    reference_idx_(0u),
81    stack_frame_idx_(0u) {
82  }
83
84  ALWAYS_INLINE void SetReference(ObjPtr<mirror::Object> reference)
85      REQUIRES_SHARED(Locks::mutator_lock_) {
86    references_->Set(reference_idx_++, reference);
87  }
88
89  ALWAYS_INLINE void Set(const uint32_t value) REQUIRES_SHARED(Locks::mutator_lock_) {
90    int8_t* array = stack_frame_->GetData();
91
92    CHECK_LE((stack_frame_idx_ + 4u), stack_frame_size_);
93    memcpy(array + stack_frame_idx_, &value, sizeof(uint32_t));
94    stack_frame_idx_ += 4u;
95  }
96
97  ALWAYS_INLINE void SetLong(const int64_t value) REQUIRES_SHARED(Locks::mutator_lock_) {
98    int8_t* array = stack_frame_->GetData();
99
100    CHECK_LE((stack_frame_idx_ + 8u), stack_frame_size_);
101    memcpy(array + stack_frame_idx_, &value, sizeof(int64_t));
102    stack_frame_idx_ += 8u;
103  }
104
105  ALWAYS_INLINE ObjPtr<mirror::Object> GetReference() REQUIRES_SHARED(Locks::mutator_lock_) {
106    return ObjPtr<mirror::Object>(references_->Get(reference_idx_++));
107  }
108
109  ALWAYS_INLINE uint32_t Get() REQUIRES_SHARED(Locks::mutator_lock_) {
110    const int8_t* array = stack_frame_->GetData();
111
112    CHECK_LE((stack_frame_idx_ + 4u), stack_frame_size_);
113    uint32_t val = 0;
114
115    memcpy(&val, array + stack_frame_idx_, sizeof(uint32_t));
116    stack_frame_idx_ += 4u;
117    return val;
118  }
119
120  ALWAYS_INLINE int64_t GetLong() REQUIRES_SHARED(Locks::mutator_lock_) {
121    const int8_t* array = stack_frame_->GetData();
122
123    CHECK_LE((stack_frame_idx_ + 8u), stack_frame_size_);
124    int64_t val = 0;
125
126    memcpy(&val, array + stack_frame_idx_, sizeof(int64_t));
127    stack_frame_idx_ += 8u;
128    return val;
129  }
130
131 private:
132  Handle<mirror::ObjectArray<mirror::Object>> references_;
133  Handle<mirror::ByteArray> stack_frame_;
134  const size_t stack_frame_size_;
135
136  size_t reference_idx_;
137  size_t stack_frame_idx_;
138
139  DISALLOW_COPY_AND_ASSIGN(EmulatedStackFrameAccessor);
140};
141
142template <bool is_range>
143mirror::EmulatedStackFrame* EmulatedStackFrame::CreateFromShadowFrameAndArgs(
144    Thread* self,
145    Handle<mirror::MethodType> caller_type,
146    Handle<mirror::MethodType> callee_type,
147    const ShadowFrame& caller_frame,
148    const uint32_t first_src_reg,
149    const uint32_t (&arg)[Instruction::kMaxVarArgRegs]) {
150  StackHandleScope<6> hs(self);
151
152  // Step 1: We must throw a WrongMethodTypeException if there's a mismatch in the
153  // number of arguments between the caller and the callsite.
154  Handle<mirror::ObjectArray<mirror::Class>> from_types(hs.NewHandle(caller_type->GetPTypes()));
155  Handle<mirror::ObjectArray<mirror::Class>> to_types(hs.NewHandle(callee_type->GetPTypes()));
156
157  const int32_t num_method_params = from_types->GetLength();
158  if (to_types->GetLength() != num_method_params) {
159    ThrowWrongMethodTypeException(callee_type.Get(), caller_type.Get());
160    return nullptr;
161  }
162
163  // Step 2: Calculate the size of the reference / byte arrays in the emulated
164  // stack frame.
165  size_t frame_size = 0;
166  size_t refs_size = 0;
167  Handle<mirror::Class> r_type(hs.NewHandle(callee_type->GetRType()));
168  CalculateFrameAndReferencesSize(to_types.Get(), r_type.Get(), &frame_size, &refs_size);
169
170  // Step 3 : Allocate the arrays.
171  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
172  ObjPtr<mirror::Class> array_class(class_linker->GetClassRoot(ClassLinker::kObjectArrayClass));
173
174  Handle<mirror::ObjectArray<mirror::Object>> references(hs.NewHandle(
175      mirror::ObjectArray<mirror::Object>::Alloc(self, array_class, refs_size)));
176  if (references.Get() == nullptr) {
177    DCHECK(self->IsExceptionPending());
178    return nullptr;
179  }
180
181  Handle<ByteArray> stack_frame(hs.NewHandle(ByteArray::Alloc(self, frame_size)));
182  if (stack_frame.Get() == nullptr) {
183    DCHECK(self->IsExceptionPending());
184    return nullptr;
185  }
186
187  // Step 4 : Perform argument conversions (if required).
188  ShadowFrameGetter<is_range> getter(first_src_reg, arg, caller_frame);
189  EmulatedStackFrameAccessor setter(references, stack_frame, stack_frame->GetLength());
190  if (!PerformConversions<ShadowFrameGetter<is_range>, EmulatedStackFrameAccessor>(
191          self, from_types, to_types, &getter, &setter, num_method_params)) {
192    return nullptr;
193  }
194
195  // Step 5: Construct the EmulatedStackFrame object.
196  Handle<EmulatedStackFrame> sf(hs.NewHandle(
197      ObjPtr<EmulatedStackFrame>::DownCast(StaticClass()->AllocObject(self))));
198  sf->SetFieldObject<false>(TypeOffset(), callee_type.Get());
199  sf->SetFieldObject<false>(ReferencesOffset(), references.Get());
200  sf->SetFieldObject<false>(StackFrameOffset(), stack_frame.Get());
201
202  return sf.Get();
203}
204
205bool EmulatedStackFrame::WriteToShadowFrame(Thread* self,
206                                            Handle<mirror::MethodType> callee_type,
207                                            const uint32_t first_dest_reg,
208                                            ShadowFrame* callee_frame) {
209  StackHandleScope<4> hs(self);
210  Handle<mirror::ObjectArray<mirror::Class>> from_types(hs.NewHandle(GetType()->GetPTypes()));
211  Handle<mirror::ObjectArray<mirror::Class>> to_types(hs.NewHandle(callee_type->GetPTypes()));
212
213  const int32_t num_method_params = from_types->GetLength();
214  if (to_types->GetLength() != num_method_params) {
215    ThrowWrongMethodTypeException(callee_type.Get(), GetType());
216    return false;
217  }
218
219  Handle<mirror::ObjectArray<mirror::Object>> references(hs.NewHandle(GetReferences()));
220  Handle<ByteArray> stack_frame(hs.NewHandle(GetStackFrame()));
221
222  EmulatedStackFrameAccessor getter(references, stack_frame, stack_frame->GetLength());
223  ShadowFrameSetter setter(callee_frame, first_dest_reg);
224
225  return PerformConversions<EmulatedStackFrameAccessor, ShadowFrameSetter>(
226      self, from_types, to_types, &getter, &setter, num_method_params);
227}
228
229void EmulatedStackFrame::GetReturnValue(Thread* self, JValue* value) {
230  StackHandleScope<2> hs(self);
231  Handle<mirror::Class> r_type(hs.NewHandle(GetType()->GetRType()));
232
233  const Primitive::Type type = r_type->GetPrimitiveType();
234  if (type == Primitive::kPrimNot) {
235    Handle<mirror::ObjectArray<mirror::Object>> references(hs.NewHandle(GetReferences()));
236    value->SetL(references->GetWithoutChecks(references->GetLength() - 1));
237  } else {
238    Handle<ByteArray> stack_frame(hs.NewHandle(GetStackFrame()));
239    const int8_t* array = stack_frame->GetData();
240    const size_t length = stack_frame->GetLength();
241    if (Primitive::Is64BitType(type)) {
242      int64_t primitive = 0;
243      memcpy(&primitive, array + length - sizeof(int64_t), sizeof(int64_t));
244      value->SetJ(primitive);
245    } else {
246      uint32_t primitive = 0;
247      memcpy(&primitive, array + length - sizeof(uint32_t), sizeof(uint32_t));
248      value->SetI(primitive);
249    }
250  }
251}
252
253void EmulatedStackFrame::SetReturnValue(Thread* self, const JValue& value) {
254  StackHandleScope<2> hs(self);
255  Handle<mirror::Class> r_type(hs.NewHandle(GetType()->GetRType()));
256
257  const Primitive::Type type = r_type->GetPrimitiveType();
258  if (type == Primitive::kPrimNot) {
259    Handle<mirror::ObjectArray<mirror::Object>> references(hs.NewHandle(GetReferences()));
260    references->SetWithoutChecks<false>(references->GetLength() - 1, value.GetL());
261  } else {
262    Handle<ByteArray> stack_frame(hs.NewHandle(GetStackFrame()));
263    int8_t* array = stack_frame->GetData();
264    const size_t length = stack_frame->GetLength();
265    if (Primitive::Is64BitType(type)) {
266      const int64_t primitive = value.GetJ();
267      memcpy(array + length - sizeof(int64_t), &primitive, sizeof(int64_t));
268    } else {
269      const uint32_t primitive = value.GetI();
270      memcpy(array + length - sizeof(uint32_t), &primitive, sizeof(uint32_t));
271    }
272  }
273}
274
275void EmulatedStackFrame::SetClass(Class* klass) {
276  CHECK(static_class_.IsNull()) << static_class_.Read() << " " << klass;
277  CHECK(klass != nullptr);
278  static_class_ = GcRoot<Class>(klass);
279}
280
281void EmulatedStackFrame::ResetClass() {
282  CHECK(!static_class_.IsNull());
283  static_class_ = GcRoot<Class>(nullptr);
284}
285
286void EmulatedStackFrame::VisitRoots(RootVisitor* visitor) {
287  static_class_.VisitRootIfNonNull(visitor, RootInfo(kRootStickyClass));
288}
289
290// Explicit DoInvokePolymorphic template function declarations.
291#define EXPLICIT_CREATE_FROM_SHADOW_FRAME_AND_ARGS_DECL(_is_range)                         \
292  template REQUIRES_SHARED(Locks::mutator_lock_)                                           \
293  mirror::EmulatedStackFrame* EmulatedStackFrame::CreateFromShadowFrameAndArgs<_is_range>( \
294    Thread* self,                                                                          \
295    Handle<mirror::MethodType> caller_type,                                                \
296    Handle<mirror::MethodType> callee_type,                                                \
297    const ShadowFrame& caller_frame,                                                       \
298    const uint32_t first_src_reg,                                                          \
299    const uint32_t (&arg)[Instruction::kMaxVarArgRegs])                                    \
300
301EXPLICIT_CREATE_FROM_SHADOW_FRAME_AND_ARGS_DECL(true);
302EXPLICIT_CREATE_FROM_SHADOW_FRAME_AND_ARGS_DECL(false);
303#undef EXPLICIT_CREATE_FROM_SHADOW_FRAME_AND_ARGS_DECL
304
305
306}  // namespace mirror
307}  // namespace art
308