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/stringprintf.h"
20 
21 #include "common_dex_operations.h"
22 #include "jvalue.h"
23 #include "jvalue-inl.h"
24 #include "mirror/emulated_stack_frame.h"
25 #include "mirror/method_handle_impl-inl.h"
26 #include "mirror/method_type.h"
27 #include "reflection.h"
28 #include "reflection-inl.h"
29 #include "well_known_classes.h"
30 
31 namespace art {
32 
33 using android::base::StringPrintf;
34 
35 namespace {
36 
37 #define PRIMITIVES_LIST(V) \
38   V(Primitive::kPrimBoolean, Boolean, Boolean, Z) \
39   V(Primitive::kPrimByte, Byte, Byte, B)          \
40   V(Primitive::kPrimChar, Char, Character, C)     \
41   V(Primitive::kPrimShort, Short, Short, S)       \
42   V(Primitive::kPrimInt, Int, Integer, I)         \
43   V(Primitive::kPrimLong, Long, Long, J)          \
44   V(Primitive::kPrimFloat, Float, Float, F)       \
45   V(Primitive::kPrimDouble, Double, Double, D)
46 
47 // Assigns |type| to the primitive type associated with |klass|. Returns
48 // true iff. |klass| was a boxed type (Integer, Long etc.), false otherwise.
GetUnboxedPrimitiveType(ObjPtr<mirror::Class> klass,Primitive::Type * type)49 bool GetUnboxedPrimitiveType(ObjPtr<mirror::Class> klass, Primitive::Type* type)
50     REQUIRES_SHARED(Locks::mutator_lock_) {
51   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
52   std::string storage;
53   const char* descriptor = klass->GetDescriptor(&storage);
54   static const char kJavaLangPrefix[] = "Ljava/lang/";
55   static const size_t kJavaLangPrefixSize = sizeof(kJavaLangPrefix) - 1;
56   if (strncmp(descriptor, kJavaLangPrefix, kJavaLangPrefixSize) != 0) {
57     return false;
58   }
59 
60   descriptor += kJavaLangPrefixSize;
61 #define LOOKUP_PRIMITIVE(primitive, _, java_name, ___) \
62   if (strcmp(descriptor, #java_name ";") == 0) {       \
63     *type = primitive;                                 \
64     return true;                                       \
65   }
66 
67   PRIMITIVES_LIST(LOOKUP_PRIMITIVE);
68 #undef LOOKUP_PRIMITIVE
69   return false;
70 }
71 
GetBoxedPrimitiveClass(Primitive::Type type)72 ObjPtr<mirror::Class> GetBoxedPrimitiveClass(Primitive::Type type)
73     REQUIRES_SHARED(Locks::mutator_lock_) {
74   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
75   jmethodID m = nullptr;
76   switch (type) {
77 #define CASE_PRIMITIVE(primitive, _, java_name, __)              \
78     case primitive:                                              \
79       m = WellKnownClasses::java_lang_ ## java_name ## _valueOf; \
80       break;
81     PRIMITIVES_LIST(CASE_PRIMITIVE);
82 #undef CASE_PRIMITIVE
83     case Primitive::Type::kPrimNot:
84     case Primitive::Type::kPrimVoid:
85       return nullptr;
86   }
87   return jni::DecodeArtMethod(m)->GetDeclaringClass();
88 }
89 
GetUnboxedTypeAndValue(ObjPtr<mirror::Object> o,Primitive::Type * type,JValue * value)90 bool GetUnboxedTypeAndValue(ObjPtr<mirror::Object> o, Primitive::Type* type, JValue* value)
91     REQUIRES_SHARED(Locks::mutator_lock_) {
92   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
93   ObjPtr<mirror::Class> klass = o->GetClass();
94   ArtField* primitive_field = &klass->GetIFieldsPtr()->At(0);
95 #define CASE_PRIMITIVE(primitive, abbrev, _, shorthand)         \
96   if (klass == GetBoxedPrimitiveClass(primitive)) {             \
97     *type = primitive;                                          \
98     value->Set ## shorthand(primitive_field->Get ## abbrev(o)); \
99     return true;                                                \
100   }
101   PRIMITIVES_LIST(CASE_PRIMITIVE)
102 #undef CASE_PRIMITIVE
103   return false;
104 }
105 
IsReferenceType(Primitive::Type type)106 inline bool IsReferenceType(Primitive::Type type) {
107   return type == Primitive::kPrimNot;
108 }
109 
IsPrimitiveType(Primitive::Type type)110 inline bool IsPrimitiveType(Primitive::Type type) {
111   return !IsReferenceType(type);
112 }
113 
114 }  // namespace
115 
IsParameterTypeConvertible(ObjPtr<mirror::Class> from,ObjPtr<mirror::Class> to)116 bool IsParameterTypeConvertible(ObjPtr<mirror::Class> from, ObjPtr<mirror::Class> to)
117     REQUIRES_SHARED(Locks::mutator_lock_) {
118   // This function returns true if there's any conceivable conversion
119   // between |from| and |to|. It's expected this method will be used
120   // to determine if a WrongMethodTypeException should be raised. The
121   // decision logic follows the documentation for MethodType.asType().
122   if (from == to) {
123     return true;
124   }
125 
126   Primitive::Type from_primitive = from->GetPrimitiveType();
127   Primitive::Type to_primitive = to->GetPrimitiveType();
128   DCHECK(from_primitive != Primitive::Type::kPrimVoid);
129   DCHECK(to_primitive != Primitive::Type::kPrimVoid);
130 
131   // If |to| and |from| are references.
132   if (IsReferenceType(from_primitive) && IsReferenceType(to_primitive)) {
133     // Assignability is determined during parameter conversion when
134     // invoking the associated method handle.
135     return true;
136   }
137 
138   // If |to| and |from| are primitives and a widening conversion exists.
139   if (Primitive::IsWidenable(from_primitive, to_primitive)) {
140     return true;
141   }
142 
143   // If |to| is a reference and |from| is a primitive, then boxing conversion.
144   if (IsReferenceType(to_primitive) && IsPrimitiveType(from_primitive)) {
145     return to->IsAssignableFrom(GetBoxedPrimitiveClass(from_primitive));
146   }
147 
148   // If |from| is a reference and |to| is a primitive, then unboxing conversion.
149   if (IsPrimitiveType(to_primitive) && IsReferenceType(from_primitive)) {
150     if (from->DescriptorEquals("Ljava/lang/Object;")) {
151       // Object might be converted into a primitive during unboxing.
152       return true;
153     }
154 
155     if (Primitive::IsNumericType(to_primitive) && from->DescriptorEquals("Ljava/lang/Number;")) {
156       // Number might be unboxed into any of the number primitive types.
157       return true;
158     }
159 
160     Primitive::Type unboxed_type;
161     if (GetUnboxedPrimitiveType(from, &unboxed_type)) {
162       if (unboxed_type == to_primitive) {
163         // Straightforward unboxing conversion such as Boolean => boolean.
164         return true;
165       }
166 
167       // Check if widening operations for numeric primitives would work,
168       // such as Byte => byte => long.
169       return Primitive::IsWidenable(unboxed_type, to_primitive);
170     }
171   }
172 
173   return false;
174 }
175 
IsReturnTypeConvertible(ObjPtr<mirror::Class> from,ObjPtr<mirror::Class> to)176 bool IsReturnTypeConvertible(ObjPtr<mirror::Class> from, ObjPtr<mirror::Class> to)
177     REQUIRES_SHARED(Locks::mutator_lock_) {
178   if (to->GetPrimitiveType() == Primitive::Type::kPrimVoid) {
179     // Result will be ignored.
180     return true;
181   } else if (from->GetPrimitiveType() == Primitive::Type::kPrimVoid) {
182     // Returned value will be 0 / null.
183     return true;
184   } else {
185     // Otherwise apply usual parameter conversion rules.
186     return IsParameterTypeConvertible(from, to);
187   }
188 }
189 
ConvertJValueCommon(Handle<mirror::MethodType> callsite_type,Handle<mirror::MethodType> callee_type,ObjPtr<mirror::Class> from,ObjPtr<mirror::Class> to,JValue * value)190 bool ConvertJValueCommon(
191     Handle<mirror::MethodType> callsite_type,
192     Handle<mirror::MethodType> callee_type,
193     ObjPtr<mirror::Class> from,
194     ObjPtr<mirror::Class> to,
195     JValue* value) {
196   // The reader maybe concerned about the safety of the heap object
197   // that may be in |value|. There is only one case where allocation
198   // is obviously needed and that's for boxing. However, in the case
199   // of boxing |value| contains a non-reference type.
200 
201   const Primitive::Type from_type = from->GetPrimitiveType();
202   const Primitive::Type to_type = to->GetPrimitiveType();
203 
204   // Put incoming value into |src_value| and set return value to 0.
205   // Errors and conversions from void require the return value to be 0.
206   const JValue src_value(*value);
207   value->SetJ(0);
208 
209   // Conversion from void set result to zero.
210   if (from_type == Primitive::kPrimVoid) {
211     return true;
212   }
213 
214   // This method must be called only when the types don't match.
215   DCHECK(from != to);
216 
217   if (IsPrimitiveType(from_type) && IsPrimitiveType(to_type)) {
218     // The source and target types are both primitives.
219     if (UNLIKELY(!ConvertPrimitiveValueNoThrow(from_type, to_type, src_value, value))) {
220       ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
221       return false;
222     }
223     return true;
224   } else if (IsReferenceType(from_type) && IsReferenceType(to_type)) {
225     // They're both reference types. If "from" is null, we can pass it
226     // through unchanged. If not, we must generate a cast exception if
227     // |to| is not assignable from the dynamic type of |ref|.
228     //
229     // Playing it safe with StackHandleScope here, not expecting any allocation
230     // in mirror::Class::IsAssignable().
231     StackHandleScope<2> hs(Thread::Current());
232     Handle<mirror::Class> h_to(hs.NewHandle(to));
233     Handle<mirror::Object> h_obj(hs.NewHandle(src_value.GetL()));
234     if (h_obj != nullptr && !to->IsAssignableFrom(h_obj->GetClass())) {
235       ThrowClassCastException(h_to.Get(), h_obj->GetClass());
236       return false;
237     }
238     value->SetL(h_obj.Get());
239     return true;
240   } else if (IsReferenceType(to_type)) {
241     DCHECK(IsPrimitiveType(from_type));
242     // The source type is a primitive and the target type is a reference, so we must box.
243     // The target type maybe a super class of the boxed source type, for example,
244     // if the source type is int, it's boxed type is java.lang.Integer, and the target
245     // type could be java.lang.Number.
246     Primitive::Type type;
247     if (!GetUnboxedPrimitiveType(to, &type)) {
248       ObjPtr<mirror::Class> boxed_from_class = GetBoxedPrimitiveClass(from_type);
249       if (boxed_from_class->IsSubClass(to)) {
250         type = from_type;
251       } else {
252         ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
253         return false;
254       }
255     }
256 
257     if (UNLIKELY(from_type != type)) {
258       ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
259       return false;
260     }
261 
262     if (!ConvertPrimitiveValueNoThrow(from_type, type, src_value, value)) {
263       ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
264       return false;
265     }
266 
267     // Then perform the actual boxing, and then set the reference.
268     ObjPtr<mirror::Object> boxed = BoxPrimitive(type, src_value);
269     value->SetL(boxed.Ptr());
270     return true;
271   } else {
272     // The source type is a reference and the target type is a primitive, so we must unbox.
273     DCHECK(IsReferenceType(from_type));
274     DCHECK(IsPrimitiveType(to_type));
275 
276     ObjPtr<mirror::Object> from_obj(src_value.GetL());
277     if (UNLIKELY(from_obj == nullptr)) {
278       ThrowNullPointerException(
279           StringPrintf("Expected to unbox a '%s' primitive type but was returned null",
280                        from->PrettyDescriptor().c_str()).c_str());
281       return false;
282     }
283 
284     Primitive::Type unboxed_type;
285     JValue unboxed_value;
286     if (UNLIKELY(!GetUnboxedTypeAndValue(from_obj, &unboxed_type, &unboxed_value))) {
287       ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
288       return false;
289     }
290 
291     if (UNLIKELY(!ConvertPrimitiveValueNoThrow(unboxed_type, to_type, unboxed_value, value))) {
292       ThrowClassCastException(from, to);
293       return false;
294     }
295 
296     return true;
297   }
298 }
299 
300 namespace {
301 
302 template <bool is_range>
CopyArgumentsFromCallerFrame(const ShadowFrame & caller_frame,ShadowFrame * callee_frame,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,const size_t first_dst_reg,const size_t num_regs)303 inline void CopyArgumentsFromCallerFrame(const ShadowFrame& caller_frame,
304                                          ShadowFrame* callee_frame,
305                                          const uint32_t (&args)[Instruction::kMaxVarArgRegs],
306                                          uint32_t first_arg,
307                                          const size_t first_dst_reg,
308                                          const size_t num_regs)
309     REQUIRES_SHARED(Locks::mutator_lock_) {
310   for (size_t i = 0; i < num_regs; ++i) {
311     size_t dst_reg = first_dst_reg + i;
312     size_t src_reg = is_range ? (first_arg + i) : args[i];
313     // Uint required, so that sign extension does not make this wrong on 64-bit systems
314     uint32_t src_value = caller_frame.GetVReg(src_reg);
315     ObjPtr<mirror::Object> o = caller_frame.GetVRegReference<kVerifyNone>(src_reg);
316     // If both register locations contains the same value, the register probably holds a reference.
317     // Note: As an optimization, non-moving collectors leave a stale reference value
318     // in the references array even after the original vreg was overwritten to a non-reference.
319     if (src_value == reinterpret_cast<uintptr_t>(o.Ptr())) {
320       callee_frame->SetVRegReference(dst_reg, o.Ptr());
321     } else {
322       callee_frame->SetVReg(dst_reg, src_value);
323     }
324   }
325 }
326 
327 template <bool is_range>
ConvertAndCopyArgumentsFromCallerFrame(Thread * self,Handle<mirror::MethodType> callsite_type,Handle<mirror::MethodType> callee_type,const ShadowFrame & caller_frame,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,uint32_t first_dst_reg,ShadowFrame * callee_frame)328 inline bool ConvertAndCopyArgumentsFromCallerFrame(
329     Thread* self,
330     Handle<mirror::MethodType> callsite_type,
331     Handle<mirror::MethodType> callee_type,
332     const ShadowFrame& caller_frame,
333     const uint32_t (&args)[Instruction::kMaxVarArgRegs],
334     uint32_t first_arg,
335     uint32_t first_dst_reg,
336     ShadowFrame* callee_frame)
337     REQUIRES_SHARED(Locks::mutator_lock_) {
338   ObjPtr<mirror::ObjectArray<mirror::Class>> from_types(callsite_type->GetPTypes());
339   ObjPtr<mirror::ObjectArray<mirror::Class>> to_types(callee_type->GetPTypes());
340 
341   const int32_t num_method_params = from_types->GetLength();
342   if (to_types->GetLength() != num_method_params) {
343     ThrowWrongMethodTypeException(callee_type.Get(), callsite_type.Get());
344     return false;
345   }
346 
347   ShadowFrameGetter<is_range> getter(first_arg, args, caller_frame);
348   ShadowFrameSetter setter(callee_frame, first_dst_reg);
349 
350   return PerformConversions<ShadowFrameGetter<is_range>, ShadowFrameSetter>(self,
351                                                                             callsite_type,
352                                                                             callee_type,
353                                                                             &getter,
354                                                                             &setter,
355                                                                             num_method_params);
356 }
357 
IsMethodHandleInvokeExact(const ArtMethod * const method)358 inline bool IsMethodHandleInvokeExact(const ArtMethod* const method) {
359   if (method == jni::DecodeArtMethod(WellKnownClasses::java_lang_invoke_MethodHandle_invokeExact)) {
360     return true;
361   } else {
362     DCHECK_EQ(method, jni::DecodeArtMethod(WellKnownClasses::java_lang_invoke_MethodHandle_invoke));
363     return false;
364   }
365 }
366 
IsInvoke(const mirror::MethodHandle::Kind handle_kind)367 inline bool IsInvoke(const mirror::MethodHandle::Kind handle_kind) {
368   return handle_kind <= mirror::MethodHandle::Kind::kLastInvokeKind;
369 }
370 
IsInvokeTransform(const mirror::MethodHandle::Kind handle_kind)371 inline bool IsInvokeTransform(const mirror::MethodHandle::Kind handle_kind) {
372   return (handle_kind == mirror::MethodHandle::Kind::kInvokeTransform
373           || handle_kind == mirror::MethodHandle::Kind::kInvokeCallSiteTransform);
374 }
375 
IsFieldAccess(mirror::MethodHandle::Kind handle_kind)376 inline bool IsFieldAccess(mirror::MethodHandle::Kind handle_kind) {
377   return (handle_kind >= mirror::MethodHandle::Kind::kFirstAccessorKind
378           && handle_kind <= mirror::MethodHandle::Kind::kLastAccessorKind);
379 }
380 
381 // Calculate the number of ins for a proxy or native method, where we
382 // can't just look at the code item.
GetInsForProxyOrNativeMethod(ArtMethod * method)383 static inline size_t GetInsForProxyOrNativeMethod(ArtMethod* method)
384     REQUIRES_SHARED(Locks::mutator_lock_) {
385   DCHECK(method->IsNative() || method->IsProxyMethod());
386   method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
387   uint32_t shorty_length = 0;
388   const char* shorty = method->GetShorty(&shorty_length);
389 
390   // Static methods do not include the receiver. The receiver isn't included
391   // in the shorty_length though the return value is.
392   size_t num_ins = method->IsStatic() ? shorty_length - 1 : shorty_length;
393   for (const char* c = shorty + 1; *c != '\0'; ++c) {
394     if (*c == 'J' || *c == 'D') {
395       ++num_ins;
396     }
397   }
398   return num_ins;
399 }
400 
401 // Returns true iff. the callsite type for a polymorphic invoke is transformer
402 // like, i.e that it has a single input argument whose type is
403 // dalvik.system.EmulatedStackFrame.
IsCallerTransformer(Handle<mirror::MethodType> callsite_type)404 static inline bool IsCallerTransformer(Handle<mirror::MethodType> callsite_type)
405     REQUIRES_SHARED(Locks::mutator_lock_) {
406   ObjPtr<mirror::ObjectArray<mirror::Class>> param_types(callsite_type->GetPTypes());
407   if (param_types->GetLength() == 1) {
408     ObjPtr<mirror::Class> param(param_types->GetWithoutChecks(0));
409     // NB Comparing descriptor here as it appears faster in cycle simulation than using:
410     //   param == WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_EmulatedStackFrame)
411     // Costs are 98 vs 173 cycles per invocation.
412     return param->DescriptorEquals("Ldalvik/system/EmulatedStackFrame;");
413   }
414 
415   return false;
416 }
417 
418 template <bool is_range>
DoCallPolymorphic(ArtMethod * called_method,Handle<mirror::MethodType> callsite_type,Handle<mirror::MethodType> target_type,Thread * self,ShadowFrame & shadow_frame,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,JValue * result)419 static inline bool DoCallPolymorphic(ArtMethod* called_method,
420                                      Handle<mirror::MethodType> callsite_type,
421                                      Handle<mirror::MethodType> target_type,
422                                      Thread* self,
423                                      ShadowFrame& shadow_frame,
424                                      const uint32_t (&args)[Instruction::kMaxVarArgRegs],
425                                      uint32_t first_arg,
426                                      JValue* result)
427     REQUIRES_SHARED(Locks::mutator_lock_) {
428   // Compute method information.
429   const DexFile::CodeItem* code_item = called_method->GetCodeItem();
430 
431   // Number of registers for the callee's call frame. Note that for non-exact
432   // invokes, we always derive this information from the callee method. We
433   // cannot guarantee during verification that the number of registers encoded
434   // in the invoke is equal to the number of ins for the callee. This is because
435   // some transformations (such as boxing a long -> Long or wideining an
436   // int -> long will change that number.
437   uint16_t num_regs;
438   size_t num_input_regs;
439   size_t first_dest_reg;
440   if (LIKELY(code_item != nullptr)) {
441     num_regs = code_item->registers_size_;
442     first_dest_reg = num_regs - code_item->ins_size_;
443     num_input_regs = code_item->ins_size_;
444     // Parameter registers go at the end of the shadow frame.
445     DCHECK_NE(first_dest_reg, (size_t)-1);
446   } else {
447     // No local regs for proxy and native methods.
448     DCHECK(called_method->IsNative() || called_method->IsProxyMethod());
449     num_regs = num_input_regs = GetInsForProxyOrNativeMethod(called_method);
450     first_dest_reg = 0;
451   }
452 
453   // Allocate shadow frame on the stack.
454   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
455       CREATE_SHADOW_FRAME(num_regs, &shadow_frame, called_method, /* dex pc */ 0);
456   ShadowFrame* new_shadow_frame = shadow_frame_unique_ptr.get();
457 
458   // Whether this polymorphic invoke was issued by a transformer method.
459   bool is_caller_transformer = false;
460   // Thread might be suspended during PerformArgumentConversions due to the
461   // allocations performed during boxing.
462   {
463     ScopedStackedShadowFramePusher pusher(
464         self, new_shadow_frame, StackedShadowFrameType::kShadowFrameUnderConstruction);
465     if (callsite_type->IsExactMatch(target_type.Get())) {
466       // This is an exact invoke, we can take the fast path of just copying all
467       // registers without performing any argument conversions.
468       CopyArgumentsFromCallerFrame<is_range>(shadow_frame,
469                                              new_shadow_frame,
470                                              args,
471                                              first_arg,
472                                              first_dest_reg,
473                                              num_input_regs);
474     } else {
475       // This includes the case where we're entering this invoke-polymorphic
476       // from a transformer method. In that case, the callsite_type will contain
477       // a single argument of type dalvik.system.EmulatedStackFrame. In that
478       // case, we'll have to unmarshal the EmulatedStackFrame into the
479       // new_shadow_frame and perform argument conversions on it.
480       if (IsCallerTransformer(callsite_type)) {
481         is_caller_transformer = true;
482         // The emulated stack frame is the first and only argument when we're coming
483         // through from a transformer.
484         size_t first_arg_register = (is_range) ? first_arg : args[0];
485         ObjPtr<mirror::EmulatedStackFrame> emulated_stack_frame(
486             reinterpret_cast<mirror::EmulatedStackFrame*>(
487                 shadow_frame.GetVRegReference(first_arg_register)));
488         if (!emulated_stack_frame->WriteToShadowFrame(self,
489                                                       target_type,
490                                                       first_dest_reg,
491                                                       new_shadow_frame)) {
492           DCHECK(self->IsExceptionPending());
493           result->SetL(0);
494           return false;
495         }
496       } else {
497         if (!callsite_type->IsConvertible(target_type.Get())) {
498           ThrowWrongMethodTypeException(target_type.Get(), callsite_type.Get());
499           return false;
500         }
501         if (!ConvertAndCopyArgumentsFromCallerFrame<is_range>(self,
502                                                               callsite_type,
503                                                               target_type,
504                                                               shadow_frame,
505                                                               args,
506                                                               first_arg,
507                                                               first_dest_reg,
508                                                               new_shadow_frame)) {
509           DCHECK(self->IsExceptionPending());
510           result->SetL(0);
511           return false;
512         }
513       }
514     }
515   }
516 
517   PerformCall(self, code_item, shadow_frame.GetMethod(), first_dest_reg, new_shadow_frame, result);
518   if (self->IsExceptionPending()) {
519     return false;
520   }
521 
522   // If the caller of this signature polymorphic method was a transformer,
523   // we need to copy the result back out to the emulated stack frame.
524   if (is_caller_transformer) {
525     StackHandleScope<2> hs(self);
526     size_t first_callee_register = is_range ? (first_arg) : args[0];
527     Handle<mirror::EmulatedStackFrame> emulated_stack_frame(
528         hs.NewHandle(reinterpret_cast<mirror::EmulatedStackFrame*>(
529             shadow_frame.GetVRegReference(first_callee_register))));
530     Handle<mirror::MethodType> emulated_stack_type(hs.NewHandle(emulated_stack_frame->GetType()));
531     JValue local_result;
532     local_result.SetJ(result->GetJ());
533 
534     if (ConvertReturnValue(emulated_stack_type, target_type, &local_result)) {
535       emulated_stack_frame->SetReturnValue(self, local_result);
536       return true;
537     }
538 
539     DCHECK(self->IsExceptionPending());
540     return false;
541   }
542 
543   return ConvertReturnValue(callsite_type, target_type, result);
544 }
545 
546 template <bool is_range>
DoCallTransform(ArtMethod * called_method,Handle<mirror::MethodType> callsite_type,Handle<mirror::MethodType> callee_type,Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> receiver,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,JValue * result)547 static inline bool DoCallTransform(ArtMethod* called_method,
548                                    Handle<mirror::MethodType> callsite_type,
549                                    Handle<mirror::MethodType> callee_type,
550                                    Thread* self,
551                                    ShadowFrame& shadow_frame,
552                                    Handle<mirror::MethodHandle> receiver,
553                                    const uint32_t (&args)[Instruction::kMaxVarArgRegs],
554                                    uint32_t first_arg,
555                                    JValue* result)
556     REQUIRES_SHARED(Locks::mutator_lock_) {
557   // This can be fixed to two, because the method we're calling here
558   // (MethodHandle.transformInternal) doesn't have any locals and the signature
559   // is known :
560   //
561   // private MethodHandle.transformInternal(EmulatedStackFrame sf);
562   //
563   // This means we need only two vregs :
564   // - One for the receiver object.
565   // - One for the only method argument (an EmulatedStackFrame).
566   static constexpr size_t kNumRegsForTransform = 2;
567 
568   const DexFile::CodeItem* code_item = called_method->GetCodeItem();
569   DCHECK(code_item != nullptr);
570   DCHECK_EQ(kNumRegsForTransform, code_item->registers_size_);
571   DCHECK_EQ(kNumRegsForTransform, code_item->ins_size_);
572 
573   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
574       CREATE_SHADOW_FRAME(kNumRegsForTransform, &shadow_frame, called_method, /* dex pc */ 0);
575   ShadowFrame* new_shadow_frame = shadow_frame_unique_ptr.get();
576 
577   StackHandleScope<1> hs(self);
578   MutableHandle<mirror::EmulatedStackFrame> sf(hs.NewHandle<mirror::EmulatedStackFrame>(nullptr));
579   if (IsCallerTransformer(callsite_type)) {
580     // If we're entering this transformer from another transformer, we can pass
581     // through the handle directly to the callee, instead of having to
582     // instantiate a new stack frame based on the shadow frame.
583     size_t first_callee_register = is_range ? first_arg : args[0];
584     sf.Assign(reinterpret_cast<mirror::EmulatedStackFrame*>(
585         shadow_frame.GetVRegReference(first_callee_register)));
586   } else {
587     sf.Assign(mirror::EmulatedStackFrame::CreateFromShadowFrameAndArgs<is_range>(self,
588                                                                                  callsite_type,
589                                                                                  callee_type,
590                                                                                  shadow_frame,
591                                                                                  first_arg,
592                                                                                  args));
593 
594     // Something went wrong while creating the emulated stack frame, we should
595     // throw the pending exception.
596     if (sf == nullptr) {
597       DCHECK(self->IsExceptionPending());
598       return false;
599     }
600   }
601 
602   new_shadow_frame->SetVRegReference(0, receiver.Get());
603   new_shadow_frame->SetVRegReference(1, sf.Get());
604 
605   PerformCall(self,
606               code_item,
607               shadow_frame.GetMethod(),
608               0 /* first destination register */,
609               new_shadow_frame,
610               result);
611   if (self->IsExceptionPending()) {
612     return false;
613   }
614 
615   // If the called transformer method we called has returned a value, then we
616   // need to copy it back to |result|.
617   sf->GetReturnValue(self, result);
618   return ConvertReturnValue(callsite_type, callee_type, result);
619 }
620 
GetAndInitializeDeclaringClass(Thread * self,ArtField * field)621 inline static ObjPtr<mirror::Class> GetAndInitializeDeclaringClass(Thread* self, ArtField* field)
622     REQUIRES_SHARED(Locks::mutator_lock_) {
623   // Method handle invocations on static fields should ensure class is
624   // initialized. This usually happens when an instance is constructed
625   // or class members referenced, but this is not guaranteed when
626   // looking up method handles.
627   ObjPtr<mirror::Class> klass = field->GetDeclaringClass();
628   if (UNLIKELY(!klass->IsInitialized())) {
629     StackHandleScope<1> hs(self);
630     HandleWrapperObjPtr<mirror::Class> h(hs.NewHandleWrapper(&klass));
631     if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h, true, true)) {
632       DCHECK(self->IsExceptionPending());
633       return nullptr;
634     }
635   }
636   return klass;
637 }
638 
RefineTargetMethod(Thread * self,ShadowFrame & shadow_frame,const mirror::MethodHandle::Kind & handle_kind,Handle<mirror::MethodType> handle_type,Handle<mirror::MethodType> callsite_type,const uint32_t receiver_reg,ArtMethod * target_method)639 ArtMethod* RefineTargetMethod(Thread* self,
640                               ShadowFrame& shadow_frame,
641                               const mirror::MethodHandle::Kind& handle_kind,
642                               Handle<mirror::MethodType> handle_type,
643                               Handle<mirror::MethodType> callsite_type,
644                               const uint32_t receiver_reg,
645                               ArtMethod* target_method)
646     REQUIRES_SHARED(Locks::mutator_lock_) {
647   if (handle_kind == mirror::MethodHandle::Kind::kInvokeVirtual ||
648       handle_kind == mirror::MethodHandle::Kind::kInvokeInterface) {
649     // For virtual and interface methods ensure target_method points to
650     // the actual method to invoke.
651     ObjPtr<mirror::Object> receiver(shadow_frame.GetVRegReference(receiver_reg));
652     if (IsCallerTransformer(callsite_type)) {
653       // The current receiver is an emulated stack frame, the method's
654       // receiver needs to be fetched from there as the emulated frame
655       // will be unpacked into a new frame.
656       receiver = ObjPtr<mirror::EmulatedStackFrame>::DownCast(receiver)->GetReceiver();
657     }
658 
659     ObjPtr<mirror::Class> declaring_class(target_method->GetDeclaringClass());
660     if (receiver == nullptr || receiver->GetClass() != declaring_class) {
661       // Verify that _vRegC is an object reference and of the type expected by
662       // the receiver.
663       if (!VerifyObjectIsClass(receiver, declaring_class)) {
664         DCHECK(self->IsExceptionPending());
665         return nullptr;
666       }
667       return receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(
668           target_method, kRuntimePointerSize);
669     }
670   } else if (handle_kind == mirror::MethodHandle::Kind::kInvokeDirect) {
671     // String constructors are a special case, they are replaced with
672     // StringFactory methods.
673     if (target_method->IsConstructor() && target_method->GetDeclaringClass()->IsStringClass()) {
674       DCHECK(handle_type->GetRType()->IsStringClass());
675       return WellKnownClasses::StringInitToStringFactory(target_method);
676     }
677   } else if (handle_kind == mirror::MethodHandle::Kind::kInvokeSuper) {
678     ObjPtr<mirror::Class> declaring_class = target_method->GetDeclaringClass();
679 
680     // Note that we're not dynamically dispatching on the type of the receiver
681     // here. We use the static type of the "receiver" object that we've
682     // recorded in the method handle's type, which will be the same as the
683     // special caller that was specified at the point of lookup.
684     ObjPtr<mirror::Class> referrer_class = handle_type->GetPTypes()->Get(0);
685     if (!declaring_class->IsInterface()) {
686       ObjPtr<mirror::Class> super_class = referrer_class->GetSuperClass();
687       uint16_t vtable_index = target_method->GetMethodIndex();
688       DCHECK(super_class != nullptr);
689       DCHECK(super_class->HasVTable());
690       // Note that super_class is a super of referrer_class and target_method
691       // will always be declared by super_class (or one of its super classes).
692       DCHECK_LT(vtable_index, super_class->GetVTableLength());
693       return super_class->GetVTableEntry(vtable_index, kRuntimePointerSize);
694     } else {
695       return referrer_class->FindVirtualMethodForInterfaceSuper(target_method, kRuntimePointerSize);
696     }
697   }
698   return target_method;
699 }
700 
701 template <bool is_range>
DoInvokePolymorphicMethod(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,JValue * result)702 bool DoInvokePolymorphicMethod(Thread* self,
703                                ShadowFrame& shadow_frame,
704                                Handle<mirror::MethodHandle> method_handle,
705                                Handle<mirror::MethodType> callsite_type,
706                                const uint32_t (&args)[Instruction::kMaxVarArgRegs],
707                                uint32_t first_arg,
708                                JValue* result)
709   REQUIRES_SHARED(Locks::mutator_lock_) {
710   StackHandleScope<1> hs(self);
711   Handle<mirror::MethodType> handle_type(hs.NewHandle(method_handle->GetMethodType()));
712   const mirror::MethodHandle::Kind handle_kind = method_handle->GetHandleKind();
713   DCHECK(IsInvoke(handle_kind));
714 
715   // Get the method we're actually invoking along with the kind of
716   // invoke that is desired. We don't need to perform access checks at this
717   // point because they would have been performed on our behalf at the point
718   // of creation of the method handle.
719   ArtMethod* target_method = method_handle->GetTargetMethod();
720   uint32_t receiver_reg = is_range ? first_arg: args[0];
721   ArtMethod* called_method = RefineTargetMethod(self,
722                                                 shadow_frame,
723                                                 handle_kind,
724                                                 handle_type,
725                                                 callsite_type,
726                                                 receiver_reg,
727                                                 target_method);
728   if (called_method == nullptr) {
729     DCHECK(self->IsExceptionPending());
730     return false;
731   }
732 
733   if (IsInvokeTransform(handle_kind)) {
734     // There are two cases here - method handles representing regular
735     // transforms and those representing call site transforms. Method
736     // handles for call site transforms adapt their MethodType to match
737     // the call site. For these, the |callee_type| is the same as the
738     // |callsite_type|. The VarargsCollector is such a tranform, its
739     // method type depends on the call site, ie. x(a) or x(a, b), or
740     // x(a, b, c). The VarargsCollector invokes a variable arity method
741     // with the arity arguments in an array.
742     Handle<mirror::MethodType> callee_type =
743         (handle_kind == mirror::MethodHandle::Kind::kInvokeCallSiteTransform) ? callsite_type
744         : handle_type;
745     return DoCallTransform<is_range>(called_method,
746                                      callsite_type,
747                                      callee_type,
748                                      self,
749                                      shadow_frame,
750                                      method_handle /* receiver */,
751                                      args,
752                                      first_arg,
753                                      result);
754   } else {
755     return DoCallPolymorphic<is_range>(called_method,
756                                        callsite_type,
757                                        handle_type,
758                                        self,
759                                        shadow_frame,
760                                        args,
761                                        first_arg,
762                                        result);
763   }
764 }
765 
766 // Helper for getters in invoke-polymorphic.
DoFieldGetForInvokePolymorphic(Thread * self,const ShadowFrame & shadow_frame,ObjPtr<mirror::Object> & obj,ArtField * field,Primitive::Type field_type,JValue * result)767 inline static void DoFieldGetForInvokePolymorphic(Thread* self,
768                                                   const ShadowFrame& shadow_frame,
769                                                   ObjPtr<mirror::Object>& obj,
770                                                   ArtField* field,
771                                                   Primitive::Type field_type,
772                                                   JValue* result)
773     REQUIRES_SHARED(Locks::mutator_lock_) {
774   switch (field_type) {
775     case Primitive::kPrimBoolean:
776       DoFieldGetCommon<Primitive::kPrimBoolean>(self, shadow_frame, obj, field, result);
777       break;
778     case Primitive::kPrimByte:
779       DoFieldGetCommon<Primitive::kPrimByte>(self, shadow_frame, obj, field, result);
780       break;
781     case Primitive::kPrimChar:
782       DoFieldGetCommon<Primitive::kPrimChar>(self, shadow_frame, obj, field, result);
783       break;
784     case Primitive::kPrimShort:
785       DoFieldGetCommon<Primitive::kPrimShort>(self, shadow_frame, obj, field, result);
786       break;
787     case Primitive::kPrimInt:
788       DoFieldGetCommon<Primitive::kPrimInt>(self, shadow_frame, obj, field, result);
789       break;
790     case Primitive::kPrimLong:
791       DoFieldGetCommon<Primitive::kPrimLong>(self, shadow_frame, obj, field, result);
792       break;
793     case Primitive::kPrimFloat:
794       DoFieldGetCommon<Primitive::kPrimInt>(self, shadow_frame, obj, field, result);
795       break;
796     case Primitive::kPrimDouble:
797       DoFieldGetCommon<Primitive::kPrimLong>(self, shadow_frame, obj, field, result);
798       break;
799     case Primitive::kPrimNot:
800       DoFieldGetCommon<Primitive::kPrimNot>(self, shadow_frame, obj, field, result);
801       break;
802     case Primitive::kPrimVoid:
803       LOG(FATAL) << "Unreachable: " << field_type;
804       UNREACHABLE();
805   }
806 }
807 
808 // Helper for setters in invoke-polymorphic.
DoFieldPutForInvokePolymorphic(Thread * self,ShadowFrame & shadow_frame,ObjPtr<mirror::Object> & obj,ArtField * field,Primitive::Type field_type,const JValue & value)809 inline bool DoFieldPutForInvokePolymorphic(Thread* self,
810                                            ShadowFrame& shadow_frame,
811                                            ObjPtr<mirror::Object>& obj,
812                                            ArtField* field,
813                                            Primitive::Type field_type,
814                                            const JValue& value)
815     REQUIRES_SHARED(Locks::mutator_lock_) {
816   DCHECK(!Runtime::Current()->IsActiveTransaction());
817   static const bool kTransaction = false;         // Not in a transaction.
818   static const bool kAssignabilityCheck = false;  // No access check.
819   switch (field_type) {
820     case Primitive::kPrimBoolean:
821       return
822           DoFieldPutCommon<Primitive::kPrimBoolean, kAssignabilityCheck, kTransaction>(
823               self, shadow_frame, obj, field, value);
824     case Primitive::kPrimByte:
825       return DoFieldPutCommon<Primitive::kPrimByte, kAssignabilityCheck, kTransaction>(
826           self, shadow_frame, obj, field, value);
827     case Primitive::kPrimChar:
828       return DoFieldPutCommon<Primitive::kPrimChar, kAssignabilityCheck, kTransaction>(
829           self, shadow_frame, obj, field, value);
830     case Primitive::kPrimShort:
831       return DoFieldPutCommon<Primitive::kPrimShort, kAssignabilityCheck, kTransaction>(
832           self, shadow_frame, obj, field, value);
833     case Primitive::kPrimInt:
834     case Primitive::kPrimFloat:
835       return DoFieldPutCommon<Primitive::kPrimInt, kAssignabilityCheck, kTransaction>(
836           self, shadow_frame, obj, field, value);
837     case Primitive::kPrimLong:
838     case Primitive::kPrimDouble:
839       return DoFieldPutCommon<Primitive::kPrimLong, kAssignabilityCheck, kTransaction>(
840           self, shadow_frame, obj, field, value);
841     case Primitive::kPrimNot:
842       return DoFieldPutCommon<Primitive::kPrimNot, kAssignabilityCheck, kTransaction>(
843           self, shadow_frame, obj, field, value);
844     case Primitive::kPrimVoid:
845       LOG(FATAL) << "Unreachable: " << field_type;
846       UNREACHABLE();
847   }
848 }
849 
GetValueFromShadowFrame(const ShadowFrame & shadow_frame,Primitive::Type field_type,uint32_t vreg)850 static JValue GetValueFromShadowFrame(const ShadowFrame& shadow_frame,
851                                       Primitive::Type field_type,
852                                       uint32_t vreg)
853     REQUIRES_SHARED(Locks::mutator_lock_) {
854   JValue field_value;
855   switch (field_type) {
856     case Primitive::kPrimBoolean:
857       field_value.SetZ(static_cast<uint8_t>(shadow_frame.GetVReg(vreg)));
858       break;
859     case Primitive::kPrimByte:
860       field_value.SetB(static_cast<int8_t>(shadow_frame.GetVReg(vreg)));
861       break;
862     case Primitive::kPrimChar:
863       field_value.SetC(static_cast<uint16_t>(shadow_frame.GetVReg(vreg)));
864       break;
865     case Primitive::kPrimShort:
866       field_value.SetS(static_cast<int16_t>(shadow_frame.GetVReg(vreg)));
867       break;
868     case Primitive::kPrimInt:
869     case Primitive::kPrimFloat:
870       field_value.SetI(shadow_frame.GetVReg(vreg));
871       break;
872     case Primitive::kPrimLong:
873     case Primitive::kPrimDouble:
874       field_value.SetJ(shadow_frame.GetVRegLong(vreg));
875       break;
876     case Primitive::kPrimNot:
877       field_value.SetL(shadow_frame.GetVRegReference(vreg));
878       break;
879     case Primitive::kPrimVoid:
880       LOG(FATAL) << "Unreachable: " << field_type;
881       UNREACHABLE();
882   }
883   return field_value;
884 }
885 
886 template <bool is_range, bool do_conversions>
DoInvokePolymorphicFieldAccess(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,JValue * result)887 bool DoInvokePolymorphicFieldAccess(Thread* self,
888                                     ShadowFrame& shadow_frame,
889                                     Handle<mirror::MethodHandle> method_handle,
890                                     Handle<mirror::MethodType> callsite_type,
891                                     const uint32_t (&args)[Instruction::kMaxVarArgRegs],
892                                     uint32_t first_arg,
893                                     JValue* result)
894     REQUIRES_SHARED(Locks::mutator_lock_) {
895   StackHandleScope<1> hs(self);
896   Handle<mirror::MethodType> handle_type(hs.NewHandle(method_handle->GetMethodType()));
897   const mirror::MethodHandle::Kind handle_kind = method_handle->GetHandleKind();
898   ArtField* field = method_handle->GetTargetField();
899   Primitive::Type field_type = field->GetTypeAsPrimitiveType();
900 
901   switch (handle_kind) {
902     case mirror::MethodHandle::kInstanceGet: {
903       size_t obj_reg = is_range ? first_arg : args[0];
904       ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(obj_reg);
905       DoFieldGetForInvokePolymorphic(self, shadow_frame, obj, field, field_type, result);
906       if (do_conversions && !ConvertReturnValue(callsite_type, handle_type, result)) {
907         DCHECK(self->IsExceptionPending());
908         return false;
909       }
910       return true;
911     }
912     case mirror::MethodHandle::kStaticGet: {
913       ObjPtr<mirror::Object> obj = GetAndInitializeDeclaringClass(self, field);
914       if (obj == nullptr) {
915         DCHECK(self->IsExceptionPending());
916         return false;
917       }
918       DoFieldGetForInvokePolymorphic(self, shadow_frame, obj, field, field_type, result);
919       if (do_conversions && !ConvertReturnValue(callsite_type, handle_type, result)) {
920         DCHECK(self->IsExceptionPending());
921         return false;
922       }
923       return true;
924     }
925     case mirror::MethodHandle::kInstancePut: {
926       size_t obj_reg = is_range ? first_arg : args[0];
927       size_t value_reg = is_range ? (first_arg + 1) : args[1];
928       const size_t kPTypeIndex = 1;
929       // Use ptypes instead of field type since we may be unboxing a reference for a primitive
930       // field. The field type is incorrect for this case.
931       JValue value = GetValueFromShadowFrame(
932           shadow_frame,
933           callsite_type->GetPTypes()->Get(kPTypeIndex)->GetPrimitiveType(),
934           value_reg);
935       if (do_conversions && !ConvertArgumentValue(callsite_type,
936                                                   handle_type,
937                                                   kPTypeIndex,
938                                                   &value)) {
939         DCHECK(self->IsExceptionPending());
940         return false;
941       }
942       ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(obj_reg);
943       return DoFieldPutForInvokePolymorphic(self, shadow_frame, obj, field, field_type, value);
944     }
945     case mirror::MethodHandle::kStaticPut: {
946       ObjPtr<mirror::Object> obj = GetAndInitializeDeclaringClass(self, field);
947       if (obj == nullptr) {
948         DCHECK(self->IsExceptionPending());
949         return false;
950       }
951       size_t value_reg = is_range ? first_arg : args[0];
952       const size_t kPTypeIndex = 0;
953       // Use ptypes instead of field type since we may be unboxing a reference for a primitive
954       // field. The field type is incorrect for this case.
955       JValue value = GetValueFromShadowFrame(
956           shadow_frame,
957           callsite_type->GetPTypes()->Get(kPTypeIndex)->GetPrimitiveType(),
958           value_reg);
959       if (do_conversions && !ConvertArgumentValue(callsite_type,
960                                                   handle_type,
961                                                   kPTypeIndex,
962                                                   &value)) {
963         DCHECK(self->IsExceptionPending());
964         return false;
965       }
966       return DoFieldPutForInvokePolymorphic(self, shadow_frame, obj, field, field_type, value);
967     }
968     default:
969       LOG(FATAL) << "Unreachable: " << handle_kind;
970       UNREACHABLE();
971   }
972 }
973 
974 template <bool is_range>
DoInvokePolymorphicNonExact(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,JValue * result)975 static inline bool DoInvokePolymorphicNonExact(Thread* self,
976                                                ShadowFrame& shadow_frame,
977                                                Handle<mirror::MethodHandle> method_handle,
978                                                Handle<mirror::MethodType> callsite_type,
979                                                const uint32_t (&args)[Instruction::kMaxVarArgRegs],
980                                                uint32_t first_arg,
981                                                JValue* result)
982     REQUIRES_SHARED(Locks::mutator_lock_) {
983   const mirror::MethodHandle::Kind handle_kind = method_handle->GetHandleKind();
984   ObjPtr<mirror::MethodType> handle_type(method_handle->GetMethodType());
985   CHECK(handle_type != nullptr);
986 
987   if (IsFieldAccess(handle_kind)) {
988     DCHECK(!callsite_type->IsExactMatch(handle_type.Ptr()));
989     if (!callsite_type->IsConvertible(handle_type.Ptr())) {
990       ThrowWrongMethodTypeException(handle_type.Ptr(), callsite_type.Get());
991       return false;
992     }
993     const bool do_convert = true;
994     return DoInvokePolymorphicFieldAccess<is_range, do_convert>(
995         self,
996         shadow_frame,
997         method_handle,
998         callsite_type,
999         args,
1000         first_arg,
1001         result);
1002   }
1003 
1004   return DoInvokePolymorphicMethod<is_range>(self,
1005                                              shadow_frame,
1006                                              method_handle,
1007                                              callsite_type,
1008                                              args,
1009                                              first_arg,
1010                                              result);
1011 }
1012 
1013 template <bool is_range>
DoInvokePolymorphicExact(Thread * self,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,JValue * result)1014 bool DoInvokePolymorphicExact(Thread* self,
1015                               ShadowFrame& shadow_frame,
1016                               Handle<mirror::MethodHandle> method_handle,
1017                               Handle<mirror::MethodType> callsite_type,
1018                               const uint32_t (&args)[Instruction::kMaxVarArgRegs],
1019                               uint32_t first_arg,
1020                               JValue* result)
1021     REQUIRES_SHARED(Locks::mutator_lock_) {
1022   StackHandleScope<1> hs(self);
1023   const mirror::MethodHandle::Kind handle_kind = method_handle->GetHandleKind();
1024   Handle<mirror::MethodType> method_handle_type(hs.NewHandle(method_handle->GetMethodType()));
1025   if (IsFieldAccess(handle_kind)) {
1026     const bool do_convert = false;
1027     return DoInvokePolymorphicFieldAccess<is_range, do_convert>(
1028         self,
1029         shadow_frame,
1030         method_handle,
1031         callsite_type,
1032         args,
1033         first_arg,
1034         result);
1035   }
1036 
1037   // Slow-path check.
1038   if (IsInvokeTransform(handle_kind) || IsCallerTransformer(callsite_type)) {
1039     return DoInvokePolymorphicMethod<is_range>(self,
1040                                                shadow_frame,
1041                                                method_handle,
1042                                                callsite_type,
1043                                                args,
1044                                                first_arg,
1045                                                result);
1046   }
1047 
1048   // On the fast-path. This is equivalent to DoCallPolymoprhic without the conversion paths.
1049   ArtMethod* target_method = method_handle->GetTargetMethod();
1050   uint32_t receiver_reg = is_range ? first_arg : args[0];
1051   ArtMethod* called_method = RefineTargetMethod(self,
1052                                                 shadow_frame,
1053                                                 handle_kind,
1054                                                 method_handle_type,
1055                                                 callsite_type,
1056                                                 receiver_reg,
1057                                                 target_method);
1058   if (called_method == nullptr) {
1059     DCHECK(self->IsExceptionPending());
1060     return false;
1061   }
1062 
1063   // Compute method information.
1064   const DexFile::CodeItem* code_item = called_method->GetCodeItem();
1065   uint16_t num_regs;
1066   size_t num_input_regs;
1067   size_t first_dest_reg;
1068   if (LIKELY(code_item != nullptr)) {
1069     num_regs = code_item->registers_size_;
1070     first_dest_reg = num_regs - code_item->ins_size_;
1071     num_input_regs = code_item->ins_size_;
1072     // Parameter registers go at the end of the shadow frame.
1073     DCHECK_NE(first_dest_reg, (size_t)-1);
1074   } else {
1075     // No local regs for proxy and native methods.
1076     DCHECK(called_method->IsNative() || called_method->IsProxyMethod());
1077     num_regs = num_input_regs = GetInsForProxyOrNativeMethod(called_method);
1078     first_dest_reg = 0;
1079   }
1080 
1081   // Allocate shadow frame on the stack.
1082   const char* old_cause = self->StartAssertNoThreadSuspension("DoCallCommon");
1083   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
1084       CREATE_SHADOW_FRAME(num_regs, &shadow_frame, called_method, /* dex pc */ 0);
1085   ShadowFrame* new_shadow_frame = shadow_frame_unique_ptr.get();
1086   CopyArgumentsFromCallerFrame<is_range>(shadow_frame,
1087                                          new_shadow_frame,
1088                                          args,
1089                                          first_arg,
1090                                          first_dest_reg,
1091                                          num_input_regs);
1092   self->EndAssertNoThreadSuspension(old_cause);
1093 
1094   PerformCall(self, code_item, shadow_frame.GetMethod(), first_dest_reg, new_shadow_frame, result);
1095   if (self->IsExceptionPending()) {
1096     return false;
1097   }
1098   return true;
1099 }
1100 
1101 }  // namespace
1102 
1103 template <bool is_range>
DoInvokePolymorphic(Thread * self,ArtMethod * invoke_method,ShadowFrame & shadow_frame,Handle<mirror::MethodHandle> method_handle,Handle<mirror::MethodType> callsite_type,const uint32_t (& args)[Instruction::kMaxVarArgRegs],uint32_t first_arg,JValue * result)1104 bool DoInvokePolymorphic(Thread* self,
1105                          ArtMethod* invoke_method,
1106                          ShadowFrame& shadow_frame,
1107                          Handle<mirror::MethodHandle> method_handle,
1108                          Handle<mirror::MethodType> callsite_type,
1109                          const uint32_t (&args)[Instruction::kMaxVarArgRegs],
1110                          uint32_t first_arg,
1111                          JValue* result)
1112     REQUIRES_SHARED(Locks::mutator_lock_) {
1113   ObjPtr<mirror::MethodType> method_handle_type = method_handle->GetMethodType();
1114   if (IsMethodHandleInvokeExact(invoke_method)) {
1115     // We need to check the nominal type of the handle in addition to the
1116     // real type. The "nominal" type is present when MethodHandle.asType is
1117     // called any handle, and results in the declared type of the handle
1118     // changing.
1119     ObjPtr<mirror::MethodType> nominal_type(method_handle->GetNominalType());
1120     if (UNLIKELY(nominal_type != nullptr)) {
1121       if (UNLIKELY(!callsite_type->IsExactMatch(nominal_type.Ptr()))) {
1122         ThrowWrongMethodTypeException(nominal_type.Ptr(), callsite_type.Get());
1123         return false;
1124       }
1125 
1126       if (LIKELY(!nominal_type->IsExactMatch(method_handle_type.Ptr()))) {
1127         // Different nominal type means we have to treat as non-exact.
1128         return DoInvokePolymorphicNonExact<is_range>(self,
1129                                                      shadow_frame,
1130                                                      method_handle,
1131                                                      callsite_type,
1132                                                      args,
1133                                                      first_arg,
1134                                                      result);
1135       }
1136     }
1137 
1138     if (!callsite_type->IsExactMatch(method_handle_type.Ptr())) {
1139       ThrowWrongMethodTypeException(method_handle_type.Ptr(), callsite_type.Get());
1140       return false;
1141     }
1142     return DoInvokePolymorphicExact<is_range>(self,
1143                                               shadow_frame,
1144                                               method_handle,
1145                                               callsite_type,
1146                                               args,
1147                                               first_arg,
1148                                               result);
1149   } else {
1150     if (UNLIKELY(callsite_type->IsExactMatch(method_handle_type.Ptr()))) {
1151       // A non-exact invoke that can be invoked exactly.
1152       return DoInvokePolymorphicExact<is_range>(self,
1153                                                 shadow_frame,
1154                                                 method_handle,
1155                                                 callsite_type,
1156                                                 args,
1157                                                 first_arg,
1158                                                 result);
1159     }
1160     return DoInvokePolymorphicNonExact<is_range>(self,
1161                                                  shadow_frame,
1162                                                  method_handle,
1163                                                  callsite_type,
1164                                                  args,
1165                                                  first_arg,
1166                                                  result);
1167   }
1168 }
1169 
1170 #define EXPLICIT_DO_INVOKE_POLYMORPHIC_TEMPLATE_DECL(_is_range)  \
1171   template REQUIRES_SHARED(Locks::mutator_lock_)                 \
1172   bool DoInvokePolymorphic<_is_range>(                           \
1173       Thread* self,                                              \
1174       ArtMethod* invoke_method,                                  \
1175       ShadowFrame& shadow_frame,                                 \
1176       Handle<mirror::MethodHandle> method_handle,                \
1177       Handle<mirror::MethodType> callsite_type,                  \
1178       const uint32_t (&args)[Instruction::kMaxVarArgRegs],       \
1179       uint32_t first_arg,                                        \
1180       JValue* result)
1181 
1182 EXPLICIT_DO_INVOKE_POLYMORPHIC_TEMPLATE_DECL(true);
1183 EXPLICIT_DO_INVOKE_POLYMORPHIC_TEMPLATE_DECL(false);
1184 #undef EXPLICIT_DO_INVOKE_POLYMORPHIC_TEMPLATE_DECL
1185 
1186 }  // namespace art
1187