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 #ifndef ART_RUNTIME_INTERPRETER_INTERPRETER_COMMON_H_
18 #define ART_RUNTIME_INTERPRETER_INTERPRETER_COMMON_H_
19
20 #include "interpreter.h"
21 #include "interpreter_intrinsics.h"
22
23 #include <math.h>
24
25 #include <atomic>
26 #include <iostream>
27 #include <sstream>
28
29 #include <android-base/logging.h>
30 #include <android-base/stringprintf.h>
31
32 #include "art_field-inl.h"
33 #include "art_method-inl.h"
34 #include "base/enums.h"
35 #include "base/locks.h"
36 #include "base/macros.h"
37 #include "class_linker-inl.h"
38 #include "class_root.h"
39 #include "common_dex_operations.h"
40 #include "common_throws.h"
41 #include "dex/dex_file-inl.h"
42 #include "dex/dex_instruction-inl.h"
43 #include "entrypoints/entrypoint_utils-inl.h"
44 #include "handle_scope-inl.h"
45 #include "interpreter_mterp_impl.h"
46 #include "interpreter_switch_impl.h"
47 #include "jit/jit-inl.h"
48 #include "mirror/call_site.h"
49 #include "mirror/class-inl.h"
50 #include "mirror/dex_cache.h"
51 #include "mirror/method.h"
52 #include "mirror/method_handles_lookup.h"
53 #include "mirror/object-inl.h"
54 #include "mirror/object_array-inl.h"
55 #include "mirror/string-inl.h"
56 #include "mterp/mterp.h"
57 #include "obj_ptr.h"
58 #include "stack.h"
59 #include "thread.h"
60 #include "unstarted_runtime.h"
61 #include "well_known_classes.h"
62
63 namespace art {
64 namespace interpreter {
65
66 void ThrowNullPointerExceptionFromInterpreter()
67 REQUIRES_SHARED(Locks::mutator_lock_);
68
69 template <bool kMonitorCounting>
DoMonitorEnter(Thread * self,ShadowFrame * frame,ObjPtr<mirror::Object> ref)70 static inline void DoMonitorEnter(Thread* self, ShadowFrame* frame, ObjPtr<mirror::Object> ref)
71 NO_THREAD_SAFETY_ANALYSIS
72 REQUIRES(!Roles::uninterruptible_) {
73 DCHECK(!ref.IsNull());
74 StackHandleScope<1> hs(self);
75 Handle<mirror::Object> h_ref(hs.NewHandle(ref));
76 h_ref->MonitorEnter(self);
77 DCHECK(self->HoldsLock(h_ref.Get()));
78 if (UNLIKELY(self->IsExceptionPending())) {
79 bool unlocked = h_ref->MonitorExit(self);
80 DCHECK(unlocked);
81 return;
82 }
83 if (kMonitorCounting && frame->GetMethod()->MustCountLocks()) {
84 frame->GetLockCountData().AddMonitor(self, h_ref.Get());
85 }
86 }
87
88 template <bool kMonitorCounting>
DoMonitorExit(Thread * self,ShadowFrame * frame,ObjPtr<mirror::Object> ref)89 static inline void DoMonitorExit(Thread* self, ShadowFrame* frame, ObjPtr<mirror::Object> ref)
90 NO_THREAD_SAFETY_ANALYSIS
91 REQUIRES(!Roles::uninterruptible_) {
92 StackHandleScope<1> hs(self);
93 Handle<mirror::Object> h_ref(hs.NewHandle(ref));
94 h_ref->MonitorExit(self);
95 if (kMonitorCounting && frame->GetMethod()->MustCountLocks()) {
96 frame->GetLockCountData().RemoveMonitorOrThrow(self, h_ref.Get());
97 }
98 }
99
100 template <bool kMonitorCounting>
DoMonitorCheckOnExit(Thread * self,ShadowFrame * frame)101 static inline bool DoMonitorCheckOnExit(Thread* self, ShadowFrame* frame)
102 NO_THREAD_SAFETY_ANALYSIS
103 REQUIRES(!Roles::uninterruptible_) {
104 if (kMonitorCounting && frame->GetMethod()->MustCountLocks()) {
105 return frame->GetLockCountData().CheckAllMonitorsReleasedOrThrow(self);
106 }
107 return true;
108 }
109
110 void AbortTransactionF(Thread* self, const char* fmt, ...)
111 __attribute__((__format__(__printf__, 2, 3)))
112 REQUIRES_SHARED(Locks::mutator_lock_);
113
114 void AbortTransactionV(Thread* self, const char* fmt, va_list args)
115 REQUIRES_SHARED(Locks::mutator_lock_);
116
117 void RecordArrayElementsInTransaction(ObjPtr<mirror::Array> array, int32_t count)
118 REQUIRES_SHARED(Locks::mutator_lock_);
119
120 // Invokes the given method. This is part of the invocation support and is used by DoInvoke,
121 // DoFastInvoke and DoInvokeVirtualQuick functions.
122 // Returns true on success, otherwise throws an exception and returns false.
123 template<bool is_range, bool do_assignability_check>
124 bool DoCall(ArtMethod* called_method, Thread* self, ShadowFrame& shadow_frame,
125 const Instruction* inst, uint16_t inst_data, JValue* result);
126
127 bool UseFastInterpreterToInterpreterInvoke(ArtMethod* method)
128 REQUIRES_SHARED(Locks::mutator_lock_);
129
130 // Throws exception if we are getting close to the end of the stack.
131 NO_INLINE bool CheckStackOverflow(Thread* self, size_t frame_size)
132 REQUIRES_SHARED(Locks::mutator_lock_);
133
134 // Handles all invoke-XXX/range instructions except for invoke-polymorphic[/range].
135 // Returns true on success, otherwise throws an exception and returns false.
136 template<InvokeType type, bool is_range, bool do_access_check, bool is_mterp, bool is_quick = false>
DoInvoke(Thread * self,ShadowFrame & shadow_frame,const Instruction * inst,uint16_t inst_data,JValue * result)137 static ALWAYS_INLINE bool DoInvoke(Thread* self,
138 ShadowFrame& shadow_frame,
139 const Instruction* inst,
140 uint16_t inst_data,
141 JValue* result)
142 REQUIRES_SHARED(Locks::mutator_lock_) {
143 // Make sure to check for async exceptions before anything else.
144 if (is_mterp && self->UseMterp()) {
145 DCHECK(!self->ObserveAsyncException());
146 } else if (UNLIKELY(self->ObserveAsyncException())) {
147 return false;
148 }
149 const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
150 const uint32_t vregC = (is_range) ? inst->VRegC_3rc() : inst->VRegC_35c();
151 ArtMethod* sf_method = shadow_frame.GetMethod();
152
153 // Try to find the method in small thread-local cache first.
154 InterpreterCache* tls_cache = self->GetInterpreterCache();
155 size_t tls_value;
156 ArtMethod* resolved_method;
157 if (is_quick) {
158 resolved_method = nullptr; // We don't know/care what the original method was.
159 } else if (LIKELY(tls_cache->Get(inst, &tls_value))) {
160 resolved_method = reinterpret_cast<ArtMethod*>(tls_value);
161 } else {
162 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
163 constexpr ClassLinker::ResolveMode resolve_mode =
164 do_access_check ? ClassLinker::ResolveMode::kCheckICCEAndIAE
165 : ClassLinker::ResolveMode::kNoChecks;
166 resolved_method = class_linker->ResolveMethod<resolve_mode>(self, method_idx, sf_method, type);
167 if (UNLIKELY(resolved_method == nullptr)) {
168 CHECK(self->IsExceptionPending());
169 result->SetJ(0);
170 return false;
171 }
172 tls_cache->Set(inst, reinterpret_cast<size_t>(resolved_method));
173 }
174
175 // Null pointer check and virtual method resolution.
176 ObjPtr<mirror::Object> receiver =
177 (type == kStatic) ? nullptr : shadow_frame.GetVRegReference(vregC);
178 ArtMethod* called_method;
179 if (is_quick) {
180 if (UNLIKELY(receiver == nullptr)) {
181 // We lost the reference to the method index so we cannot get a more precise exception.
182 ThrowNullPointerExceptionFromDexPC();
183 return false;
184 }
185 DCHECK(receiver->GetClass()->ShouldHaveEmbeddedVTable());
186 called_method = receiver->GetClass()->GetEmbeddedVTableEntry(
187 /*vtable_idx=*/ method_idx, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
188 } else {
189 called_method = FindMethodToCall<type, do_access_check>(
190 method_idx, resolved_method, &receiver, sf_method, self);
191 }
192 if (UNLIKELY(called_method == nullptr)) {
193 CHECK(self->IsExceptionPending());
194 result->SetJ(0);
195 return false;
196 }
197 if (UNLIKELY(!called_method->IsInvokable())) {
198 called_method->ThrowInvocationTimeError();
199 result->SetJ(0);
200 return false;
201 }
202
203 jit::Jit* jit = Runtime::Current()->GetJit();
204 if (jit != nullptr && (type == kVirtual || type == kInterface)) {
205 jit->InvokeVirtualOrInterface(receiver, sf_method, shadow_frame.GetDexPC(), called_method);
206 }
207
208 if (is_mterp && !is_range && called_method->IsIntrinsic()) {
209 if (MterpHandleIntrinsic(&shadow_frame, called_method, inst, inst_data,
210 shadow_frame.GetResultRegister())) {
211 if (jit != nullptr && sf_method != nullptr) {
212 jit->NotifyInterpreterToCompiledCodeTransition(self, sf_method);
213 }
214 return !self->IsExceptionPending();
215 }
216 }
217
218 // Check whether we can use the fast path. The result is cached in the ArtMethod.
219 // If the bit is not set, we explicitly recheck all the conditions.
220 // If any of the conditions get falsified, it is important to clear the bit.
221 bool use_fast_path = false;
222 if (is_mterp && self->UseMterp()) {
223 use_fast_path = called_method->UseFastInterpreterToInterpreterInvoke();
224 if (!use_fast_path) {
225 use_fast_path = UseFastInterpreterToInterpreterInvoke(called_method);
226 if (use_fast_path) {
227 called_method->SetFastInterpreterToInterpreterInvokeFlag();
228 }
229 }
230 }
231
232 if (use_fast_path) {
233 DCHECK(Runtime::Current()->IsStarted());
234 DCHECK(!Runtime::Current()->IsActiveTransaction());
235 DCHECK(called_method->SkipAccessChecks());
236 DCHECK(!called_method->IsNative());
237 DCHECK(!called_method->IsProxyMethod());
238 DCHECK(!called_method->IsIntrinsic());
239 DCHECK(!(called_method->GetDeclaringClass()->IsStringClass() &&
240 called_method->IsConstructor()));
241 DCHECK(type != kStatic || called_method->GetDeclaringClass()->IsInitialized());
242
243 const uint16_t number_of_inputs =
244 (is_range) ? inst->VRegA_3rc(inst_data) : inst->VRegA_35c(inst_data);
245 CodeItemDataAccessor accessor(called_method->DexInstructionData());
246 uint32_t num_regs = accessor.RegistersSize();
247 DCHECK_EQ(number_of_inputs, accessor.InsSize());
248 DCHECK_GE(num_regs, number_of_inputs);
249 size_t first_dest_reg = num_regs - number_of_inputs;
250
251 if (UNLIKELY(!CheckStackOverflow(self, ShadowFrame::ComputeSize(num_regs)))) {
252 return false;
253 }
254
255 if (jit != nullptr) {
256 jit->AddSamples(self, called_method, 1, /* with_backedges */false);
257 }
258
259 // Create shadow frame on the stack.
260 const char* old_cause = self->StartAssertNoThreadSuspension("DoFastInvoke");
261 ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
262 CREATE_SHADOW_FRAME(num_regs, &shadow_frame, called_method, /* dex pc */ 0);
263 ShadowFrame* new_shadow_frame = shadow_frame_unique_ptr.get();
264 if (is_range) {
265 size_t src = vregC;
266 for (size_t i = 0, dst = first_dest_reg; i < number_of_inputs; ++i, ++dst, ++src) {
267 *new_shadow_frame->GetVRegAddr(dst) = *shadow_frame.GetVRegAddr(src);
268 *new_shadow_frame->GetShadowRefAddr(dst) = *shadow_frame.GetShadowRefAddr(src);
269 }
270 } else {
271 uint32_t arg[Instruction::kMaxVarArgRegs];
272 inst->GetVarArgs(arg, inst_data);
273 for (size_t i = 0, dst = first_dest_reg; i < number_of_inputs; ++i, ++dst) {
274 *new_shadow_frame->GetVRegAddr(dst) = *shadow_frame.GetVRegAddr(arg[i]);
275 *new_shadow_frame->GetShadowRefAddr(dst) = *shadow_frame.GetShadowRefAddr(arg[i]);
276 }
277 }
278 self->PushShadowFrame(new_shadow_frame);
279 self->EndAssertNoThreadSuspension(old_cause);
280
281 DCheckStaticState(self, called_method);
282 while (true) {
283 // Mterp does not support all instrumentation/debugging.
284 if (!self->UseMterp()) {
285 *result =
286 ExecuteSwitchImpl<false, false>(self, accessor, *new_shadow_frame, *result, false);
287 break;
288 }
289 if (ExecuteMterpImpl(self, accessor.Insns(), new_shadow_frame, result)) {
290 break;
291 } else {
292 // Mterp didn't like that instruction. Single-step it with the reference interpreter.
293 *result = ExecuteSwitchImpl<false, false>(self, accessor, *new_shadow_frame, *result, true);
294 if (new_shadow_frame->GetDexPC() == dex::kDexNoIndex) {
295 break; // Single-stepped a return or an exception not handled locally.
296 }
297 }
298 }
299 self->PopShadowFrame();
300
301 return !self->IsExceptionPending();
302 }
303
304 return DoCall<is_range, do_access_check>(called_method, self, shadow_frame, inst, inst_data,
305 result);
306 }
307
ResolveMethodHandle(Thread * self,uint32_t method_handle_index,ArtMethod * referrer)308 static inline ObjPtr<mirror::MethodHandle> ResolveMethodHandle(Thread* self,
309 uint32_t method_handle_index,
310 ArtMethod* referrer)
311 REQUIRES_SHARED(Locks::mutator_lock_) {
312 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
313 return class_linker->ResolveMethodHandle(self, method_handle_index, referrer);
314 }
315
ResolveMethodType(Thread * self,dex::ProtoIndex method_type_index,ArtMethod * referrer)316 static inline ObjPtr<mirror::MethodType> ResolveMethodType(Thread* self,
317 dex::ProtoIndex method_type_index,
318 ArtMethod* referrer)
319 REQUIRES_SHARED(Locks::mutator_lock_) {
320 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
321 return class_linker->ResolveMethodType(self, method_type_index, referrer);
322 }
323
324 #define DECLARE_SIGNATURE_POLYMORPHIC_HANDLER(Name, ...) \
325 bool Do ## Name(Thread* self, \
326 ShadowFrame& shadow_frame, \
327 const Instruction* inst, \
328 uint16_t inst_data, \
329 JValue* result) REQUIRES_SHARED(Locks::mutator_lock_);
330 #include "intrinsics_list.h"
331 INTRINSICS_LIST(DECLARE_SIGNATURE_POLYMORPHIC_HANDLER)
332 #undef INTRINSICS_LIST
333 #undef DECLARE_SIGNATURE_POLYMORPHIC_HANDLER
334
335 // Performs a invoke-polymorphic or invoke-polymorphic-range.
336 template<bool is_range>
337 bool DoInvokePolymorphic(Thread* self,
338 ShadowFrame& shadow_frame,
339 const Instruction* inst,
340 uint16_t inst_data,
341 JValue* result)
342 REQUIRES_SHARED(Locks::mutator_lock_);
343
344 bool DoInvokeCustom(Thread* self,
345 ShadowFrame& shadow_frame,
346 uint32_t call_site_idx,
347 const InstructionOperands* operands,
348 JValue* result)
349 REQUIRES_SHARED(Locks::mutator_lock_);
350
351 // Performs a custom invoke (invoke-custom/invoke-custom-range).
352 template<bool is_range>
DoInvokeCustom(Thread * self,ShadowFrame & shadow_frame,const Instruction * inst,uint16_t inst_data,JValue * result)353 bool DoInvokeCustom(Thread* self,
354 ShadowFrame& shadow_frame,
355 const Instruction* inst,
356 uint16_t inst_data,
357 JValue* result)
358 REQUIRES_SHARED(Locks::mutator_lock_) {
359 const uint32_t call_site_idx = is_range ? inst->VRegB_3rc() : inst->VRegB_35c();
360 if (is_range) {
361 RangeInstructionOperands operands(inst->VRegC_3rc(), inst->VRegA_3rc());
362 return DoInvokeCustom(self, shadow_frame, call_site_idx, &operands, result);
363 } else {
364 uint32_t args[Instruction::kMaxVarArgRegs];
365 inst->GetVarArgs(args, inst_data);
366 VarArgsInstructionOperands operands(args, inst->VRegA_35c());
367 return DoInvokeCustom(self, shadow_frame, call_site_idx, &operands, result);
368 }
369 }
370
371 // Handles iget-XXX and sget-XXX instructions.
372 // Returns true on success, otherwise throws an exception and returns false.
373 template<FindFieldType find_type, Primitive::Type field_type, bool do_access_check,
374 bool transaction_active = false>
375 bool DoFieldGet(Thread* self, ShadowFrame& shadow_frame, const Instruction* inst,
376 uint16_t inst_data) REQUIRES_SHARED(Locks::mutator_lock_);
377
378 // Handles iget-quick, iget-wide-quick and iget-object-quick instructions.
379 // Returns true on success, otherwise throws an exception and returns false.
380 template<Primitive::Type field_type>
381 bool DoIGetQuick(ShadowFrame& shadow_frame, const Instruction* inst, uint16_t inst_data)
382 REQUIRES_SHARED(Locks::mutator_lock_);
383
384 // Handles iput-XXX and sput-XXX instructions.
385 // Returns true on success, otherwise throws an exception and returns false.
386 template<FindFieldType find_type, Primitive::Type field_type, bool do_access_check,
387 bool transaction_active>
388 bool DoFieldPut(Thread* self, const ShadowFrame& shadow_frame, const Instruction* inst,
389 uint16_t inst_data) REQUIRES_SHARED(Locks::mutator_lock_);
390
391 // Handles iput-quick, iput-wide-quick and iput-object-quick instructions.
392 // Returns true on success, otherwise throws an exception and returns false.
393 template<Primitive::Type field_type, bool transaction_active>
394 bool DoIPutQuick(const ShadowFrame& shadow_frame, const Instruction* inst, uint16_t inst_data)
395 REQUIRES_SHARED(Locks::mutator_lock_);
396
397
398 // Handles string resolution for const-string and const-string-jumbo instructions. Also ensures the
399 // java.lang.String class is initialized.
ResolveString(Thread * self,ShadowFrame & shadow_frame,dex::StringIndex string_idx)400 static inline ObjPtr<mirror::String> ResolveString(Thread* self,
401 ShadowFrame& shadow_frame,
402 dex::StringIndex string_idx)
403 REQUIRES_SHARED(Locks::mutator_lock_) {
404 ObjPtr<mirror::Class> java_lang_string_class = GetClassRoot<mirror::String>();
405 if (UNLIKELY(!java_lang_string_class->IsInitialized())) {
406 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
407 StackHandleScope<1> hs(self);
408 Handle<mirror::Class> h_class(hs.NewHandle(java_lang_string_class));
409 if (UNLIKELY(!class_linker->EnsureInitialized(self, h_class, true, true))) {
410 DCHECK(self->IsExceptionPending());
411 return nullptr;
412 }
413 }
414 ArtMethod* method = shadow_frame.GetMethod();
415 ObjPtr<mirror::String> string_ptr =
416 Runtime::Current()->GetClassLinker()->ResolveString(string_idx, method);
417 return string_ptr;
418 }
419
420 // Handles div-int, div-int/2addr, div-int/li16 and div-int/lit8 instructions.
421 // Returns true on success, otherwise throws a java.lang.ArithmeticException and return false.
DoIntDivide(ShadowFrame & shadow_frame,size_t result_reg,int32_t dividend,int32_t divisor)422 static inline bool DoIntDivide(ShadowFrame& shadow_frame, size_t result_reg,
423 int32_t dividend, int32_t divisor)
424 REQUIRES_SHARED(Locks::mutator_lock_) {
425 constexpr int32_t kMinInt = std::numeric_limits<int32_t>::min();
426 if (UNLIKELY(divisor == 0)) {
427 ThrowArithmeticExceptionDivideByZero();
428 return false;
429 }
430 if (UNLIKELY(dividend == kMinInt && divisor == -1)) {
431 shadow_frame.SetVReg(result_reg, kMinInt);
432 } else {
433 shadow_frame.SetVReg(result_reg, dividend / divisor);
434 }
435 return true;
436 }
437
438 // Handles rem-int, rem-int/2addr, rem-int/li16 and rem-int/lit8 instructions.
439 // Returns true on success, otherwise throws a java.lang.ArithmeticException and return false.
DoIntRemainder(ShadowFrame & shadow_frame,size_t result_reg,int32_t dividend,int32_t divisor)440 static inline bool DoIntRemainder(ShadowFrame& shadow_frame, size_t result_reg,
441 int32_t dividend, int32_t divisor)
442 REQUIRES_SHARED(Locks::mutator_lock_) {
443 constexpr int32_t kMinInt = std::numeric_limits<int32_t>::min();
444 if (UNLIKELY(divisor == 0)) {
445 ThrowArithmeticExceptionDivideByZero();
446 return false;
447 }
448 if (UNLIKELY(dividend == kMinInt && divisor == -1)) {
449 shadow_frame.SetVReg(result_reg, 0);
450 } else {
451 shadow_frame.SetVReg(result_reg, dividend % divisor);
452 }
453 return true;
454 }
455
456 // Handles div-long and div-long-2addr instructions.
457 // Returns true on success, otherwise throws a java.lang.ArithmeticException and return false.
DoLongDivide(ShadowFrame & shadow_frame,size_t result_reg,int64_t dividend,int64_t divisor)458 static inline bool DoLongDivide(ShadowFrame& shadow_frame,
459 size_t result_reg,
460 int64_t dividend,
461 int64_t divisor)
462 REQUIRES_SHARED(Locks::mutator_lock_) {
463 const int64_t kMinLong = std::numeric_limits<int64_t>::min();
464 if (UNLIKELY(divisor == 0)) {
465 ThrowArithmeticExceptionDivideByZero();
466 return false;
467 }
468 if (UNLIKELY(dividend == kMinLong && divisor == -1)) {
469 shadow_frame.SetVRegLong(result_reg, kMinLong);
470 } else {
471 shadow_frame.SetVRegLong(result_reg, dividend / divisor);
472 }
473 return true;
474 }
475
476 // Handles rem-long and rem-long-2addr instructions.
477 // Returns true on success, otherwise throws a java.lang.ArithmeticException and return false.
DoLongRemainder(ShadowFrame & shadow_frame,size_t result_reg,int64_t dividend,int64_t divisor)478 static inline bool DoLongRemainder(ShadowFrame& shadow_frame,
479 size_t result_reg,
480 int64_t dividend,
481 int64_t divisor)
482 REQUIRES_SHARED(Locks::mutator_lock_) {
483 const int64_t kMinLong = std::numeric_limits<int64_t>::min();
484 if (UNLIKELY(divisor == 0)) {
485 ThrowArithmeticExceptionDivideByZero();
486 return false;
487 }
488 if (UNLIKELY(dividend == kMinLong && divisor == -1)) {
489 shadow_frame.SetVRegLong(result_reg, 0);
490 } else {
491 shadow_frame.SetVRegLong(result_reg, dividend % divisor);
492 }
493 return true;
494 }
495
496 // Handles filled-new-array and filled-new-array-range instructions.
497 // Returns true on success, otherwise throws an exception and returns false.
498 template <bool is_range, bool do_access_check, bool transaction_active>
499 bool DoFilledNewArray(const Instruction* inst, const ShadowFrame& shadow_frame,
500 Thread* self, JValue* result);
501
502 // Handles packed-switch instruction.
503 // Returns the branch offset to the next instruction to execute.
DoPackedSwitch(const Instruction * inst,const ShadowFrame & shadow_frame,uint16_t inst_data)504 static inline int32_t DoPackedSwitch(const Instruction* inst, const ShadowFrame& shadow_frame,
505 uint16_t inst_data)
506 REQUIRES_SHARED(Locks::mutator_lock_) {
507 DCHECK(inst->Opcode() == Instruction::PACKED_SWITCH);
508 const uint16_t* switch_data = reinterpret_cast<const uint16_t*>(inst) + inst->VRegB_31t();
509 int32_t test_val = shadow_frame.GetVReg(inst->VRegA_31t(inst_data));
510 DCHECK_EQ(switch_data[0], static_cast<uint16_t>(Instruction::kPackedSwitchSignature));
511 uint16_t size = switch_data[1];
512 if (size == 0) {
513 // Empty packed switch, move forward by 3 (size of PACKED_SWITCH).
514 return 3;
515 }
516 const int32_t* keys = reinterpret_cast<const int32_t*>(&switch_data[2]);
517 DCHECK_ALIGNED(keys, 4);
518 int32_t first_key = keys[0];
519 const int32_t* targets = reinterpret_cast<const int32_t*>(&switch_data[4]);
520 DCHECK_ALIGNED(targets, 4);
521 int32_t index = test_val - first_key;
522 if (index >= 0 && index < size) {
523 return targets[index];
524 } else {
525 // No corresponding value: move forward by 3 (size of PACKED_SWITCH).
526 return 3;
527 }
528 }
529
530 // Handles sparse-switch instruction.
531 // Returns the branch offset to the next instruction to execute.
DoSparseSwitch(const Instruction * inst,const ShadowFrame & shadow_frame,uint16_t inst_data)532 static inline int32_t DoSparseSwitch(const Instruction* inst, const ShadowFrame& shadow_frame,
533 uint16_t inst_data)
534 REQUIRES_SHARED(Locks::mutator_lock_) {
535 DCHECK(inst->Opcode() == Instruction::SPARSE_SWITCH);
536 const uint16_t* switch_data = reinterpret_cast<const uint16_t*>(inst) + inst->VRegB_31t();
537 int32_t test_val = shadow_frame.GetVReg(inst->VRegA_31t(inst_data));
538 DCHECK_EQ(switch_data[0], static_cast<uint16_t>(Instruction::kSparseSwitchSignature));
539 uint16_t size = switch_data[1];
540 // Return length of SPARSE_SWITCH if size is 0.
541 if (size == 0) {
542 return 3;
543 }
544 const int32_t* keys = reinterpret_cast<const int32_t*>(&switch_data[2]);
545 DCHECK_ALIGNED(keys, 4);
546 const int32_t* entries = keys + size;
547 DCHECK_ALIGNED(entries, 4);
548 int lo = 0;
549 int hi = size - 1;
550 while (lo <= hi) {
551 int mid = (lo + hi) / 2;
552 int32_t foundVal = keys[mid];
553 if (test_val < foundVal) {
554 hi = mid - 1;
555 } else if (test_val > foundVal) {
556 lo = mid + 1;
557 } else {
558 return entries[mid];
559 }
560 }
561 // No corresponding value: move forward by 3 (size of SPARSE_SWITCH).
562 return 3;
563 }
564
565 // We execute any instrumentation events triggered by throwing and/or handing the pending exception
566 // and change the shadow_frames dex_pc to the appropriate exception handler if the current method
567 // has one. If the exception has been handled and the shadow_frame is now pointing to a catch clause
568 // we return true. If the current method is unable to handle the exception we return false.
569 // This function accepts a null Instrumentation* as a way to cause instrumentation events not to be
570 // reported.
571 // TODO We might wish to reconsider how we cause some events to be ignored.
572 bool MoveToExceptionHandler(Thread* self,
573 ShadowFrame& shadow_frame,
574 const instrumentation::Instrumentation* instrumentation)
575 REQUIRES_SHARED(Locks::mutator_lock_);
576
577 NO_RETURN void UnexpectedOpcode(const Instruction* inst, const ShadowFrame& shadow_frame)
578 __attribute__((cold))
579 REQUIRES_SHARED(Locks::mutator_lock_);
580
581 // Set true if you want TraceExecution invocation before each bytecode execution.
582 constexpr bool kTraceExecutionEnabled = false;
583
TraceExecution(const ShadowFrame & shadow_frame,const Instruction * inst,const uint32_t dex_pc)584 static inline void TraceExecution(const ShadowFrame& shadow_frame, const Instruction* inst,
585 const uint32_t dex_pc)
586 REQUIRES_SHARED(Locks::mutator_lock_) {
587 if (kTraceExecutionEnabled) {
588 #define TRACE_LOG std::cerr
589 std::ostringstream oss;
590 oss << shadow_frame.GetMethod()->PrettyMethod()
591 << android::base::StringPrintf("\n0x%x: ", dex_pc)
592 << inst->DumpString(shadow_frame.GetMethod()->GetDexFile()) << "\n";
593 for (uint32_t i = 0; i < shadow_frame.NumberOfVRegs(); ++i) {
594 uint32_t raw_value = shadow_frame.GetVReg(i);
595 ObjPtr<mirror::Object> ref_value = shadow_frame.GetVRegReference(i);
596 oss << android::base::StringPrintf(" vreg%u=0x%08X", i, raw_value);
597 if (ref_value != nullptr) {
598 if (ref_value->GetClass()->IsStringClass() &&
599 !ref_value->AsString()->IsValueNull()) {
600 oss << "/java.lang.String \"" << ref_value->AsString()->ToModifiedUtf8() << "\"";
601 } else {
602 oss << "/" << ref_value->PrettyTypeOf();
603 }
604 }
605 }
606 TRACE_LOG << oss.str() << "\n";
607 #undef TRACE_LOG
608 }
609 }
610
IsBackwardBranch(int32_t branch_offset)611 static inline bool IsBackwardBranch(int32_t branch_offset) {
612 return branch_offset <= 0;
613 }
614
615 // The arg_offset is the offset to the first input register in the frame.
616 void ArtInterpreterToCompiledCodeBridge(Thread* self,
617 ArtMethod* caller,
618 ShadowFrame* shadow_frame,
619 uint16_t arg_offset,
620 JValue* result);
621
IsStringInit(const DexFile * dex_file,uint32_t method_idx)622 static inline bool IsStringInit(const DexFile* dex_file, uint32_t method_idx)
623 REQUIRES_SHARED(Locks::mutator_lock_) {
624 const dex::MethodId& method_id = dex_file->GetMethodId(method_idx);
625 const char* class_name = dex_file->StringByTypeIdx(method_id.class_idx_);
626 const char* method_name = dex_file->GetMethodName(method_id);
627 // Instead of calling ResolveMethod() which has suspend point and can trigger
628 // GC, look up the method symbolically.
629 // Compare method's class name and method name against string init.
630 // It's ok since it's not allowed to create your own java/lang/String.
631 // TODO: verify that assumption.
632 if ((strcmp(class_name, "Ljava/lang/String;") == 0) &&
633 (strcmp(method_name, "<init>") == 0)) {
634 return true;
635 }
636 return false;
637 }
638
IsStringInit(const Instruction * instr,ArtMethod * caller)639 static inline bool IsStringInit(const Instruction* instr, ArtMethod* caller)
640 REQUIRES_SHARED(Locks::mutator_lock_) {
641 if (instr->Opcode() == Instruction::INVOKE_DIRECT ||
642 instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE) {
643 uint16_t callee_method_idx = (instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE) ?
644 instr->VRegB_3rc() : instr->VRegB_35c();
645 return IsStringInit(caller->GetDexFile(), callee_method_idx);
646 }
647 return false;
648 }
649
650 // Set string value created from StringFactory.newStringFromXXX() into all aliases of
651 // StringFactory.newEmptyString().
652 void SetStringInitValueToAllAliases(ShadowFrame* shadow_frame,
653 uint16_t this_obj_vreg,
654 JValue result);
655
656 } // namespace interpreter
657 } // namespace art
658
659 #endif // ART_RUNTIME_INTERPRETER_INTERPRETER_COMMON_H_
660