• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "method_handles-inl.h"
18 
19 #include "android-base/macros.h"
20 #include "android-base/stringprintf.h"
21 #include "class_root-inl.h"
22 #include "common_dex_operations.h"
23 #include "common_throws.h"
24 #include "interpreter/shadow_frame-inl.h"
25 #include "interpreter/shadow_frame.h"
26 #include "jvalue-inl.h"
27 #include "mirror/class-inl.h"
28 #include "mirror/emulated_stack_frame-inl.h"
29 #include "mirror/emulated_stack_frame.h"
30 #include "mirror/method_handle_impl-inl.h"
31 #include "mirror/method_handle_impl.h"
32 #include "mirror/method_type-inl.h"
33 #include "mirror/var_handle.h"
34 #include "reflection-inl.h"
35 #include "reflection.h"
36 #include "thread.h"
37 #include "var_handles.h"
38 #include "well_known_classes.h"
39 
40 namespace art {
41 
42 using android::base::StringPrintf;
43 
44 namespace {
45 
46 #define PRIMITIVES_LIST(V) \
47   V(Primitive::kPrimBoolean, Boolean, Boolean, Z) \
48   V(Primitive::kPrimByte, Byte, Byte, B)          \
49   V(Primitive::kPrimChar, Char, Character, C)     \
50   V(Primitive::kPrimShort, Short, Short, S)       \
51   V(Primitive::kPrimInt, Int, Integer, I)         \
52   V(Primitive::kPrimLong, Long, Long, J)          \
53   V(Primitive::kPrimFloat, Float, Float, F)       \
54   V(Primitive::kPrimDouble, Double, Double, D)
55 
56 // Assigns |type| to the primitive type associated with |klass|. Returns
57 // true iff. |klass| was a boxed type (Integer, Long etc.), false otherwise.
GetUnboxedPrimitiveType(ObjPtr<mirror::Class> klass,Primitive::Type * type)58 bool GetUnboxedPrimitiveType(ObjPtr<mirror::Class> klass, Primitive::Type* type)
59     REQUIRES_SHARED(Locks::mutator_lock_) {
60   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
61   std::string storage;
62   const char* descriptor = klass->GetDescriptor(&storage);
63   static const char kJavaLangPrefix[] = "Ljava/lang/";
64   static const size_t kJavaLangPrefixSize = sizeof(kJavaLangPrefix) - 1;
65   if (strncmp(descriptor, kJavaLangPrefix, kJavaLangPrefixSize) != 0) {
66     return false;
67   }
68 
69   descriptor += kJavaLangPrefixSize;
70 #define LOOKUP_PRIMITIVE(primitive, _, java_name, ___) \
71   if (strcmp(descriptor, #java_name ";") == 0) {       \
72     *type = primitive;                                 \
73     return true;                                       \
74   }
75 
76   PRIMITIVES_LIST(LOOKUP_PRIMITIVE);
77 #undef LOOKUP_PRIMITIVE
78   return false;
79 }
80 
GetBoxedPrimitiveClass(Primitive::Type type)81 ObjPtr<mirror::Class> GetBoxedPrimitiveClass(Primitive::Type type)
82     REQUIRES_SHARED(Locks::mutator_lock_) {
83   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
84   ArtMethod* m = nullptr;
85   switch (type) {
86 #define CASE_PRIMITIVE(primitive, _, java_name, __)              \
87     case primitive:                                              \
88       m = WellKnownClasses::java_lang_ ## java_name ## _valueOf; \
89       break;
90     PRIMITIVES_LIST(CASE_PRIMITIVE);
91 #undef CASE_PRIMITIVE
92     case Primitive::Type::kPrimNot:
93     case Primitive::Type::kPrimVoid:
94       return nullptr;
95   }
96   return m->GetDeclaringClass();
97 }
98 
GetUnboxedTypeAndValue(ObjPtr<mirror::Object> o,Primitive::Type * type,JValue * value)99 bool GetUnboxedTypeAndValue(ObjPtr<mirror::Object> o, Primitive::Type* type, JValue* value)
100     REQUIRES_SHARED(Locks::mutator_lock_) {
101   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
102   ObjPtr<mirror::Class> klass = o->GetClass();
103   ArtField* primitive_field = &klass->GetIFieldsPtr()->At(0);
104 #define CASE_PRIMITIVE(primitive, abbrev, _, shorthand)         \
105   if (klass == GetBoxedPrimitiveClass(primitive)) {             \
106     *type = primitive;                                          \
107     value->Set ## shorthand(primitive_field->Get ## abbrev(o)); \
108     return true;                                                \
109   }
110   PRIMITIVES_LIST(CASE_PRIMITIVE)
111 #undef CASE_PRIMITIVE
112   return false;
113 }
114 
IsReferenceType(Primitive::Type type)115 inline bool IsReferenceType(Primitive::Type type) {
116   return type == Primitive::kPrimNot;
117 }
118 
IsPrimitiveType(Primitive::Type type)119 inline bool IsPrimitiveType(Primitive::Type type) {
120   return !IsReferenceType(type);
121 }
122 
123 }  // namespace
124 
IsParameterTypeConvertible(ObjPtr<mirror::Class> from,ObjPtr<mirror::Class> to)125 bool IsParameterTypeConvertible(ObjPtr<mirror::Class> from, ObjPtr<mirror::Class> to)
126     REQUIRES_SHARED(Locks::mutator_lock_) {
127   // This function returns true if there's any conceivable conversion
128   // between |from| and |to|. It's expected this method will be used
129   // to determine if a WrongMethodTypeException should be raised. The
130   // decision logic follows the documentation for MethodType.asType().
131   if (from == to) {
132     return true;
133   }
134 
135   Primitive::Type from_primitive = from->GetPrimitiveType();
136   Primitive::Type to_primitive = to->GetPrimitiveType();
137   DCHECK(from_primitive != Primitive::Type::kPrimVoid);
138   DCHECK(to_primitive != Primitive::Type::kPrimVoid);
139 
140   // If |to| and |from| are references.
141   if (IsReferenceType(from_primitive) && IsReferenceType(to_primitive)) {
142     // Assignability is determined during parameter conversion when
143     // invoking the associated method handle.
144     return true;
145   }
146 
147   // If |to| and |from| are primitives and a widening conversion exists.
148   if (Primitive::IsWidenable(from_primitive, to_primitive)) {
149     return true;
150   }
151 
152   // If |to| is a reference and |from| is a primitive, then boxing conversion.
153   if (IsReferenceType(to_primitive) && IsPrimitiveType(from_primitive)) {
154     return to->IsAssignableFrom(GetBoxedPrimitiveClass(from_primitive));
155   }
156 
157   // If |from| is a reference and |to| is a primitive, then unboxing conversion.
158   if (IsPrimitiveType(to_primitive) && IsReferenceType(from_primitive)) {
159     if (from->DescriptorEquals("Ljava/lang/Object;")) {
160       // Object might be converted into a primitive during unboxing.
161       return true;
162     }
163 
164     if (Primitive::IsNumericType(to_primitive) && from->DescriptorEquals("Ljava/lang/Number;")) {
165       // Number might be unboxed into any of the number primitive types.
166       return true;
167     }
168 
169     Primitive::Type unboxed_type;
170     if (GetUnboxedPrimitiveType(from, &unboxed_type)) {
171       if (unboxed_type == to_primitive) {
172         // Straightforward unboxing conversion such as Boolean => boolean.
173         return true;
174       }
175 
176       // Check if widening operations for numeric primitives would work,
177       // such as Byte => byte => long.
178       return Primitive::IsWidenable(unboxed_type, to_primitive);
179     }
180   }
181 
182   return false;
183 }
184 
IsReturnTypeConvertible(ObjPtr<mirror::Class> from,ObjPtr<mirror::Class> to)185 bool IsReturnTypeConvertible(ObjPtr<mirror::Class> from, ObjPtr<mirror::Class> to)
186     REQUIRES_SHARED(Locks::mutator_lock_) {
187   if (to->GetPrimitiveType() == Primitive::Type::kPrimVoid) {
188     // Result will be ignored.
189     return true;
190   } else if (from->GetPrimitiveType() == Primitive::Type::kPrimVoid) {
191     // Returned value will be 0 / null.
192     return true;
193   } else {
194     // Otherwise apply usual parameter conversion rules.
195     return IsParameterTypeConvertible(from, to);
196   }
197 }
198 
ConvertJValueCommon(Handle<mirror::MethodType> callsite_type,Handle<mirror::MethodType> callee_type,ObjPtr<mirror::Class> from,ObjPtr<mirror::Class> to,JValue * value)199 bool ConvertJValueCommon(
200     Handle<mirror::MethodType> callsite_type,
201     Handle<mirror::MethodType> callee_type,
202     ObjPtr<mirror::Class> from,
203     ObjPtr<mirror::Class> to,
204     JValue* value) {
205   // The reader maybe concerned about the safety of the heap object
206   // that may be in |value|. There is only one case where allocation
207   // is obviously needed and that's for boxing. However, in the case
208   // of boxing |value| contains a non-reference type.
209 
210   const Primitive::Type from_type = from->GetPrimitiveType();
211   const Primitive::Type to_type = to->GetPrimitiveType();
212 
213   // Put incoming value into |src_value| and set return value to 0.
214   // Errors and conversions from void require the return value to be 0.
215   const JValue src_value(*value);
216   value->SetJ(0);
217 
218   // Conversion from void set result to zero.
219   if (from_type == Primitive::kPrimVoid) {
220     return true;
221   }
222 
223   // This method must be called only when the types don't match.
224   DCHECK(from != to);
225 
226   if (IsPrimitiveType(from_type) && IsPrimitiveType(to_type)) {
227     // The source and target types are both primitives.
228     if (UNLIKELY(!ConvertPrimitiveValueNoThrow(from_type, to_type, src_value, value))) {
229       ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
230       return false;
231     }
232     return true;
233   } else if (IsReferenceType(from_type) && IsReferenceType(to_type)) {
234     // They're both reference types. If "from" is null, we can pass it
235     // through unchanged. If not, we must generate a cast exception if
236     // |to| is not assignable from the dynamic type of |ref|.
237     //
238     // Playing it safe with StackHandleScope here, not expecting any allocation
239     // in mirror::Class::IsAssignable().
240     StackHandleScope<2> hs(Thread::Current());
241     Handle<mirror::Class> h_to(hs.NewHandle(to));
242     Handle<mirror::Object> h_obj(hs.NewHandle(src_value.GetL()));
243     if (UNLIKELY(!h_obj.IsNull() && !to->IsAssignableFrom(h_obj->GetClass()))) {
244       ThrowClassCastException(h_to.Get(), h_obj->GetClass());
245       return false;
246     }
247     value->SetL(h_obj.Get());
248     return true;
249   } else if (IsReferenceType(to_type)) {
250     DCHECK(IsPrimitiveType(from_type));
251     // The source type is a primitive and the target type is a reference, so we must box.
252     // The target type maybe a super class of the boxed source type, for example,
253     // if the source type is int, it's boxed type is java.lang.Integer, and the target
254     // type could be java.lang.Number.
255     Primitive::Type type;
256     if (!GetUnboxedPrimitiveType(to, &type)) {
257       ObjPtr<mirror::Class> boxed_from_class = GetBoxedPrimitiveClass(from_type);
258       if (LIKELY(boxed_from_class->IsSubClass(to))) {
259         type = from_type;
260       } else {
261         ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
262         return false;
263       }
264     }
265 
266     if (UNLIKELY(from_type != type)) {
267       ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
268       return false;
269     }
270 
271     if (UNLIKELY(!ConvertPrimitiveValueNoThrow(from_type, type, src_value, value))) {
272       ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
273       return false;
274     }
275 
276     // Then perform the actual boxing, and then set the reference.
277     ObjPtr<mirror::Object> boxed = BoxPrimitive(type, src_value);
278     value->SetL(boxed);
279     return true;
280   } else {
281     // The source type is a reference and the target type is a primitive, so we must unbox.
282     DCHECK(IsReferenceType(from_type));
283     DCHECK(IsPrimitiveType(to_type));
284 
285     ObjPtr<mirror::Object> from_obj(src_value.GetL());
286     if (UNLIKELY(from_obj.IsNull())) {
287       ThrowNullPointerException(
288           StringPrintf("Expected to unbox a '%s' primitive type but was returned null",
289                        from->PrettyDescriptor().c_str()).c_str());
290       return false;
291     }
292 
293     ObjPtr<mirror::Class> from_obj_type = from_obj->GetClass();
294     Primitive::Type from_primitive_type;
295     if (!GetUnboxedPrimitiveType(from_obj_type, &from_primitive_type)) {
296       ThrowClassCastException(from, to);
297       return false;
298     }
299 
300     Primitive::Type unboxed_type;
301     JValue unboxed_value;
302     if (UNLIKELY(!GetUnboxedTypeAndValue(from_obj, &unboxed_type, &unboxed_value))) {
303       ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
304       return false;
305     }
306 
307     if (UNLIKELY(!ConvertPrimitiveValueNoThrow(unboxed_type, to_type, unboxed_value, value))) {
308       if (from->IsAssignableFrom(GetBoxedPrimitiveClass(to_type))) {
309         // CallSite may be Number, but the Number object is
310         // incompatible, e.g. Number (Integer) for a short.
311         ThrowClassCastException(from, to);
312       } else {
313         // CallSite is incompatible, e.g. Integer for a short.
314         ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
315       }
316       return false;
317     }
318 
319     return true;
320   }
321 }
322 
323 namespace {
324 
CopyArgumentsFromCallerFrame(const ShadowFrame & caller_frame,ShadowFrame * callee_frame,const InstructionOperands * const operands,const size_t first_dst_reg)325 inline void CopyArgumentsFromCallerFrame(const ShadowFrame& caller_frame,
326                                          ShadowFrame* callee_frame,
327                                          const InstructionOperands* const operands,
328                                          const size_t first_dst_reg)
329     REQUIRES_SHARED(Locks::mutator_lock_) {
330   for (size_t i = 0; i < operands->GetNumberOfOperands(); ++i) {
331     size_t dst_reg = first_dst_reg + i;
332     size_t src_reg = operands->GetOperand(i);
333     // Uint required, so that sign extension does not make this wrong on 64-bit systems
334     uint32_t src_value = caller_frame.GetVReg(src_reg);
335     ObjPtr<mirror::Object> o = caller_frame.GetVRegReference<kVerifyNone>(src_reg);
336     // If both register locations contains the same value, the register probably holds a reference.
337     // Note: As an optimization, non-moving collectors leave a stale reference value
338     // in the references array even after the original vreg was overwritten to a non-reference.
339     if (src_value == reinterpret_cast<uintptr_t>(o.Ptr())) {
340       callee_frame->SetVRegReference(dst_reg, o);
341     } else {
342       callee_frame->SetVReg(dst_reg, src_value);
343     }
344   }
345 }
346 
347 // Calculate the number of ins for a proxy or native method, where we
348 // can't just look at the code item.
GetInsForProxyOrNativeMethod(ArtMethod * method)349 static inline size_t GetInsForProxyOrNativeMethod(ArtMethod* method)
350     REQUIRES_SHARED(Locks::mutator_lock_) {
351   DCHECK(method->IsNative() || method->IsProxyMethod());
352   method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
353   uint32_t shorty_length = 0;
354   const char* shorty = method->GetShorty(&shorty_length);
355 
356   // Static methods do not include the receiver. The receiver isn't included
357   // in the shorty_length though the return value is.
358   size_t num_ins = method->IsStatic() ? shorty_length - 1 : shorty_length;
359   for (const char* c = shorty + 1; *c != '\0'; ++c) {
360     if (*c == 'J' || *c == 'D') {
361       ++num_ins;
362     }
363   }
364   return num_ins;
365 }
366 
MethodHandleInvokeTransform(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const InstructionOperands * const operands,JValue * result)367 static inline bool MethodHandleInvokeTransform(Thread* self,
368                                                ShadowFrame& shadow_frame,
369                                                Handle<mirror::MethodHandle> method_handle,
370                                                Handle<mirror::MethodType> callsite_type,
371                                                const InstructionOperands* const operands,
372                                                JValue* result)
373     REQUIRES_SHARED(Locks::mutator_lock_) {
374   // This can be fixed to two, because the method we're calling here
375   // (MethodHandle.transformInternal) doesn't have any locals and the signature
376   // is known :
377   //
378   // private MethodHandle.transformInternal(EmulatedStackFrame sf);
379   //
380   // This means we need only two vregs :
381   // - One for the method_handle object.
382   // - One for the only method argument (an EmulatedStackFrame).
383   static constexpr size_t kNumRegsForTransform = 2;
384 
385   ArtMethod* called_method = method_handle->GetTargetMethod();
386   CodeItemDataAccessor accessor(called_method->DexInstructionData());
387   DCHECK_EQ(kNumRegsForTransform, accessor.RegistersSize());
388   DCHECK_EQ(kNumRegsForTransform, accessor.InsSize());
389 
390   StackHandleScope<2> hs(self);
391   Handle<mirror::MethodType> callee_type(hs.NewHandle(method_handle->GetMethodType()));
392   Handle<mirror::EmulatedStackFrame> sf(
393       hs.NewHandle<mirror::EmulatedStackFrame>(
394           mirror::EmulatedStackFrame::CreateFromShadowFrameAndArgs(
395               self, callsite_type, callee_type, shadow_frame, operands)));
396   if (sf == nullptr) {
397     DCHECK(self->IsExceptionPending());
398     return false;
399   }
400 
401   const char* old_cause = self->StartAssertNoThreadSuspension("MethodHandleInvokeTransform");
402   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
403       CREATE_SHADOW_FRAME(kNumRegsForTransform, called_method, /* dex pc */ 0);
404   ShadowFrame* new_shadow_frame = shadow_frame_unique_ptr.get();
405   new_shadow_frame->SetVRegReference(0, method_handle.Get());
406   new_shadow_frame->SetVRegReference(1, sf.Get());
407   self->EndAssertNoThreadSuspension(old_cause);
408 
409   PerformCall(self,
410               accessor,
411               shadow_frame.GetMethod(),
412               0 /* first destination register */,
413               new_shadow_frame,
414               result,
415               interpreter::ShouldStayInSwitchInterpreter(called_method));
416   if (self->IsExceptionPending()) {
417     return false;
418   }
419 
420   // If the called transformer method we called has returned a value, then we
421   // need to copy it back to |result|.
422   sf->GetReturnValue(self, result);
423   return true;
424 }
425 
GetAndInitializeDeclaringClass(Thread * self,ArtField * field)426 inline static ObjPtr<mirror::Class> GetAndInitializeDeclaringClass(Thread* self, ArtField* field)
427     REQUIRES_SHARED(Locks::mutator_lock_) {
428   // Method handle invocations on static fields should ensure class is
429   // initialized. This usually happens when an instance is constructed
430   // or class members referenced, but this is not guaranteed when
431   // looking up method handles.
432   ObjPtr<mirror::Class> klass = field->GetDeclaringClass();
433   if (UNLIKELY(!klass->IsInitialized())) {
434     StackHandleScope<1> hs(self);
435     HandleWrapperObjPtr<mirror::Class> h(hs.NewHandleWrapper(&klass));
436     if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h, true, true)) {
437       DCHECK(self->IsExceptionPending());
438       return nullptr;
439     }
440   }
441   return klass;
442 }
443 
RefineTargetMethod(Thread * self,ShadowFrame & shadow_frame,const mirror::MethodHandle::Kind & handle_kind,ObjPtr<mirror::MethodType> handle_type,const uint32_t receiver_reg,ArtMethod * target_method)444 ArtMethod* RefineTargetMethod(Thread* self,
445                               ShadowFrame& shadow_frame,
446                               const mirror::MethodHandle::Kind& handle_kind,
447                               ObjPtr<mirror::MethodType> handle_type,
448                               const uint32_t receiver_reg,
449                               ArtMethod* target_method) REQUIRES_SHARED(Locks::mutator_lock_) {
450   if (handle_kind == mirror::MethodHandle::Kind::kInvokeVirtual ||
451       handle_kind == mirror::MethodHandle::Kind::kInvokeInterface) {
452     // For virtual and interface methods ensure target_method points to
453     // the actual method to invoke.
454     ObjPtr<mirror::Object> receiver(shadow_frame.GetVRegReference(receiver_reg));
455     ObjPtr<mirror::Class> declaring_class(target_method->GetDeclaringClass());
456     if (receiver == nullptr || receiver->GetClass() != declaring_class) {
457       // Verify that _vRegC is an object reference and of the type expected by
458       // the receiver.
459       if (!VerifyObjectIsClass(receiver, declaring_class)) {
460         DCHECK(self->IsExceptionPending());
461         return nullptr;
462       }
463       return receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(
464           target_method, kRuntimePointerSize);
465     }
466   } else if (handle_kind == mirror::MethodHandle::Kind::kInvokeDirect) {
467     // String constructors are a special case, they are replaced with
468     // StringFactory methods.
469     if (target_method->IsStringConstructor()) {
470       DCHECK(handle_type->GetRType()->IsStringClass());
471       return WellKnownClasses::StringInitToStringFactory(target_method);
472     }
473   } else if (handle_kind == mirror::MethodHandle::Kind::kInvokeSuper) {
474     // Note that we're not dynamically dispatching on the type of the receiver
475     // here. We use the static type of the "receiver" object that we've
476     // recorded in the method handle's type, which will be the same as the
477     // special caller that was specified at the point of lookup.
478     ObjPtr<mirror::Class> referrer_class = handle_type->GetPTypes()->Get(0);
479     ObjPtr<mirror::Class> declaring_class = target_method->GetDeclaringClass();
480     if (referrer_class == declaring_class) {
481       return target_method;
482     }
483     if (declaring_class->IsInterface()) {
484       if (target_method->IsAbstract()) {
485         std::string msg =
486             "Method " + target_method->PrettyMethod() + " is abstract interface method!";
487         ThrowIllegalAccessException(msg.c_str());
488         return nullptr;
489       }
490     } else {
491       ObjPtr<mirror::Class> super_class = referrer_class->GetSuperClass();
492       uint16_t vtable_index = target_method->GetMethodIndex();
493       DCHECK(super_class != nullptr);
494       DCHECK(super_class->HasVTable());
495       // Note that super_class is a super of referrer_class and target_method
496       // will always be declared by super_class (or one of its super classes).
497       DCHECK_LT(vtable_index, super_class->GetVTableLength());
498       return super_class->GetVTableEntry(vtable_index, kRuntimePointerSize);
499     }
500   }
501   return target_method;
502 }
503 
504 // Helper for getters in invoke-polymorphic.
MethodHandleFieldGet(Thread * self,const ShadowFrame & shadow_frame,ObjPtr<mirror::Object> & obj,ArtField * field,Primitive::Type field_type,JValue * result)505 inline static void MethodHandleFieldGet(Thread* self,
506                                         const ShadowFrame& shadow_frame,
507                                         ObjPtr<mirror::Object>& obj,
508                                         ArtField* field,
509                                         Primitive::Type field_type,
510                                         JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
511   switch (field_type) {
512     case Primitive::kPrimBoolean:
513       DoFieldGetCommon<Primitive::kPrimBoolean>(self, shadow_frame, obj, field, result);
514       break;
515     case Primitive::kPrimByte:
516       DoFieldGetCommon<Primitive::kPrimByte>(self, shadow_frame, obj, field, result);
517       break;
518     case Primitive::kPrimChar:
519       DoFieldGetCommon<Primitive::kPrimChar>(self, shadow_frame, obj, field, result);
520       break;
521     case Primitive::kPrimShort:
522       DoFieldGetCommon<Primitive::kPrimShort>(self, shadow_frame, obj, field, result);
523       break;
524     case Primitive::kPrimInt:
525       DoFieldGetCommon<Primitive::kPrimInt>(self, shadow_frame, obj, field, result);
526       break;
527     case Primitive::kPrimLong:
528       DoFieldGetCommon<Primitive::kPrimLong>(self, shadow_frame, obj, field, result);
529       break;
530     case Primitive::kPrimFloat:
531       DoFieldGetCommon<Primitive::kPrimInt>(self, shadow_frame, obj, field, result);
532       break;
533     case Primitive::kPrimDouble:
534       DoFieldGetCommon<Primitive::kPrimLong>(self, shadow_frame, obj, field, result);
535       break;
536     case Primitive::kPrimNot:
537       DoFieldGetCommon<Primitive::kPrimNot>(self, shadow_frame, obj, field, result);
538       break;
539     case Primitive::kPrimVoid:
540       LOG(FATAL) << "Unreachable: " << field_type;
541       UNREACHABLE();
542   }
543 }
544 
545 // Helper for setters in invoke-polymorphic.
MethodHandleFieldPut(Thread * self,ShadowFrame & shadow_frame,ObjPtr<mirror::Object> & obj,ArtField * field,Primitive::Type field_type,JValue & value)546 inline bool MethodHandleFieldPut(Thread* self,
547                                  ShadowFrame& shadow_frame,
548                                  ObjPtr<mirror::Object>& obj,
549                                  ArtField* field,
550                                  Primitive::Type field_type,
551                                  JValue& value) REQUIRES_SHARED(Locks::mutator_lock_) {
552   DCHECK(!Runtime::Current()->IsActiveTransaction());
553   static const bool kTransaction = false;         // Not in a transaction.
554   switch (field_type) {
555     case Primitive::kPrimBoolean:
556       return
557           DoFieldPutCommon<Primitive::kPrimBoolean, kTransaction>(
558               self, shadow_frame, obj, field, value);
559     case Primitive::kPrimByte:
560       return DoFieldPutCommon<Primitive::kPrimByte, kTransaction>(
561           self, shadow_frame, obj, field, value);
562     case Primitive::kPrimChar:
563       return DoFieldPutCommon<Primitive::kPrimChar, kTransaction>(
564           self, shadow_frame, obj, field, value);
565     case Primitive::kPrimShort:
566       return DoFieldPutCommon<Primitive::kPrimShort, kTransaction>(
567           self, shadow_frame, obj, field, value);
568     case Primitive::kPrimInt:
569     case Primitive::kPrimFloat:
570       return DoFieldPutCommon<Primitive::kPrimInt, kTransaction>(
571           self, shadow_frame, obj, field, value);
572     case Primitive::kPrimLong:
573     case Primitive::kPrimDouble:
574       return DoFieldPutCommon<Primitive::kPrimLong, kTransaction>(
575           self, shadow_frame, obj, field, value);
576     case Primitive::kPrimNot:
577       return DoFieldPutCommon<Primitive::kPrimNot, kTransaction>(
578           self, shadow_frame, obj, field, value);
579     case Primitive::kPrimVoid:
580       LOG(FATAL) << "Unreachable: " << field_type;
581       UNREACHABLE();
582   }
583 }
584 
GetValueFromShadowFrame(const ShadowFrame & shadow_frame,Primitive::Type field_type,uint32_t vreg)585 static JValue GetValueFromShadowFrame(const ShadowFrame& shadow_frame,
586                                       Primitive::Type field_type,
587                                       uint32_t vreg) REQUIRES_SHARED(Locks::mutator_lock_) {
588   JValue field_value;
589   switch (field_type) {
590     case Primitive::kPrimBoolean:
591       field_value.SetZ(static_cast<uint8_t>(shadow_frame.GetVReg(vreg)));
592       break;
593     case Primitive::kPrimByte:
594       field_value.SetB(static_cast<int8_t>(shadow_frame.GetVReg(vreg)));
595       break;
596     case Primitive::kPrimChar:
597       field_value.SetC(static_cast<uint16_t>(shadow_frame.GetVReg(vreg)));
598       break;
599     case Primitive::kPrimShort:
600       field_value.SetS(static_cast<int16_t>(shadow_frame.GetVReg(vreg)));
601       break;
602     case Primitive::kPrimInt:
603     case Primitive::kPrimFloat:
604       field_value.SetI(shadow_frame.GetVReg(vreg));
605       break;
606     case Primitive::kPrimLong:
607     case Primitive::kPrimDouble:
608       field_value.SetJ(shadow_frame.GetVRegLong(vreg));
609       break;
610     case Primitive::kPrimNot:
611       field_value.SetL(shadow_frame.GetVRegReference(vreg));
612       break;
613     case Primitive::kPrimVoid:
614       LOG(FATAL) << "Unreachable: " << field_type;
615       UNREACHABLE();
616   }
617   return field_value;
618 }
619 
MethodHandleFieldAccess(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const InstructionOperands * const operands,JValue * result)620 bool MethodHandleFieldAccess(Thread* self,
621                              ShadowFrame& shadow_frame,
622                              Handle<mirror::MethodHandle> method_handle,
623                              Handle<mirror::MethodType> callsite_type,
624                              const InstructionOperands* const operands,
625                              JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
626   StackHandleScope<1> hs(self);
627   const mirror::MethodHandle::Kind handle_kind = method_handle->GetHandleKind();
628   ArtField* field = method_handle->GetTargetField();
629   Primitive::Type field_type = field->GetTypeAsPrimitiveType();
630   switch (handle_kind) {
631     case mirror::MethodHandle::kInstanceGet: {
632       size_t obj_reg = operands->GetOperand(0);
633       ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(obj_reg);
634       if (obj == nullptr) {
635         ThrowNullPointerException("Receiver is null");
636         return false;
637       }
638       MethodHandleFieldGet(self, shadow_frame, obj, field, field_type, result);
639       return true;
640     }
641     case mirror::MethodHandle::kStaticGet: {
642       ObjPtr<mirror::Object> obj = GetAndInitializeDeclaringClass(self, field);
643       if (obj == nullptr) {
644         DCHECK(self->IsExceptionPending());
645         return false;
646       }
647       MethodHandleFieldGet(self, shadow_frame, obj, field, field_type, result);
648       return true;
649     }
650     case mirror::MethodHandle::kInstancePut: {
651       size_t obj_reg = operands->GetOperand(0);
652       size_t value_reg = operands->GetOperand(1);
653       const size_t kPTypeIndex = 1;
654       // Use ptypes instead of field type since we may be unboxing a reference for a primitive
655       // field. The field type is incorrect for this case.
656       JValue value = GetValueFromShadowFrame(
657           shadow_frame,
658           callsite_type->GetPTypes()->Get(kPTypeIndex)->GetPrimitiveType(),
659           value_reg);
660       ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(obj_reg);
661       if (obj == nullptr) {
662         ThrowNullPointerException("Receiver is null");
663         return false;
664       }
665       return MethodHandleFieldPut(self, shadow_frame, obj, field, field_type, value);
666     }
667     case mirror::MethodHandle::kStaticPut: {
668       ObjPtr<mirror::Object> obj = GetAndInitializeDeclaringClass(self, field);
669       if (obj == nullptr) {
670         DCHECK(self->IsExceptionPending());
671         return false;
672       }
673       size_t value_reg = operands->GetOperand(0);
674       const size_t kPTypeIndex = 0;
675       // Use ptypes instead of field type since we may be unboxing a reference for a primitive
676       // field. The field type is incorrect for this case.
677       JValue value = GetValueFromShadowFrame(
678           shadow_frame,
679           callsite_type->GetPTypes()->Get(kPTypeIndex)->GetPrimitiveType(),
680           value_reg);
681       return MethodHandleFieldPut(self, shadow_frame, obj, field, field_type, value);
682     }
683     default:
684       LOG(FATAL) << "Unreachable: " << handle_kind;
685       UNREACHABLE();
686   }
687 }
688 
DoVarHandleInvokeTranslation(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const InstructionOperands * const operands,JValue * result)689 bool DoVarHandleInvokeTranslation(Thread* self,
690                                   ShadowFrame& shadow_frame,
691                                   Handle<mirror::MethodHandle> method_handle,
692                                   Handle<mirror::MethodType> callsite_type,
693                                   const InstructionOperands* const operands,
694                                   JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
695   //
696   // Basic checks that apply in all cases.
697   //
698   StackHandleScope<6> hs(self);
699   Handle<mirror::ObjectArray<mirror::Class>>
700       callsite_ptypes(hs.NewHandle(callsite_type->GetPTypes()));
701   Handle<mirror::ObjectArray<mirror::Class>>
702          mh_ptypes(hs.NewHandle(method_handle->GetMethodType()->GetPTypes()));
703 
704   // Check that the first parameter is a VarHandle
705   if (callsite_ptypes->GetLength() < 1 ||
706       !mh_ptypes->Get(0)->IsAssignableFrom(callsite_ptypes->Get(0)) ||
707       mh_ptypes->Get(0) != GetClassRoot<mirror::VarHandle>()) {
708     ThrowWrongMethodTypeException(method_handle->GetMethodType(), callsite_type.Get());
709     return false;
710   }
711 
712   // Get the receiver
713   ObjPtr<mirror::Object> receiver = shadow_frame.GetVRegReference(operands->GetOperand(0));
714   if (receiver == nullptr) {
715     ThrowNullPointerException("Expected argument 1 to be a non-null VarHandle");
716     return false;
717   }
718 
719   // Cast to VarHandle instance
720   Handle<mirror::VarHandle> vh(hs.NewHandle(ObjPtr<mirror::VarHandle>::DownCast(receiver)));
721   DCHECK(GetClassRoot<mirror::VarHandle>()->IsAssignableFrom(vh->GetClass()));
722 
723   // Determine the accessor kind to dispatch
724   ArtMethod* target_method = method_handle->GetTargetMethod();
725   int intrinsic_index = target_method->GetIntrinsic();
726   mirror::VarHandle::AccessMode access_mode =
727       mirror::VarHandle::GetAccessModeByIntrinsic(static_cast<Intrinsics>(intrinsic_index));
728   Handle<mirror::MethodType> vh_type =
729       hs.NewHandle(vh->GetMethodTypeForAccessMode(self, access_mode));
730   Handle<mirror::MethodType> mh_invoke_type = hs.NewHandle(
731       mirror::MethodType::CloneWithoutLeadingParameter(self, method_handle->GetMethodType()));
732   if (method_handle->GetHandleKind() == mirror::MethodHandle::Kind::kInvokeVarHandleExact) {
733     if (!mh_invoke_type->IsExactMatch(vh_type.Get())) {
734       ThrowWrongMethodTypeException(vh_type.Get(), mh_invoke_type.Get());
735       return false;
736     }
737   }
738 
739   Handle<mirror::MethodType> callsite_type_without_varhandle =
740       hs.NewHandle(mirror::MethodType::CloneWithoutLeadingParameter(self, callsite_type.Get()));
741   NoReceiverInstructionOperands varhandle_operands(operands);
742   return VarHandleInvokeAccessor(self,
743                                  shadow_frame,
744                                  vh,
745                                  callsite_type_without_varhandle,
746                                  access_mode,
747                                  &varhandle_operands,
748                                  result);
749 }
750 
DoMethodHandleInvokeMethod(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,const InstructionOperands * const operands,JValue * result)751 static bool DoMethodHandleInvokeMethod(Thread* self,
752                                        ShadowFrame& shadow_frame,
753                                        Handle<mirror::MethodHandle> method_handle,
754                                        const InstructionOperands* const operands,
755                                        JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
756   ArtMethod* target_method = method_handle->GetTargetMethod();
757   uint32_t receiver_reg = (operands->GetNumberOfOperands() > 0) ? operands->GetOperand(0) : 0u;
758   ArtMethod* called_method = RefineTargetMethod(self,
759                                                 shadow_frame,
760                                                 method_handle->GetHandleKind(),
761                                                 method_handle->GetMethodType(),
762                                                 receiver_reg,
763                                                 target_method);
764   if (called_method == nullptr) {
765     DCHECK(self->IsExceptionPending());
766     return false;
767   }
768   // Compute method information.
769   CodeItemDataAccessor accessor(called_method->DexInstructionData());
770   uint16_t num_regs;
771   size_t first_dest_reg;
772   if (LIKELY(accessor.HasCodeItem())) {
773     num_regs = accessor.RegistersSize();
774     first_dest_reg = num_regs - accessor.InsSize();
775     // Parameter registers go at the end of the shadow frame.
776     DCHECK_NE(first_dest_reg, (size_t)-1);
777   } else {
778     // No local regs for proxy and native methods.
779     DCHECK(called_method->IsNative() || called_method->IsProxyMethod());
780     num_regs = GetInsForProxyOrNativeMethod(called_method);
781     first_dest_reg = 0;
782   }
783 
784   const char* old_cause = self->StartAssertNoThreadSuspension("DoMethodHandleInvokeMethod");
785   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
786       CREATE_SHADOW_FRAME(num_regs, called_method, /* dex pc */ 0);
787   ShadowFrame* new_shadow_frame = shadow_frame_unique_ptr.get();
788   CopyArgumentsFromCallerFrame(shadow_frame, new_shadow_frame, operands, first_dest_reg);
789   self->EndAssertNoThreadSuspension(old_cause);
790 
791   PerformCall(self,
792               accessor,
793               shadow_frame.GetMethod(),
794               first_dest_reg,
795               new_shadow_frame,
796               result,
797               interpreter::ShouldStayInSwitchInterpreter(called_method));
798   if (self->IsExceptionPending()) {
799     return false;
800   }
801   return true;
802 }
803 
MethodHandleInvokeExactInternal(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const InstructionOperands * const operands,JValue * result)804 static bool MethodHandleInvokeExactInternal(Thread* self,
805                                             ShadowFrame& shadow_frame,
806                                             Handle<mirror::MethodHandle> method_handle,
807                                             Handle<mirror::MethodType> callsite_type,
808                                             const InstructionOperands* const operands,
809                                             JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
810   if (!callsite_type->IsExactMatch(method_handle->GetMethodType())) {
811     ThrowWrongMethodTypeException(method_handle->GetMethodType(), callsite_type.Get());
812     return false;
813   }
814 
815   switch (method_handle->GetHandleKind()) {
816     case mirror::MethodHandle::Kind::kInvokeDirect:
817     case mirror::MethodHandle::Kind::kInvokeInterface:
818     case mirror::MethodHandle::Kind::kInvokeStatic:
819     case mirror::MethodHandle::Kind::kInvokeSuper:
820     case mirror::MethodHandle::Kind::kInvokeVirtual:
821       return DoMethodHandleInvokeMethod(self, shadow_frame, method_handle, operands, result);
822     case mirror::MethodHandle::Kind::kInstanceGet:
823     case mirror::MethodHandle::Kind::kInstancePut:
824     case mirror::MethodHandle::Kind::kStaticGet:
825     case mirror::MethodHandle::Kind::kStaticPut:
826       return MethodHandleFieldAccess(
827           self, shadow_frame, method_handle, callsite_type, operands, result);
828     case mirror::MethodHandle::Kind::kInvokeTransform:
829       return MethodHandleInvokeTransform(
830           self, shadow_frame, method_handle, callsite_type, operands, result);
831     case mirror::MethodHandle::Kind::kInvokeVarHandle:
832     case mirror::MethodHandle::Kind::kInvokeVarHandleExact:
833       return DoVarHandleInvokeTranslation(
834           self, shadow_frame, method_handle, callsite_type, operands, result);
835   }
836 }
837 
MethodHandleInvokeInternal(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const InstructionOperands * const operands,JValue * result)838 static bool MethodHandleInvokeInternal(Thread* self,
839                                        ShadowFrame& shadow_frame,
840                                        Handle<mirror::MethodHandle> method_handle,
841                                        Handle<mirror::MethodType> callsite_type,
842                                        const InstructionOperands* const operands,
843                                        JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
844   StackHandleScope<2> hs(self);
845   Handle<mirror::MethodType> method_handle_type(hs.NewHandle(method_handle->GetMethodType()));
846   // Non-exact invoke behaves as calling mh.asType(newType). In ART, asType() is implemented
847   // as a transformer and it is expensive to call so check first if it's really necessary.
848   //
849   // There are two cases where the asType() transformation can be skipped:
850   //
851   // 1) the call site and type of the MethodHandle match, ie code is calling invoke()
852   //    unnecessarily.
853   //
854   // 2) when the call site can be trivially converted to the MethodHandle type due to how
855   //    values are represented in the ShadowFrame, ie all registers in the shadow frame are
856   //    32-bit, there is no byte, short, char, etc. So a call site with arguments of these
857   //    kinds can be trivially converted to one with int arguments. Similarly if the reference
858   //    types are assignable between the call site and MethodHandle type, then as asType()
859   //    transformation isn't really doing any work.
860   //
861   // The following IsInPlaceConvertible check determines if either of these opportunities to
862   // skip asType() are true.
863   if (callsite_type->IsInPlaceConvertible(method_handle_type.Get())) {
864     return MethodHandleInvokeExact(
865         self, shadow_frame, method_handle, method_handle_type, operands, result);
866   }
867 
868   // Use asType() variant of this MethodHandle to adapt callsite to the target.
869   MutableHandle<mirror::MethodHandle> atc(hs.NewHandle(method_handle->GetAsTypeCache()));
870   if (atc == nullptr || !callsite_type->IsExactMatch(atc->GetMethodType())) {
871     // Cached asType adapter does not exist or is for another call site. Call
872     // MethodHandle::asType() to get an appropriate adapter.
873     ArtMethod* as_type = WellKnownClasses::java_lang_invoke_MethodHandle_asType;
874     ObjPtr<mirror::MethodHandle> atc_method_handle = ObjPtr<mirror::MethodHandle>::DownCast(
875         as_type->InvokeVirtual<'L', 'L'>(self, method_handle.Get(), callsite_type.Get()));
876     if (atc_method_handle == nullptr) {
877       DCHECK(self->IsExceptionPending());
878       return false;
879     }
880     atc.Assign(atc_method_handle);
881     DCHECK(!atc.IsNull());
882   }
883 
884   return MethodHandleInvokeExact(self, shadow_frame, atc, callsite_type, operands, result);
885 }
886 
887 }  // namespace
888 
MethodHandleInvoke(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const InstructionOperands * const operands,JValue * result)889 bool MethodHandleInvoke(Thread* self,
890                         ShadowFrame& shadow_frame,
891                         Handle<mirror::MethodHandle> method_handle,
892                         Handle<mirror::MethodType> callsite_type,
893                         const InstructionOperands* const operands,
894                         JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
895     return MethodHandleInvokeInternal(
896         self, shadow_frame, method_handle, callsite_type, operands, result);
897 }
898 
MethodHandleInvokeExact(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const InstructionOperands * const operands,JValue * result)899 bool MethodHandleInvokeExact(Thread* self,
900                              ShadowFrame& shadow_frame,
901                              Handle<mirror::MethodHandle> method_handle,
902                              Handle<mirror::MethodType> callsite_type,
903                              const InstructionOperands* const operands,
904                              JValue* result) REQUIRES_SHARED(Locks::mutator_lock_) {
905     return MethodHandleInvokeExactInternal(
906         self, shadow_frame, method_handle, callsite_type, operands, result);
907 }
908 
MethodHandleInvokeExactWithFrame(Thread * self,Handle<mirror::MethodHandle> method_handle,Handle<mirror::EmulatedStackFrame> emulated_frame)909 void MethodHandleInvokeExactWithFrame(Thread* self,
910                                       Handle<mirror::MethodHandle> method_handle,
911                                       Handle<mirror::EmulatedStackFrame> emulated_frame)
912     REQUIRES_SHARED(Locks::mutator_lock_) {
913   StackHandleScope<1> hs(self);
914   Handle<mirror::MethodType> callsite_type = hs.NewHandle(emulated_frame->GetType());
915 
916   // Copy arguments from the EmalatedStackFrame to a ShadowFrame.
917   const uint16_t num_vregs = callsite_type->NumberOfVRegs();
918 
919   const char* old_cause = self->StartAssertNoThreadSuspension("EmulatedStackFrame to ShadowFrame");
920   ArtMethod* invoke_exact = WellKnownClasses::java_lang_invoke_MethodHandle_invokeExact;
921   ShadowFrameAllocaUniquePtr shadow_frame =
922       CREATE_SHADOW_FRAME(num_vregs, invoke_exact, /*dex_pc*/ 0);
923   emulated_frame->WriteToShadowFrame(self, callsite_type, 0, shadow_frame.get());
924   self->EndAssertNoThreadSuspension(old_cause);
925 
926   ManagedStack fragment;
927   self->PushManagedStackFragment(&fragment);
928   self->PushShadowFrame(shadow_frame.get());
929 
930   JValue result;
931   RangeInstructionOperands operands(0, num_vregs);
932   bool success = MethodHandleInvokeExact(self,
933                                          *shadow_frame.get(),
934                                          method_handle,
935                                          callsite_type,
936                                          &operands,
937                                          &result);
938   DCHECK_NE(success, self->IsExceptionPending());
939   if (success) {
940     emulated_frame->SetReturnValue(self, result);
941   }
942 
943   self->PopShadowFrame();
944   self->PopManagedStackFragment(fragment);
945 }
946 
947 }  // namespace art
948