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