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