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