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 "interpreter.h"
18 
19 #include <limits>
20 #include <string_view>
21 
22 #include "common_dex_operations.h"
23 #include "common_throws.h"
24 #include "dex/dex_file_types.h"
25 #include "interpreter_common.h"
26 #include "interpreter_switch_impl.h"
27 #include "jit/jit.h"
28 #include "jit/jit_code_cache.h"
29 #include "jvalue-inl.h"
30 #include "mirror/string-inl.h"
31 #include "nativehelper/scoped_local_ref.h"
32 #include "scoped_thread_state_change-inl.h"
33 #include "shadow_frame-inl.h"
34 #include "stack.h"
35 #include "thread-inl.h"
36 #include "unstarted_runtime.h"
37 
38 namespace art HIDDEN {
39 namespace interpreter {
40 
ObjArg(uint32_t arg)41 ALWAYS_INLINE static ObjPtr<mirror::Object> ObjArg(uint32_t arg)
42     REQUIRES_SHARED(Locks::mutator_lock_) {
43   return reinterpret_cast<mirror::Object*>(arg);
44 }
45 
InterpreterJni(Thread * self,ArtMethod * method,std::string_view shorty,ObjPtr<mirror::Object> receiver,uint32_t * args,JValue * result)46 static void InterpreterJni(Thread* self,
47                            ArtMethod* method,
48                            std::string_view shorty,
49                            ObjPtr<mirror::Object> receiver,
50                            uint32_t* args,
51                            JValue* result)
52     REQUIRES_SHARED(Locks::mutator_lock_) {
53   // TODO: The following enters JNI code using a typedef-ed function rather than the JNI compiler,
54   //       it should be removed and JNI compiled stubs used instead.
55   ScopedObjectAccessUnchecked soa(self);
56   if (method->IsStatic()) {
57     if (shorty == "L") {
58       using fntype = jobject(JNIEnv*, jclass);
59       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
60       ScopedLocalRef<jclass> klass(soa.Env(),
61                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
62       jobject jresult;
63       {
64         ScopedThreadStateChange tsc(self, ThreadState::kNative);
65         jresult = fn(soa.Env(), klass.get());
66       }
67       result->SetL(soa.Decode<mirror::Object>(jresult));
68     } else if (shorty == "V") {
69       using fntype = void(JNIEnv*, jclass);
70       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
71       ScopedLocalRef<jclass> klass(soa.Env(),
72                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
73       ScopedThreadStateChange tsc(self, ThreadState::kNative);
74       fn(soa.Env(), klass.get());
75     } else if (shorty == "Z") {
76       using fntype = jboolean(JNIEnv*, jclass);
77       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
78       ScopedLocalRef<jclass> klass(soa.Env(),
79                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
80       ScopedThreadStateChange tsc(self, ThreadState::kNative);
81       result->SetZ(fn(soa.Env(), klass.get()));
82     } else if (shorty == "BI") {
83       using fntype = jbyte(JNIEnv*, jclass, jint);
84       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
85       ScopedLocalRef<jclass> klass(soa.Env(),
86                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
87       ScopedThreadStateChange tsc(self, ThreadState::kNative);
88       result->SetB(fn(soa.Env(), klass.get(), args[0]));
89     } else if (shorty == "II") {
90       using fntype = jint(JNIEnv*, jclass, jint);
91       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
92       ScopedLocalRef<jclass> klass(soa.Env(),
93                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
94       ScopedThreadStateChange tsc(self, ThreadState::kNative);
95       result->SetI(fn(soa.Env(), klass.get(), args[0]));
96     } else if (shorty == "LL") {
97       using fntype = jobject(JNIEnv*, jclass, jobject);
98       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
99       ScopedLocalRef<jclass> klass(soa.Env(),
100                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
101       ScopedLocalRef<jobject> arg0(soa.Env(),
102                                    soa.AddLocalReference<jobject>(ObjArg(args[0])));
103       jobject jresult;
104       {
105         ScopedThreadStateChange tsc(self, ThreadState::kNative);
106         jresult = fn(soa.Env(), klass.get(), arg0.get());
107       }
108       result->SetL(soa.Decode<mirror::Object>(jresult));
109     } else if (shorty == "IIZ") {
110       using fntype = jint(JNIEnv*, jclass, jint, jboolean);
111       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
112       ScopedLocalRef<jclass> klass(soa.Env(),
113                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
114       ScopedThreadStateChange tsc(self, ThreadState::kNative);
115       result->SetI(fn(soa.Env(), klass.get(), args[0], args[1]));
116     } else if (shorty == "ILI") {
117       using fntype = jint(JNIEnv*, jclass, jobject, jint);
118       fntype* const fn = reinterpret_cast<fntype*>(const_cast<void*>(
119           method->GetEntryPointFromJni()));
120       ScopedLocalRef<jclass> klass(soa.Env(),
121                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
122       ScopedLocalRef<jobject> arg0(soa.Env(),
123                                    soa.AddLocalReference<jobject>(ObjArg(args[0])));
124       ScopedThreadStateChange tsc(self, ThreadState::kNative);
125       result->SetI(fn(soa.Env(), klass.get(), arg0.get(), args[1]));
126     } else if (shorty == "SIZ") {
127       using fntype = jshort(JNIEnv*, jclass, jint, jboolean);
128       fntype* const fn =
129           reinterpret_cast<fntype*>(const_cast<void*>(method->GetEntryPointFromJni()));
130       ScopedLocalRef<jclass> klass(soa.Env(),
131                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
132       ScopedThreadStateChange tsc(self, ThreadState::kNative);
133       result->SetS(fn(soa.Env(), klass.get(), args[0], args[1]));
134     } else if (shorty == "VIZ") {
135       using fntype = void(JNIEnv*, jclass, jint, jboolean);
136       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
137       ScopedLocalRef<jclass> klass(soa.Env(),
138                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
139       ScopedThreadStateChange tsc(self, ThreadState::kNative);
140       fn(soa.Env(), klass.get(), args[0], args[1]);
141     } else if (shorty == "ZLL") {
142       using fntype = jboolean(JNIEnv*, jclass, jobject, jobject);
143       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
144       ScopedLocalRef<jclass> klass(soa.Env(),
145                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
146       ScopedLocalRef<jobject> arg0(soa.Env(),
147                                    soa.AddLocalReference<jobject>(ObjArg(args[0])));
148       ScopedLocalRef<jobject> arg1(soa.Env(),
149                                    soa.AddLocalReference<jobject>(ObjArg(args[1])));
150       ScopedThreadStateChange tsc(self, ThreadState::kNative);
151       result->SetZ(fn(soa.Env(), klass.get(), arg0.get(), arg1.get()));
152     } else if (shorty == "ZILL") {
153       using fntype = jboolean(JNIEnv*, jclass, jint, jobject, jobject);
154       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
155       ScopedLocalRef<jclass> klass(soa.Env(),
156                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
157       ScopedLocalRef<jobject> arg1(soa.Env(),
158                                    soa.AddLocalReference<jobject>(ObjArg(args[1])));
159       ScopedLocalRef<jobject> arg2(soa.Env(),
160                                    soa.AddLocalReference<jobject>(ObjArg(args[2])));
161       ScopedThreadStateChange tsc(self, ThreadState::kNative);
162       result->SetZ(fn(soa.Env(), klass.get(), args[0], arg1.get(), arg2.get()));
163     } else if (shorty == "VILII") {
164       using fntype = void(JNIEnv*, jclass, jint, jobject, jint, jint);
165       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
166       ScopedLocalRef<jclass> klass(soa.Env(),
167                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
168       ScopedLocalRef<jobject> arg1(soa.Env(),
169                                    soa.AddLocalReference<jobject>(ObjArg(args[1])));
170       ScopedThreadStateChange tsc(self, ThreadState::kNative);
171       fn(soa.Env(), klass.get(), args[0], arg1.get(), args[2], args[3]);
172     } else if (shorty == "VLILII") {
173       using fntype = void(JNIEnv*, jclass, jobject, jint, jobject, jint, jint);
174       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
175       ScopedLocalRef<jclass> klass(soa.Env(),
176                                    soa.AddLocalReference<jclass>(method->GetDeclaringClass()));
177       ScopedLocalRef<jobject> arg0(soa.Env(),
178                                    soa.AddLocalReference<jobject>(ObjArg(args[0])));
179       ScopedLocalRef<jobject> arg2(soa.Env(),
180                                    soa.AddLocalReference<jobject>(ObjArg(args[2])));
181       ScopedThreadStateChange tsc(self, ThreadState::kNative);
182       fn(soa.Env(), klass.get(), arg0.get(), args[1], arg2.get(), args[3], args[4]);
183     } else {
184       LOG(FATAL) << "Do something with static native method: " << method->PrettyMethod()
185           << " shorty: " << shorty;
186     }
187   } else {
188     if (shorty == "L") {
189       using fntype = jobject(JNIEnv*, jobject);
190       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
191       ScopedLocalRef<jobject> rcvr(soa.Env(),
192                                    soa.AddLocalReference<jobject>(receiver));
193       jobject jresult;
194       {
195         ScopedThreadStateChange tsc(self, ThreadState::kNative);
196         jresult = fn(soa.Env(), rcvr.get());
197       }
198       result->SetL(soa.Decode<mirror::Object>(jresult));
199     } else if (shorty == "V") {
200       using fntype = void(JNIEnv*, jobject);
201       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
202       ScopedLocalRef<jobject> rcvr(soa.Env(),
203                                    soa.AddLocalReference<jobject>(receiver));
204       ScopedThreadStateChange tsc(self, ThreadState::kNative);
205       fn(soa.Env(), rcvr.get());
206     } else if (shorty == "LL") {
207       using fntype = jobject(JNIEnv*, jobject, jobject);
208       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
209       ScopedLocalRef<jobject> rcvr(soa.Env(),
210                                    soa.AddLocalReference<jobject>(receiver));
211       ScopedLocalRef<jobject> arg0(soa.Env(),
212                                    soa.AddLocalReference<jobject>(ObjArg(args[0])));
213       jobject jresult;
214       {
215         ScopedThreadStateChange tsc(self, ThreadState::kNative);
216         jresult = fn(soa.Env(), rcvr.get(), arg0.get());
217       }
218       result->SetL(soa.Decode<mirror::Object>(jresult));
219       ScopedThreadStateChange tsc(self, ThreadState::kNative);
220     } else if (shorty == "III") {
221       using fntype = jint(JNIEnv*, jobject, jint, jint);
222       fntype* const fn = reinterpret_cast<fntype*>(method->GetEntryPointFromJni());
223       ScopedLocalRef<jobject> rcvr(soa.Env(),
224                                    soa.AddLocalReference<jobject>(receiver));
225       ScopedThreadStateChange tsc(self, ThreadState::kNative);
226       result->SetI(fn(soa.Env(), rcvr.get(), args[0], args[1]));
227     } else {
228       LOG(FATAL) << "Do something with native method: " << method->PrettyMethod()
229           << " shorty: " << shorty;
230     }
231   }
232 }
233 
234 NO_STACK_PROTECTOR
ExecuteSwitch(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame & shadow_frame,JValue result_register,bool interpret_one_instruction)235 static JValue ExecuteSwitch(Thread* self,
236                             const CodeItemDataAccessor& accessor,
237                             ShadowFrame& shadow_frame,
238                             JValue result_register,
239                             bool interpret_one_instruction) REQUIRES_SHARED(Locks::mutator_lock_) {
240   if (Runtime::Current()->IsActiveTransaction()) {
241     return ExecuteSwitchImpl<true>(
242         self, accessor, shadow_frame, result_register, interpret_one_instruction);
243   } else {
244     return ExecuteSwitchImpl<false>(
245         self, accessor, shadow_frame, result_register, interpret_one_instruction);
246   }
247 }
248 
249 NO_STACK_PROTECTOR
Execute(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame & shadow_frame,JValue result_register,bool stay_in_interpreter=false,bool from_deoptimize=false)250 static inline JValue Execute(
251     Thread* self,
252     const CodeItemDataAccessor& accessor,
253     ShadowFrame& shadow_frame,
254     JValue result_register,
255     bool stay_in_interpreter = false,
256     bool from_deoptimize = false) REQUIRES_SHARED(Locks::mutator_lock_) {
257   DCHECK(!shadow_frame.GetMethod()->IsAbstract());
258   DCHECK(!shadow_frame.GetMethod()->IsNative());
259 
260   // We cache the result of NeedsDexPcEvents in the shadow frame so we don't need to call
261   // NeedsDexPcEvents on every instruction for better performance. NeedsDexPcEvents only gets
262   // updated asynchronoulsy in a SuspendAll scope and any existing shadow frames are updated with
263   // new value. So it is safe to cache it here.
264   shadow_frame.SetNotifyDexPcMoveEvents(
265       Runtime::Current()->GetInstrumentation()->NeedsDexPcEvents(shadow_frame.GetMethod(), self));
266 
267   if (LIKELY(!from_deoptimize)) {  // Entering the method, but not via deoptimization.
268     if (kIsDebugBuild) {
269       CHECK_EQ(shadow_frame.GetDexPC(), 0u);
270       self->AssertNoPendingException();
271     }
272     ArtMethod *method = shadow_frame.GetMethod();
273 
274     // If we can continue in JIT and have JITed code available execute JITed code.
275     if (!stay_in_interpreter &&
276         !self->IsForceInterpreter() &&
277         !shadow_frame.GetForcePopFrame() &&
278         !shadow_frame.GetNotifyDexPcMoveEvents()) {
279       jit::Jit* jit = Runtime::Current()->GetJit();
280       if (jit != nullptr) {
281         jit->MethodEntered(self, shadow_frame.GetMethod());
282         if (jit->CanInvokeCompiledCode(method)) {
283           JValue result;
284 
285           // Pop the shadow frame before calling into compiled code.
286           self->PopShadowFrame();
287           // Calculate the offset of the first input reg. The input registers are in the high regs.
288           // It's ok to access the code item here since JIT code will have been touched by the
289           // interpreter and compiler already.
290           uint16_t arg_offset = accessor.RegistersSize() - accessor.InsSize();
291           ArtInterpreterToCompiledCodeBridge(self, nullptr, &shadow_frame, arg_offset, &result);
292           // Push the shadow frame back as the caller will expect it.
293           self->PushShadowFrame(&shadow_frame);
294 
295           return result;
296         }
297       }
298     }
299 
300     instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
301     if (UNLIKELY(instrumentation->HasMethodEntryListeners() || shadow_frame.GetForcePopFrame())) {
302       instrumentation->MethodEnterEvent(self, method);
303       if (UNLIKELY(shadow_frame.GetForcePopFrame())) {
304         // The caller will retry this invoke or ignore the result. Just return immediately without
305         // any value.
306         DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
307         JValue ret = JValue();
308         PerformNonStandardReturn(self,
309                                  shadow_frame,
310                                  ret,
311                                  instrumentation,
312                                  /* unlock_monitors= */ false);
313         return ret;
314       }
315       if (UNLIKELY(self->IsExceptionPending())) {
316         instrumentation->MethodUnwindEvent(self,
317                                            method,
318                                            0);
319         JValue ret = JValue();
320         if (UNLIKELY(shadow_frame.GetForcePopFrame())) {
321           DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
322           PerformNonStandardReturn(self,
323                                    shadow_frame,
324                                    ret,
325                                    instrumentation,
326                                    /* unlock_monitors= */ false);
327         }
328         return ret;
329       }
330     }
331   }
332 
333   ArtMethod* method = shadow_frame.GetMethod();
334 
335   DCheckStaticState(self, method);
336 
337   // Lock counting is a special version of accessibility checks, and for simplicity and
338   // reduction of template parameters, we gate it behind access-checks mode.
339   DCHECK_IMPLIES(method->SkipAccessChecks(), !method->MustCountLocks());
340 
341   VLOG(interpreter) << "Interpreting " << method->PrettyMethod();
342 
343   return ExecuteSwitch(
344       self, accessor, shadow_frame, result_register, /*interpret_one_instruction=*/ false);
345 }
346 
EnterInterpreterFromInvoke(Thread * self,ArtMethod * method,ObjPtr<mirror::Object> receiver,uint32_t * args,JValue * result,bool stay_in_interpreter)347 void EnterInterpreterFromInvoke(Thread* self,
348                                 ArtMethod* method,
349                                 ObjPtr<mirror::Object> receiver,
350                                 uint32_t* args,
351                                 JValue* result,
352                                 bool stay_in_interpreter) {
353   DCHECK_EQ(self, Thread::Current());
354   bool implicit_check = Runtime::Current()->GetImplicitStackOverflowChecks();
355   if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
356     ThrowStackOverflowError(self);
357     return;
358   }
359 
360   // This can happen if we are in forced interpreter mode and an obsolete method is called using
361   // reflection.
362   if (UNLIKELY(method->IsObsolete())) {
363     ThrowInternalError("Attempting to invoke obsolete version of '%s'.",
364                        method->PrettyMethod().c_str());
365     return;
366   }
367 
368   const char* old_cause = self->StartAssertNoThreadSuspension("EnterInterpreterFromInvoke");
369   CodeItemDataAccessor accessor(method->DexInstructionData());
370   uint16_t num_regs;
371   uint16_t num_ins;
372   if (accessor.HasCodeItem()) {
373     num_regs =  accessor.RegistersSize();
374     num_ins = accessor.InsSize();
375   } else if (!method->IsInvokable()) {
376     self->EndAssertNoThreadSuspension(old_cause);
377     method->ThrowInvocationTimeError(receiver);
378     return;
379   } else {
380     DCHECK(method->IsNative()) << method->PrettyMethod();
381     num_regs = num_ins = ArtMethod::NumArgRegisters(method->GetShortyView());
382     if (!method->IsStatic()) {
383       num_regs++;
384       num_ins++;
385     }
386   }
387   // Set up shadow frame with matching number of reference slots to vregs.
388   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
389       CREATE_SHADOW_FRAME(num_regs, method, /* dex pc */ 0);
390   ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
391 
392   size_t cur_reg = num_regs - num_ins;
393   if (!method->IsStatic()) {
394     CHECK(receiver != nullptr);
395     shadow_frame->SetVRegReference(cur_reg, receiver);
396     ++cur_reg;
397   }
398   uint32_t shorty_len = 0;
399   const char* shorty = method->GetShorty(&shorty_len);
400   for (size_t shorty_pos = 0, arg_pos = 0; cur_reg < num_regs; ++shorty_pos, ++arg_pos, cur_reg++) {
401     DCHECK_LT(shorty_pos + 1, shorty_len);
402     switch (shorty[shorty_pos + 1]) {
403       case 'L': {
404         ObjPtr<mirror::Object> o =
405             reinterpret_cast<StackReference<mirror::Object>*>(&args[arg_pos])->AsMirrorPtr();
406         shadow_frame->SetVRegReference(cur_reg, o);
407         break;
408       }
409       case 'J': case 'D': {
410         uint64_t wide_value = (static_cast<uint64_t>(args[arg_pos + 1]) << 32) | args[arg_pos];
411         shadow_frame->SetVRegLong(cur_reg, wide_value);
412         cur_reg++;
413         arg_pos++;
414         break;
415       }
416       default:
417         shadow_frame->SetVReg(cur_reg, args[arg_pos]);
418         break;
419     }
420   }
421   self->EndAssertNoThreadSuspension(old_cause);
422   if (!EnsureInitialized(self, shadow_frame)) {
423     return;
424   }
425   self->PushShadowFrame(shadow_frame);
426   if (LIKELY(!method->IsNative())) {
427     JValue r = Execute(self, accessor, *shadow_frame, JValue(), stay_in_interpreter);
428     if (result != nullptr) {
429       *result = r;
430     }
431   } else {
432     // We don't expect to be asked to interpret native code (which is entered via a JNI compiler
433     // generated stub) except during testing and image writing.
434     // Update args to be the args in the shadow frame since the input ones could hold stale
435     // references pointers due to moving GC.
436     args = shadow_frame->GetVRegArgs(method->IsStatic() ? 0 : 1);
437     if (!Runtime::Current()->IsStarted()) {
438       UnstartedRuntime::Jni(self, method, receiver.Ptr(), args, result);
439     } else {
440       InterpreterJni(self, method, shorty, receiver, args, result);
441     }
442   }
443   self->PopShadowFrame();
444 }
445 
GetReceiverRegisterForStringInit(const Instruction * instr)446 static int16_t GetReceiverRegisterForStringInit(const Instruction* instr) {
447   DCHECK(instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE ||
448          instr->Opcode() == Instruction::INVOKE_DIRECT);
449   return (instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE) ?
450       instr->VRegC_3rc() : instr->VRegC_35c();
451 }
452 
EnterInterpreterFromDeoptimize(Thread * self,ShadowFrame * shadow_frame,JValue * ret_val,bool from_code,DeoptimizationMethodType deopt_method_type)453 void EnterInterpreterFromDeoptimize(Thread* self,
454                                     ShadowFrame* shadow_frame,
455                                     JValue* ret_val,
456                                     bool from_code,
457                                     DeoptimizationMethodType deopt_method_type)
458     REQUIRES_SHARED(Locks::mutator_lock_) {
459   JValue value;
460   // Set value to last known result in case the shadow frame chain is empty.
461   value.SetJ(ret_val->GetJ());
462   // How many frames we have executed.
463   size_t frame_cnt = 0;
464   while (shadow_frame != nullptr) {
465     // We do not want to recover lock state for lock counting when deoptimizing. Currently,
466     // the compiler should not have compiled a method that failed structured-locking checks.
467     DCHECK(!shadow_frame->GetMethod()->MustCountLocks());
468 
469     self->SetTopOfShadowStack(shadow_frame);
470     CodeItemDataAccessor accessor(shadow_frame->GetMethod()->DexInstructionData());
471     const uint32_t dex_pc = shadow_frame->GetDexPC();
472     uint32_t new_dex_pc = dex_pc;
473     if (UNLIKELY(self->IsExceptionPending())) {
474       DCHECK(self->GetException() != Thread::GetDeoptimizationException());
475       // If we deoptimize from the QuickExceptionHandler, we already reported the exception throw
476       // event to the instrumentation. Skip throw listeners for the first frame. The deopt check
477       // should happen after the throw listener is called as throw listener can trigger a
478       // deoptimization.
479       new_dex_pc = MoveToExceptionHandler(self,
480                                           *shadow_frame,
481                                           /* skip_listeners= */ false,
482                                           /* skip_throw_listener= */ frame_cnt == 0) ?
483                        shadow_frame->GetDexPC() :
484                        dex::kDexNoIndex;
485     } else if (!from_code) {
486       // Deoptimization is not called from code directly.
487       const Instruction* instr = &accessor.InstructionAt(dex_pc);
488       if (deopt_method_type == DeoptimizationMethodType::kKeepDexPc ||
489           shadow_frame->GetForceRetryInstruction()) {
490         DCHECK(frame_cnt == 0 || shadow_frame->GetForceRetryInstruction())
491             << "frame_cnt: " << frame_cnt
492             << " force-retry: " << shadow_frame->GetForceRetryInstruction();
493         // Need to re-execute the dex instruction.
494         // (1) An invocation might be split into class initialization and invoke.
495         //     In this case, the invoke should not be skipped.
496         // (2) A suspend check should also execute the dex instruction at the
497         //     corresponding dex pc.
498         // If the ForceRetryInstruction bit is set this must be the second frame (the first being
499         // the one that is being popped).
500         DCHECK_EQ(new_dex_pc, dex_pc);
501         shadow_frame->SetForceRetryInstruction(false);
502       } else if (instr->Opcode() == Instruction::MONITOR_ENTER ||
503                  instr->Opcode() == Instruction::MONITOR_EXIT) {
504         DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
505         DCHECK_EQ(frame_cnt, 0u);
506         // Non-idempotent dex instruction should not be re-executed.
507         // On the other hand, if a MONITOR_ENTER is at the dex_pc of a suspend
508         // check, that MONITOR_ENTER should be executed. That case is handled
509         // above.
510         new_dex_pc = dex_pc + instr->SizeInCodeUnits();
511       } else if (instr->IsInvoke()) {
512         DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
513         if (IsStringInit(*instr, shadow_frame->GetMethod())) {
514           uint16_t this_obj_vreg = GetReceiverRegisterForStringInit(instr);
515           // Move the StringFactory.newStringFromChars() result into the register representing
516           // "this object" when invoking the string constructor in the original dex instruction.
517           // Also move the result into all aliases.
518           DCHECK(value.GetL()->IsString());
519           SetStringInitValueToAllAliases(shadow_frame, this_obj_vreg, value);
520           // Calling string constructor in the original dex code doesn't generate a result value.
521           value.SetJ(0);
522         }
523         new_dex_pc = dex_pc + instr->SizeInCodeUnits();
524       } else if (instr->Opcode() == Instruction::NEW_INSTANCE) {
525         // A NEW_INSTANCE is simply re-executed, including
526         // "new-instance String" which is compiled into a call into
527         // StringFactory.newEmptyString().
528         DCHECK_EQ(new_dex_pc, dex_pc);
529       } else {
530         DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
531         DCHECK_EQ(frame_cnt, 0u);
532         // By default, we re-execute the dex instruction since if they are not
533         // an invoke, so that we don't have to decode the dex instruction to move
534         // result into the right vreg. All slow paths have been audited to be
535         // idempotent except monitor-enter/exit and invocation stubs.
536         // TODO: move result and advance dex pc. That also requires that we
537         // can tell the return type of a runtime method, possibly by decoding
538         // the dex instruction at the caller.
539         DCHECK_EQ(new_dex_pc, dex_pc);
540       }
541     } else {
542       // Nothing to do, the dex_pc is the one at which the code requested
543       // the deoptimization.
544       DCHECK_EQ(frame_cnt, 0u);
545       DCHECK_EQ(new_dex_pc, dex_pc);
546     }
547     if (new_dex_pc != dex::kDexNoIndex) {
548       shadow_frame->SetDexPC(new_dex_pc);
549       value = Execute(self,
550                       accessor,
551                       *shadow_frame,
552                       value,
553                       /* stay_in_interpreter= */ true,
554                       /* from_deoptimize= */ true);
555     }
556     ShadowFrame* old_frame = shadow_frame;
557     shadow_frame = shadow_frame->GetLink();
558     ShadowFrame::DeleteDeoptimizedFrame(old_frame);
559     // Following deoptimizations of shadow frames must be at invocation point
560     // and should advance dex pc past the invoke instruction.
561     from_code = false;
562     deopt_method_type = DeoptimizationMethodType::kDefault;
563     frame_cnt++;
564   }
565   ret_val->SetJ(value.GetJ());
566 }
567 
568 NO_STACK_PROTECTOR
EnterInterpreterFromEntryPoint(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame * shadow_frame)569 JValue EnterInterpreterFromEntryPoint(Thread* self, const CodeItemDataAccessor& accessor,
570                                       ShadowFrame* shadow_frame) {
571   DCHECK_EQ(self, Thread::Current());
572   bool implicit_check = Runtime::Current()->GetImplicitStackOverflowChecks();
573   if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
574     ThrowStackOverflowError(self);
575     return JValue();
576   }
577 
578   jit::Jit* jit = Runtime::Current()->GetJit();
579   if (jit != nullptr) {
580     jit->NotifyCompiledCodeToInterpreterTransition(self, shadow_frame->GetMethod());
581   }
582   return Execute(self, accessor, *shadow_frame, JValue());
583 }
584 
585 NO_STACK_PROTECTOR
ArtInterpreterToInterpreterBridge(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame * shadow_frame,JValue * result)586 void ArtInterpreterToInterpreterBridge(Thread* self,
587                                        const CodeItemDataAccessor& accessor,
588                                        ShadowFrame* shadow_frame,
589                                        JValue* result) {
590   bool implicit_check = Runtime::Current()->GetImplicitStackOverflowChecks();
591   if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
592     ThrowStackOverflowError(self);
593     return;
594   }
595 
596   self->PushShadowFrame(shadow_frame);
597 
598   if (LIKELY(!shadow_frame->GetMethod()->IsNative())) {
599     result->SetJ(Execute(self, accessor, *shadow_frame, JValue()).GetJ());
600   } else {
601     // We don't expect to be asked to interpret native code (which is entered via a JNI compiler
602     // generated stub) except during testing and image writing.
603     CHECK(!Runtime::Current()->IsStarted());
604     bool is_static = shadow_frame->GetMethod()->IsStatic();
605     ObjPtr<mirror::Object> receiver = is_static ? nullptr : shadow_frame->GetVRegReference(0);
606     uint32_t* args = shadow_frame->GetVRegArgs(is_static ? 0 : 1);
607     UnstartedRuntime::Jni(self, shadow_frame->GetMethod(), receiver.Ptr(), args, result);
608   }
609 
610   self->PopShadowFrame();
611 }
612 
CheckInterpreterAsmConstants()613 void CheckInterpreterAsmConstants() {
614   CheckNterpAsmConstants();
615 }
616 
PrevFrameWillRetry(Thread * self,const ShadowFrame & frame)617 bool PrevFrameWillRetry(Thread* self, const ShadowFrame& frame) {
618   ShadowFrame* prev_frame = frame.GetLink();
619   if (prev_frame == nullptr) {
620     NthCallerVisitor vis(self, 1, false);
621     vis.WalkStack();
622     prev_frame = vis.GetCurrentShadowFrame();
623     if (prev_frame == nullptr) {
624       prev_frame = self->FindDebuggerShadowFrame(vis.GetFrameId());
625     }
626   }
627   return prev_frame != nullptr && prev_frame->GetForceRetryInstruction();
628 }
629 
630 }  // namespace interpreter
631 }  // namespace art
632