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