• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 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 "art_method-inl.h"
18 #include "base/callee_save_type.h"
19 #include "base/enums.h"
20 #include "callee_save_frame.h"
21 #include "common_throws.h"
22 #include "class_root-inl.h"
23 #include "debug_print.h"
24 #include "debugger.h"
25 #include "dex/dex_file-inl.h"
26 #include "dex/dex_file_types.h"
27 #include "dex/dex_instruction-inl.h"
28 #include "dex/method_reference.h"
29 #include "entrypoints/entrypoint_utils-inl.h"
30 #include "entrypoints/quick/callee_save_frame.h"
31 #include "entrypoints/runtime_asm_entrypoints.h"
32 #include "gc/accounting/card_table-inl.h"
33 #include "imt_conflict_table.h"
34 #include "imtable-inl.h"
35 #include "instrumentation.h"
36 #include "interpreter/interpreter.h"
37 #include "interpreter/interpreter_common.h"
38 #include "interpreter/shadow_frame-inl.h"
39 #include "jit/jit.h"
40 #include "jit/jit_code_cache.h"
41 #include "linear_alloc.h"
42 #include "method_handles.h"
43 #include "mirror/class-inl.h"
44 #include "mirror/dex_cache-inl.h"
45 #include "mirror/method.h"
46 #include "mirror/method_handle_impl.h"
47 #include "mirror/object-inl.h"
48 #include "mirror/object_array-inl.h"
49 #include "mirror/var_handle.h"
50 #include "oat.h"
51 #include "oat_file.h"
52 #include "oat_quick_method_header.h"
53 #include "quick_exception_handler.h"
54 #include "runtime.h"
55 #include "scoped_thread_state_change-inl.h"
56 #include "stack.h"
57 #include "thread-inl.h"
58 #include "var_handles.h"
59 #include "well_known_classes.h"
60 
61 namespace art {
62 
63 extern "C" NO_RETURN void artDeoptimizeFromCompiledCode(DeoptimizationKind kind, Thread* self);
64 extern "C" NO_RETURN void artDeoptimize(Thread* self);
65 
66 // Visits the arguments as saved to the stack by a CalleeSaveType::kRefAndArgs callee save frame.
67 class QuickArgumentVisitor {
68   // Number of bytes for each out register in the caller method's frame.
69   static constexpr size_t kBytesStackArgLocation = 4;
70   // Frame size in bytes of a callee-save frame for RefsAndArgs.
71   static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_FrameSize =
72       RuntimeCalleeSaveFrame::GetFrameSize(CalleeSaveType::kSaveRefsAndArgs);
73   // Offset of first GPR arg.
74   static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset =
75       RuntimeCalleeSaveFrame::GetGpr1Offset(CalleeSaveType::kSaveRefsAndArgs);
76   // Offset of first FPR arg.
77   static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset =
78       RuntimeCalleeSaveFrame::GetFpr1Offset(CalleeSaveType::kSaveRefsAndArgs);
79   // Offset of return address.
80   static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_ReturnPcOffset =
81       RuntimeCalleeSaveFrame::GetReturnPcOffset(CalleeSaveType::kSaveRefsAndArgs);
82 #if defined(__arm__)
83   // The callee save frame is pointed to by SP.
84   // | argN       |  |
85   // | ...        |  |
86   // | arg4       |  |
87   // | arg3 spill |  |  Caller's frame
88   // | arg2 spill |  |
89   // | arg1 spill |  |
90   // | Method*    | ---
91   // | LR         |
92   // | ...        |    4x6 bytes callee saves
93   // | R3         |
94   // | R2         |
95   // | R1         |
96   // | S15        |
97   // | :          |
98   // | S0         |
99   // |            |    4x2 bytes padding
100   // | Method*    |  <- sp
101   static constexpr bool kSplitPairAcrossRegisterAndStack = false;
102   static constexpr bool kAlignPairRegister = true;
103   static constexpr bool kQuickSoftFloatAbi = false;
104   static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = true;
105   static constexpr bool kQuickSkipOddFpRegisters = false;
106   static constexpr size_t kNumQuickGprArgs = 3;
107   static constexpr size_t kNumQuickFprArgs = 16;
108   static constexpr bool kGprFprLockstep = false;
GprIndexToGprOffset(uint32_t gpr_index)109   static size_t GprIndexToGprOffset(uint32_t gpr_index) {
110     return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
111   }
112 #elif defined(__aarch64__)
113   // The callee save frame is pointed to by SP.
114   // | argN       |  |
115   // | ...        |  |
116   // | arg4       |  |
117   // | arg3 spill |  |  Caller's frame
118   // | arg2 spill |  |
119   // | arg1 spill |  |
120   // | Method*    | ---
121   // | LR         |
122   // | X29        |
123   // |  :         |
124   // | X20        |
125   // | X7         |
126   // | :          |
127   // | X1         |
128   // | D7         |
129   // |  :         |
130   // | D0         |
131   // |            |    padding
132   // | Method*    |  <- sp
133   static constexpr bool kSplitPairAcrossRegisterAndStack = false;
134   static constexpr bool kAlignPairRegister = false;
135   static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
136   static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
137   static constexpr bool kQuickSkipOddFpRegisters = false;
138   static constexpr size_t kNumQuickGprArgs = 7;  // 7 arguments passed in GPRs.
139   static constexpr size_t kNumQuickFprArgs = 8;  // 8 arguments passed in FPRs.
140   static constexpr bool kGprFprLockstep = false;
GprIndexToGprOffset(uint32_t gpr_index)141   static size_t GprIndexToGprOffset(uint32_t gpr_index) {
142     return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
143   }
144 #elif defined(__i386__)
145   // The callee save frame is pointed to by SP.
146   // | argN        |  |
147   // | ...         |  |
148   // | arg4        |  |
149   // | arg3 spill  |  |  Caller's frame
150   // | arg2 spill  |  |
151   // | arg1 spill  |  |
152   // | Method*     | ---
153   // | Return      |
154   // | EBP,ESI,EDI |    callee saves
155   // | EBX         |    arg3
156   // | EDX         |    arg2
157   // | ECX         |    arg1
158   // | XMM3        |    float arg 4
159   // | XMM2        |    float arg 3
160   // | XMM1        |    float arg 2
161   // | XMM0        |    float arg 1
162   // | EAX/Method* |  <- sp
163   static constexpr bool kSplitPairAcrossRegisterAndStack = false;
164   static constexpr bool kAlignPairRegister = false;
165   static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
166   static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
167   static constexpr bool kQuickSkipOddFpRegisters = false;
168   static constexpr size_t kNumQuickGprArgs = 3;  // 3 arguments passed in GPRs.
169   static constexpr size_t kNumQuickFprArgs = 4;  // 4 arguments passed in FPRs.
170   static constexpr bool kGprFprLockstep = false;
GprIndexToGprOffset(uint32_t gpr_index)171   static size_t GprIndexToGprOffset(uint32_t gpr_index) {
172     return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
173   }
174 #elif defined(__x86_64__)
175   // The callee save frame is pointed to by SP.
176   // | argN            |  |
177   // | ...             |  |
178   // | reg. arg spills |  |  Caller's frame
179   // | Method*         | ---
180   // | Return          |
181   // | R15             |    callee save
182   // | R14             |    callee save
183   // | R13             |    callee save
184   // | R12             |    callee save
185   // | R9              |    arg5
186   // | R8              |    arg4
187   // | RSI/R6          |    arg1
188   // | RBP/R5          |    callee save
189   // | RBX/R3          |    callee save
190   // | RDX/R2          |    arg2
191   // | RCX/R1          |    arg3
192   // | XMM7            |    float arg 8
193   // | XMM6            |    float arg 7
194   // | XMM5            |    float arg 6
195   // | XMM4            |    float arg 5
196   // | XMM3            |    float arg 4
197   // | XMM2            |    float arg 3
198   // | XMM1            |    float arg 2
199   // | XMM0            |    float arg 1
200   // | Padding         |
201   // | RDI/Method*     |  <- sp
202   static constexpr bool kSplitPairAcrossRegisterAndStack = false;
203   static constexpr bool kAlignPairRegister = false;
204   static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
205   static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
206   static constexpr bool kQuickSkipOddFpRegisters = false;
207   static constexpr size_t kNumQuickGprArgs = 5;  // 5 arguments passed in GPRs.
208   static constexpr size_t kNumQuickFprArgs = 8;  // 8 arguments passed in FPRs.
209   static constexpr bool kGprFprLockstep = false;
GprIndexToGprOffset(uint32_t gpr_index)210   static size_t GprIndexToGprOffset(uint32_t gpr_index) {
211     switch (gpr_index) {
212       case 0: return (4 * GetBytesPerGprSpillLocation(kRuntimeISA));
213       case 1: return (1 * GetBytesPerGprSpillLocation(kRuntimeISA));
214       case 2: return (0 * GetBytesPerGprSpillLocation(kRuntimeISA));
215       case 3: return (5 * GetBytesPerGprSpillLocation(kRuntimeISA));
216       case 4: return (6 * GetBytesPerGprSpillLocation(kRuntimeISA));
217       default:
218       LOG(FATAL) << "Unexpected GPR index: " << gpr_index;
219       UNREACHABLE();
220     }
221   }
222 #else
223 #error "Unsupported architecture"
224 #endif
225 
226  public:
227   // Special handling for proxy methods. Proxy methods are instance methods so the
228   // 'this' object is the 1st argument. They also have the same frame layout as the
229   // kRefAndArgs runtime method. Since 'this' is a reference, it is located in the
230   // 1st GPR.
GetProxyThisObjectReference(ArtMethod ** sp)231   static StackReference<mirror::Object>* GetProxyThisObjectReference(ArtMethod** sp)
232       REQUIRES_SHARED(Locks::mutator_lock_) {
233     CHECK((*sp)->IsProxyMethod());
234     CHECK_GT(kNumQuickGprArgs, 0u);
235     constexpr uint32_t kThisGprIndex = 0u;  // 'this' is in the 1st GPR.
236     size_t this_arg_offset = kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset +
237         GprIndexToGprOffset(kThisGprIndex);
238     uint8_t* this_arg_address = reinterpret_cast<uint8_t*>(sp) + this_arg_offset;
239     return reinterpret_cast<StackReference<mirror::Object>*>(this_arg_address);
240   }
241 
GetCallingMethod(ArtMethod ** sp)242   static ArtMethod* GetCallingMethod(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
243     DCHECK((*sp)->IsCalleeSaveMethod());
244     return GetCalleeSaveMethodCaller(sp, CalleeSaveType::kSaveRefsAndArgs);
245   }
246 
GetOuterMethod(ArtMethod ** sp)247   static ArtMethod* GetOuterMethod(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
248     DCHECK((*sp)->IsCalleeSaveMethod());
249     uint8_t* previous_sp =
250         reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_FrameSize;
251     return *reinterpret_cast<ArtMethod**>(previous_sp);
252   }
253 
GetCallingDexPc(ArtMethod ** sp)254   static uint32_t GetCallingDexPc(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
255     DCHECK((*sp)->IsCalleeSaveMethod());
256     constexpr size_t callee_frame_size =
257         RuntimeCalleeSaveFrame::GetFrameSize(CalleeSaveType::kSaveRefsAndArgs);
258     ArtMethod** caller_sp = reinterpret_cast<ArtMethod**>(
259         reinterpret_cast<uintptr_t>(sp) + callee_frame_size);
260     uintptr_t outer_pc = QuickArgumentVisitor::GetCallingPc(sp);
261     const OatQuickMethodHeader* current_code = (*caller_sp)->GetOatQuickMethodHeader(outer_pc);
262     uintptr_t outer_pc_offset = current_code->NativeQuickPcOffset(outer_pc);
263 
264     if (current_code->IsOptimized()) {
265       CodeInfo code_info = CodeInfo::DecodeInlineInfoOnly(current_code);
266       StackMap stack_map = code_info.GetStackMapForNativePcOffset(outer_pc_offset);
267       DCHECK(stack_map.IsValid());
268       BitTableRange<InlineInfo> inline_infos = code_info.GetInlineInfosOf(stack_map);
269       if (!inline_infos.empty()) {
270         return inline_infos.back().GetDexPc();
271       } else {
272         return stack_map.GetDexPc();
273       }
274     } else {
275       return current_code->ToDexPc(caller_sp, outer_pc);
276     }
277   }
278 
GetCallingPcAddr(ArtMethod ** sp)279   static uint8_t* GetCallingPcAddr(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
280     DCHECK((*sp)->IsCalleeSaveMethod());
281     uint8_t* return_adress_spill =
282         reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_ReturnPcOffset;
283     return return_adress_spill;
284   }
285 
286   // For the given quick ref and args quick frame, return the caller's PC.
GetCallingPc(ArtMethod ** sp)287   static uintptr_t GetCallingPc(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
288     return *reinterpret_cast<uintptr_t*>(GetCallingPcAddr(sp));
289   }
290 
QuickArgumentVisitor(ArtMethod ** sp,bool is_static,const char * shorty,uint32_t shorty_len)291   QuickArgumentVisitor(ArtMethod** sp, bool is_static, const char* shorty,
292                        uint32_t shorty_len) REQUIRES_SHARED(Locks::mutator_lock_) :
293           is_static_(is_static), shorty_(shorty), shorty_len_(shorty_len),
294           gpr_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset),
295           fpr_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset),
296           stack_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_FrameSize
297               + sizeof(ArtMethod*)),  // Skip ArtMethod*.
298           gpr_index_(0), fpr_index_(0), fpr_double_index_(0), stack_index_(0),
299           cur_type_(Primitive::kPrimVoid), is_split_long_or_double_(false) {
300     static_assert(kQuickSoftFloatAbi == (kNumQuickFprArgs == 0),
301                   "Number of Quick FPR arguments unexpected");
302     static_assert(!(kQuickSoftFloatAbi && kQuickDoubleRegAlignedFloatBackFilled),
303                   "Double alignment unexpected");
304     // For register alignment, we want to assume that counters(fpr_double_index_) are even if the
305     // next register is even.
306     static_assert(!kQuickDoubleRegAlignedFloatBackFilled || kNumQuickFprArgs % 2 == 0,
307                   "Number of Quick FPR arguments not even");
308     DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
309   }
310 
~QuickArgumentVisitor()311   virtual ~QuickArgumentVisitor() {}
312 
313   virtual void Visit() = 0;
314 
GetParamPrimitiveType() const315   Primitive::Type GetParamPrimitiveType() const {
316     return cur_type_;
317   }
318 
GetParamAddress() const319   uint8_t* GetParamAddress() const {
320     if (!kQuickSoftFloatAbi) {
321       Primitive::Type type = GetParamPrimitiveType();
322       if (UNLIKELY((type == Primitive::kPrimDouble) || (type == Primitive::kPrimFloat))) {
323         if (type == Primitive::kPrimDouble && kQuickDoubleRegAlignedFloatBackFilled) {
324           if (fpr_double_index_ + 2 < kNumQuickFprArgs + 1) {
325             return fpr_args_ + (fpr_double_index_ * GetBytesPerFprSpillLocation(kRuntimeISA));
326           }
327         } else if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
328           return fpr_args_ + (fpr_index_ * GetBytesPerFprSpillLocation(kRuntimeISA));
329         }
330         return stack_args_ + (stack_index_ * kBytesStackArgLocation);
331       }
332     }
333     if (gpr_index_ < kNumQuickGprArgs) {
334       return gpr_args_ + GprIndexToGprOffset(gpr_index_);
335     }
336     return stack_args_ + (stack_index_ * kBytesStackArgLocation);
337   }
338 
IsSplitLongOrDouble() const339   bool IsSplitLongOrDouble() const {
340     if ((GetBytesPerGprSpillLocation(kRuntimeISA) == 4) ||
341         (GetBytesPerFprSpillLocation(kRuntimeISA) == 4)) {
342       return is_split_long_or_double_;
343     } else {
344       return false;  // An optimization for when GPR and FPRs are 64bit.
345     }
346   }
347 
IsParamAReference() const348   bool IsParamAReference() const {
349     return GetParamPrimitiveType() == Primitive::kPrimNot;
350   }
351 
IsParamALongOrDouble() const352   bool IsParamALongOrDouble() const {
353     Primitive::Type type = GetParamPrimitiveType();
354     return type == Primitive::kPrimLong || type == Primitive::kPrimDouble;
355   }
356 
ReadSplitLongParam() const357   uint64_t ReadSplitLongParam() const {
358     // The splitted long is always available through the stack.
359     return *reinterpret_cast<uint64_t*>(stack_args_
360         + stack_index_ * kBytesStackArgLocation);
361   }
362 
IncGprIndex()363   void IncGprIndex() {
364     gpr_index_++;
365     if (kGprFprLockstep) {
366       fpr_index_++;
367     }
368   }
369 
IncFprIndex()370   void IncFprIndex() {
371     fpr_index_++;
372     if (kGprFprLockstep) {
373       gpr_index_++;
374     }
375   }
376 
VisitArguments()377   void VisitArguments() REQUIRES_SHARED(Locks::mutator_lock_) {
378     // (a) 'stack_args_' should point to the first method's argument
379     // (b) whatever the argument type it is, the 'stack_index_' should
380     //     be moved forward along with every visiting.
381     gpr_index_ = 0;
382     fpr_index_ = 0;
383     if (kQuickDoubleRegAlignedFloatBackFilled) {
384       fpr_double_index_ = 0;
385     }
386     stack_index_ = 0;
387     if (!is_static_) {  // Handle this.
388       cur_type_ = Primitive::kPrimNot;
389       is_split_long_or_double_ = false;
390       Visit();
391       stack_index_++;
392       if (kNumQuickGprArgs > 0) {
393         IncGprIndex();
394       }
395     }
396     for (uint32_t shorty_index = 1; shorty_index < shorty_len_; ++shorty_index) {
397       cur_type_ = Primitive::GetType(shorty_[shorty_index]);
398       switch (cur_type_) {
399         case Primitive::kPrimNot:
400         case Primitive::kPrimBoolean:
401         case Primitive::kPrimByte:
402         case Primitive::kPrimChar:
403         case Primitive::kPrimShort:
404         case Primitive::kPrimInt:
405           is_split_long_or_double_ = false;
406           Visit();
407           stack_index_++;
408           if (gpr_index_ < kNumQuickGprArgs) {
409             IncGprIndex();
410           }
411           break;
412         case Primitive::kPrimFloat:
413           is_split_long_or_double_ = false;
414           Visit();
415           stack_index_++;
416           if (kQuickSoftFloatAbi) {
417             if (gpr_index_ < kNumQuickGprArgs) {
418               IncGprIndex();
419             }
420           } else {
421             if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
422               IncFprIndex();
423               if (kQuickDoubleRegAlignedFloatBackFilled) {
424                 // Double should not overlap with float.
425                 // For example, if fpr_index_ = 3, fpr_double_index_ should be at least 4.
426                 fpr_double_index_ = std::max(fpr_double_index_, RoundUp(fpr_index_, 2));
427                 // Float should not overlap with double.
428                 if (fpr_index_ % 2 == 0) {
429                   fpr_index_ = std::max(fpr_double_index_, fpr_index_);
430                 }
431               } else if (kQuickSkipOddFpRegisters) {
432                 IncFprIndex();
433               }
434             }
435           }
436           break;
437         case Primitive::kPrimDouble:
438         case Primitive::kPrimLong:
439           if (kQuickSoftFloatAbi || (cur_type_ == Primitive::kPrimLong)) {
440             if (cur_type_ == Primitive::kPrimLong &&
441                 gpr_index_ == 0 &&
442                 kAlignPairRegister) {
443               // Currently, this is only for ARM, where we align long parameters with
444               // even-numbered registers by skipping R1 and using R2 instead.
445               IncGprIndex();
446             }
447             is_split_long_or_double_ = (GetBytesPerGprSpillLocation(kRuntimeISA) == 4) &&
448                 ((gpr_index_ + 1) == kNumQuickGprArgs);
449             if (!kSplitPairAcrossRegisterAndStack && is_split_long_or_double_) {
450               // We don't want to split this. Pass over this register.
451               gpr_index_++;
452               is_split_long_or_double_ = false;
453             }
454             Visit();
455             if (kBytesStackArgLocation == 4) {
456               stack_index_+= 2;
457             } else {
458               CHECK_EQ(kBytesStackArgLocation, 8U);
459               stack_index_++;
460             }
461             if (gpr_index_ < kNumQuickGprArgs) {
462               IncGprIndex();
463               if (GetBytesPerGprSpillLocation(kRuntimeISA) == 4) {
464                 if (gpr_index_ < kNumQuickGprArgs) {
465                   IncGprIndex();
466                 }
467               }
468             }
469           } else {
470             is_split_long_or_double_ = (GetBytesPerFprSpillLocation(kRuntimeISA) == 4) &&
471                 ((fpr_index_ + 1) == kNumQuickFprArgs) && !kQuickDoubleRegAlignedFloatBackFilled;
472             Visit();
473             if (kBytesStackArgLocation == 4) {
474               stack_index_+= 2;
475             } else {
476               CHECK_EQ(kBytesStackArgLocation, 8U);
477               stack_index_++;
478             }
479             if (kQuickDoubleRegAlignedFloatBackFilled) {
480               if (fpr_double_index_ + 2 < kNumQuickFprArgs + 1) {
481                 fpr_double_index_ += 2;
482                 // Float should not overlap with double.
483                 if (fpr_index_ % 2 == 0) {
484                   fpr_index_ = std::max(fpr_double_index_, fpr_index_);
485                 }
486               }
487             } else if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
488               IncFprIndex();
489               if (GetBytesPerFprSpillLocation(kRuntimeISA) == 4) {
490                 if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
491                   IncFprIndex();
492                 }
493               }
494             }
495           }
496           break;
497         default:
498           LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty_;
499       }
500     }
501   }
502 
503  protected:
504   const bool is_static_;
505   const char* const shorty_;
506   const uint32_t shorty_len_;
507 
508  private:
509   uint8_t* const gpr_args_;  // Address of GPR arguments in callee save frame.
510   uint8_t* const fpr_args_;  // Address of FPR arguments in callee save frame.
511   uint8_t* const stack_args_;  // Address of stack arguments in caller's frame.
512   uint32_t gpr_index_;  // Index into spilled GPRs.
513   // Index into spilled FPRs.
514   // In case kQuickDoubleRegAlignedFloatBackFilled, it may index a hole while fpr_double_index_
515   // holds a higher register number.
516   uint32_t fpr_index_;
517   // Index into spilled FPRs for aligned double.
518   // Only used when kQuickDoubleRegAlignedFloatBackFilled. Next available double register indexed in
519   // terms of singles, may be behind fpr_index.
520   uint32_t fpr_double_index_;
521   uint32_t stack_index_;  // Index into arguments on the stack.
522   // The current type of argument during VisitArguments.
523   Primitive::Type cur_type_;
524   // Does a 64bit parameter straddle the register and stack arguments?
525   bool is_split_long_or_double_;
526 };
527 
528 // Returns the 'this' object of a proxy method. This function is only used by StackVisitor. It
529 // allows to use the QuickArgumentVisitor constants without moving all the code in its own module.
artQuickGetProxyThisObject(ArtMethod ** sp)530 extern "C" mirror::Object* artQuickGetProxyThisObject(ArtMethod** sp)
531     REQUIRES_SHARED(Locks::mutator_lock_) {
532   return QuickArgumentVisitor::GetProxyThisObjectReference(sp)->AsMirrorPtr();
533 }
534 
535 // Visits arguments on the stack placing them into the shadow frame.
536 class BuildQuickShadowFrameVisitor final : public QuickArgumentVisitor {
537  public:
BuildQuickShadowFrameVisitor(ArtMethod ** sp,bool is_static,const char * shorty,uint32_t shorty_len,ShadowFrame * sf,size_t first_arg_reg)538   BuildQuickShadowFrameVisitor(ArtMethod** sp, bool is_static, const char* shorty,
539                                uint32_t shorty_len, ShadowFrame* sf, size_t first_arg_reg) :
540       QuickArgumentVisitor(sp, is_static, shorty, shorty_len), sf_(sf), cur_reg_(first_arg_reg) {}
541 
542   void Visit() REQUIRES_SHARED(Locks::mutator_lock_) override;
543 
544  private:
545   ShadowFrame* const sf_;
546   uint32_t cur_reg_;
547 
548   DISALLOW_COPY_AND_ASSIGN(BuildQuickShadowFrameVisitor);
549 };
550 
Visit()551 void BuildQuickShadowFrameVisitor::Visit() {
552   Primitive::Type type = GetParamPrimitiveType();
553   switch (type) {
554     case Primitive::kPrimLong:  // Fall-through.
555     case Primitive::kPrimDouble:
556       if (IsSplitLongOrDouble()) {
557         sf_->SetVRegLong(cur_reg_, ReadSplitLongParam());
558       } else {
559         sf_->SetVRegLong(cur_reg_, *reinterpret_cast<jlong*>(GetParamAddress()));
560       }
561       ++cur_reg_;
562       break;
563     case Primitive::kPrimNot: {
564         StackReference<mirror::Object>* stack_ref =
565             reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
566         sf_->SetVRegReference(cur_reg_, stack_ref->AsMirrorPtr());
567       }
568       break;
569     case Primitive::kPrimBoolean:  // Fall-through.
570     case Primitive::kPrimByte:     // Fall-through.
571     case Primitive::kPrimChar:     // Fall-through.
572     case Primitive::kPrimShort:    // Fall-through.
573     case Primitive::kPrimInt:      // Fall-through.
574     case Primitive::kPrimFloat:
575       sf_->SetVReg(cur_reg_, *reinterpret_cast<jint*>(GetParamAddress()));
576       break;
577     case Primitive::kPrimVoid:
578       LOG(FATAL) << "UNREACHABLE";
579       UNREACHABLE();
580   }
581   ++cur_reg_;
582 }
583 
584 // Don't inline. See b/65159206.
585 NO_INLINE
HandleDeoptimization(JValue * result,ArtMethod * method,ShadowFrame * deopt_frame,ManagedStack * fragment)586 static void HandleDeoptimization(JValue* result,
587                                  ArtMethod* method,
588                                  ShadowFrame* deopt_frame,
589                                  ManagedStack* fragment)
590     REQUIRES_SHARED(Locks::mutator_lock_) {
591   // Coming from partial-fragment deopt.
592   Thread* self = Thread::Current();
593   if (kIsDebugBuild) {
594     // Consistency-check: are the methods as expected? We check that the last shadow frame
595     // (the bottom of the call-stack) corresponds to the called method.
596     ShadowFrame* linked = deopt_frame;
597     while (linked->GetLink() != nullptr) {
598       linked = linked->GetLink();
599     }
600     CHECK_EQ(method, linked->GetMethod()) << method->PrettyMethod() << " "
601         << ArtMethod::PrettyMethod(linked->GetMethod());
602   }
603 
604   if (VLOG_IS_ON(deopt)) {
605     // Print out the stack to verify that it was a partial-fragment deopt.
606     LOG(INFO) << "Continue-ing from deopt. Stack is:";
607     QuickExceptionHandler::DumpFramesWithType(self, true);
608   }
609 
610   ObjPtr<mirror::Throwable> pending_exception;
611   bool from_code = false;
612   DeoptimizationMethodType method_type;
613   self->PopDeoptimizationContext(/* out */ result,
614                                  /* out */ &pending_exception,
615                                  /* out */ &from_code,
616                                  /* out */ &method_type);
617 
618   // Push a transition back into managed code onto the linked list in thread.
619   self->PushManagedStackFragment(fragment);
620 
621   // Ensure that the stack is still in order.
622   if (kIsDebugBuild) {
623     class EntireStackVisitor : public StackVisitor {
624      public:
625       explicit EntireStackVisitor(Thread* self_in) REQUIRES_SHARED(Locks::mutator_lock_)
626           : StackVisitor(self_in, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames) {}
627 
628       bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
629         // Nothing to do here. In a debug build, ValidateFrame will do the work in the walking
630         // logic. Just always say we want to continue.
631         return true;
632       }
633     };
634     EntireStackVisitor esv(self);
635     esv.WalkStack();
636   }
637 
638   // Restore the exception that was pending before deoptimization then interpret the
639   // deoptimized frames.
640   if (pending_exception != nullptr) {
641     self->SetException(pending_exception);
642   }
643   interpreter::EnterInterpreterFromDeoptimize(self,
644                                               deopt_frame,
645                                               result,
646                                               from_code,
647                                               method_type);
648 }
649 
artQuickToInterpreterBridge(ArtMethod * method,Thread * self,ArtMethod ** sp)650 extern "C" uint64_t artQuickToInterpreterBridge(ArtMethod* method, Thread* self, ArtMethod** sp)
651     REQUIRES_SHARED(Locks::mutator_lock_) {
652   // Ensure we don't get thread suspension until the object arguments are safely in the shadow
653   // frame.
654   ScopedQuickEntrypointChecks sqec(self);
655 
656   if (UNLIKELY(!method->IsInvokable())) {
657     method->ThrowInvocationTimeError();
658     return 0;
659   }
660 
661   JValue tmp_value;
662   ShadowFrame* deopt_frame = self->PopStackedShadowFrame(
663       StackedShadowFrameType::kDeoptimizationShadowFrame, false);
664   ManagedStack fragment;
665 
666   DCHECK(!method->IsNative()) << method->PrettyMethod();
667   uint32_t shorty_len = 0;
668   ArtMethod* non_proxy_method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
669   DCHECK(non_proxy_method->GetCodeItem() != nullptr) << method->PrettyMethod();
670   CodeItemDataAccessor accessor(non_proxy_method->DexInstructionData());
671   const char* shorty = non_proxy_method->GetShorty(&shorty_len);
672 
673   JValue result;
674   bool force_frame_pop = false;
675 
676   if (UNLIKELY(deopt_frame != nullptr)) {
677     HandleDeoptimization(&result, method, deopt_frame, &fragment);
678   } else {
679     const char* old_cause = self->StartAssertNoThreadSuspension(
680         "Building interpreter shadow frame");
681     uint16_t num_regs = accessor.RegistersSize();
682     // No last shadow coming from quick.
683     ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
684         CREATE_SHADOW_FRAME(num_regs, /* link= */ nullptr, method, /* dex_pc= */ 0);
685     ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
686     size_t first_arg_reg = accessor.RegistersSize() - accessor.InsSize();
687     BuildQuickShadowFrameVisitor shadow_frame_builder(sp, method->IsStatic(), shorty, shorty_len,
688                                                       shadow_frame, first_arg_reg);
689     shadow_frame_builder.VisitArguments();
690     // Push a transition back into managed code onto the linked list in thread.
691     self->PushManagedStackFragment(&fragment);
692     self->PushShadowFrame(shadow_frame);
693     self->EndAssertNoThreadSuspension(old_cause);
694 
695     if (NeedsClinitCheckBeforeCall(method)) {
696       ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
697       if (UNLIKELY(!declaring_class->IsVisiblyInitialized())) {
698         // Ensure static method's class is initialized.
699         StackHandleScope<1> hs(self);
700         Handle<mirror::Class> h_class(hs.NewHandle(declaring_class));
701         if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
702           DCHECK(Thread::Current()->IsExceptionPending()) << method->PrettyMethod();
703           self->PopManagedStackFragment(fragment);
704           return 0;
705         }
706       }
707     }
708 
709     result = interpreter::EnterInterpreterFromEntryPoint(self, accessor, shadow_frame);
710     force_frame_pop = shadow_frame->GetForcePopFrame();
711   }
712 
713   // Pop transition.
714   self->PopManagedStackFragment(fragment);
715 
716   // Request a stack deoptimization if needed
717   ArtMethod* caller = QuickArgumentVisitor::GetCallingMethod(sp);
718   uintptr_t caller_pc = QuickArgumentVisitor::GetCallingPc(sp);
719   // If caller_pc is the instrumentation exit stub, the stub will check to see if deoptimization
720   // should be done and it knows the real return pc. NB If the upcall is null we don't need to do
721   // anything. This can happen during shutdown or early startup.
722   if (UNLIKELY(
723           caller != nullptr &&
724           caller_pc != reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()) &&
725           (self->IsForceInterpreter() || Dbg::IsForcedInterpreterNeededForUpcall(self, caller)))) {
726     if (!Runtime::Current()->IsAsyncDeoptimizeable(caller_pc)) {
727       LOG(WARNING) << "Got a deoptimization request on un-deoptimizable method "
728                    << caller->PrettyMethod();
729     } else {
730       VLOG(deopt) << "Forcing deoptimization on return from method " << method->PrettyMethod()
731                   << " to " << caller->PrettyMethod()
732                   << (force_frame_pop ? " for frame-pop" : "");
733       DCHECK_IMPLIES(force_frame_pop, result.GetJ() == 0)
734           << "Force frame pop should have no result.";
735       if (force_frame_pop && self->GetException() != nullptr) {
736         LOG(WARNING) << "Suppressing exception for instruction-retry: "
737                      << self->GetException()->Dump();
738       }
739       // Push the context of the deoptimization stack so we can restore the return value and the
740       // exception before executing the deoptimized frames.
741       self->PushDeoptimizationContext(
742           result,
743           shorty[0] == 'L' || shorty[0] == '[',  /* class or array */
744           force_frame_pop ? nullptr : self->GetException(),
745           /* from_code= */ false,
746           DeoptimizationMethodType::kDefault);
747 
748       // Set special exception to cause deoptimization.
749       self->SetException(Thread::GetDeoptimizationException());
750     }
751   }
752 
753   // No need to restore the args since the method has already been run by the interpreter.
754   return result.GetJ();
755 }
756 
757 // Visits arguments on the stack placing them into the args vector, Object* arguments are converted
758 // to jobjects.
759 class BuildQuickArgumentVisitor final : public QuickArgumentVisitor {
760  public:
BuildQuickArgumentVisitor(ArtMethod ** sp,bool is_static,const char * shorty,uint32_t shorty_len,ScopedObjectAccessUnchecked * soa,std::vector<jvalue> * args)761   BuildQuickArgumentVisitor(ArtMethod** sp, bool is_static, const char* shorty, uint32_t shorty_len,
762                             ScopedObjectAccessUnchecked* soa, std::vector<jvalue>* args) :
763       QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa), args_(args) {}
764 
765   void Visit() REQUIRES_SHARED(Locks::mutator_lock_) override;
766 
767  private:
768   ScopedObjectAccessUnchecked* const soa_;
769   std::vector<jvalue>* const args_;
770 
771   DISALLOW_COPY_AND_ASSIGN(BuildQuickArgumentVisitor);
772 };
773 
Visit()774 void BuildQuickArgumentVisitor::Visit() {
775   jvalue val;
776   Primitive::Type type = GetParamPrimitiveType();
777   switch (type) {
778     case Primitive::kPrimNot: {
779       StackReference<mirror::Object>* stack_ref =
780           reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
781       val.l = soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
782       break;
783     }
784     case Primitive::kPrimLong:  // Fall-through.
785     case Primitive::kPrimDouble:
786       if (IsSplitLongOrDouble()) {
787         val.j = ReadSplitLongParam();
788       } else {
789         val.j = *reinterpret_cast<jlong*>(GetParamAddress());
790       }
791       break;
792     case Primitive::kPrimBoolean:  // Fall-through.
793     case Primitive::kPrimByte:     // Fall-through.
794     case Primitive::kPrimChar:     // Fall-through.
795     case Primitive::kPrimShort:    // Fall-through.
796     case Primitive::kPrimInt:      // Fall-through.
797     case Primitive::kPrimFloat:
798       val.i = *reinterpret_cast<jint*>(GetParamAddress());
799       break;
800     case Primitive::kPrimVoid:
801       LOG(FATAL) << "UNREACHABLE";
802       UNREACHABLE();
803   }
804   args_->push_back(val);
805 }
806 
807 // Handler for invocation on proxy methods. On entry a frame will exist for the proxy object method
808 // which is responsible for recording callee save registers. We explicitly place into jobjects the
809 // incoming reference arguments (so they survive GC). We invoke the invocation handler, which is a
810 // field within the proxy object, which will box the primitive arguments and deal with error cases.
artQuickProxyInvokeHandler(ArtMethod * proxy_method,mirror::Object * receiver,Thread * self,ArtMethod ** sp)811 extern "C" uint64_t artQuickProxyInvokeHandler(
812     ArtMethod* proxy_method, mirror::Object* receiver, Thread* self, ArtMethod** sp)
813     REQUIRES_SHARED(Locks::mutator_lock_) {
814   DCHECK(proxy_method->IsProxyMethod()) << proxy_method->PrettyMethod();
815   DCHECK(receiver->GetClass()->IsProxyClass()) << proxy_method->PrettyMethod();
816   // Ensure we don't get thread suspension until the object arguments are safely in jobjects.
817   const char* old_cause =
818       self->StartAssertNoThreadSuspension("Adding to IRT proxy object arguments");
819   // Register the top of the managed stack, making stack crawlable.
820   DCHECK_EQ((*sp), proxy_method) << proxy_method->PrettyMethod();
821   self->VerifyStack();
822   // Start new JNI local reference state.
823   JNIEnvExt* env = self->GetJniEnv();
824   ScopedObjectAccessUnchecked soa(env);
825   ScopedJniEnvLocalRefState env_state(env);
826   // Create local ref. copies of proxy method and the receiver.
827   jobject rcvr_jobj = soa.AddLocalReference<jobject>(receiver);
828 
829   // Placing arguments into args vector and remove the receiver.
830   ArtMethod* non_proxy_method = proxy_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
831   CHECK(!non_proxy_method->IsStatic()) << proxy_method->PrettyMethod() << " "
832                                        << non_proxy_method->PrettyMethod();
833   std::vector<jvalue> args;
834   uint32_t shorty_len = 0;
835   const char* shorty = non_proxy_method->GetShorty(&shorty_len);
836   BuildQuickArgumentVisitor local_ref_visitor(
837       sp, /* is_static= */ false, shorty, shorty_len, &soa, &args);
838 
839   local_ref_visitor.VisitArguments();
840   DCHECK_GT(args.size(), 0U) << proxy_method->PrettyMethod();
841   args.erase(args.begin());
842 
843   // Convert proxy method into expected interface method.
844   ArtMethod* interface_method = proxy_method->FindOverriddenMethod(kRuntimePointerSize);
845   DCHECK(interface_method != nullptr) << proxy_method->PrettyMethod();
846   DCHECK(!interface_method->IsProxyMethod()) << interface_method->PrettyMethod();
847   self->EndAssertNoThreadSuspension(old_cause);
848   DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
849   DCHECK(!Runtime::Current()->IsActiveTransaction());
850   ObjPtr<mirror::Method> interface_reflect_method =
851       mirror::Method::CreateFromArtMethod<kRuntimePointerSize>(soa.Self(), interface_method);
852   if (interface_reflect_method == nullptr) {
853     soa.Self()->AssertPendingOOMException();
854     return 0;
855   }
856   jobject interface_method_jobj = soa.AddLocalReference<jobject>(interface_reflect_method);
857 
858   // All naked Object*s should now be in jobjects, so its safe to go into the main invoke code
859   // that performs allocations or instrumentation events.
860   instrumentation::Instrumentation* instr = Runtime::Current()->GetInstrumentation();
861   if (instr->HasMethodEntryListeners()) {
862     instr->MethodEnterEvent(soa.Self(), proxy_method);
863     if (soa.Self()->IsExceptionPending()) {
864       instr->MethodUnwindEvent(self,
865                                soa.Decode<mirror::Object>(rcvr_jobj),
866                                proxy_method,
867                                0);
868       return 0;
869     }
870   }
871   JValue result = InvokeProxyInvocationHandler(soa, shorty, rcvr_jobj, interface_method_jobj, args);
872   if (soa.Self()->IsExceptionPending()) {
873     if (instr->HasMethodUnwindListeners()) {
874       instr->MethodUnwindEvent(self,
875                                soa.Decode<mirror::Object>(rcvr_jobj),
876                                proxy_method,
877                                0);
878     }
879   } else if (instr->HasMethodExitListeners()) {
880     instr->MethodExitEvent(self,
881                            proxy_method,
882                            {},
883                            result);
884   }
885   return result.GetJ();
886 }
887 
888 // Visitor returning a reference argument at a given position in a Quick stack frame.
889 // NOTE: Only used for testing purposes.
890 class GetQuickReferenceArgumentAtVisitor final : public QuickArgumentVisitor {
891  public:
GetQuickReferenceArgumentAtVisitor(ArtMethod ** sp,const char * shorty,uint32_t shorty_len,size_t arg_pos)892   GetQuickReferenceArgumentAtVisitor(ArtMethod** sp,
893                                      const char* shorty,
894                                      uint32_t shorty_len,
895                                      size_t arg_pos)
896       : QuickArgumentVisitor(sp, /* is_static= */ false, shorty, shorty_len),
897         cur_pos_(0u),
898         arg_pos_(arg_pos),
899         ref_arg_(nullptr) {
900           CHECK_LT(arg_pos, shorty_len) << "Argument position greater than the number arguments";
901         }
902 
Visit()903   void Visit() REQUIRES_SHARED(Locks::mutator_lock_) override {
904     if (cur_pos_ == arg_pos_) {
905       Primitive::Type type = GetParamPrimitiveType();
906       CHECK_EQ(type, Primitive::kPrimNot) << "Argument at searched position is not a reference";
907       ref_arg_ = reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
908     }
909     ++cur_pos_;
910   }
911 
GetReferenceArgument()912   StackReference<mirror::Object>* GetReferenceArgument() {
913     return ref_arg_;
914   }
915 
916  private:
917   // The position of the currently visited argument.
918   size_t cur_pos_;
919   // The position of the searched argument.
920   const size_t arg_pos_;
921   // The reference argument, if found.
922   StackReference<mirror::Object>* ref_arg_;
923 
924   DISALLOW_COPY_AND_ASSIGN(GetQuickReferenceArgumentAtVisitor);
925 };
926 
927 // Returning reference argument at position `arg_pos` in Quick stack frame at address `sp`.
928 // NOTE: Only used for testing purposes.
artQuickGetProxyReferenceArgumentAt(size_t arg_pos,ArtMethod ** sp)929 extern "C" StackReference<mirror::Object>* artQuickGetProxyReferenceArgumentAt(size_t arg_pos,
930                                                                                ArtMethod** sp)
931     REQUIRES_SHARED(Locks::mutator_lock_) {
932   ArtMethod* proxy_method = *sp;
933   ArtMethod* non_proxy_method = proxy_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
934   CHECK(!non_proxy_method->IsStatic())
935       << proxy_method->PrettyMethod() << " " << non_proxy_method->PrettyMethod();
936   uint32_t shorty_len = 0;
937   const char* shorty = non_proxy_method->GetShorty(&shorty_len);
938   GetQuickReferenceArgumentAtVisitor ref_arg_visitor(sp, shorty, shorty_len, arg_pos);
939   ref_arg_visitor.VisitArguments();
940   StackReference<mirror::Object>* ref_arg = ref_arg_visitor.GetReferenceArgument();
941   return ref_arg;
942 }
943 
944 // Visitor returning all the reference arguments in a Quick stack frame.
945 class GetQuickReferenceArgumentsVisitor final : public QuickArgumentVisitor {
946  public:
GetQuickReferenceArgumentsVisitor(ArtMethod ** sp,bool is_static,const char * shorty,uint32_t shorty_len)947   GetQuickReferenceArgumentsVisitor(ArtMethod** sp,
948                                     bool is_static,
949                                     const char* shorty,
950                                     uint32_t shorty_len)
951       : QuickArgumentVisitor(sp, is_static, shorty, shorty_len) {}
952 
Visit()953   void Visit() REQUIRES_SHARED(Locks::mutator_lock_) override {
954     Primitive::Type type = GetParamPrimitiveType();
955     if (type == Primitive::kPrimNot) {
956       StackReference<mirror::Object>* ref_arg =
957           reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
958       ref_args_.push_back(ref_arg);
959     }
960   }
961 
GetReferenceArguments()962   std::vector<StackReference<mirror::Object>*> GetReferenceArguments() {
963     return ref_args_;
964   }
965 
966  private:
967   // The reference arguments.
968   std::vector<StackReference<mirror::Object>*> ref_args_;
969 
970   DISALLOW_COPY_AND_ASSIGN(GetQuickReferenceArgumentsVisitor);
971 };
972 
973 // Returning all reference arguments in Quick stack frame at address `sp`.
GetProxyReferenceArguments(ArtMethod ** sp)974 std::vector<StackReference<mirror::Object>*> GetProxyReferenceArguments(ArtMethod** sp)
975     REQUIRES_SHARED(Locks::mutator_lock_) {
976   ArtMethod* proxy_method = *sp;
977   ArtMethod* non_proxy_method = proxy_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
978   CHECK(!non_proxy_method->IsStatic())
979       << proxy_method->PrettyMethod() << " " << non_proxy_method->PrettyMethod();
980   uint32_t shorty_len = 0;
981   const char* shorty = non_proxy_method->GetShorty(&shorty_len);
982   GetQuickReferenceArgumentsVisitor ref_args_visitor(sp, /*is_static=*/ false, shorty, shorty_len);
983   ref_args_visitor.VisitArguments();
984   std::vector<StackReference<mirror::Object>*> ref_args = ref_args_visitor.GetReferenceArguments();
985   return ref_args;
986 }
987 
988 // Read object references held in arguments from quick frames and place in a JNI local references,
989 // so they don't get garbage collected.
990 class RememberForGcArgumentVisitor final : public QuickArgumentVisitor {
991  public:
RememberForGcArgumentVisitor(ArtMethod ** sp,bool is_static,const char * shorty,uint32_t shorty_len,ScopedObjectAccessUnchecked * soa)992   RememberForGcArgumentVisitor(ArtMethod** sp, bool is_static, const char* shorty,
993                                uint32_t shorty_len, ScopedObjectAccessUnchecked* soa) :
994       QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa) {}
995 
996   void Visit() REQUIRES_SHARED(Locks::mutator_lock_) override;
997 
998   void FixupReferences() REQUIRES_SHARED(Locks::mutator_lock_);
999 
1000  private:
1001   ScopedObjectAccessUnchecked* const soa_;
1002   // References which we must update when exiting in case the GC moved the objects.
1003   std::vector<std::pair<jobject, StackReference<mirror::Object>*> > references_;
1004 
1005   DISALLOW_COPY_AND_ASSIGN(RememberForGcArgumentVisitor);
1006 };
1007 
Visit()1008 void RememberForGcArgumentVisitor::Visit() {
1009   if (IsParamAReference()) {
1010     StackReference<mirror::Object>* stack_ref =
1011         reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
1012     jobject reference =
1013         soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
1014     references_.push_back(std::make_pair(reference, stack_ref));
1015   }
1016 }
1017 
FixupReferences()1018 void RememberForGcArgumentVisitor::FixupReferences() {
1019   // Fixup any references which may have changed.
1020   for (const auto& pair : references_) {
1021     pair.second->Assign(soa_->Decode<mirror::Object>(pair.first));
1022     soa_->Env()->DeleteLocalRef(pair.first);
1023   }
1024 }
1025 
artInstrumentationMethodEntryFromCode(ArtMethod * method,mirror::Object * this_object,Thread * self,ArtMethod ** sp)1026 extern "C" const void* artInstrumentationMethodEntryFromCode(ArtMethod* method,
1027                                                              mirror::Object* this_object,
1028                                                              Thread* self,
1029                                                              ArtMethod** sp)
1030     REQUIRES_SHARED(Locks::mutator_lock_) {
1031   const void* result;
1032   // Instrumentation changes the stack. Thus, when exiting, the stack cannot be verified, so skip
1033   // that part.
1034   ScopedQuickEntrypointChecks sqec(self, kIsDebugBuild, false);
1035   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1036   DCHECK(!method->IsProxyMethod())
1037       << "Proxy method " << method->PrettyMethod()
1038       << " (declaring class: " << method->GetDeclaringClass()->PrettyClass() << ")"
1039       << " should not hit instrumentation entrypoint.";
1040   DCHECK(!instrumentation->IsDeoptimized(method));
1041   // This will get the entry point either from the oat file, the JIT or the appropriate bridge
1042   // method if none of those can be found.
1043   result = instrumentation->GetCodeForInvoke(method);
1044   DCHECK_NE(result, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
1045   bool interpreter_entry = Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(result);
1046   bool is_static = method->IsStatic();
1047   uint32_t shorty_len;
1048   const char* shorty =
1049       method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetShorty(&shorty_len);
1050 
1051   ScopedObjectAccessUnchecked soa(self);
1052   RememberForGcArgumentVisitor visitor(sp, is_static, shorty, shorty_len, &soa);
1053   visitor.VisitArguments();
1054 
1055   StackHandleScope<2> hs(self);
1056   Handle<mirror::Object> h_object(hs.NewHandle(is_static ? nullptr : this_object));
1057   Handle<mirror::Class> h_class(hs.NewHandle(method->GetDeclaringClass()));
1058 
1059   // Ensure that the called method's class is initialized.
1060   if (NeedsClinitCheckBeforeCall(method) && !h_class->IsVisiblyInitialized()) {
1061     if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
1062       visitor.FixupReferences();
1063       DCHECK(self->IsExceptionPending());
1064       return nullptr;
1065     }
1066   }
1067 
1068   instrumentation->PushInstrumentationStackFrame(self,
1069                                                  is_static ? nullptr : h_object.Get(),
1070                                                  method,
1071                                                  reinterpret_cast<uintptr_t>(
1072                                                      QuickArgumentVisitor::GetCallingPcAddr(sp)),
1073                                                  QuickArgumentVisitor::GetCallingPc(sp),
1074                                                  interpreter_entry);
1075 
1076   visitor.FixupReferences();
1077   if (UNLIKELY(self->IsExceptionPending())) {
1078     return nullptr;
1079   }
1080   CHECK(result != nullptr) << method->PrettyMethod();
1081   return result;
1082 }
1083 
artInstrumentationMethodExitFromCode(Thread * self,ArtMethod ** sp,uint64_t * gpr_result,uint64_t * fpr_result)1084 extern "C" TwoWordReturn artInstrumentationMethodExitFromCode(Thread* self,
1085                                                               ArtMethod** sp,
1086                                                               uint64_t* gpr_result,
1087                                                               uint64_t* fpr_result)
1088     REQUIRES_SHARED(Locks::mutator_lock_) {
1089   DCHECK_EQ(reinterpret_cast<uintptr_t>(self), reinterpret_cast<uintptr_t>(Thread::Current()));
1090   CHECK(gpr_result != nullptr);
1091   CHECK(fpr_result != nullptr);
1092   // Instrumentation exit stub must not be entered with a pending exception.
1093   CHECK(!self->IsExceptionPending()) << "Enter instrumentation exit stub with pending exception "
1094                                      << self->GetException()->Dump();
1095   // Compute address of return PC and check that it currently holds 0.
1096   constexpr size_t return_pc_offset =
1097       RuntimeCalleeSaveFrame::GetReturnPcOffset(CalleeSaveType::kSaveEverything);
1098   uintptr_t* return_pc_addr = reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(sp) +
1099                                                            return_pc_offset);
1100   CHECK_EQ(*return_pc_addr, 0U);
1101 
1102   // Pop the frame filling in the return pc. The low half of the return value is 0 when
1103   // deoptimization shouldn't be performed with the high-half having the return address. When
1104   // deoptimization should be performed the low half is zero and the high-half the address of the
1105   // deoptimization entry point.
1106   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1107   TwoWordReturn return_or_deoptimize_pc = instrumentation->PopInstrumentationStackFrame(
1108       self, return_pc_addr, gpr_result, fpr_result);
1109   if (self->IsExceptionPending() || self->ObserveAsyncException()) {
1110     return GetTwoWordFailureValue();
1111   }
1112   return return_or_deoptimize_pc;
1113 }
1114 
DumpInstruction(ArtMethod * method,uint32_t dex_pc)1115 static std::string DumpInstruction(ArtMethod* method, uint32_t dex_pc)
1116     REQUIRES_SHARED(Locks::mutator_lock_) {
1117   if (dex_pc == static_cast<uint32_t>(-1)) {
1118     CHECK(method == jni::DecodeArtMethod(WellKnownClasses::java_lang_String_charAt));
1119     return "<native>";
1120   } else {
1121     CodeItemInstructionAccessor accessor = method->DexInstructions();
1122     CHECK_LT(dex_pc, accessor.InsnsSizeInCodeUnits());
1123     return accessor.InstructionAt(dex_pc).DumpString(method->GetDexFile());
1124   }
1125 }
1126 
DumpB74410240ClassData(ObjPtr<mirror::Class> klass)1127 static void DumpB74410240ClassData(ObjPtr<mirror::Class> klass)
1128     REQUIRES_SHARED(Locks::mutator_lock_) {
1129   std::string storage;
1130   const char* descriptor = klass->GetDescriptor(&storage);
1131   LOG(FATAL_WITHOUT_ABORT) << "  " << DescribeLoaders(klass->GetClassLoader(), descriptor);
1132   const OatDexFile* oat_dex_file = klass->GetDexFile().GetOatDexFile();
1133   if (oat_dex_file != nullptr) {
1134     const OatFile* oat_file = oat_dex_file->GetOatFile();
1135     const char* dex2oat_cmdline =
1136         oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kDex2OatCmdLineKey);
1137     LOG(FATAL_WITHOUT_ABORT) << "    OatFile: " << oat_file->GetLocation()
1138         << "; " << (dex2oat_cmdline != nullptr ? dex2oat_cmdline : "<not recorded>");
1139   }
1140 }
1141 
DumpB74410240DebugData(ArtMethod ** sp)1142 static void DumpB74410240DebugData(ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
1143   // Mimick the search for the caller and dump some data while doing so.
1144   LOG(FATAL_WITHOUT_ABORT) << "Dumping debugging data, please attach a bugreport to b/74410240.";
1145 
1146   constexpr CalleeSaveType type = CalleeSaveType::kSaveRefsAndArgs;
1147   CHECK_EQ(*sp, Runtime::Current()->GetCalleeSaveMethod(type));
1148 
1149   constexpr size_t callee_frame_size = RuntimeCalleeSaveFrame::GetFrameSize(type);
1150   auto** caller_sp = reinterpret_cast<ArtMethod**>(
1151       reinterpret_cast<uintptr_t>(sp) + callee_frame_size);
1152   constexpr size_t callee_return_pc_offset = RuntimeCalleeSaveFrame::GetReturnPcOffset(type);
1153   uintptr_t caller_pc = *reinterpret_cast<uintptr_t*>(
1154       (reinterpret_cast<uint8_t*>(sp) + callee_return_pc_offset));
1155   ArtMethod* outer_method = *caller_sp;
1156 
1157   if (UNLIKELY(caller_pc == reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()))) {
1158     LOG(FATAL_WITHOUT_ABORT) << "Method: " << outer_method->PrettyMethod()
1159         << " native pc: " << caller_pc << " Instrumented!";
1160     return;
1161   }
1162 
1163   const OatQuickMethodHeader* current_code = outer_method->GetOatQuickMethodHeader(caller_pc);
1164   CHECK(current_code != nullptr);
1165   CHECK(current_code->IsOptimized());
1166   uintptr_t native_pc_offset = current_code->NativeQuickPcOffset(caller_pc);
1167   CodeInfo code_info(current_code);
1168   StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
1169   CHECK(stack_map.IsValid());
1170   uint32_t dex_pc = stack_map.GetDexPc();
1171 
1172   // Log the outer method and its associated dex file and class table pointer which can be used
1173   // to find out if the inlined methods were defined by other dex file(s) or class loader(s).
1174   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1175   LOG(FATAL_WITHOUT_ABORT) << "Outer: " << outer_method->PrettyMethod()
1176       << " native pc: " << caller_pc
1177       << " dex pc: " << dex_pc
1178       << " dex file: " << outer_method->GetDexFile()->GetLocation()
1179       << " class table: " << class_linker->ClassTableForClassLoader(outer_method->GetClassLoader());
1180   DumpB74410240ClassData(outer_method->GetDeclaringClass());
1181   LOG(FATAL_WITHOUT_ABORT) << "  instruction: " << DumpInstruction(outer_method, dex_pc);
1182 
1183   ArtMethod* caller = outer_method;
1184   BitTableRange<InlineInfo> inline_infos = code_info.GetInlineInfosOf(stack_map);
1185   for (InlineInfo inline_info : inline_infos) {
1186     const char* tag = "";
1187     dex_pc = inline_info.GetDexPc();
1188     if (inline_info.EncodesArtMethod()) {
1189       tag = "encoded ";
1190       caller = inline_info.GetArtMethod();
1191     } else {
1192       uint32_t method_index = code_info.GetMethodIndexOf(inline_info);
1193       if (dex_pc == static_cast<uint32_t>(-1)) {
1194         tag = "special ";
1195         CHECK(inline_info.Equals(inline_infos.back()));
1196         caller = jni::DecodeArtMethod(WellKnownClasses::java_lang_String_charAt);
1197         CHECK_EQ(caller->GetDexMethodIndex(), method_index);
1198       } else {
1199         ObjPtr<mirror::DexCache> dex_cache = caller->GetDexCache();
1200         ObjPtr<mirror::ClassLoader> class_loader = caller->GetClassLoader();
1201         caller = class_linker->LookupResolvedMethod(method_index, dex_cache, class_loader);
1202         CHECK(caller != nullptr);
1203       }
1204     }
1205     LOG(FATAL_WITHOUT_ABORT) << "InlineInfo #" << inline_info.Row()
1206         << ": " << tag << caller->PrettyMethod()
1207         << " dex pc: " << dex_pc
1208         << " dex file: " << caller->GetDexFile()->GetLocation()
1209         << " class table: "
1210         << class_linker->ClassTableForClassLoader(caller->GetClassLoader());
1211     DumpB74410240ClassData(caller->GetDeclaringClass());
1212     LOG(FATAL_WITHOUT_ABORT) << "  instruction: " << DumpInstruction(caller, dex_pc);
1213   }
1214 }
1215 
1216 // Lazily resolve a method for quick. Called by stub code.
artQuickResolutionTrampoline(ArtMethod * called,mirror::Object * receiver,Thread * self,ArtMethod ** sp)1217 extern "C" const void* artQuickResolutionTrampoline(
1218     ArtMethod* called, mirror::Object* receiver, Thread* self, ArtMethod** sp)
1219     REQUIRES_SHARED(Locks::mutator_lock_) {
1220   // The resolution trampoline stashes the resolved method into the callee-save frame to transport
1221   // it. Thus, when exiting, the stack cannot be verified (as the resolved method most likely
1222   // does not have the same stack layout as the callee-save method).
1223   ScopedQuickEntrypointChecks sqec(self, kIsDebugBuild, false);
1224   // Start new JNI local reference state
1225   JNIEnvExt* env = self->GetJniEnv();
1226   ScopedObjectAccessUnchecked soa(env);
1227   ScopedJniEnvLocalRefState env_state(env);
1228   const char* old_cause = self->StartAssertNoThreadSuspension("Quick method resolution set up");
1229 
1230   // Compute details about the called method (avoid GCs)
1231   ClassLinker* linker = Runtime::Current()->GetClassLinker();
1232   InvokeType invoke_type;
1233   MethodReference called_method(nullptr, 0);
1234   const bool called_method_known_on_entry = !called->IsRuntimeMethod();
1235   ArtMethod* caller = nullptr;
1236   if (!called_method_known_on_entry) {
1237     caller = QuickArgumentVisitor::GetCallingMethod(sp);
1238     called_method.dex_file = caller->GetDexFile();
1239 
1240     {
1241       uint32_t dex_pc = QuickArgumentVisitor::GetCallingDexPc(sp);
1242       CodeItemInstructionAccessor accessor(caller->DexInstructions());
1243       CHECK_LT(dex_pc, accessor.InsnsSizeInCodeUnits());
1244       const Instruction& instr = accessor.InstructionAt(dex_pc);
1245       Instruction::Code instr_code = instr.Opcode();
1246       bool is_range;
1247       switch (instr_code) {
1248         case Instruction::INVOKE_DIRECT:
1249           invoke_type = kDirect;
1250           is_range = false;
1251           break;
1252         case Instruction::INVOKE_DIRECT_RANGE:
1253           invoke_type = kDirect;
1254           is_range = true;
1255           break;
1256         case Instruction::INVOKE_STATIC:
1257           invoke_type = kStatic;
1258           is_range = false;
1259           break;
1260         case Instruction::INVOKE_STATIC_RANGE:
1261           invoke_type = kStatic;
1262           is_range = true;
1263           break;
1264         case Instruction::INVOKE_SUPER:
1265           invoke_type = kSuper;
1266           is_range = false;
1267           break;
1268         case Instruction::INVOKE_SUPER_RANGE:
1269           invoke_type = kSuper;
1270           is_range = true;
1271           break;
1272         case Instruction::INVOKE_VIRTUAL:
1273           invoke_type = kVirtual;
1274           is_range = false;
1275           break;
1276         case Instruction::INVOKE_VIRTUAL_RANGE:
1277           invoke_type = kVirtual;
1278           is_range = true;
1279           break;
1280         case Instruction::INVOKE_INTERFACE:
1281           invoke_type = kInterface;
1282           is_range = false;
1283           break;
1284         case Instruction::INVOKE_INTERFACE_RANGE:
1285           invoke_type = kInterface;
1286           is_range = true;
1287           break;
1288         default:
1289           DumpB74410240DebugData(sp);
1290           LOG(FATAL) << "Unexpected call into trampoline: " << instr.DumpString(nullptr);
1291           UNREACHABLE();
1292       }
1293       called_method.index = (is_range) ? instr.VRegB_3rc() : instr.VRegB_35c();
1294       VLOG(dex) << "Accessed dex file for invoke " << invoke_type << " "
1295                 << called_method.index;
1296     }
1297   } else {
1298     invoke_type = kStatic;
1299     called_method.dex_file = called->GetDexFile();
1300     called_method.index = called->GetDexMethodIndex();
1301   }
1302   uint32_t shorty_len;
1303   const char* shorty =
1304       called_method.dex_file->GetMethodShorty(called_method.GetMethodId(), &shorty_len);
1305   RememberForGcArgumentVisitor visitor(sp, invoke_type == kStatic, shorty, shorty_len, &soa);
1306   visitor.VisitArguments();
1307   self->EndAssertNoThreadSuspension(old_cause);
1308   const bool virtual_or_interface = invoke_type == kVirtual || invoke_type == kInterface;
1309   // Resolve method filling in dex cache.
1310   if (!called_method_known_on_entry) {
1311     StackHandleScope<1> hs(self);
1312     mirror::Object* fake_receiver = nullptr;
1313     HandleWrapper<mirror::Object> h_receiver(
1314         hs.NewHandleWrapper(virtual_or_interface ? &receiver : &fake_receiver));
1315     DCHECK_EQ(caller->GetDexFile(), called_method.dex_file);
1316     called = linker->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
1317         self, called_method.index, caller, invoke_type);
1318   }
1319   const void* code = nullptr;
1320   if (LIKELY(!self->IsExceptionPending())) {
1321     // Incompatible class change should have been handled in resolve method.
1322     CHECK(!called->CheckIncompatibleClassChange(invoke_type))
1323         << called->PrettyMethod() << " " << invoke_type;
1324     if (virtual_or_interface || invoke_type == kSuper) {
1325       // Refine called method based on receiver for kVirtual/kInterface, and
1326       // caller for kSuper.
1327       ArtMethod* orig_called = called;
1328       if (invoke_type == kVirtual) {
1329         CHECK(receiver != nullptr) << invoke_type;
1330         called = receiver->GetClass()->FindVirtualMethodForVirtual(called, kRuntimePointerSize);
1331       } else if (invoke_type == kInterface) {
1332         CHECK(receiver != nullptr) << invoke_type;
1333         called = receiver->GetClass()->FindVirtualMethodForInterface(called, kRuntimePointerSize);
1334       } else {
1335         DCHECK_EQ(invoke_type, kSuper);
1336         CHECK(caller != nullptr) << invoke_type;
1337         ObjPtr<mirror::Class> ref_class = linker->LookupResolvedType(
1338             caller->GetDexFile()->GetMethodId(called_method.index).class_idx_, caller);
1339         if (ref_class->IsInterface()) {
1340           called = ref_class->FindVirtualMethodForInterfaceSuper(called, kRuntimePointerSize);
1341         } else {
1342           called = caller->GetDeclaringClass()->GetSuperClass()->GetVTableEntry(
1343               called->GetMethodIndex(), kRuntimePointerSize);
1344         }
1345       }
1346 
1347       CHECK(called != nullptr) << orig_called->PrettyMethod() << " "
1348                                << mirror::Object::PrettyTypeOf(receiver) << " "
1349                                << invoke_type << " " << orig_called->GetVtableIndex();
1350     }
1351     // Now that we know the actual target, update .bss entry in oat file, if
1352     // any.
1353     if (!called_method_known_on_entry) {
1354       // We only put non copied methods in the BSS. Putting a copy can lead to an
1355       // odd situation where the ArtMethod being executed is unrelated to the
1356       // receiver of the method.
1357       called = called->GetCanonicalMethod();
1358       if (invoke_type == kSuper || invoke_type == kInterface || invoke_type == kVirtual) {
1359         if (called->GetDexFile() == called_method.dex_file) {
1360           called_method.index = called->GetDexMethodIndex();
1361         } else {
1362           called_method.index = called->FindDexMethodIndexInOtherDexFile(
1363               *called_method.dex_file, called_method.index);
1364           DCHECK_NE(called_method.index, dex::kDexNoIndex);
1365         }
1366       }
1367       ArtMethod* outer_method = QuickArgumentVisitor::GetOuterMethod(sp);
1368       MaybeUpdateBssMethodEntry(called, called_method, outer_method);
1369     }
1370 
1371     // Static invokes need class initialization check but instance invokes can proceed even if
1372     // the class is erroneous, i.e. in the edge case of escaping instances of erroneous classes.
1373     bool success = true;
1374     ObjPtr<mirror::Class> called_class = called->GetDeclaringClass();
1375     if (NeedsClinitCheckBeforeCall(called) && !called_class->IsVisiblyInitialized()) {
1376       // Ensure that the called method's class is initialized.
1377       StackHandleScope<1> hs(soa.Self());
1378       HandleWrapperObjPtr<mirror::Class> h_called_class(hs.NewHandleWrapper(&called_class));
1379       success = linker->EnsureInitialized(soa.Self(), h_called_class, true, true);
1380     }
1381     if (success) {
1382       instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
1383       // Check if we need instrumented code here. Since resolution stubs could suspend, it is
1384       // possible that we instrumented the entry points after we started executing the resolution
1385       // stub.
1386       code = instrumentation->GetMaybeInstrumentedCodeForInvoke(called);
1387     } else {
1388       DCHECK(called_class->IsErroneous());
1389       DCHECK(self->IsExceptionPending());
1390     }
1391   }
1392   CHECK_EQ(code == nullptr, self->IsExceptionPending());
1393   // Fixup any locally saved objects may have moved during a GC.
1394   visitor.FixupReferences();
1395   // Place called method in callee-save frame to be placed as first argument to quick method.
1396   *sp = called;
1397 
1398   return code;
1399 }
1400 
1401 /*
1402  * This class uses a couple of observations to unite the different calling conventions through
1403  * a few constants.
1404  *
1405  * 1) Number of registers used for passing is normally even, so counting down has no penalty for
1406  *    possible alignment.
1407  * 2) Known 64b architectures store 8B units on the stack, both for integral and floating point
1408  *    types, so using uintptr_t is OK. Also means that we can use kRegistersNeededX to denote
1409  *    when we have to split things
1410  * 3) The only soft-float, Arm, is 32b, so no widening needs to be taken into account for floats
1411  *    and we can use Int handling directly.
1412  * 4) Only 64b architectures widen, and their stack is aligned 8B anyways, so no padding code
1413  *    necessary when widening. Also, widening of Ints will take place implicitly, and the
1414  *    extension should be compatible with Aarch64, which mandates copying the available bits
1415  *    into LSB and leaving the rest unspecified.
1416  * 5) Aligning longs and doubles is necessary on arm only, and it's the same in registers and on
1417  *    the stack.
1418  * 6) There is only little endian.
1419  *
1420  *
1421  * Actual work is supposed to be done in a delegate of the template type. The interface is as
1422  * follows:
1423  *
1424  * void PushGpr(uintptr_t):   Add a value for the next GPR
1425  *
1426  * void PushFpr4(float):      Add a value for the next FPR of size 32b. Is only called if we need
1427  *                            padding, that is, think the architecture is 32b and aligns 64b.
1428  *
1429  * void PushFpr8(uint64_t):   Push a double. We _will_ call this on 32b, it's the callee's job to
1430  *                            split this if necessary. The current state will have aligned, if
1431  *                            necessary.
1432  *
1433  * void PushStack(uintptr_t): Push a value to the stack.
1434  */
1435 template<class T> class BuildNativeCallFrameStateMachine {
1436  public:
1437 #if defined(__arm__)
1438   static constexpr bool kNativeSoftFloatAbi = true;
1439   static constexpr size_t kNumNativeGprArgs = 4;  // 4 arguments passed in GPRs, r0-r3
1440   static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
1441 
1442   static constexpr size_t kRegistersNeededForLong = 2;
1443   static constexpr size_t kRegistersNeededForDouble = 2;
1444   static constexpr bool kMultiRegistersAligned = true;
1445   static constexpr bool kMultiFPRegistersWidened = false;
1446   static constexpr bool kMultiGPRegistersWidened = false;
1447   static constexpr bool kAlignLongOnStack = true;
1448   static constexpr bool kAlignDoubleOnStack = true;
1449 #elif defined(__aarch64__)
1450   static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
1451   static constexpr size_t kNumNativeGprArgs = 8;  // 8 arguments passed in GPRs.
1452   static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
1453 
1454   static constexpr size_t kRegistersNeededForLong = 1;
1455   static constexpr size_t kRegistersNeededForDouble = 1;
1456   static constexpr bool kMultiRegistersAligned = false;
1457   static constexpr bool kMultiFPRegistersWidened = false;
1458   static constexpr bool kMultiGPRegistersWidened = false;
1459   static constexpr bool kAlignLongOnStack = false;
1460   static constexpr bool kAlignDoubleOnStack = false;
1461 #elif defined(__i386__)
1462   static constexpr bool kNativeSoftFloatAbi = false;  // Not using int registers for fp
1463   static constexpr size_t kNumNativeGprArgs = 0;  // 0 arguments passed in GPRs.
1464   static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
1465 
1466   static constexpr size_t kRegistersNeededForLong = 2;
1467   static constexpr size_t kRegistersNeededForDouble = 2;
1468   static constexpr bool kMultiRegistersAligned = false;  // x86 not using regs, anyways
1469   static constexpr bool kMultiFPRegistersWidened = false;
1470   static constexpr bool kMultiGPRegistersWidened = false;
1471   static constexpr bool kAlignLongOnStack = false;
1472   static constexpr bool kAlignDoubleOnStack = false;
1473 #elif defined(__x86_64__)
1474   static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
1475   static constexpr size_t kNumNativeGprArgs = 6;  // 6 arguments passed in GPRs.
1476   static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
1477 
1478   static constexpr size_t kRegistersNeededForLong = 1;
1479   static constexpr size_t kRegistersNeededForDouble = 1;
1480   static constexpr bool kMultiRegistersAligned = false;
1481   static constexpr bool kMultiFPRegistersWidened = false;
1482   static constexpr bool kMultiGPRegistersWidened = false;
1483   static constexpr bool kAlignLongOnStack = false;
1484   static constexpr bool kAlignDoubleOnStack = false;
1485 #else
1486 #error "Unsupported architecture"
1487 #endif
1488 
1489  public:
BuildNativeCallFrameStateMachine(T * delegate)1490   explicit BuildNativeCallFrameStateMachine(T* delegate)
1491       : gpr_index_(kNumNativeGprArgs),
1492         fpr_index_(kNumNativeFprArgs),
1493         stack_entries_(0),
1494         delegate_(delegate) {
1495     // For register alignment, we want to assume that counters (gpr_index_, fpr_index_) are even iff
1496     // the next register is even; counting down is just to make the compiler happy...
1497     static_assert(kNumNativeGprArgs % 2 == 0U, "Number of native GPR arguments not even");
1498     static_assert(kNumNativeFprArgs % 2 == 0U, "Number of native FPR arguments not even");
1499   }
1500 
~BuildNativeCallFrameStateMachine()1501   virtual ~BuildNativeCallFrameStateMachine() {}
1502 
HavePointerGpr() const1503   bool HavePointerGpr() const {
1504     return gpr_index_ > 0;
1505   }
1506 
AdvancePointer(const void * val)1507   void AdvancePointer(const void* val) {
1508     if (HavePointerGpr()) {
1509       gpr_index_--;
1510       PushGpr(reinterpret_cast<uintptr_t>(val));
1511     } else {
1512       stack_entries_++;  // TODO: have a field for pointer length as multiple of 32b
1513       PushStack(reinterpret_cast<uintptr_t>(val));
1514       gpr_index_ = 0;
1515     }
1516   }
1517 
HaveIntGpr() const1518   bool HaveIntGpr() const {
1519     return gpr_index_ > 0;
1520   }
1521 
AdvanceInt(uint32_t val)1522   void AdvanceInt(uint32_t val) {
1523     if (HaveIntGpr()) {
1524       gpr_index_--;
1525       if (kMultiGPRegistersWidened) {
1526         DCHECK_EQ(sizeof(uintptr_t), sizeof(int64_t));
1527         PushGpr(static_cast<int64_t>(bit_cast<int32_t, uint32_t>(val)));
1528       } else {
1529         PushGpr(val);
1530       }
1531     } else {
1532       stack_entries_++;
1533       if (kMultiGPRegistersWidened) {
1534         DCHECK_EQ(sizeof(uintptr_t), sizeof(int64_t));
1535         PushStack(static_cast<int64_t>(bit_cast<int32_t, uint32_t>(val)));
1536       } else {
1537         PushStack(val);
1538       }
1539       gpr_index_ = 0;
1540     }
1541   }
1542 
HaveLongGpr() const1543   bool HaveLongGpr() const {
1544     return gpr_index_ >= kRegistersNeededForLong + (LongGprNeedsPadding() ? 1 : 0);
1545   }
1546 
LongGprNeedsPadding() const1547   bool LongGprNeedsPadding() const {
1548     return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1549         kAlignLongOnStack &&                  // and when it needs alignment
1550         (gpr_index_ & 1) == 1;                // counter is odd, see constructor
1551   }
1552 
LongStackNeedsPadding() const1553   bool LongStackNeedsPadding() const {
1554     return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1555         kAlignLongOnStack &&                  // and when it needs 8B alignment
1556         (stack_entries_ & 1) == 1;            // counter is odd
1557   }
1558 
AdvanceLong(uint64_t val)1559   void AdvanceLong(uint64_t val) {
1560     if (HaveLongGpr()) {
1561       if (LongGprNeedsPadding()) {
1562         PushGpr(0);
1563         gpr_index_--;
1564       }
1565       if (kRegistersNeededForLong == 1) {
1566         PushGpr(static_cast<uintptr_t>(val));
1567       } else {
1568         PushGpr(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1569         PushGpr(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1570       }
1571       gpr_index_ -= kRegistersNeededForLong;
1572     } else {
1573       if (LongStackNeedsPadding()) {
1574         PushStack(0);
1575         stack_entries_++;
1576       }
1577       if (kRegistersNeededForLong == 1) {
1578         PushStack(static_cast<uintptr_t>(val));
1579         stack_entries_++;
1580       } else {
1581         PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1582         PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1583         stack_entries_ += 2;
1584       }
1585       gpr_index_ = 0;
1586     }
1587   }
1588 
HaveFloatFpr() const1589   bool HaveFloatFpr() const {
1590     return fpr_index_ > 0;
1591   }
1592 
AdvanceFloat(float val)1593   void AdvanceFloat(float val) {
1594     if (kNativeSoftFloatAbi) {
1595       AdvanceInt(bit_cast<uint32_t, float>(val));
1596     } else {
1597       if (HaveFloatFpr()) {
1598         fpr_index_--;
1599         if (kRegistersNeededForDouble == 1) {
1600           if (kMultiFPRegistersWidened) {
1601             PushFpr8(bit_cast<uint64_t, double>(val));
1602           } else {
1603             // No widening, just use the bits.
1604             PushFpr8(static_cast<uint64_t>(bit_cast<uint32_t, float>(val)));
1605           }
1606         } else {
1607           PushFpr4(val);
1608         }
1609       } else {
1610         stack_entries_++;
1611         if (kRegistersNeededForDouble == 1 && kMultiFPRegistersWidened) {
1612           // Need to widen before storing: Note the "double" in the template instantiation.
1613           // Note: We need to jump through those hoops to make the compiler happy.
1614           DCHECK_EQ(sizeof(uintptr_t), sizeof(uint64_t));
1615           PushStack(static_cast<uintptr_t>(bit_cast<uint64_t, double>(val)));
1616         } else {
1617           PushStack(static_cast<uintptr_t>(bit_cast<uint32_t, float>(val)));
1618         }
1619         fpr_index_ = 0;
1620       }
1621     }
1622   }
1623 
HaveDoubleFpr() const1624   bool HaveDoubleFpr() const {
1625     return fpr_index_ >= kRegistersNeededForDouble + (DoubleFprNeedsPadding() ? 1 : 0);
1626   }
1627 
DoubleFprNeedsPadding() const1628   bool DoubleFprNeedsPadding() const {
1629     return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1630         kAlignDoubleOnStack &&                  // and when it needs alignment
1631         (fpr_index_ & 1) == 1;                  // counter is odd, see constructor
1632   }
1633 
DoubleStackNeedsPadding() const1634   bool DoubleStackNeedsPadding() const {
1635     return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1636         kAlignDoubleOnStack &&                  // and when it needs 8B alignment
1637         (stack_entries_ & 1) == 1;              // counter is odd
1638   }
1639 
AdvanceDouble(uint64_t val)1640   void AdvanceDouble(uint64_t val) {
1641     if (kNativeSoftFloatAbi) {
1642       AdvanceLong(val);
1643     } else {
1644       if (HaveDoubleFpr()) {
1645         if (DoubleFprNeedsPadding()) {
1646           PushFpr4(0);
1647           fpr_index_--;
1648         }
1649         PushFpr8(val);
1650         fpr_index_ -= kRegistersNeededForDouble;
1651       } else {
1652         if (DoubleStackNeedsPadding()) {
1653           PushStack(0);
1654           stack_entries_++;
1655         }
1656         if (kRegistersNeededForDouble == 1) {
1657           PushStack(static_cast<uintptr_t>(val));
1658           stack_entries_++;
1659         } else {
1660           PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1661           PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1662           stack_entries_ += 2;
1663         }
1664         fpr_index_ = 0;
1665       }
1666     }
1667   }
1668 
GetStackEntries() const1669   uint32_t GetStackEntries() const {
1670     return stack_entries_;
1671   }
1672 
GetNumberOfUsedGprs() const1673   uint32_t GetNumberOfUsedGprs() const {
1674     return kNumNativeGprArgs - gpr_index_;
1675   }
1676 
GetNumberOfUsedFprs() const1677   uint32_t GetNumberOfUsedFprs() const {
1678     return kNumNativeFprArgs - fpr_index_;
1679   }
1680 
1681  private:
PushGpr(uintptr_t val)1682   void PushGpr(uintptr_t val) {
1683     delegate_->PushGpr(val);
1684   }
PushFpr4(float val)1685   void PushFpr4(float val) {
1686     delegate_->PushFpr4(val);
1687   }
PushFpr8(uint64_t val)1688   void PushFpr8(uint64_t val) {
1689     delegate_->PushFpr8(val);
1690   }
PushStack(uintptr_t val)1691   void PushStack(uintptr_t val) {
1692     delegate_->PushStack(val);
1693   }
1694 
1695   uint32_t gpr_index_;      // Number of free GPRs
1696   uint32_t fpr_index_;      // Number of free FPRs
1697   uint32_t stack_entries_;  // Stack entries are in multiples of 32b, as floats are usually not
1698                             // extended
1699   T* const delegate_;             // What Push implementation gets called
1700 };
1701 
1702 // Computes the sizes of register stacks and call stack area. Handling of references can be extended
1703 // in subclasses.
1704 //
1705 // To handle native pointers, use "L" in the shorty for an object reference, which simulates
1706 // them with handles.
1707 class ComputeNativeCallFrameSize {
1708  public:
ComputeNativeCallFrameSize()1709   ComputeNativeCallFrameSize() : num_stack_entries_(0) {}
1710 
~ComputeNativeCallFrameSize()1711   virtual ~ComputeNativeCallFrameSize() {}
1712 
GetStackSize() const1713   uint32_t GetStackSize() const {
1714     return num_stack_entries_ * sizeof(uintptr_t);
1715   }
1716 
LayoutStackArgs(uint8_t * sp8) const1717   uint8_t* LayoutStackArgs(uint8_t* sp8) const {
1718     sp8 -= GetStackSize();
1719     // Align by kStackAlignment; it is at least as strict as native stack alignment.
1720     sp8 = reinterpret_cast<uint8_t*>(RoundDown(reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1721     return sp8;
1722   }
1723 
WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize> * sm ATTRIBUTE_UNUSED)1724   virtual void WalkHeader(
1725       BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm ATTRIBUTE_UNUSED)
1726       REQUIRES_SHARED(Locks::mutator_lock_) {
1727   }
1728 
Walk(const char * shorty,uint32_t shorty_len)1729   void Walk(const char* shorty, uint32_t shorty_len) REQUIRES_SHARED(Locks::mutator_lock_) {
1730     BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize> sm(this);
1731 
1732     WalkHeader(&sm);
1733 
1734     for (uint32_t i = 1; i < shorty_len; ++i) {
1735       Primitive::Type cur_type_ = Primitive::GetType(shorty[i]);
1736       switch (cur_type_) {
1737         case Primitive::kPrimNot:
1738           sm.AdvancePointer(nullptr);
1739           break;
1740         case Primitive::kPrimBoolean:
1741         case Primitive::kPrimByte:
1742         case Primitive::kPrimChar:
1743         case Primitive::kPrimShort:
1744         case Primitive::kPrimInt:
1745           sm.AdvanceInt(0);
1746           break;
1747         case Primitive::kPrimFloat:
1748           sm.AdvanceFloat(0);
1749           break;
1750         case Primitive::kPrimDouble:
1751           sm.AdvanceDouble(0);
1752           break;
1753         case Primitive::kPrimLong:
1754           sm.AdvanceLong(0);
1755           break;
1756         default:
1757           LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty;
1758           UNREACHABLE();
1759       }
1760     }
1761 
1762     num_stack_entries_ = sm.GetStackEntries();
1763   }
1764 
PushGpr(uintptr_t)1765   void PushGpr(uintptr_t /* val */) {
1766     // not optimizing registers, yet
1767   }
1768 
PushFpr4(float)1769   void PushFpr4(float /* val */) {
1770     // not optimizing registers, yet
1771   }
1772 
PushFpr8(uint64_t)1773   void PushFpr8(uint64_t /* val */) {
1774     // not optimizing registers, yet
1775   }
1776 
PushStack(uintptr_t)1777   void PushStack(uintptr_t /* val */) {
1778     // counting is already done in the superclass
1779   }
1780 
1781  protected:
1782   uint32_t num_stack_entries_;
1783 };
1784 
1785 class ComputeGenericJniFrameSize final : public ComputeNativeCallFrameSize {
1786  public:
ComputeGenericJniFrameSize(bool critical_native)1787   explicit ComputeGenericJniFrameSize(bool critical_native)
1788     : critical_native_(critical_native) {}
1789 
ComputeLayout(ArtMethod ** managed_sp,const char * shorty,uint32_t shorty_len)1790   uintptr_t* ComputeLayout(ArtMethod** managed_sp, const char* shorty, uint32_t shorty_len)
1791       REQUIRES_SHARED(Locks::mutator_lock_) {
1792     DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), kRuntimePointerSize);
1793 
1794     Walk(shorty, shorty_len);
1795 
1796     // Add space for cookie.
1797     DCHECK_ALIGNED(managed_sp, sizeof(uintptr_t));
1798     static_assert(sizeof(uintptr_t) >= sizeof(IRTSegmentState));
1799     uint8_t* sp8 = reinterpret_cast<uint8_t*>(managed_sp) - sizeof(uintptr_t);
1800 
1801     // Layout stack arguments.
1802     sp8 = LayoutStackArgs(sp8);
1803 
1804     // Return the new bottom.
1805     DCHECK_ALIGNED(sp8, sizeof(uintptr_t));
1806     return reinterpret_cast<uintptr_t*>(sp8);
1807   }
1808 
GetStartGprRegs(uintptr_t * reserved_area)1809   static uintptr_t* GetStartGprRegs(uintptr_t* reserved_area) {
1810     return reserved_area;
1811   }
1812 
GetStartFprRegs(uintptr_t * reserved_area)1813   static uint32_t* GetStartFprRegs(uintptr_t* reserved_area) {
1814     constexpr size_t num_gprs =
1815         BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeGprArgs;
1816     return reinterpret_cast<uint32_t*>(GetStartGprRegs(reserved_area) + num_gprs);
1817   }
1818 
GetHiddenArgSlot(uintptr_t * reserved_area)1819   static uintptr_t* GetHiddenArgSlot(uintptr_t* reserved_area) {
1820     // Note: `num_fprs` is 0 on architectures where sizeof(uintptr_t) does not match the
1821     // FP register size (it is actually 0 on all supported 32-bit architectures).
1822     constexpr size_t num_fprs =
1823         BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeFprArgs;
1824     return reinterpret_cast<uintptr_t*>(GetStartFprRegs(reserved_area)) + num_fprs;
1825   }
1826 
GetOutArgsSpSlot(uintptr_t * reserved_area)1827   static uintptr_t* GetOutArgsSpSlot(uintptr_t* reserved_area) {
1828     return GetHiddenArgSlot(reserved_area) + 1;
1829   }
1830 
1831   // Add JNIEnv* and jobj/jclass before the shorty-derived elements.
1832   void WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) override
1833       REQUIRES_SHARED(Locks::mutator_lock_);
1834 
1835  private:
1836   const bool critical_native_;
1837 };
1838 
WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize> * sm)1839 void ComputeGenericJniFrameSize::WalkHeader(
1840     BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) {
1841   // First 2 parameters are always excluded for @CriticalNative.
1842   if (UNLIKELY(critical_native_)) {
1843     return;
1844   }
1845 
1846   // JNIEnv
1847   sm->AdvancePointer(nullptr);
1848 
1849   // Class object or this as first argument
1850   sm->AdvancePointer(nullptr);
1851 }
1852 
1853 // Class to push values to three separate regions. Used to fill the native call part. Adheres to
1854 // the template requirements of BuildGenericJniFrameStateMachine.
1855 class FillNativeCall {
1856  public:
FillNativeCall(uintptr_t * gpr_regs,uint32_t * fpr_regs,uintptr_t * stack_args)1857   FillNativeCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) :
1858       cur_gpr_reg_(gpr_regs), cur_fpr_reg_(fpr_regs), cur_stack_arg_(stack_args) {}
1859 
~FillNativeCall()1860   virtual ~FillNativeCall() {}
1861 
Reset(uintptr_t * gpr_regs,uint32_t * fpr_regs,uintptr_t * stack_args)1862   void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) {
1863     cur_gpr_reg_ = gpr_regs;
1864     cur_fpr_reg_ = fpr_regs;
1865     cur_stack_arg_ = stack_args;
1866   }
1867 
PushGpr(uintptr_t val)1868   void PushGpr(uintptr_t val) {
1869     *cur_gpr_reg_ = val;
1870     cur_gpr_reg_++;
1871   }
1872 
PushFpr4(float val)1873   void PushFpr4(float val) {
1874     *cur_fpr_reg_ = val;
1875     cur_fpr_reg_++;
1876   }
1877 
PushFpr8(uint64_t val)1878   void PushFpr8(uint64_t val) {
1879     uint64_t* tmp = reinterpret_cast<uint64_t*>(cur_fpr_reg_);
1880     *tmp = val;
1881     cur_fpr_reg_ += 2;
1882   }
1883 
PushStack(uintptr_t val)1884   void PushStack(uintptr_t val) {
1885     *cur_stack_arg_ = val;
1886     cur_stack_arg_++;
1887   }
1888 
1889  private:
1890   uintptr_t* cur_gpr_reg_;
1891   uint32_t* cur_fpr_reg_;
1892   uintptr_t* cur_stack_arg_;
1893 };
1894 
1895 // Visits arguments on the stack placing them into a region lower down the stack for the benefit
1896 // of transitioning into native code.
1897 class BuildGenericJniFrameVisitor final : public QuickArgumentVisitor {
1898  public:
BuildGenericJniFrameVisitor(Thread * self,bool is_static,bool critical_native,const char * shorty,uint32_t shorty_len,ArtMethod ** managed_sp,uintptr_t * reserved_area)1899   BuildGenericJniFrameVisitor(Thread* self,
1900                               bool is_static,
1901                               bool critical_native,
1902                               const char* shorty,
1903                               uint32_t shorty_len,
1904                               ArtMethod** managed_sp,
1905                               uintptr_t* reserved_area)
1906      : QuickArgumentVisitor(managed_sp, is_static, shorty, shorty_len),
1907        jni_call_(nullptr, nullptr, nullptr, critical_native),
1908        sm_(&jni_call_),
1909        current_vreg_(nullptr) {
1910     DCHECK_ALIGNED(managed_sp, kStackAlignment);
1911     DCHECK_ALIGNED(reserved_area, sizeof(uintptr_t));
1912 
1913     ComputeGenericJniFrameSize fsc(critical_native);
1914     uintptr_t* out_args_sp = fsc.ComputeLayout(managed_sp, shorty, shorty_len);
1915 
1916     // Store hidden argument for @CriticalNative.
1917     uintptr_t* hidden_arg_slot = fsc.GetHiddenArgSlot(reserved_area);
1918     constexpr uintptr_t kGenericJniTag = 1u;
1919     ArtMethod* method = *managed_sp;
1920     *hidden_arg_slot = critical_native ? (reinterpret_cast<uintptr_t>(method) | kGenericJniTag)
1921                                        : 0xebad6a89u;  // Bad value.
1922 
1923     // Set out args SP.
1924     uintptr_t* out_args_sp_slot = fsc.GetOutArgsSpSlot(reserved_area);
1925     *out_args_sp_slot = reinterpret_cast<uintptr_t>(out_args_sp);
1926 
1927     // Prepare vreg pointer for spilling references.
1928     static constexpr size_t frame_size =
1929         RuntimeCalleeSaveFrame::GetFrameSize(CalleeSaveType::kSaveRefsAndArgs);
1930     current_vreg_ = reinterpret_cast<uint32_t*>(
1931         reinterpret_cast<uint8_t*>(managed_sp) + frame_size + sizeof(ArtMethod*));
1932 
1933     jni_call_.Reset(fsc.GetStartGprRegs(reserved_area),
1934                     fsc.GetStartFprRegs(reserved_area),
1935                     out_args_sp);
1936 
1937     // First 2 parameters are always excluded for CriticalNative methods.
1938     if (LIKELY(!critical_native)) {
1939       // jni environment is always first argument
1940       sm_.AdvancePointer(self->GetJniEnv());
1941 
1942       if (is_static) {
1943         // The `jclass` is a pointer to the method's declaring class.
1944         // The declaring class must be marked.
1945         auto* declaring_class = reinterpret_cast<mirror::CompressedReference<mirror::Class>*>(
1946             method->GetDeclaringClassAddressWithoutBarrier());
1947         if (kUseReadBarrier) {
1948           artJniReadBarrier(method);
1949         }
1950         sm_.AdvancePointer(declaring_class);
1951       }  // else "this" reference is already handled by QuickArgumentVisitor.
1952     }
1953   }
1954 
1955   void Visit() REQUIRES_SHARED(Locks::mutator_lock_) override;
1956 
1957  private:
1958   // A class to fill a JNI call. Adds reference/handle-scope management to FillNativeCall.
1959   class FillJniCall final : public FillNativeCall {
1960    public:
FillJniCall(uintptr_t * gpr_regs,uint32_t * fpr_regs,uintptr_t * stack_args,bool critical_native)1961     FillJniCall(uintptr_t* gpr_regs,
1962                 uint32_t* fpr_regs,
1963                 uintptr_t* stack_args,
1964                 bool critical_native)
1965         : FillNativeCall(gpr_regs, fpr_regs, stack_args),
1966           cur_entry_(0),
1967           critical_native_(critical_native) {}
1968 
Reset(uintptr_t * gpr_regs,uint32_t * fpr_regs,uintptr_t * stack_args)1969     void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) {
1970       FillNativeCall::Reset(gpr_regs, fpr_regs, stack_args);
1971       cur_entry_ = 0U;
1972     }
1973 
CriticalNative() const1974     bool CriticalNative() const {
1975       return critical_native_;
1976     }
1977 
1978    private:
1979     size_t cur_entry_;
1980     const bool critical_native_;
1981   };
1982 
1983   FillJniCall jni_call_;
1984   BuildNativeCallFrameStateMachine<FillJniCall> sm_;
1985 
1986   // Pointer to the current vreg in caller's reserved out vreg area.
1987   // Used for spilling reference arguments.
1988   uint32_t* current_vreg_;
1989 
1990   DISALLOW_COPY_AND_ASSIGN(BuildGenericJniFrameVisitor);
1991 };
1992 
Visit()1993 void BuildGenericJniFrameVisitor::Visit() {
1994   Primitive::Type type = GetParamPrimitiveType();
1995   switch (type) {
1996     case Primitive::kPrimLong: {
1997       jlong long_arg;
1998       if (IsSplitLongOrDouble()) {
1999         long_arg = ReadSplitLongParam();
2000       } else {
2001         long_arg = *reinterpret_cast<jlong*>(GetParamAddress());
2002       }
2003       sm_.AdvanceLong(long_arg);
2004       current_vreg_ += 2u;
2005       break;
2006     }
2007     case Primitive::kPrimDouble: {
2008       uint64_t double_arg;
2009       if (IsSplitLongOrDouble()) {
2010         // Read into union so that we don't case to a double.
2011         double_arg = ReadSplitLongParam();
2012       } else {
2013         double_arg = *reinterpret_cast<uint64_t*>(GetParamAddress());
2014       }
2015       sm_.AdvanceDouble(double_arg);
2016       current_vreg_ += 2u;
2017       break;
2018     }
2019     case Primitive::kPrimNot: {
2020       mirror::Object* obj =
2021           reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress())->AsMirrorPtr();
2022       StackReference<mirror::Object>* spill_ref =
2023           reinterpret_cast<StackReference<mirror::Object>*>(current_vreg_);
2024       spill_ref->Assign(obj);
2025       sm_.AdvancePointer(obj != nullptr ? spill_ref : nullptr);
2026       current_vreg_ += 1u;
2027       break;
2028     }
2029     case Primitive::kPrimFloat:
2030       sm_.AdvanceFloat(*reinterpret_cast<float*>(GetParamAddress()));
2031       current_vreg_ += 1u;
2032       break;
2033     case Primitive::kPrimBoolean:  // Fall-through.
2034     case Primitive::kPrimByte:     // Fall-through.
2035     case Primitive::kPrimChar:     // Fall-through.
2036     case Primitive::kPrimShort:    // Fall-through.
2037     case Primitive::kPrimInt:      // Fall-through.
2038       sm_.AdvanceInt(*reinterpret_cast<jint*>(GetParamAddress()));
2039       current_vreg_ += 1u;
2040       break;
2041     case Primitive::kPrimVoid:
2042       LOG(FATAL) << "UNREACHABLE";
2043       UNREACHABLE();
2044   }
2045 }
2046 
2047 /*
2048  * Initializes the reserved area assumed to be directly below `managed_sp` for a native call:
2049  *
2050  * On entry, the stack has a standard callee-save frame above `managed_sp`,
2051  * and the reserved area below it. Starting below `managed_sp`, we reserve space
2052  * for local reference cookie (not present for @CriticalNative), HandleScope
2053  * (not present for @CriticalNative) and stack args (if args do not fit into
2054  * registers). At the bottom of the reserved area, there is space for register
2055  * arguments, hidden arg (for @CriticalNative) and the SP for the native call
2056  * (i.e. pointer to the stack args area), which the calling stub shall load
2057  * to perform the native call. We fill all these fields, perform class init
2058  * check (for static methods) and/or locking (for synchronized methods) if
2059  * needed and return to the stub.
2060  *
2061  * The return value is the pointer to the native code, null on failure.
2062  *
2063  * NO_THREAD_SAFETY_ANALYSIS: Depending on the use case, the trampoline may
2064  * or may not lock a synchronization object and transition out of Runnable.
2065  */
artQuickGenericJniTrampoline(Thread * self,ArtMethod ** managed_sp,uintptr_t * reserved_area)2066 extern "C" const void* artQuickGenericJniTrampoline(Thread* self,
2067                                                     ArtMethod** managed_sp,
2068                                                     uintptr_t* reserved_area)
2069     REQUIRES_SHARED(Locks::mutator_lock_) NO_THREAD_SAFETY_ANALYSIS {
2070   // Note: We cannot walk the stack properly until fixed up below.
2071   ArtMethod* called = *managed_sp;
2072   DCHECK(called->IsNative()) << called->PrettyMethod(true);
2073   Runtime* runtime = Runtime::Current();
2074   uint32_t shorty_len = 0;
2075   const char* shorty = called->GetShorty(&shorty_len);
2076   bool critical_native = called->IsCriticalNative();
2077   bool fast_native = called->IsFastNative();
2078   bool normal_native = !critical_native && !fast_native;
2079 
2080   // Run the visitor and update sp.
2081   BuildGenericJniFrameVisitor visitor(self,
2082                                       called->IsStatic(),
2083                                       critical_native,
2084                                       shorty,
2085                                       shorty_len,
2086                                       managed_sp,
2087                                       reserved_area);
2088   {
2089     ScopedAssertNoThreadSuspension sants(__FUNCTION__);
2090     visitor.VisitArguments();
2091   }
2092 
2093   // Fix up managed-stack things in Thread. After this we can walk the stack.
2094   self->SetTopOfStackTagged(managed_sp);
2095 
2096   self->VerifyStack();
2097 
2098   // We can now walk the stack if needed by JIT GC from MethodEntered() for JIT-on-first-use.
2099   jit::Jit* jit = runtime->GetJit();
2100   if (jit != nullptr) {
2101     jit->MethodEntered(self, called);
2102   }
2103 
2104   // We can set the entrypoint of a native method to generic JNI even when the
2105   // class hasn't been initialized, so we need to do the initialization check
2106   // before invoking the native code.
2107   if (NeedsClinitCheckBeforeCall(called)) {
2108     ObjPtr<mirror::Class> declaring_class = called->GetDeclaringClass();
2109     if (UNLIKELY(!declaring_class->IsVisiblyInitialized())) {
2110       // Ensure static method's class is initialized.
2111       StackHandleScope<1> hs(self);
2112       Handle<mirror::Class> h_class(hs.NewHandle(declaring_class));
2113       if (!runtime->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
2114         DCHECK(Thread::Current()->IsExceptionPending()) << called->PrettyMethod();
2115         return nullptr;  // Report error.
2116       }
2117     }
2118   }
2119 
2120   // Skip calling `artJniMethodStart()` for @CriticalNative and @FastNative.
2121   if (LIKELY(normal_native)) {
2122     // Start JNI.
2123     if (called->IsSynchronized()) {
2124       ObjPtr<mirror::Object> lock = GetGenericJniSynchronizationObject(self, called);
2125       DCHECK(lock != nullptr);
2126       lock->MonitorEnter(self);
2127       if (self->IsExceptionPending()) {
2128         return nullptr;  // Report error.
2129       }
2130     }
2131     if (UNLIKELY(self->ReadFlag(ThreadFlag::kMonitorJniEntryExit))) {
2132       artJniMonitoredMethodStart(self);
2133     } else {
2134       artJniMethodStart(self);
2135     }
2136   } else {
2137     DCHECK(!called->IsSynchronized())
2138         << "@FastNative/@CriticalNative and synchronize is not supported";
2139   }
2140 
2141   // Skip pushing IRT frame for @CriticalNative.
2142   if (LIKELY(!critical_native)) {
2143     // Push local reference frame.
2144     JNIEnvExt* env = self->GetJniEnv();
2145     DCHECK(env != nullptr);
2146     uint32_t cookie = bit_cast<uint32_t>(env->GetLocalRefCookie());
2147     env->SetLocalRefCookie(env->GetLocalsSegmentState());
2148 
2149     // Save the cookie on the stack.
2150     uint32_t* sp32 = reinterpret_cast<uint32_t*>(managed_sp);
2151     *(sp32 - 1) = cookie;
2152   }
2153 
2154   // Retrieve the stored native code.
2155   // Note that it may point to the lookup stub or trampoline.
2156   // FIXME: This is broken for @CriticalNative as the art_jni_dlsym_lookup_stub
2157   // does not handle that case. Calls from compiled stubs are also broken.
2158   void const* nativeCode = called->GetEntryPointFromJni();
2159 
2160   VLOG(third_party_jni) << "GenericJNI: "
2161                         << called->PrettyMethod()
2162                         << " -> "
2163                         << std::hex << reinterpret_cast<uintptr_t>(nativeCode);
2164 
2165   // Return native code.
2166   return nativeCode;
2167 }
2168 
2169 // Defined in quick_jni_entrypoints.cc.
2170 extern uint64_t GenericJniMethodEnd(Thread* self,
2171                                     uint32_t saved_local_ref_cookie,
2172                                     jvalue result,
2173                                     uint64_t result_f,
2174                                     ArtMethod* called);
2175 
2176 /*
2177  * Is called after the native JNI code. Responsible for cleanup (handle scope, saved state) and
2178  * unlocking.
2179  */
artQuickGenericJniEndTrampoline(Thread * self,jvalue result,uint64_t result_f)2180 extern "C" uint64_t artQuickGenericJniEndTrampoline(Thread* self,
2181                                                     jvalue result,
2182                                                     uint64_t result_f) {
2183   // We're here just back from a native call. We don't have the shared mutator lock at this point
2184   // yet until we call GoToRunnable() later in GenericJniMethodEnd(). Accessing objects or doing
2185   // anything that requires a mutator lock before that would cause problems as GC may have the
2186   // exclusive mutator lock and may be moving objects, etc.
2187   ArtMethod** sp = self->GetManagedStack()->GetTopQuickFrame();
2188   DCHECK(self->GetManagedStack()->GetTopQuickFrameTag());
2189   uint32_t* sp32 = reinterpret_cast<uint32_t*>(sp);
2190   ArtMethod* called = *sp;
2191   uint32_t cookie = *(sp32 - 1);
2192   return GenericJniMethodEnd(self, cookie, result, result_f, called);
2193 }
2194 
2195 // Fast path method resolution that can't throw exceptions.
2196 template <InvokeType type>
FindMethodFast(uint32_t method_idx,ObjPtr<mirror::Object> this_object,ArtMethod * referrer)2197 inline ArtMethod* FindMethodFast(uint32_t method_idx,
2198                                  ObjPtr<mirror::Object> this_object,
2199                                  ArtMethod* referrer)
2200     REQUIRES_SHARED(Locks::mutator_lock_)
2201     REQUIRES(!Roles::uninterruptible_) {
2202   ScopedAssertNoThreadSuspension ants(__FUNCTION__);
2203   if (UNLIKELY(this_object == nullptr && type != kStatic)) {
2204     return nullptr;
2205   }
2206   ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
2207   ObjPtr<mirror::DexCache> dex_cache = referrer->GetDexCache();
2208   constexpr ClassLinker::ResolveMode resolve_mode = ClassLinker::ResolveMode::kCheckICCEAndIAE;
2209   ClassLinker* linker = Runtime::Current()->GetClassLinker();
2210   ArtMethod* resolved_method = linker->GetResolvedMethod<type, resolve_mode>(method_idx, referrer);
2211   if (UNLIKELY(resolved_method == nullptr)) {
2212     return nullptr;
2213   }
2214   if (type == kInterface) {  // Most common form of slow path dispatch.
2215     return this_object->GetClass()->FindVirtualMethodForInterface(resolved_method,
2216                                                                   kRuntimePointerSize);
2217   }
2218   if (type == kStatic || type == kDirect) {
2219     return resolved_method;
2220   }
2221 
2222   if (type == kSuper) {
2223     // TODO This lookup is rather slow.
2224     dex::TypeIndex method_type_idx = dex_cache->GetDexFile()->GetMethodId(method_idx).class_idx_;
2225     ObjPtr<mirror::Class> method_reference_class = linker->LookupResolvedType(
2226         method_type_idx, dex_cache, referrer->GetClassLoader());
2227     if (method_reference_class == nullptr) {
2228       // Need to do full type resolution...
2229       return nullptr;
2230     }
2231 
2232     // If the referring class is in the class hierarchy of the
2233     // referenced class in the bytecode, we use its super class. Otherwise, we cannot
2234     // resolve the method.
2235     if (!method_reference_class->IsAssignableFrom(referring_class)) {
2236       return nullptr;
2237     }
2238 
2239     if (method_reference_class->IsInterface()) {
2240       return method_reference_class->FindVirtualMethodForInterfaceSuper(
2241           resolved_method, kRuntimePointerSize);
2242     }
2243 
2244     ObjPtr<mirror::Class> super_class = referring_class->GetSuperClass();
2245     if (resolved_method->GetMethodIndex() >= super_class->GetVTableLength()) {
2246       // The super class does not have the method.
2247       return nullptr;
2248     }
2249     return super_class->GetVTableEntry(resolved_method->GetMethodIndex(), kRuntimePointerSize);
2250   }
2251 
2252   DCHECK(type == kVirtual);
2253   return this_object->GetClass()->GetVTableEntry(
2254       resolved_method->GetMethodIndex(), kRuntimePointerSize);
2255 }
2256 
2257 // We use TwoWordReturn to optimize scalar returns. We use the hi value for code, and the lo value
2258 // for the method pointer.
2259 //
2260 // It is valid to use this, as at the usage points here (returns from C functions) we are assuming
2261 // to hold the mutator lock (see REQUIRES_SHARED(Locks::mutator_lock_) annotations).
2262 
2263 template <InvokeType type>
artInvokeCommon(uint32_t method_idx,ObjPtr<mirror::Object> this_object,Thread * self,ArtMethod ** sp)2264 static TwoWordReturn artInvokeCommon(uint32_t method_idx,
2265                                      ObjPtr<mirror::Object> this_object,
2266                                      Thread* self,
2267                                      ArtMethod** sp) {
2268   ScopedQuickEntrypointChecks sqec(self);
2269   DCHECK_EQ(*sp, Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
2270   ArtMethod* caller_method = QuickArgumentVisitor::GetCallingMethod(sp);
2271   ArtMethod* method = FindMethodFast<type>(method_idx, this_object, caller_method);
2272   if (UNLIKELY(method == nullptr)) {
2273     const DexFile* dex_file = caller_method->GetDexFile();
2274     uint32_t shorty_len;
2275     const char* shorty = dex_file->GetMethodShorty(dex_file->GetMethodId(method_idx), &shorty_len);
2276     {
2277       // Remember the args in case a GC happens in FindMethodFromCode.
2278       ScopedObjectAccessUnchecked soa(self->GetJniEnv());
2279       RememberForGcArgumentVisitor visitor(sp, type == kStatic, shorty, shorty_len, &soa);
2280       visitor.VisitArguments();
2281       method = FindMethodFromCode<type, /*access_check=*/true>(
2282           method_idx, &this_object, caller_method, self);
2283       visitor.FixupReferences();
2284     }
2285 
2286     if (UNLIKELY(method == nullptr)) {
2287       CHECK(self->IsExceptionPending());
2288       return GetTwoWordFailureValue();  // Failure.
2289     }
2290   }
2291   DCHECK(!self->IsExceptionPending());
2292   const void* code = method->GetEntryPointFromQuickCompiledCode();
2293 
2294   // When we return, the caller will branch to this address, so it had better not be 0!
2295   DCHECK(code != nullptr) << "Code was null in method: " << method->PrettyMethod()
2296                           << " location: "
2297                           << method->GetDexFile()->GetLocation();
2298 
2299   return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(code),
2300                                 reinterpret_cast<uintptr_t>(method));
2301 }
2302 
2303 // Explicit artInvokeCommon template function declarations to please analysis tool.
2304 #define EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(type)                                            \
2305   template REQUIRES_SHARED(Locks::mutator_lock_)                                              \
2306   TwoWordReturn artInvokeCommon<type>(                                                        \
2307       uint32_t method_idx, ObjPtr<mirror::Object> his_object, Thread* self, ArtMethod** sp)
2308 
2309 EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kVirtual);
2310 EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kInterface);
2311 EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kDirect);
2312 EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kStatic);
2313 EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kSuper);
2314 #undef EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL
2315 
2316 // See comments in runtime_support_asm.S
artInvokeInterfaceTrampolineWithAccessCheck(uint32_t method_idx,mirror::Object * this_object,Thread * self,ArtMethod ** sp)2317 extern "C" TwoWordReturn artInvokeInterfaceTrampolineWithAccessCheck(
2318     uint32_t method_idx, mirror::Object* this_object, Thread* self, ArtMethod** sp)
2319     REQUIRES_SHARED(Locks::mutator_lock_) {
2320   return artInvokeCommon<kInterface>(method_idx, this_object, self, sp);
2321 }
2322 
artInvokeDirectTrampolineWithAccessCheck(uint32_t method_idx,mirror::Object * this_object,Thread * self,ArtMethod ** sp)2323 extern "C" TwoWordReturn artInvokeDirectTrampolineWithAccessCheck(
2324     uint32_t method_idx, mirror::Object* this_object, Thread* self, ArtMethod** sp)
2325     REQUIRES_SHARED(Locks::mutator_lock_) {
2326   return artInvokeCommon<kDirect>(method_idx, this_object, self, sp);
2327 }
2328 
artInvokeStaticTrampolineWithAccessCheck(uint32_t method_idx,mirror::Object * this_object ATTRIBUTE_UNUSED,Thread * self,ArtMethod ** sp)2329 extern "C" TwoWordReturn artInvokeStaticTrampolineWithAccessCheck(
2330     uint32_t method_idx,
2331     mirror::Object* this_object ATTRIBUTE_UNUSED,
2332     Thread* self,
2333     ArtMethod** sp) REQUIRES_SHARED(Locks::mutator_lock_) {
2334   // For static, this_object is not required and may be random garbage. Don't pass it down so that
2335   // it doesn't cause ObjPtr alignment failure check.
2336   return artInvokeCommon<kStatic>(method_idx, nullptr, self, sp);
2337 }
2338 
artInvokeSuperTrampolineWithAccessCheck(uint32_t method_idx,mirror::Object * this_object,Thread * self,ArtMethod ** sp)2339 extern "C" TwoWordReturn artInvokeSuperTrampolineWithAccessCheck(
2340     uint32_t method_idx, mirror::Object* this_object, Thread* self, ArtMethod** sp)
2341     REQUIRES_SHARED(Locks::mutator_lock_) {
2342   return artInvokeCommon<kSuper>(method_idx, this_object, self, sp);
2343 }
2344 
artInvokeVirtualTrampolineWithAccessCheck(uint32_t method_idx,mirror::Object * this_object,Thread * self,ArtMethod ** sp)2345 extern "C" TwoWordReturn artInvokeVirtualTrampolineWithAccessCheck(
2346     uint32_t method_idx, mirror::Object* this_object, Thread* self, ArtMethod** sp)
2347     REQUIRES_SHARED(Locks::mutator_lock_) {
2348   return artInvokeCommon<kVirtual>(method_idx, this_object, self, sp);
2349 }
2350 
2351 // Determine target of interface dispatch. The interface method and this object are known non-null.
2352 // The interface method is the method returned by the dex cache in the conflict trampoline.
artInvokeInterfaceTrampoline(ArtMethod * interface_method,mirror::Object * raw_this_object,Thread * self,ArtMethod ** sp)2353 extern "C" TwoWordReturn artInvokeInterfaceTrampoline(ArtMethod* interface_method,
2354                                                       mirror::Object* raw_this_object,
2355                                                       Thread* self,
2356                                                       ArtMethod** sp)
2357     REQUIRES_SHARED(Locks::mutator_lock_) {
2358   ScopedQuickEntrypointChecks sqec(self);
2359 
2360   Runtime* runtime = Runtime::Current();
2361   bool resolve_method = ((interface_method == nullptr) || interface_method->IsRuntimeMethod());
2362   if (UNLIKELY(resolve_method)) {
2363     // The interface method is unresolved, so resolve it in the dex file of the caller.
2364     // Fetch the dex_method_idx of the target interface method from the caller.
2365     StackHandleScope<1> hs(self);
2366     Handle<mirror::Object> this_object = hs.NewHandle(raw_this_object);
2367     ArtMethod* caller_method = QuickArgumentVisitor::GetCallingMethod(sp);
2368     uint32_t dex_method_idx;
2369     uint32_t dex_pc = QuickArgumentVisitor::GetCallingDexPc(sp);
2370     const Instruction& instr = caller_method->DexInstructions().InstructionAt(dex_pc);
2371     Instruction::Code instr_code = instr.Opcode();
2372     DCHECK(instr_code == Instruction::INVOKE_INTERFACE ||
2373            instr_code == Instruction::INVOKE_INTERFACE_RANGE)
2374         << "Unexpected call into interface trampoline: " << instr.DumpString(nullptr);
2375     if (instr_code == Instruction::INVOKE_INTERFACE) {
2376       dex_method_idx = instr.VRegB_35c();
2377     } else {
2378       DCHECK_EQ(instr_code, Instruction::INVOKE_INTERFACE_RANGE);
2379       dex_method_idx = instr.VRegB_3rc();
2380     }
2381 
2382     const DexFile& dex_file = *caller_method->GetDexFile();
2383     uint32_t shorty_len;
2384     const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(dex_method_idx),
2385                                                   &shorty_len);
2386     {
2387       // Remember the args in case a GC happens in ClassLinker::ResolveMethod().
2388       ScopedObjectAccessUnchecked soa(self->GetJniEnv());
2389       RememberForGcArgumentVisitor visitor(sp, false, shorty, shorty_len, &soa);
2390       visitor.VisitArguments();
2391       ClassLinker* class_linker = runtime->GetClassLinker();
2392       interface_method = class_linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
2393           self, dex_method_idx, caller_method, kInterface);
2394       visitor.FixupReferences();
2395     }
2396 
2397     if (UNLIKELY(interface_method == nullptr)) {
2398       CHECK(self->IsExceptionPending());
2399       return GetTwoWordFailureValue();  // Failure.
2400     }
2401     ArtMethod* outer_method = QuickArgumentVisitor::GetOuterMethod(sp);
2402     MaybeUpdateBssMethodEntry(
2403         interface_method, MethodReference(&dex_file, dex_method_idx), outer_method);
2404 
2405     // Refresh `raw_this_object` which may have changed after resolution.
2406     raw_this_object = this_object.Get();
2407   }
2408 
2409   // The compiler and interpreter make sure the conflict trampoline is never
2410   // called on a method that resolves to j.l.Object.
2411   DCHECK(!interface_method->GetDeclaringClass()->IsObjectClass());
2412   DCHECK(interface_method->GetDeclaringClass()->IsInterface());
2413   DCHECK(!interface_method->IsRuntimeMethod());
2414   DCHECK(!interface_method->IsCopied());
2415 
2416   ObjPtr<mirror::Object> obj_this = raw_this_object;
2417   ObjPtr<mirror::Class> cls = obj_this->GetClass();
2418   uint32_t imt_index = interface_method->GetImtIndex();
2419   ImTable* imt = cls->GetImt(kRuntimePointerSize);
2420   ArtMethod* conflict_method = imt->Get(imt_index, kRuntimePointerSize);
2421   DCHECK(conflict_method->IsRuntimeMethod());
2422 
2423   if (UNLIKELY(resolve_method)) {
2424     // Now that we know the interface method, look it up in the conflict table.
2425     ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
2426     DCHECK(current_table != nullptr);
2427     ArtMethod* method = current_table->Lookup(interface_method, kRuntimePointerSize);
2428     if (method != nullptr) {
2429       return GetTwoWordSuccessValue(
2430           reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCode()),
2431           reinterpret_cast<uintptr_t>(method));
2432     }
2433     // Interface method is not in the conflict table. Continue looking up in the
2434     // iftable.
2435   }
2436 
2437   ArtMethod* method = cls->FindVirtualMethodForInterface(interface_method, kRuntimePointerSize);
2438   if (UNLIKELY(method == nullptr)) {
2439     ArtMethod* caller_method = QuickArgumentVisitor::GetCallingMethod(sp);
2440     ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(
2441         interface_method, obj_this.Ptr(), caller_method);
2442     return GetTwoWordFailureValue();
2443   }
2444 
2445   // We arrive here if we have found an implementation, and it is not in the ImtConflictTable.
2446   // We create a new table with the new pair { interface_method, method }.
2447 
2448   // Classes in the boot image should never need to update conflict methods in
2449   // their IMT.
2450   CHECK(!runtime->GetHeap()->ObjectIsInBootImageSpace(cls.Ptr())) << cls->PrettyClass();
2451   ArtMethod* new_conflict_method = runtime->GetClassLinker()->AddMethodToConflictTable(
2452       cls.Ptr(),
2453       conflict_method,
2454       interface_method,
2455       method);
2456   if (new_conflict_method != conflict_method) {
2457     // Update the IMT if we create a new conflict method. No fence needed here, as the
2458     // data is consistent.
2459     imt->Set(imt_index,
2460              new_conflict_method,
2461              kRuntimePointerSize);
2462   }
2463 
2464   const void* code = method->GetEntryPointFromQuickCompiledCode();
2465 
2466   // When we return, the caller will branch to this address, so it had better not be 0!
2467   DCHECK(code != nullptr) << "Code was null in method: " << method->PrettyMethod()
2468                           << " location: " << method->GetDexFile()->GetLocation();
2469 
2470   return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(code),
2471                                 reinterpret_cast<uintptr_t>(method));
2472 }
2473 
2474 // Returns uint64_t representing raw bits from JValue.
artInvokePolymorphic(mirror::Object * raw_receiver,Thread * self,ArtMethod ** sp)2475 extern "C" uint64_t artInvokePolymorphic(mirror::Object* raw_receiver, Thread* self, ArtMethod** sp)
2476     REQUIRES_SHARED(Locks::mutator_lock_) {
2477   ScopedQuickEntrypointChecks sqec(self);
2478   DCHECK(raw_receiver != nullptr);
2479   DCHECK_EQ(*sp, Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
2480 
2481   // Start new JNI local reference state
2482   JNIEnvExt* env = self->GetJniEnv();
2483   ScopedObjectAccessUnchecked soa(env);
2484   ScopedJniEnvLocalRefState env_state(env);
2485   const char* old_cause = self->StartAssertNoThreadSuspension("Making stack arguments safe.");
2486 
2487   // From the instruction, get the |callsite_shorty| and expose arguments on the stack to the GC.
2488   ArtMethod* caller_method = QuickArgumentVisitor::GetCallingMethod(sp);
2489   uint32_t dex_pc = QuickArgumentVisitor::GetCallingDexPc(sp);
2490   const Instruction& inst = caller_method->DexInstructions().InstructionAt(dex_pc);
2491   DCHECK(inst.Opcode() == Instruction::INVOKE_POLYMORPHIC ||
2492          inst.Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE);
2493   const dex::ProtoIndex proto_idx(inst.VRegH());
2494   const char* shorty = caller_method->GetDexFile()->GetShorty(proto_idx);
2495   const size_t shorty_length = strlen(shorty);
2496   static const bool kMethodIsStatic = false;  // invoke() and invokeExact() are not static.
2497   RememberForGcArgumentVisitor gc_visitor(sp, kMethodIsStatic, shorty, shorty_length, &soa);
2498   gc_visitor.VisitArguments();
2499 
2500   // Wrap raw_receiver in a Handle for safety.
2501   StackHandleScope<3> hs(self);
2502   Handle<mirror::Object> receiver_handle(hs.NewHandle(raw_receiver));
2503   raw_receiver = nullptr;
2504   self->EndAssertNoThreadSuspension(old_cause);
2505 
2506   // Resolve method.
2507   ClassLinker* linker = Runtime::Current()->GetClassLinker();
2508   ArtMethod* resolved_method = linker->ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
2509       self, inst.VRegB(), caller_method, kVirtual);
2510 
2511   Handle<mirror::MethodType> method_type(
2512       hs.NewHandle(linker->ResolveMethodType(self, proto_idx, caller_method)));
2513   if (UNLIKELY(method_type.IsNull())) {
2514     // This implies we couldn't resolve one or more types in this method handle.
2515     CHECK(self->IsExceptionPending());
2516     return 0UL;
2517   }
2518 
2519   DCHECK_EQ(ArtMethod::NumArgRegisters(shorty) + 1u, (uint32_t)inst.VRegA());
2520   DCHECK_EQ(resolved_method->IsStatic(), kMethodIsStatic);
2521 
2522   // Fix references before constructing the shadow frame.
2523   gc_visitor.FixupReferences();
2524 
2525   // Construct shadow frame placing arguments consecutively from |first_arg|.
2526   const bool is_range = (inst.Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE);
2527   const size_t num_vregs = is_range ? inst.VRegA_4rcc() : inst.VRegA_45cc();
2528   const size_t first_arg = 0;
2529   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
2530       CREATE_SHADOW_FRAME(num_vregs, /* link= */ nullptr, resolved_method, dex_pc);
2531   ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
2532   ScopedStackedShadowFramePusher
2533       frame_pusher(self, shadow_frame, StackedShadowFrameType::kShadowFrameUnderConstruction);
2534   BuildQuickShadowFrameVisitor shadow_frame_builder(sp,
2535                                                     kMethodIsStatic,
2536                                                     shorty,
2537                                                     strlen(shorty),
2538                                                     shadow_frame,
2539                                                     first_arg);
2540   shadow_frame_builder.VisitArguments();
2541 
2542   // Push a transition back into managed code onto the linked list in thread.
2543   ManagedStack fragment;
2544   self->PushManagedStackFragment(&fragment);
2545 
2546   // Call DoInvokePolymorphic with |is_range| = true, as shadow frame has argument registers in
2547   // consecutive order.
2548   RangeInstructionOperands operands(first_arg + 1, num_vregs - 1);
2549   Intrinsics intrinsic = static_cast<Intrinsics>(resolved_method->GetIntrinsic());
2550   JValue result;
2551   bool success = false;
2552   if (resolved_method->GetDeclaringClass() == GetClassRoot<mirror::MethodHandle>(linker)) {
2553     Handle<mirror::MethodHandle> method_handle(hs.NewHandle(
2554         ObjPtr<mirror::MethodHandle>::DownCast(receiver_handle.Get())));
2555     if (intrinsic == Intrinsics::kMethodHandleInvokeExact) {
2556       success = MethodHandleInvokeExact(self,
2557                                         *shadow_frame,
2558                                         method_handle,
2559                                         method_type,
2560                                         &operands,
2561                                         &result);
2562     } else {
2563       DCHECK_EQ(static_cast<uint32_t>(intrinsic),
2564                 static_cast<uint32_t>(Intrinsics::kMethodHandleInvoke));
2565       success = MethodHandleInvoke(self,
2566                                    *shadow_frame,
2567                                    method_handle,
2568                                    method_type,
2569                                    &operands,
2570                                    &result);
2571     }
2572   } else {
2573     DCHECK_EQ(GetClassRoot<mirror::VarHandle>(linker), resolved_method->GetDeclaringClass());
2574     Handle<mirror::VarHandle> var_handle(hs.NewHandle(
2575         ObjPtr<mirror::VarHandle>::DownCast(receiver_handle.Get())));
2576     mirror::VarHandle::AccessMode access_mode =
2577         mirror::VarHandle::GetAccessModeByIntrinsic(intrinsic);
2578     success = VarHandleInvokeAccessor(self,
2579                                       *shadow_frame,
2580                                       var_handle,
2581                                       method_type,
2582                                       access_mode,
2583                                       &operands,
2584                                       &result);
2585   }
2586 
2587   DCHECK(success || self->IsExceptionPending());
2588 
2589   // Pop transition record.
2590   self->PopManagedStackFragment(fragment);
2591 
2592   return result.GetJ();
2593 }
2594 
2595 // Returns uint64_t representing raw bits from JValue.
artInvokeCustom(uint32_t call_site_idx,Thread * self,ArtMethod ** sp)2596 extern "C" uint64_t artInvokeCustom(uint32_t call_site_idx, Thread* self, ArtMethod** sp)
2597     REQUIRES_SHARED(Locks::mutator_lock_) {
2598   ScopedQuickEntrypointChecks sqec(self);
2599   DCHECK_EQ(*sp, Runtime::Current()->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs));
2600 
2601   // invoke-custom is effectively a static call (no receiver).
2602   static constexpr bool kMethodIsStatic = true;
2603 
2604   // Start new JNI local reference state
2605   JNIEnvExt* env = self->GetJniEnv();
2606   ScopedObjectAccessUnchecked soa(env);
2607   ScopedJniEnvLocalRefState env_state(env);
2608 
2609   const char* old_cause = self->StartAssertNoThreadSuspension("Making stack arguments safe.");
2610 
2611   // From the instruction, get the |callsite_shorty| and expose arguments on the stack to the GC.
2612   ArtMethod* caller_method = QuickArgumentVisitor::GetCallingMethod(sp);
2613   uint32_t dex_pc = QuickArgumentVisitor::GetCallingDexPc(sp);
2614   const DexFile* dex_file = caller_method->GetDexFile();
2615   const dex::ProtoIndex proto_idx(dex_file->GetProtoIndexForCallSite(call_site_idx));
2616   const char* shorty = caller_method->GetDexFile()->GetShorty(proto_idx);
2617   const uint32_t shorty_len = strlen(shorty);
2618 
2619   // Construct the shadow frame placing arguments consecutively from |first_arg|.
2620   const size_t first_arg = 0;
2621   const size_t num_vregs = ArtMethod::NumArgRegisters(shorty);
2622   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
2623       CREATE_SHADOW_FRAME(num_vregs, /* link= */ nullptr, caller_method, dex_pc);
2624   ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
2625   ScopedStackedShadowFramePusher
2626       frame_pusher(self, shadow_frame, StackedShadowFrameType::kShadowFrameUnderConstruction);
2627   BuildQuickShadowFrameVisitor shadow_frame_builder(sp,
2628                                                     kMethodIsStatic,
2629                                                     shorty,
2630                                                     shorty_len,
2631                                                     shadow_frame,
2632                                                     first_arg);
2633   shadow_frame_builder.VisitArguments();
2634 
2635   // Push a transition back into managed code onto the linked list in thread.
2636   ManagedStack fragment;
2637   self->PushManagedStackFragment(&fragment);
2638   self->EndAssertNoThreadSuspension(old_cause);
2639 
2640   // Perform the invoke-custom operation.
2641   RangeInstructionOperands operands(first_arg, num_vregs);
2642   JValue result;
2643   bool success =
2644       interpreter::DoInvokeCustom(self, *shadow_frame, call_site_idx, &operands, &result);
2645   DCHECK(success || self->IsExceptionPending());
2646 
2647   // Pop transition record.
2648   self->PopManagedStackFragment(fragment);
2649 
2650   return result.GetJ();
2651 }
2652 
artMethodEntryHook(ArtMethod * method,Thread * self,ArtMethod ** sp ATTRIBUTE_UNUSED)2653 extern "C" void artMethodEntryHook(ArtMethod* method, Thread* self, ArtMethod** sp ATTRIBUTE_UNUSED)
2654     REQUIRES_SHARED(Locks::mutator_lock_) {
2655   instrumentation::Instrumentation* instr = Runtime::Current()->GetInstrumentation();
2656   instr->MethodEnterEvent(self, method);
2657   if (instr->IsDeoptimized(method)) {
2658     // Instrumentation can request deoptimizing only a particular method (for
2659     // ex: when there are break points on the method). In such cases deoptimize
2660     // only this method. FullFrame deoptimizations are handled on method exits.
2661     artDeoptimizeFromCompiledCode(DeoptimizationKind::kDebugging, self);
2662   }
2663 }
2664 
artMethodExitHook(Thread * self,ArtMethod * method,uint64_t * gpr_result,uint64_t * fpr_result)2665 extern "C" int artMethodExitHook(Thread* self,
2666                                  ArtMethod* method,
2667                                  uint64_t* gpr_result,
2668                                  uint64_t* fpr_result)
2669     REQUIRES_SHARED(Locks::mutator_lock_) {
2670   DCHECK_EQ(reinterpret_cast<uintptr_t>(self), reinterpret_cast<uintptr_t>(Thread::Current()));
2671   CHECK(gpr_result != nullptr);
2672   CHECK(fpr_result != nullptr);
2673   // Instrumentation exit stub must not be entered with a pending exception.
2674   CHECK(!self->IsExceptionPending())
2675       << "Enter instrumentation exit stub with pending exception " << self->GetException()->Dump();
2676 
2677   instrumentation::Instrumentation* instr = Runtime::Current()->GetInstrumentation();
2678   DCHECK(instr->AreExitStubsInstalled());
2679   bool is_ref;
2680   JValue return_value = instr->GetReturnValue(self, method, &is_ref, gpr_result, fpr_result);
2681   bool deoptimize = false;
2682   {
2683     StackHandleScope<1> hs(self);
2684     MutableHandle<mirror::Object> res(hs.NewHandle<mirror::Object>(nullptr));
2685     if (is_ref) {
2686       // Take a handle to the return value so we won't lose it if we suspend.
2687       res.Assign(return_value.GetL());
2688     }
2689     DCHECK(!method->IsRuntimeMethod());
2690 
2691     // Deoptimize if the caller needs to continue execution in the interpreter. Do nothing if we get
2692     // back to an upcall.
2693     NthCallerVisitor visitor(self, 1, /*include_runtime_and_upcalls=*/false);
2694     visitor.WalkStack(true);
2695     deoptimize = instr->ShouldDeoptimizeMethod(self, visitor);
2696 
2697     // If we need a deoptimization MethodExitEvent will be called by the interpreter when it
2698     // re-executes the return instruction.
2699     if (!deoptimize) {
2700       instr->MethodExitEvent(self,
2701                              method,
2702                              /* frame= */ {},
2703                              return_value);
2704     }
2705 
2706     if (is_ref) {
2707       // Restore the return value if it's a reference since it might have moved.
2708       *reinterpret_cast<mirror::Object**>(gpr_result) = res.Get();
2709       return_value.SetL(res.Get());
2710     }
2711   }
2712 
2713   if (self->IsExceptionPending() || self->ObserveAsyncException()) {
2714     return 1;
2715   }
2716 
2717   if (deoptimize) {
2718     DeoptimizationMethodType deopt_method_type = instr->GetDeoptimizationMethodType(method);
2719     self->PushDeoptimizationContext(return_value, is_ref, nullptr, false, deopt_method_type);
2720     artDeoptimize(self);
2721     UNREACHABLE();
2722   }
2723 
2724   return 0;
2725 }
2726 
2727 }  // namespace art
2728