• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 {
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 
ExecuteSwitch(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame & shadow_frame,JValue result_register,bool interpret_one_instruction)234 static JValue ExecuteSwitch(Thread* self,
235                             const CodeItemDataAccessor& accessor,
236                             ShadowFrame& shadow_frame,
237                             JValue result_register,
238                             bool interpret_one_instruction) REQUIRES_SHARED(Locks::mutator_lock_) {
239   if (Runtime::Current()->IsActiveTransaction()) {
240     if (shadow_frame.GetMethod()->SkipAccessChecks()) {
241       return ExecuteSwitchImpl<false, true>(
242           self, accessor, shadow_frame, result_register, interpret_one_instruction);
243     } else {
244       return ExecuteSwitchImpl<true, true>(
245           self, accessor, shadow_frame, result_register, interpret_one_instruction);
246     }
247   } else {
248     if (shadow_frame.GetMethod()->SkipAccessChecks()) {
249       return ExecuteSwitchImpl<false, false>(
250           self, accessor, shadow_frame, result_register, interpret_one_instruction);
251     } else {
252       return ExecuteSwitchImpl<true, false>(
253           self, accessor, shadow_frame, result_register, interpret_one_instruction);
254     }
255   }
256 }
257 
Execute(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame & shadow_frame,JValue result_register,bool stay_in_interpreter=false,bool from_deoptimize=false)258 static inline JValue Execute(
259     Thread* self,
260     const CodeItemDataAccessor& accessor,
261     ShadowFrame& shadow_frame,
262     JValue result_register,
263     bool stay_in_interpreter = false,
264     bool from_deoptimize = false) REQUIRES_SHARED(Locks::mutator_lock_) {
265   DCHECK(!shadow_frame.GetMethod()->IsAbstract());
266   DCHECK(!shadow_frame.GetMethod()->IsNative());
267 
268   if (LIKELY(!from_deoptimize)) {  // Entering the method, but not via deoptimization.
269     if (kIsDebugBuild) {
270       CHECK_EQ(shadow_frame.GetDexPC(), 0u);
271       self->AssertNoPendingException();
272     }
273     instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
274     ArtMethod *method = shadow_frame.GetMethod();
275 
276     if (UNLIKELY(instrumentation->HasMethodEntryListeners())) {
277       instrumentation->MethodEnterEvent(self, method);
278       if (UNLIKELY(shadow_frame.GetForcePopFrame())) {
279         // The caller will retry this invoke or ignore the result. Just return immediately without
280         // any value.
281         DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
282         JValue ret = JValue();
283         PerformNonStandardReturn<MonitorState::kNoMonitorsLocked>(
284             self, shadow_frame, ret, instrumentation, accessor.InsSize());
285         return ret;
286       }
287       if (UNLIKELY(self->IsExceptionPending())) {
288         instrumentation->MethodUnwindEvent(self,
289                                            shadow_frame.GetThisObject(accessor.InsSize()),
290                                            method,
291                                            0);
292         JValue ret = JValue();
293         if (UNLIKELY(shadow_frame.GetForcePopFrame())) {
294           DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
295           PerformNonStandardReturn<MonitorState::kNoMonitorsLocked>(
296               self, shadow_frame, ret, instrumentation, accessor.InsSize());
297         }
298         return ret;
299       }
300     }
301 
302     if (!stay_in_interpreter && !self->IsForceInterpreter()) {
303       jit::Jit* jit = Runtime::Current()->GetJit();
304       if (jit != nullptr) {
305         jit->MethodEntered(self, shadow_frame.GetMethod());
306         if (jit->CanInvokeCompiledCode(method)) {
307           JValue result;
308 
309           // Pop the shadow frame before calling into compiled code.
310           self->PopShadowFrame();
311           // Calculate the offset of the first input reg. The input registers are in the high regs.
312           // It's ok to access the code item here since JIT code will have been touched by the
313           // interpreter and compiler already.
314           uint16_t arg_offset = accessor.RegistersSize() - accessor.InsSize();
315           ArtInterpreterToCompiledCodeBridge(self, nullptr, &shadow_frame, arg_offset, &result);
316           // Push the shadow frame back as the caller will expect it.
317           self->PushShadowFrame(&shadow_frame);
318 
319           return result;
320         }
321       }
322     }
323   }
324 
325   ArtMethod* method = shadow_frame.GetMethod();
326 
327   DCheckStaticState(self, method);
328 
329   // Lock counting is a special version of accessibility checks, and for simplicity and
330   // reduction of template parameters, we gate it behind access-checks mode.
331   DCHECK_IMPLIES(method->SkipAccessChecks(), !method->MustCountLocks());
332 
333   VLOG(interpreter) << "Interpreting " << method->PrettyMethod();
334 
335   return ExecuteSwitch(
336       self, accessor, shadow_frame, result_register, /*interpret_one_instruction=*/ false);
337 }
338 
EnterInterpreterFromInvoke(Thread * self,ArtMethod * method,ObjPtr<mirror::Object> receiver,uint32_t * args,JValue * result,bool stay_in_interpreter)339 void EnterInterpreterFromInvoke(Thread* self,
340                                 ArtMethod* method,
341                                 ObjPtr<mirror::Object> receiver,
342                                 uint32_t* args,
343                                 JValue* result,
344                                 bool stay_in_interpreter) {
345   DCHECK_EQ(self, Thread::Current());
346   bool implicit_check = Runtime::Current()->GetImplicitStackOverflowChecks();
347   if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
348     ThrowStackOverflowError(self);
349     return;
350   }
351 
352   // This can happen if we are in forced interpreter mode and an obsolete method is called using
353   // reflection.
354   if (UNLIKELY(method->IsObsolete())) {
355     ThrowInternalError("Attempting to invoke obsolete version of '%s'.",
356                        method->PrettyMethod().c_str());
357     return;
358   }
359 
360   const char* old_cause = self->StartAssertNoThreadSuspension("EnterInterpreterFromInvoke");
361   CodeItemDataAccessor accessor(method->DexInstructionData());
362   uint16_t num_regs;
363   uint16_t num_ins;
364   if (accessor.HasCodeItem()) {
365     num_regs =  accessor.RegistersSize();
366     num_ins = accessor.InsSize();
367   } else if (!method->IsInvokable()) {
368     self->EndAssertNoThreadSuspension(old_cause);
369     method->ThrowInvocationTimeError();
370     return;
371   } else {
372     DCHECK(method->IsNative()) << method->PrettyMethod();
373     num_regs = num_ins = ArtMethod::NumArgRegisters(method->GetShorty());
374     if (!method->IsStatic()) {
375       num_regs++;
376       num_ins++;
377     }
378   }
379   // Set up shadow frame with matching number of reference slots to vregs.
380   ShadowFrame* last_shadow_frame = self->GetManagedStack()->GetTopShadowFrame();
381   ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
382       CREATE_SHADOW_FRAME(num_regs, last_shadow_frame, method, /* dex pc */ 0);
383   ShadowFrame* shadow_frame = shadow_frame_unique_ptr.get();
384   self->PushShadowFrame(shadow_frame);
385 
386   size_t cur_reg = num_regs - num_ins;
387   if (!method->IsStatic()) {
388     CHECK(receiver != nullptr);
389     shadow_frame->SetVRegReference(cur_reg, receiver);
390     ++cur_reg;
391   }
392   uint32_t shorty_len = 0;
393   const char* shorty = method->GetShorty(&shorty_len);
394   for (size_t shorty_pos = 0, arg_pos = 0; cur_reg < num_regs; ++shorty_pos, ++arg_pos, cur_reg++) {
395     DCHECK_LT(shorty_pos + 1, shorty_len);
396     switch (shorty[shorty_pos + 1]) {
397       case 'L': {
398         ObjPtr<mirror::Object> o =
399             reinterpret_cast<StackReference<mirror::Object>*>(&args[arg_pos])->AsMirrorPtr();
400         shadow_frame->SetVRegReference(cur_reg, o);
401         break;
402       }
403       case 'J': case 'D': {
404         uint64_t wide_value = (static_cast<uint64_t>(args[arg_pos + 1]) << 32) | args[arg_pos];
405         shadow_frame->SetVRegLong(cur_reg, wide_value);
406         cur_reg++;
407         arg_pos++;
408         break;
409       }
410       default:
411         shadow_frame->SetVReg(cur_reg, args[arg_pos]);
412         break;
413     }
414   }
415   self->EndAssertNoThreadSuspension(old_cause);
416   // Do this after populating the shadow frame in case EnsureInitialized causes a GC.
417   if (method->IsStatic()) {
418     ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
419     if (UNLIKELY(!declaring_class->IsVisiblyInitialized())) {
420       StackHandleScope<1> hs(self);
421       Handle<mirror::Class> h_class(hs.NewHandle(declaring_class));
422       if (UNLIKELY(!Runtime::Current()->GetClassLinker()->EnsureInitialized(
423                         self, h_class, /*can_init_fields=*/ true, /*can_init_parents=*/ true))) {
424         CHECK(self->IsExceptionPending());
425         self->PopShadowFrame();
426         return;
427       }
428       DCHECK(h_class->IsInitializing());
429     }
430   }
431   if (LIKELY(!method->IsNative())) {
432     JValue r = Execute(self, accessor, *shadow_frame, JValue(), stay_in_interpreter);
433     if (result != nullptr) {
434       *result = r;
435     }
436   } else {
437     // We don't expect to be asked to interpret native code (which is entered via a JNI compiler
438     // generated stub) except during testing and image writing.
439     // Update args to be the args in the shadow frame since the input ones could hold stale
440     // references pointers due to moving GC.
441     args = shadow_frame->GetVRegArgs(method->IsStatic() ? 0 : 1);
442     if (!Runtime::Current()->IsStarted()) {
443       UnstartedRuntime::Jni(self, method, receiver.Ptr(), args, result);
444     } else {
445       InterpreterJni(self, method, shorty, receiver, args, result);
446     }
447   }
448   self->PopShadowFrame();
449 }
450 
GetReceiverRegisterForStringInit(const Instruction * instr)451 static int16_t GetReceiverRegisterForStringInit(const Instruction* instr) {
452   DCHECK(instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE ||
453          instr->Opcode() == Instruction::INVOKE_DIRECT);
454   return (instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE) ?
455       instr->VRegC_3rc() : instr->VRegC_35c();
456 }
457 
EnterInterpreterFromDeoptimize(Thread * self,ShadowFrame * shadow_frame,JValue * ret_val,bool from_code,DeoptimizationMethodType deopt_method_type)458 void EnterInterpreterFromDeoptimize(Thread* self,
459                                     ShadowFrame* shadow_frame,
460                                     JValue* ret_val,
461                                     bool from_code,
462                                     DeoptimizationMethodType deopt_method_type)
463     REQUIRES_SHARED(Locks::mutator_lock_) {
464   JValue value;
465   // Set value to last known result in case the shadow frame chain is empty.
466   value.SetJ(ret_val->GetJ());
467   // How many frames we have executed.
468   size_t frame_cnt = 0;
469   while (shadow_frame != nullptr) {
470     // We do not want to recover lock state for lock counting when deoptimizing. Currently,
471     // the compiler should not have compiled a method that failed structured-locking checks.
472     DCHECK(!shadow_frame->GetMethod()->MustCountLocks());
473 
474     self->SetTopOfShadowStack(shadow_frame);
475     CodeItemDataAccessor accessor(shadow_frame->GetMethod()->DexInstructionData());
476     const uint32_t dex_pc = shadow_frame->GetDexPC();
477     uint32_t new_dex_pc = dex_pc;
478     if (UNLIKELY(self->IsExceptionPending())) {
479       // If we deoptimize from the QuickExceptionHandler, we already reported the exception throw
480       // event to the instrumentation. Skip throw listeners for the first frame. The deopt check
481       // should happen after the throw listener is called as throw listener can trigger a
482       // deoptimization.
483       new_dex_pc = MoveToExceptionHandler(self,
484                                           *shadow_frame,
485                                           /* skip_listeners= */ false,
486                                           /* skip_throw_listener= */ frame_cnt == 0) ?
487                        shadow_frame->GetDexPC() :
488                        dex::kDexNoIndex;
489     } else if (!from_code) {
490       // Deoptimization is not called from code directly.
491       const Instruction* instr = &accessor.InstructionAt(dex_pc);
492       if (deopt_method_type == DeoptimizationMethodType::kKeepDexPc ||
493           shadow_frame->GetForceRetryInstruction()) {
494         DCHECK(frame_cnt == 0 || shadow_frame->GetForceRetryInstruction())
495             << "frame_cnt: " << frame_cnt
496             << " force-retry: " << shadow_frame->GetForceRetryInstruction();
497         // Need to re-execute the dex instruction.
498         // (1) An invocation might be split into class initialization and invoke.
499         //     In this case, the invoke should not be skipped.
500         // (2) A suspend check should also execute the dex instruction at the
501         //     corresponding dex pc.
502         // If the ForceRetryInstruction bit is set this must be the second frame (the first being
503         // the one that is being popped).
504         DCHECK_EQ(new_dex_pc, dex_pc);
505         shadow_frame->SetForceRetryInstruction(false);
506       } else if (instr->Opcode() == Instruction::MONITOR_ENTER ||
507                  instr->Opcode() == Instruction::MONITOR_EXIT) {
508         DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
509         DCHECK_EQ(frame_cnt, 0u);
510         // Non-idempotent dex instruction should not be re-executed.
511         // On the other hand, if a MONITOR_ENTER is at the dex_pc of a suspend
512         // check, that MONITOR_ENTER should be executed. That case is handled
513         // above.
514         new_dex_pc = dex_pc + instr->SizeInCodeUnits();
515       } else if (instr->IsInvoke()) {
516         DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
517         if (IsStringInit(instr, shadow_frame->GetMethod())) {
518           uint16_t this_obj_vreg = GetReceiverRegisterForStringInit(instr);
519           // Move the StringFactory.newStringFromChars() result into the register representing
520           // "this object" when invoking the string constructor in the original dex instruction.
521           // Also move the result into all aliases.
522           DCHECK(value.GetL()->IsString());
523           SetStringInitValueToAllAliases(shadow_frame, this_obj_vreg, value);
524           // Calling string constructor in the original dex code doesn't generate a result value.
525           value.SetJ(0);
526         }
527         new_dex_pc = dex_pc + instr->SizeInCodeUnits();
528       } else if (instr->Opcode() == Instruction::NEW_INSTANCE) {
529         // A NEW_INSTANCE is simply re-executed, including
530         // "new-instance String" which is compiled into a call into
531         // StringFactory.newEmptyString().
532         DCHECK_EQ(new_dex_pc, dex_pc);
533       } else {
534         DCHECK(deopt_method_type == DeoptimizationMethodType::kDefault);
535         DCHECK_EQ(frame_cnt, 0u);
536         // By default, we re-execute the dex instruction since if they are not
537         // an invoke, so that we don't have to decode the dex instruction to move
538         // result into the right vreg. All slow paths have been audited to be
539         // idempotent except monitor-enter/exit and invocation stubs.
540         // TODO: move result and advance dex pc. That also requires that we
541         // can tell the return type of a runtime method, possibly by decoding
542         // the dex instruction at the caller.
543         DCHECK_EQ(new_dex_pc, dex_pc);
544       }
545     } else {
546       // Nothing to do, the dex_pc is the one at which the code requested
547       // the deoptimization.
548       DCHECK_EQ(frame_cnt, 0u);
549       DCHECK_EQ(new_dex_pc, dex_pc);
550     }
551     if (new_dex_pc != dex::kDexNoIndex) {
552       shadow_frame->SetDexPC(new_dex_pc);
553       value = Execute(self,
554                       accessor,
555                       *shadow_frame,
556                       value,
557                       /* stay_in_interpreter= */ true,
558                       /* from_deoptimize= */ true);
559     }
560     ShadowFrame* old_frame = shadow_frame;
561     shadow_frame = shadow_frame->GetLink();
562     ShadowFrame::DeleteDeoptimizedFrame(old_frame);
563     // Following deoptimizations of shadow frames must be at invocation point
564     // and should advance dex pc past the invoke instruction.
565     from_code = false;
566     deopt_method_type = DeoptimizationMethodType::kDefault;
567     frame_cnt++;
568   }
569   ret_val->SetJ(value.GetJ());
570 }
571 
EnterInterpreterFromEntryPoint(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame * shadow_frame)572 JValue EnterInterpreterFromEntryPoint(Thread* self, const CodeItemDataAccessor& accessor,
573                                       ShadowFrame* shadow_frame) {
574   DCHECK_EQ(self, Thread::Current());
575   bool implicit_check = Runtime::Current()->GetImplicitStackOverflowChecks();
576   if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
577     ThrowStackOverflowError(self);
578     return JValue();
579   }
580 
581   jit::Jit* jit = Runtime::Current()->GetJit();
582   if (jit != nullptr) {
583     jit->NotifyCompiledCodeToInterpreterTransition(self, shadow_frame->GetMethod());
584   }
585   return Execute(self, accessor, *shadow_frame, JValue());
586 }
587 
ArtInterpreterToInterpreterBridge(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame * shadow_frame,JValue * result)588 void ArtInterpreterToInterpreterBridge(Thread* self,
589                                        const CodeItemDataAccessor& accessor,
590                                        ShadowFrame* shadow_frame,
591                                        JValue* result) {
592   bool implicit_check = Runtime::Current()->GetImplicitStackOverflowChecks();
593   if (UNLIKELY(__builtin_frame_address(0) < self->GetStackEndForInterpreter(implicit_check))) {
594     ThrowStackOverflowError(self);
595     return;
596   }
597 
598   self->PushShadowFrame(shadow_frame);
599   ArtMethod* method = shadow_frame->GetMethod();
600   // Ensure static methods are initialized.
601   const bool is_static = method->IsStatic();
602   if (is_static) {
603     ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass();
604     if (UNLIKELY(!declaring_class->IsVisiblyInitialized())) {
605       StackHandleScope<1> hs(self);
606       Handle<mirror::Class> h_class(hs.NewHandle(declaring_class));
607       if (UNLIKELY(!Runtime::Current()->GetClassLinker()->EnsureInitialized(
608                         self, h_class, /*can_init_fields=*/ true, /*can_init_parents=*/ true))) {
609         DCHECK(self->IsExceptionPending());
610         self->PopShadowFrame();
611         return;
612       }
613       DCHECK(h_class->IsInitializing());
614     }
615   }
616 
617   if (LIKELY(!shadow_frame->GetMethod()->IsNative())) {
618     result->SetJ(Execute(self, accessor, *shadow_frame, JValue()).GetJ());
619   } else {
620     // We don't expect to be asked to interpret native code (which is entered via a JNI compiler
621     // generated stub) except during testing and image writing.
622     CHECK(!Runtime::Current()->IsStarted());
623     ObjPtr<mirror::Object> receiver = is_static ? nullptr : shadow_frame->GetVRegReference(0);
624     uint32_t* args = shadow_frame->GetVRegArgs(is_static ? 0 : 1);
625     UnstartedRuntime::Jni(self, shadow_frame->GetMethod(), receiver.Ptr(), args, result);
626   }
627 
628   self->PopShadowFrame();
629 }
630 
CheckInterpreterAsmConstants()631 void CheckInterpreterAsmConstants() {
632   CheckNterpAsmConstants();
633 }
634 
PrevFrameWillRetry(Thread * self,const ShadowFrame & frame)635 bool PrevFrameWillRetry(Thread* self, const ShadowFrame& frame) {
636   ShadowFrame* prev_frame = frame.GetLink();
637   if (prev_frame == nullptr) {
638     NthCallerVisitor vis(self, 1, false);
639     vis.WalkStack();
640     prev_frame = vis.GetCurrentShadowFrame();
641     if (prev_frame == nullptr) {
642       prev_frame = self->FindDebuggerShadowFrame(vis.GetFrameId());
643     }
644   }
645   return prev_frame != nullptr && prev_frame->GetForceRetryInstruction();
646 }
647 
648 }  // namespace interpreter
649 }  // namespace art
650