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 "android-base/macros.h"
21 #include "instrumentation.h"
22 #include "interpreter.h"
23 #include "interpreter_intrinsics.h"
24 #include "transaction.h"
25 
26 #include <math.h>
27 
28 #include <atomic>
29 #include <iostream>
30 #include <sstream>
31 
32 #include <android-base/logging.h>
33 #include <android-base/stringprintf.h>
34 
35 #include "art_field-inl.h"
36 #include "art_method-inl.h"
37 #include "base/enums.h"
38 #include "base/locks.h"
39 #include "base/logging.h"
40 #include "base/macros.h"
41 #include "class_linker-inl.h"
42 #include "class_root.h"
43 #include "common_dex_operations.h"
44 #include "common_throws.h"
45 #include "dex/dex_file-inl.h"
46 #include "dex/dex_instruction-inl.h"
47 #include "entrypoints/entrypoint_utils-inl.h"
48 #include "handle_scope-inl.h"
49 #include "interpreter_mterp_impl.h"
50 #include "interpreter_switch_impl.h"
51 #include "jit/jit-inl.h"
52 #include "mirror/call_site.h"
53 #include "mirror/class-inl.h"
54 #include "mirror/dex_cache.h"
55 #include "mirror/method.h"
56 #include "mirror/method_handles_lookup.h"
57 #include "mirror/object-inl.h"
58 #include "mirror/object_array-inl.h"
59 #include "mirror/string-inl.h"
60 #include "mterp/mterp.h"
61 #include "obj_ptr.h"
62 #include "stack.h"
63 #include "thread.h"
64 #include "unstarted_runtime.h"
65 #include "verifier/method_verifier.h"
66 #include "well_known_classes.h"
67 
68 namespace art {
69 namespace interpreter {
70 
71 void ThrowNullPointerExceptionFromInterpreter()
72     REQUIRES_SHARED(Locks::mutator_lock_);
73 
74 template <bool kMonitorCounting>
DoMonitorEnter(Thread * self,ShadowFrame * frame,ObjPtr<mirror::Object> ref)75 static inline void DoMonitorEnter(Thread* self, ShadowFrame* frame, ObjPtr<mirror::Object> ref)
76     NO_THREAD_SAFETY_ANALYSIS
77     REQUIRES(!Roles::uninterruptible_) {
78   DCHECK(!ref.IsNull());
79   StackHandleScope<1> hs(self);
80   Handle<mirror::Object> h_ref(hs.NewHandle(ref));
81   h_ref->MonitorEnter(self);
82   DCHECK(self->HoldsLock(h_ref.Get()));
83   if (UNLIKELY(self->IsExceptionPending())) {
84     bool unlocked = h_ref->MonitorExit(self);
85     DCHECK(unlocked);
86     return;
87   }
88   if (kMonitorCounting && frame->GetMethod()->MustCountLocks()) {
89     frame->GetLockCountData().AddMonitor(self, h_ref.Get());
90   }
91 }
92 
93 template <bool kMonitorCounting>
DoMonitorExit(Thread * self,ShadowFrame * frame,ObjPtr<mirror::Object> ref)94 static inline void DoMonitorExit(Thread* self, ShadowFrame* frame, ObjPtr<mirror::Object> ref)
95     NO_THREAD_SAFETY_ANALYSIS
96     REQUIRES(!Roles::uninterruptible_) {
97   StackHandleScope<1> hs(self);
98   Handle<mirror::Object> h_ref(hs.NewHandle(ref));
99   h_ref->MonitorExit(self);
100   if (kMonitorCounting && frame->GetMethod()->MustCountLocks()) {
101     frame->GetLockCountData().RemoveMonitorOrThrow(self, h_ref.Get());
102   }
103 }
104 
105 template <bool kMonitorCounting>
DoMonitorCheckOnExit(Thread * self,ShadowFrame * frame)106 static inline bool DoMonitorCheckOnExit(Thread* self, ShadowFrame* frame)
107     NO_THREAD_SAFETY_ANALYSIS
108     REQUIRES(!Roles::uninterruptible_) {
109   if (kMonitorCounting && frame->GetMethod()->MustCountLocks()) {
110     return frame->GetLockCountData().CheckAllMonitorsReleasedOrThrow(self);
111   }
112   return true;
113 }
114 
115 void AbortTransactionF(Thread* self, const char* fmt, ...)
116     __attribute__((__format__(__printf__, 2, 3)))
117     REQUIRES_SHARED(Locks::mutator_lock_);
118 
119 void AbortTransactionV(Thread* self, const char* fmt, va_list args)
120     REQUIRES_SHARED(Locks::mutator_lock_);
121 
122 void RecordArrayElementsInTransaction(ObjPtr<mirror::Array> array, int32_t count)
123     REQUIRES_SHARED(Locks::mutator_lock_);
124 
125 // Invokes the given method. This is part of the invocation support and is used by DoInvoke,
126 // DoFastInvoke and DoInvokeVirtualQuick functions.
127 // Returns true on success, otherwise throws an exception and returns false.
128 template<bool is_range, bool do_assignability_check>
129 bool DoCall(ArtMethod* called_method, Thread* self, ShadowFrame& shadow_frame,
130             const Instruction* inst, uint16_t inst_data, JValue* result);
131 
132 bool UseFastInterpreterToInterpreterInvoke(ArtMethod* method)
133     REQUIRES_SHARED(Locks::mutator_lock_);
134 
135 // Throws exception if we are getting close to the end of the stack.
136 NO_INLINE bool CheckStackOverflow(Thread* self, size_t frame_size)
137     REQUIRES_SHARED(Locks::mutator_lock_);
138 
139 
140 // Sends the normal method exit event.
141 // Returns true if the events succeeded and false if there is a pending exception.
142 template <typename T> bool SendMethodExitEvents(
143     Thread* self,
144     const instrumentation::Instrumentation* instrumentation,
145     ShadowFrame& frame,
146     ObjPtr<mirror::Object> thiz,
147     ArtMethod* method,
148     uint32_t dex_pc,
149     T& result) REQUIRES_SHARED(Locks::mutator_lock_);
150 
151 static inline ALWAYS_INLINE WARN_UNUSED bool
NeedsMethodExitEvent(const instrumentation::Instrumentation * ins)152 NeedsMethodExitEvent(const instrumentation::Instrumentation* ins)
153     REQUIRES_SHARED(Locks::mutator_lock_) {
154   return ins->HasMethodExitListeners() || ins->HasWatchedFramePopListeners();
155 }
156 
157 // NO_INLINE so we won't bloat the interpreter with this very cold lock-release code.
158 template <bool kMonitorCounting>
UnlockHeldMonitors(Thread * self,ShadowFrame * shadow_frame)159 static NO_INLINE void UnlockHeldMonitors(Thread* self, ShadowFrame* shadow_frame)
160     REQUIRES_SHARED(Locks::mutator_lock_) {
161   DCHECK(shadow_frame->GetForcePopFrame());
162   // Unlock all monitors.
163   if (kMonitorCounting && shadow_frame->GetMethod()->MustCountLocks()) {
164     // Get the monitors from the shadow-frame monitor-count data.
165     shadow_frame->GetLockCountData().VisitMonitors(
166       [&](mirror::Object** obj) REQUIRES_SHARED(Locks::mutator_lock_) {
167         // Since we don't use the 'obj' pointer after the DoMonitorExit everything should be fine
168         // WRT suspension.
169         DoMonitorExit<kMonitorCounting>(self, shadow_frame, *obj);
170       });
171   } else {
172     std::vector<verifier::MethodVerifier::DexLockInfo> locks;
173     verifier::MethodVerifier::FindLocksAtDexPc(shadow_frame->GetMethod(),
174                                                 shadow_frame->GetDexPC(),
175                                                 &locks,
176                                                 Runtime::Current()->GetTargetSdkVersion());
177     for (const auto& reg : locks) {
178       if (UNLIKELY(reg.dex_registers.empty())) {
179         LOG(ERROR) << "Unable to determine reference locked by "
180                     << shadow_frame->GetMethod()->PrettyMethod() << " at pc "
181                     << shadow_frame->GetDexPC();
182       } else {
183         DoMonitorExit<kMonitorCounting>(
184             self, shadow_frame, shadow_frame->GetVRegReference(*reg.dex_registers.begin()));
185       }
186     }
187   }
188 }
189 
190 enum class MonitorState {
191   kNoMonitorsLocked,
192   kCountingMonitors,
193   kNormalMonitors,
194 };
195 
196 template<MonitorState kMonitorState>
PerformNonStandardReturn(Thread * self,ShadowFrame & frame,JValue & result,const instrumentation::Instrumentation * instrumentation,uint16_t num_dex_inst,uint32_t dex_pc)197 static inline ALWAYS_INLINE WARN_UNUSED bool PerformNonStandardReturn(
198       Thread* self,
199       ShadowFrame& frame,
200       JValue& result,
201       const instrumentation::Instrumentation* instrumentation,
202       uint16_t num_dex_inst,
203       uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
204   static constexpr bool kMonitorCounting = (kMonitorState == MonitorState::kCountingMonitors);
205   if (UNLIKELY(frame.GetForcePopFrame())) {
206     ObjPtr<mirror::Object> thiz(frame.GetThisObject(num_dex_inst));
207     StackHandleScope<1> hs(self);
208     Handle<mirror::Object> h_thiz(hs.NewHandle(thiz));
209     DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
210     if (UNLIKELY(self->IsExceptionPending())) {
211       LOG(WARNING) << "Suppressing exception for non-standard method exit: "
212                    << self->GetException()->Dump();
213       self->ClearException();
214     }
215     if (kMonitorState != MonitorState::kNoMonitorsLocked) {
216       UnlockHeldMonitors<kMonitorCounting>(self, &frame);
217     }
218     DoMonitorCheckOnExit<kMonitorCounting>(self, &frame);
219     result = JValue();
220     if (UNLIKELY(NeedsMethodExitEvent(instrumentation))) {
221       SendMethodExitEvents(
222           self, instrumentation, frame, h_thiz.Get(), frame.GetMethod(), dex_pc, result);
223     }
224     return true;
225   }
226   return false;
227 }
228 
229 // Handles all invoke-XXX/range instructions except for invoke-polymorphic[/range].
230 // Returns true on success, otherwise throws an exception and returns false.
231 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)232 static ALWAYS_INLINE bool DoInvoke(Thread* self,
233                                    ShadowFrame& shadow_frame,
234                                    const Instruction* inst,
235                                    uint16_t inst_data,
236                                    JValue* result)
237     REQUIRES_SHARED(Locks::mutator_lock_) {
238   // Make sure to check for async exceptions before anything else.
239   if (is_mterp && self->UseMterp()) {
240     DCHECK(!self->ObserveAsyncException());
241   } else if (UNLIKELY(self->ObserveAsyncException())) {
242     return false;
243   }
244   const uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
245   const uint32_t vregC = (is_range) ? inst->VRegC_3rc() : inst->VRegC_35c();
246   ArtMethod* sf_method = shadow_frame.GetMethod();
247 
248   // Try to find the method in small thread-local cache first (only used when
249   // nterp is not used as mterp and nterp use the cache in an incompatible way).
250   InterpreterCache* tls_cache = self->GetInterpreterCache();
251   size_t tls_value;
252   ArtMethod* resolved_method;
253   if (is_quick) {
254     resolved_method = nullptr;  // We don't know/care what the original method was.
255   } else if (!IsNterpSupported() && LIKELY(tls_cache->Get(inst, &tls_value))) {
256     resolved_method = reinterpret_cast<ArtMethod*>(tls_value);
257   } else {
258     ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
259     constexpr ClassLinker::ResolveMode resolve_mode =
260         do_access_check ? ClassLinker::ResolveMode::kCheckICCEAndIAE
261                         : ClassLinker::ResolveMode::kNoChecks;
262     resolved_method = class_linker->ResolveMethod<resolve_mode>(self, method_idx, sf_method, type);
263     if (UNLIKELY(resolved_method == nullptr)) {
264       CHECK(self->IsExceptionPending());
265       result->SetJ(0);
266       return false;
267     }
268     if (!IsNterpSupported()) {
269       tls_cache->Set(inst, reinterpret_cast<size_t>(resolved_method));
270     }
271   }
272 
273   // Null pointer check and virtual method resolution.
274   ObjPtr<mirror::Object> receiver =
275       (type == kStatic) ? nullptr : shadow_frame.GetVRegReference(vregC);
276   ArtMethod* called_method;
277   if (is_quick) {
278     if (UNLIKELY(receiver == nullptr)) {
279       // We lost the reference to the method index so we cannot get a more precise exception.
280       ThrowNullPointerExceptionFromDexPC();
281       return false;
282     }
283     DCHECK(receiver->GetClass()->ShouldHaveEmbeddedVTable());
284     called_method = receiver->GetClass()->GetEmbeddedVTableEntry(
285         /*vtable_idx=*/ method_idx, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
286   } else {
287     called_method = FindMethodToCall<type, do_access_check>(
288         method_idx, resolved_method, &receiver, sf_method, self);
289   }
290   if (UNLIKELY(called_method == nullptr)) {
291     CHECK(self->IsExceptionPending());
292     result->SetJ(0);
293     return false;
294   }
295   if (UNLIKELY(!called_method->IsInvokable())) {
296     called_method->ThrowInvocationTimeError();
297     result->SetJ(0);
298     return false;
299   }
300 
301   jit::Jit* jit = Runtime::Current()->GetJit();
302   if (jit != nullptr && (type == kVirtual || type == kInterface)) {
303     jit->InvokeVirtualOrInterface(receiver, sf_method, shadow_frame.GetDexPC(), called_method);
304   }
305 
306   if (is_mterp && !is_range && called_method->IsIntrinsic()) {
307     if (MterpHandleIntrinsic(&shadow_frame, called_method, inst, inst_data,
308                              shadow_frame.GetResultRegister())) {
309       if (jit != nullptr && sf_method != nullptr) {
310         jit->NotifyInterpreterToCompiledCodeTransition(self, sf_method);
311       }
312       return !self->IsExceptionPending();
313     }
314   }
315 
316   // Check whether we can use the fast path. The result is cached in the ArtMethod.
317   // If the bit is not set, we explicitly recheck all the conditions.
318   // If any of the conditions get falsified, it is important to clear the bit.
319   bool use_fast_path = false;
320   if (is_mterp && self->UseMterp()) {
321     use_fast_path = called_method->UseFastInterpreterToInterpreterInvoke();
322     if (!use_fast_path) {
323       use_fast_path = UseFastInterpreterToInterpreterInvoke(called_method);
324       if (use_fast_path) {
325         called_method->SetFastInterpreterToInterpreterInvokeFlag();
326       }
327     }
328   }
329 
330   if (use_fast_path) {
331     DCHECK(Runtime::Current()->IsStarted());
332     DCHECK(!Runtime::Current()->IsActiveTransaction());
333     DCHECK(called_method->SkipAccessChecks());
334     DCHECK(!called_method->IsNative());
335     DCHECK(!called_method->IsProxyMethod());
336     DCHECK(!called_method->IsIntrinsic());
337     DCHECK(!(called_method->GetDeclaringClass()->IsStringClass() &&
338         called_method->IsConstructor()));
339     DCHECK(type != kStatic || called_method->GetDeclaringClass()->IsVisiblyInitialized());
340 
341     const uint16_t number_of_inputs =
342         (is_range) ? inst->VRegA_3rc(inst_data) : inst->VRegA_35c(inst_data);
343     CodeItemDataAccessor accessor(called_method->DexInstructionData());
344     uint32_t num_regs = accessor.RegistersSize();
345     DCHECK_EQ(number_of_inputs, accessor.InsSize());
346     DCHECK_GE(num_regs, number_of_inputs);
347     size_t first_dest_reg = num_regs - number_of_inputs;
348 
349     if (UNLIKELY(!CheckStackOverflow(self, ShadowFrame::ComputeSize(num_regs)))) {
350       return false;
351     }
352 
353     if (jit != nullptr) {
354       jit->AddSamples(self, called_method, 1, /* with_backedges */false);
355     }
356 
357     // Create shadow frame on the stack.
358     const char* old_cause = self->StartAssertNoThreadSuspension("DoFastInvoke");
359     ShadowFrameAllocaUniquePtr shadow_frame_unique_ptr =
360         CREATE_SHADOW_FRAME(num_regs, &shadow_frame, called_method, /* dex pc */ 0);
361     ShadowFrame* new_shadow_frame = shadow_frame_unique_ptr.get();
362     if (is_range) {
363       size_t src = vregC;
364       for (size_t i = 0, dst = first_dest_reg; i < number_of_inputs; ++i, ++dst, ++src) {
365         *new_shadow_frame->GetVRegAddr(dst) = *shadow_frame.GetVRegAddr(src);
366         *new_shadow_frame->GetShadowRefAddr(dst) = *shadow_frame.GetShadowRefAddr(src);
367       }
368     } else {
369       uint32_t arg[Instruction::kMaxVarArgRegs];
370       inst->GetVarArgs(arg, inst_data);
371       for (size_t i = 0, dst = first_dest_reg; i < number_of_inputs; ++i, ++dst) {
372         *new_shadow_frame->GetVRegAddr(dst) = *shadow_frame.GetVRegAddr(arg[i]);
373         *new_shadow_frame->GetShadowRefAddr(dst) = *shadow_frame.GetShadowRefAddr(arg[i]);
374       }
375     }
376     self->PushShadowFrame(new_shadow_frame);
377     self->EndAssertNoThreadSuspension(old_cause);
378 
379     VLOG(interpreter) << "Interpreting " << called_method->PrettyMethod();
380 
381     DCheckStaticState(self, called_method);
382     while (true) {
383       // Mterp does not support all instrumentation/debugging.
384       if (!self->UseMterp()) {
385         *result =
386             ExecuteSwitchImpl<false, false>(self, accessor, *new_shadow_frame, *result, false);
387         break;
388       }
389       if (ExecuteMterpImpl(self, accessor.Insns(), new_shadow_frame, result)) {
390         break;
391       } else {
392         // Mterp didn't like that instruction.  Single-step it with the reference interpreter.
393         *result = ExecuteSwitchImpl<false, false>(self, accessor, *new_shadow_frame, *result, true);
394         if (new_shadow_frame->GetDexPC() == dex::kDexNoIndex) {
395           break;  // Single-stepped a return or an exception not handled locally.
396         }
397       }
398     }
399     self->PopShadowFrame();
400 
401     return !self->IsExceptionPending();
402   }
403 
404   return DoCall<is_range, do_access_check>(called_method, self, shadow_frame, inst, inst_data,
405                                            result);
406 }
407 
ResolveMethodHandle(Thread * self,uint32_t method_handle_index,ArtMethod * referrer)408 static inline ObjPtr<mirror::MethodHandle> ResolveMethodHandle(Thread* self,
409                                                                uint32_t method_handle_index,
410                                                                ArtMethod* referrer)
411     REQUIRES_SHARED(Locks::mutator_lock_) {
412   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
413   return class_linker->ResolveMethodHandle(self, method_handle_index, referrer);
414 }
415 
ResolveMethodType(Thread * self,dex::ProtoIndex method_type_index,ArtMethod * referrer)416 static inline ObjPtr<mirror::MethodType> ResolveMethodType(Thread* self,
417                                                            dex::ProtoIndex method_type_index,
418                                                            ArtMethod* referrer)
419     REQUIRES_SHARED(Locks::mutator_lock_) {
420   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
421   return class_linker->ResolveMethodType(self, method_type_index, referrer);
422 }
423 
424 #define DECLARE_SIGNATURE_POLYMORPHIC_HANDLER(Name, ...)              \
425 bool Do ## Name(Thread* self,                                         \
426                 ShadowFrame& shadow_frame,                            \
427                 const Instruction* inst,                              \
428                 uint16_t inst_data,                                   \
429                 JValue* result) REQUIRES_SHARED(Locks::mutator_lock_);
430 #include "intrinsics_list.h"
431 INTRINSICS_LIST(DECLARE_SIGNATURE_POLYMORPHIC_HANDLER)
432 #undef INTRINSICS_LIST
433 #undef DECLARE_SIGNATURE_POLYMORPHIC_HANDLER
434 
435 // Performs a invoke-polymorphic or invoke-polymorphic-range.
436 template<bool is_range>
437 bool DoInvokePolymorphic(Thread* self,
438                          ShadowFrame& shadow_frame,
439                          const Instruction* inst,
440                          uint16_t inst_data,
441                          JValue* result)
442     REQUIRES_SHARED(Locks::mutator_lock_);
443 
444 bool DoInvokeCustom(Thread* self,
445                     ShadowFrame& shadow_frame,
446                     uint32_t call_site_idx,
447                     const InstructionOperands* operands,
448                     JValue* result)
449     REQUIRES_SHARED(Locks::mutator_lock_);
450 
451 // Performs a custom invoke (invoke-custom/invoke-custom-range).
452 template<bool is_range>
DoInvokeCustom(Thread * self,ShadowFrame & shadow_frame,const Instruction * inst,uint16_t inst_data,JValue * result)453 bool DoInvokeCustom(Thread* self,
454                     ShadowFrame& shadow_frame,
455                     const Instruction* inst,
456                     uint16_t inst_data,
457                     JValue* result)
458     REQUIRES_SHARED(Locks::mutator_lock_) {
459   const uint32_t call_site_idx = is_range ? inst->VRegB_3rc() : inst->VRegB_35c();
460   if (is_range) {
461     RangeInstructionOperands operands(inst->VRegC_3rc(), inst->VRegA_3rc());
462     return DoInvokeCustom(self, shadow_frame, call_site_idx, &operands, result);
463   } else {
464     uint32_t args[Instruction::kMaxVarArgRegs];
465     inst->GetVarArgs(args, inst_data);
466     VarArgsInstructionOperands operands(args, inst->VRegA_35c());
467     return DoInvokeCustom(self, shadow_frame, call_site_idx, &operands, result);
468   }
469 }
470 
471 template<Primitive::Type field_type>
GetFieldValue(const ShadowFrame & shadow_frame,uint32_t vreg)472 ALWAYS_INLINE static JValue GetFieldValue(const ShadowFrame& shadow_frame, uint32_t vreg)
473     REQUIRES_SHARED(Locks::mutator_lock_) {
474   JValue field_value;
475   switch (field_type) {
476     case Primitive::kPrimBoolean:
477       field_value.SetZ(static_cast<uint8_t>(shadow_frame.GetVReg(vreg)));
478       break;
479     case Primitive::kPrimByte:
480       field_value.SetB(static_cast<int8_t>(shadow_frame.GetVReg(vreg)));
481       break;
482     case Primitive::kPrimChar:
483       field_value.SetC(static_cast<uint16_t>(shadow_frame.GetVReg(vreg)));
484       break;
485     case Primitive::kPrimShort:
486       field_value.SetS(static_cast<int16_t>(shadow_frame.GetVReg(vreg)));
487       break;
488     case Primitive::kPrimInt:
489       field_value.SetI(shadow_frame.GetVReg(vreg));
490       break;
491     case Primitive::kPrimLong:
492       field_value.SetJ(shadow_frame.GetVRegLong(vreg));
493       break;
494     case Primitive::kPrimNot:
495       field_value.SetL(shadow_frame.GetVRegReference(vreg));
496       break;
497     default:
498       LOG(FATAL) << "Unreachable: " << field_type;
499       UNREACHABLE();
500   }
501   return field_value;
502 }
503 
504 // Handles iget-XXX and sget-XXX instructions.
505 // Returns true on success, otherwise throws an exception and returns false.
506 template<FindFieldType find_type, Primitive::Type field_type, bool do_access_check,
507          bool transaction_active = false>
DoFieldGet(Thread * self,ShadowFrame & shadow_frame,const Instruction * inst,uint16_t inst_data)508 ALWAYS_INLINE bool DoFieldGet(Thread* self, ShadowFrame& shadow_frame, const Instruction* inst,
509                               uint16_t inst_data) REQUIRES_SHARED(Locks::mutator_lock_) {
510   const bool is_static = (find_type == StaticObjectRead) || (find_type == StaticPrimitiveRead);
511   const uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c();
512   ArtField* f =
513       FindFieldFromCode<find_type, do_access_check>(field_idx, shadow_frame.GetMethod(), self,
514                                                     Primitive::ComponentSize(field_type));
515   if (UNLIKELY(f == nullptr)) {
516     CHECK(self->IsExceptionPending());
517     return false;
518   }
519   ObjPtr<mirror::Object> obj;
520   if (is_static) {
521     obj = f->GetDeclaringClass();
522     if (transaction_active) {
523       if (Runtime::Current()->GetTransaction()->ReadConstraint(self, obj)) {
524         Runtime::Current()->AbortTransactionAndThrowAbortError(self, "Can't read static fields of "
525             + obj->PrettyTypeOf() + " since it does not belong to clinit's class.");
526         return false;
527       }
528     }
529   } else {
530     obj = shadow_frame.GetVRegReference(inst->VRegB_22c(inst_data));
531     if (UNLIKELY(obj == nullptr)) {
532       ThrowNullPointerExceptionForFieldAccess(f, true);
533       return false;
534     }
535   }
536 
537   JValue result;
538   if (UNLIKELY(!DoFieldGetCommon<field_type>(self, shadow_frame, obj, f, &result))) {
539     // Instrumentation threw an error!
540     CHECK(self->IsExceptionPending());
541     return false;
542   }
543   uint32_t vregA = is_static ? inst->VRegA_21c(inst_data) : inst->VRegA_22c(inst_data);
544   switch (field_type) {
545     case Primitive::kPrimBoolean:
546       shadow_frame.SetVReg(vregA, result.GetZ());
547       break;
548     case Primitive::kPrimByte:
549       shadow_frame.SetVReg(vregA, result.GetB());
550       break;
551     case Primitive::kPrimChar:
552       shadow_frame.SetVReg(vregA, result.GetC());
553       break;
554     case Primitive::kPrimShort:
555       shadow_frame.SetVReg(vregA, result.GetS());
556       break;
557     case Primitive::kPrimInt:
558       shadow_frame.SetVReg(vregA, result.GetI());
559       break;
560     case Primitive::kPrimLong:
561       shadow_frame.SetVRegLong(vregA, result.GetJ());
562       break;
563     case Primitive::kPrimNot:
564       shadow_frame.SetVRegReference(vregA, result.GetL());
565       break;
566     default:
567       LOG(FATAL) << "Unreachable: " << field_type;
568       UNREACHABLE();
569   }
570   return true;
571 }
572 
573 // Handles iget-quick, iget-wide-quick and iget-object-quick instructions.
574 // Returns true on success, otherwise throws an exception and returns false.
575 template<Primitive::Type field_type>
DoIGetQuick(ShadowFrame & shadow_frame,const Instruction * inst,uint16_t inst_data)576 ALWAYS_INLINE bool DoIGetQuick(ShadowFrame& shadow_frame, const Instruction* inst,
577                                uint16_t inst_data) REQUIRES_SHARED(Locks::mutator_lock_) {
578   ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(inst->VRegB_22c(inst_data));
579   if (UNLIKELY(obj == nullptr)) {
580     // We lost the reference to the field index so we cannot get a more
581     // precised exception message.
582     ThrowNullPointerExceptionFromDexPC();
583     return false;
584   }
585   MemberOffset field_offset(inst->VRegC_22c());
586   // Report this field access to instrumentation if needed. Since we only have the offset of
587   // the field from the base of the object, we need to look for it first.
588   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
589   if (UNLIKELY(instrumentation->HasFieldReadListeners())) {
590     ArtField* f = ArtField::FindInstanceFieldWithOffset(obj->GetClass(),
591                                                         field_offset.Uint32Value());
592     DCHECK(f != nullptr);
593     DCHECK(!f->IsStatic());
594     Thread* self = Thread::Current();
595     StackHandleScope<1> hs(self);
596     // Save obj in case the instrumentation event has thread suspension.
597     HandleWrapperObjPtr<mirror::Object> h = hs.NewHandleWrapper(&obj);
598     instrumentation->FieldReadEvent(self,
599                                     obj,
600                                     shadow_frame.GetMethod(),
601                                     shadow_frame.GetDexPC(),
602                                     f);
603     if (UNLIKELY(self->IsExceptionPending())) {
604       return false;
605     }
606   }
607   // Note: iget-x-quick instructions are only for non-volatile fields.
608   const uint32_t vregA = inst->VRegA_22c(inst_data);
609   switch (field_type) {
610     case Primitive::kPrimInt:
611       shadow_frame.SetVReg(vregA, static_cast<int32_t>(obj->GetField32(field_offset)));
612       break;
613     case Primitive::kPrimBoolean:
614       shadow_frame.SetVReg(vregA, static_cast<int32_t>(obj->GetFieldBoolean(field_offset)));
615       break;
616     case Primitive::kPrimByte:
617       shadow_frame.SetVReg(vregA, static_cast<int32_t>(obj->GetFieldByte(field_offset)));
618       break;
619     case Primitive::kPrimChar:
620       shadow_frame.SetVReg(vregA, static_cast<int32_t>(obj->GetFieldChar(field_offset)));
621       break;
622     case Primitive::kPrimShort:
623       shadow_frame.SetVReg(vregA, static_cast<int32_t>(obj->GetFieldShort(field_offset)));
624       break;
625     case Primitive::kPrimLong:
626       shadow_frame.SetVRegLong(vregA, static_cast<int64_t>(obj->GetField64(field_offset)));
627       break;
628     case Primitive::kPrimNot:
629       shadow_frame.SetVRegReference(vregA, obj->GetFieldObject<mirror::Object>(field_offset));
630       break;
631     default:
632       LOG(FATAL) << "Unreachable: " << field_type;
633       UNREACHABLE();
634   }
635   return true;
636 }
637 
CheckWriteConstraint(Thread * self,ObjPtr<mirror::Object> obj)638 static inline bool CheckWriteConstraint(Thread* self, ObjPtr<mirror::Object> obj)
639     REQUIRES_SHARED(Locks::mutator_lock_) {
640   Runtime* runtime = Runtime::Current();
641   if (runtime->GetTransaction()->WriteConstraint(self, obj)) {
642     DCHECK(runtime->GetHeap()->ObjectIsInBootImageSpace(obj) || obj->IsClass());
643     const char* base_msg = runtime->GetHeap()->ObjectIsInBootImageSpace(obj)
644         ? "Can't set fields of boot image "
645         : "Can't set fields of ";
646     runtime->AbortTransactionAndThrowAbortError(self, base_msg + obj->PrettyTypeOf());
647     return false;
648   }
649   return true;
650 }
651 
CheckWriteValueConstraint(Thread * self,ObjPtr<mirror::Object> value)652 static inline bool CheckWriteValueConstraint(Thread* self, ObjPtr<mirror::Object> value)
653     REQUIRES_SHARED(Locks::mutator_lock_) {
654   Runtime* runtime = Runtime::Current();
655   if (runtime->GetTransaction()->WriteValueConstraint(self, value)) {
656     DCHECK(value != nullptr);
657     std::string msg = value->IsClass()
658         ? "Can't store reference to class " + value->AsClass()->PrettyDescriptor()
659         : "Can't store reference to instance of " + value->GetClass()->PrettyDescriptor();
660     runtime->AbortTransactionAndThrowAbortError(self, msg);
661     return false;
662   }
663   return true;
664 }
665 
666 // Handles iput-XXX and sput-XXX instructions.
667 // Returns true on success, otherwise throws an exception and returns false.
668 template<FindFieldType find_type, Primitive::Type field_type, bool do_access_check,
669          bool transaction_active>
DoFieldPut(Thread * self,const ShadowFrame & shadow_frame,const Instruction * inst,uint16_t inst_data)670 ALWAYS_INLINE bool DoFieldPut(Thread* self, const ShadowFrame& shadow_frame,
671                               const Instruction* inst, uint16_t inst_data)
672     REQUIRES_SHARED(Locks::mutator_lock_) {
673   const bool do_assignability_check = do_access_check;
674   bool is_static = (find_type == StaticObjectWrite) || (find_type == StaticPrimitiveWrite);
675   uint32_t field_idx = is_static ? inst->VRegB_21c() : inst->VRegC_22c();
676   ArtField* f =
677       FindFieldFromCode<find_type, do_access_check>(field_idx, shadow_frame.GetMethod(), self,
678                                                     Primitive::ComponentSize(field_type));
679   if (UNLIKELY(f == nullptr)) {
680     CHECK(self->IsExceptionPending());
681     return false;
682   }
683   ObjPtr<mirror::Object> obj;
684   if (is_static) {
685     obj = f->GetDeclaringClass();
686   } else {
687     obj = shadow_frame.GetVRegReference(inst->VRegB_22c(inst_data));
688     if (UNLIKELY(obj == nullptr)) {
689       ThrowNullPointerExceptionForFieldAccess(f, false);
690       return false;
691     }
692   }
693   if (transaction_active && !CheckWriteConstraint(self, obj)) {
694     return false;
695   }
696 
697   uint32_t vregA = is_static ? inst->VRegA_21c(inst_data) : inst->VRegA_22c(inst_data);
698   JValue value = GetFieldValue<field_type>(shadow_frame, vregA);
699 
700   if (transaction_active &&
701       field_type == Primitive::kPrimNot &&
702       !CheckWriteValueConstraint(self, value.GetL())) {
703     return false;
704   }
705 
706   return DoFieldPutCommon<field_type, do_assignability_check, transaction_active>(self,
707                                                                                   shadow_frame,
708                                                                                   obj,
709                                                                                   f,
710                                                                                   value);
711 }
712 
713 // Handles iput-quick, iput-wide-quick and iput-object-quick instructions.
714 // Returns true on success, otherwise throws an exception and returns false.
715 template<Primitive::Type field_type, bool transaction_active>
DoIPutQuick(const ShadowFrame & shadow_frame,const Instruction * inst,uint16_t inst_data)716 ALWAYS_INLINE bool DoIPutQuick(const ShadowFrame& shadow_frame, const Instruction* inst,
717                                uint16_t inst_data) REQUIRES_SHARED(Locks::mutator_lock_) {
718   ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(inst->VRegB_22c(inst_data));
719   if (UNLIKELY(obj == nullptr)) {
720     // We lost the reference to the field index so we cannot get a more
721     // precised exception message.
722     ThrowNullPointerExceptionFromDexPC();
723     return false;
724   }
725   MemberOffset field_offset(inst->VRegC_22c());
726   const uint32_t vregA = inst->VRegA_22c(inst_data);
727   // Report this field modification to instrumentation if needed. Since we only have the offset of
728   // the field from the base of the object, we need to look for it first.
729   instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
730   if (UNLIKELY(instrumentation->HasFieldWriteListeners())) {
731     ArtField* f = ArtField::FindInstanceFieldWithOffset(obj->GetClass(),
732                                                         field_offset.Uint32Value());
733     DCHECK(f != nullptr);
734     DCHECK(!f->IsStatic());
735     JValue field_value = GetFieldValue<field_type>(shadow_frame, vregA);
736     Thread* self = Thread::Current();
737     StackHandleScope<2> hs(self);
738     // Save obj in case the instrumentation event has thread suspension.
739     HandleWrapperObjPtr<mirror::Object> h = hs.NewHandleWrapper(&obj);
740     mirror::Object* fake_root = nullptr;
741     HandleWrapper<mirror::Object> ret(hs.NewHandleWrapper<mirror::Object>(
742         field_type == Primitive::kPrimNot ? field_value.GetGCRoot() : &fake_root));
743     instrumentation->FieldWriteEvent(self,
744                                      obj,
745                                      shadow_frame.GetMethod(),
746                                      shadow_frame.GetDexPC(),
747                                      f,
748                                      field_value);
749     if (UNLIKELY(self->IsExceptionPending())) {
750       return false;
751     }
752     if (UNLIKELY(shadow_frame.GetForcePopFrame())) {
753       // Don't actually set the field. The next instruction will force us to pop.
754       DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
755       return true;
756     }
757   }
758   // Note: iput-x-quick instructions are only for non-volatile fields.
759   switch (field_type) {
760     case Primitive::kPrimBoolean:
761       obj->SetFieldBoolean<transaction_active>(field_offset, shadow_frame.GetVReg(vregA));
762       break;
763     case Primitive::kPrimByte:
764       obj->SetFieldByte<transaction_active>(field_offset, shadow_frame.GetVReg(vregA));
765       break;
766     case Primitive::kPrimChar:
767       obj->SetFieldChar<transaction_active>(field_offset, shadow_frame.GetVReg(vregA));
768       break;
769     case Primitive::kPrimShort:
770       obj->SetFieldShort<transaction_active>(field_offset, shadow_frame.GetVReg(vregA));
771       break;
772     case Primitive::kPrimInt:
773       obj->SetField32<transaction_active>(field_offset, shadow_frame.GetVReg(vregA));
774       break;
775     case Primitive::kPrimLong:
776       obj->SetField64<transaction_active>(field_offset, shadow_frame.GetVRegLong(vregA));
777       break;
778     case Primitive::kPrimNot:
779       obj->SetFieldObject<transaction_active>(field_offset, shadow_frame.GetVRegReference(vregA));
780       break;
781     default:
782       LOG(FATAL) << "Unreachable: " << field_type;
783       UNREACHABLE();
784   }
785   return true;
786 }
787 
788 // Handles string resolution for const-string and const-string-jumbo instructions. Also ensures the
789 // java.lang.String class is initialized.
ResolveString(Thread * self,ShadowFrame & shadow_frame,dex::StringIndex string_idx)790 static inline ObjPtr<mirror::String> ResolveString(Thread* self,
791                                                    ShadowFrame& shadow_frame,
792                                                    dex::StringIndex string_idx)
793     REQUIRES_SHARED(Locks::mutator_lock_) {
794   ObjPtr<mirror::Class> java_lang_string_class = GetClassRoot<mirror::String>();
795   if (UNLIKELY(!java_lang_string_class->IsVisiblyInitialized())) {
796     StackHandleScope<1> hs(self);
797     Handle<mirror::Class> h_class(hs.NewHandle(java_lang_string_class));
798     if (UNLIKELY(!Runtime::Current()->GetClassLinker()->EnsureInitialized(
799                       self, h_class, /*can_init_fields=*/ true, /*can_init_parents=*/ true))) {
800       DCHECK(self->IsExceptionPending());
801       return nullptr;
802     }
803     DCHECK(h_class->IsInitializing());
804   }
805   ArtMethod* method = shadow_frame.GetMethod();
806   ObjPtr<mirror::String> string_ptr =
807       Runtime::Current()->GetClassLinker()->ResolveString(string_idx, method);
808   return string_ptr;
809 }
810 
811 // Handles div-int, div-int/2addr, div-int/li16 and div-int/lit8 instructions.
812 // 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)813 static inline bool DoIntDivide(ShadowFrame& shadow_frame, size_t result_reg,
814                                int32_t dividend, int32_t divisor)
815     REQUIRES_SHARED(Locks::mutator_lock_) {
816   constexpr int32_t kMinInt = std::numeric_limits<int32_t>::min();
817   if (UNLIKELY(divisor == 0)) {
818     ThrowArithmeticExceptionDivideByZero();
819     return false;
820   }
821   if (UNLIKELY(dividend == kMinInt && divisor == -1)) {
822     shadow_frame.SetVReg(result_reg, kMinInt);
823   } else {
824     shadow_frame.SetVReg(result_reg, dividend / divisor);
825   }
826   return true;
827 }
828 
829 // Handles rem-int, rem-int/2addr, rem-int/li16 and rem-int/lit8 instructions.
830 // 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)831 static inline bool DoIntRemainder(ShadowFrame& shadow_frame, size_t result_reg,
832                                   int32_t dividend, int32_t divisor)
833     REQUIRES_SHARED(Locks::mutator_lock_) {
834   constexpr int32_t kMinInt = std::numeric_limits<int32_t>::min();
835   if (UNLIKELY(divisor == 0)) {
836     ThrowArithmeticExceptionDivideByZero();
837     return false;
838   }
839   if (UNLIKELY(dividend == kMinInt && divisor == -1)) {
840     shadow_frame.SetVReg(result_reg, 0);
841   } else {
842     shadow_frame.SetVReg(result_reg, dividend % divisor);
843   }
844   return true;
845 }
846 
847 // Handles div-long and div-long-2addr instructions.
848 // 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)849 static inline bool DoLongDivide(ShadowFrame& shadow_frame,
850                                 size_t result_reg,
851                                 int64_t dividend,
852                                 int64_t divisor)
853     REQUIRES_SHARED(Locks::mutator_lock_) {
854   const int64_t kMinLong = std::numeric_limits<int64_t>::min();
855   if (UNLIKELY(divisor == 0)) {
856     ThrowArithmeticExceptionDivideByZero();
857     return false;
858   }
859   if (UNLIKELY(dividend == kMinLong && divisor == -1)) {
860     shadow_frame.SetVRegLong(result_reg, kMinLong);
861   } else {
862     shadow_frame.SetVRegLong(result_reg, dividend / divisor);
863   }
864   return true;
865 }
866 
867 // Handles rem-long and rem-long-2addr instructions.
868 // 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)869 static inline bool DoLongRemainder(ShadowFrame& shadow_frame,
870                                    size_t result_reg,
871                                    int64_t dividend,
872                                    int64_t divisor)
873     REQUIRES_SHARED(Locks::mutator_lock_) {
874   const int64_t kMinLong = std::numeric_limits<int64_t>::min();
875   if (UNLIKELY(divisor == 0)) {
876     ThrowArithmeticExceptionDivideByZero();
877     return false;
878   }
879   if (UNLIKELY(dividend == kMinLong && divisor == -1)) {
880     shadow_frame.SetVRegLong(result_reg, 0);
881   } else {
882     shadow_frame.SetVRegLong(result_reg, dividend % divisor);
883   }
884   return true;
885 }
886 
887 // Handles filled-new-array and filled-new-array-range instructions.
888 // Returns true on success, otherwise throws an exception and returns false.
889 template <bool is_range, bool do_access_check, bool transaction_active>
890 bool DoFilledNewArray(const Instruction* inst, const ShadowFrame& shadow_frame,
891                       Thread* self, JValue* result);
892 
893 // Handles packed-switch instruction.
894 // Returns the branch offset to the next instruction to execute.
DoPackedSwitch(const Instruction * inst,const ShadowFrame & shadow_frame,uint16_t inst_data)895 static inline int32_t DoPackedSwitch(const Instruction* inst, const ShadowFrame& shadow_frame,
896                                      uint16_t inst_data)
897     REQUIRES_SHARED(Locks::mutator_lock_) {
898   DCHECK(inst->Opcode() == Instruction::PACKED_SWITCH);
899   const uint16_t* switch_data = reinterpret_cast<const uint16_t*>(inst) + inst->VRegB_31t();
900   int32_t test_val = shadow_frame.GetVReg(inst->VRegA_31t(inst_data));
901   DCHECK_EQ(switch_data[0], static_cast<uint16_t>(Instruction::kPackedSwitchSignature));
902   uint16_t size = switch_data[1];
903   if (size == 0) {
904     // Empty packed switch, move forward by 3 (size of PACKED_SWITCH).
905     return 3;
906   }
907   const int32_t* keys = reinterpret_cast<const int32_t*>(&switch_data[2]);
908   DCHECK_ALIGNED(keys, 4);
909   int32_t first_key = keys[0];
910   const int32_t* targets = reinterpret_cast<const int32_t*>(&switch_data[4]);
911   DCHECK_ALIGNED(targets, 4);
912   int32_t index = test_val - first_key;
913   if (index >= 0 && index < size) {
914     return targets[index];
915   } else {
916     // No corresponding value: move forward by 3 (size of PACKED_SWITCH).
917     return 3;
918   }
919 }
920 
921 // Handles sparse-switch instruction.
922 // Returns the branch offset to the next instruction to execute.
DoSparseSwitch(const Instruction * inst,const ShadowFrame & shadow_frame,uint16_t inst_data)923 static inline int32_t DoSparseSwitch(const Instruction* inst, const ShadowFrame& shadow_frame,
924                                      uint16_t inst_data)
925     REQUIRES_SHARED(Locks::mutator_lock_) {
926   DCHECK(inst->Opcode() == Instruction::SPARSE_SWITCH);
927   const uint16_t* switch_data = reinterpret_cast<const uint16_t*>(inst) + inst->VRegB_31t();
928   int32_t test_val = shadow_frame.GetVReg(inst->VRegA_31t(inst_data));
929   DCHECK_EQ(switch_data[0], static_cast<uint16_t>(Instruction::kSparseSwitchSignature));
930   uint16_t size = switch_data[1];
931   // Return length of SPARSE_SWITCH if size is 0.
932   if (size == 0) {
933     return 3;
934   }
935   const int32_t* keys = reinterpret_cast<const int32_t*>(&switch_data[2]);
936   DCHECK_ALIGNED(keys, 4);
937   const int32_t* entries = keys + size;
938   DCHECK_ALIGNED(entries, 4);
939   int lo = 0;
940   int hi = size - 1;
941   while (lo <= hi) {
942     int mid = (lo + hi) / 2;
943     int32_t foundVal = keys[mid];
944     if (test_val < foundVal) {
945       hi = mid - 1;
946     } else if (test_val > foundVal) {
947       lo = mid + 1;
948     } else {
949       return entries[mid];
950     }
951   }
952   // No corresponding value: move forward by 3 (size of SPARSE_SWITCH).
953   return 3;
954 }
955 
956 // We execute any instrumentation events triggered by throwing and/or handing the pending exception
957 // and change the shadow_frames dex_pc to the appropriate exception handler if the current method
958 // has one. If the exception has been handled and the shadow_frame is now pointing to a catch clause
959 // we return true. If the current method is unable to handle the exception we return false.
960 // This function accepts a null Instrumentation* as a way to cause instrumentation events not to be
961 // reported.
962 // TODO We might wish to reconsider how we cause some events to be ignored.
963 bool MoveToExceptionHandler(Thread* self,
964                             ShadowFrame& shadow_frame,
965                             const instrumentation::Instrumentation* instrumentation)
966     REQUIRES_SHARED(Locks::mutator_lock_);
967 
968 NO_RETURN void UnexpectedOpcode(const Instruction* inst, const ShadowFrame& shadow_frame)
969   __attribute__((cold))
970   REQUIRES_SHARED(Locks::mutator_lock_);
971 
972 // Set true if you want TraceExecution invocation before each bytecode execution.
973 constexpr bool kTraceExecutionEnabled = false;
974 
TraceExecution(const ShadowFrame & shadow_frame,const Instruction * inst,const uint32_t dex_pc)975 static inline void TraceExecution(const ShadowFrame& shadow_frame, const Instruction* inst,
976                                   const uint32_t dex_pc)
977     REQUIRES_SHARED(Locks::mutator_lock_) {
978   if (kTraceExecutionEnabled) {
979 #define TRACE_LOG std::cerr
980     std::ostringstream oss;
981     oss << shadow_frame.GetMethod()->PrettyMethod()
982         << android::base::StringPrintf("\n0x%x: ", dex_pc)
983         << inst->DumpString(shadow_frame.GetMethod()->GetDexFile()) << "\n";
984     for (uint32_t i = 0; i < shadow_frame.NumberOfVRegs(); ++i) {
985       uint32_t raw_value = shadow_frame.GetVReg(i);
986       ObjPtr<mirror::Object> ref_value = shadow_frame.GetVRegReference(i);
987       oss << android::base::StringPrintf(" vreg%u=0x%08X", i, raw_value);
988       if (ref_value != nullptr) {
989         if (ref_value->GetClass()->IsStringClass() &&
990             !ref_value->AsString()->IsValueNull()) {
991           oss << "/java.lang.String \"" << ref_value->AsString()->ToModifiedUtf8() << "\"";
992         } else {
993           oss << "/" << ref_value->PrettyTypeOf();
994         }
995       }
996     }
997     TRACE_LOG << oss.str() << "\n";
998 #undef TRACE_LOG
999   }
1000 }
1001 
IsBackwardBranch(int32_t branch_offset)1002 static inline bool IsBackwardBranch(int32_t branch_offset) {
1003   return branch_offset <= 0;
1004 }
1005 
1006 // The arg_offset is the offset to the first input register in the frame.
1007 void ArtInterpreterToCompiledCodeBridge(Thread* self,
1008                                         ArtMethod* caller,
1009                                         ShadowFrame* shadow_frame,
1010                                         uint16_t arg_offset,
1011                                         JValue* result);
1012 
IsStringInit(const DexFile * dex_file,uint32_t method_idx)1013 static inline bool IsStringInit(const DexFile* dex_file, uint32_t method_idx)
1014     REQUIRES_SHARED(Locks::mutator_lock_) {
1015   const dex::MethodId& method_id = dex_file->GetMethodId(method_idx);
1016   const char* class_name = dex_file->StringByTypeIdx(method_id.class_idx_);
1017   const char* method_name = dex_file->GetMethodName(method_id);
1018   // Instead of calling ResolveMethod() which has suspend point and can trigger
1019   // GC, look up the method symbolically.
1020   // Compare method's class name and method name against string init.
1021   // It's ok since it's not allowed to create your own java/lang/String.
1022   // TODO: verify that assumption.
1023   if ((strcmp(class_name, "Ljava/lang/String;") == 0) &&
1024       (strcmp(method_name, "<init>") == 0)) {
1025     return true;
1026   }
1027   return false;
1028 }
1029 
IsStringInit(const Instruction * instr,ArtMethod * caller)1030 static inline bool IsStringInit(const Instruction* instr, ArtMethod* caller)
1031     REQUIRES_SHARED(Locks::mutator_lock_) {
1032   if (instr->Opcode() == Instruction::INVOKE_DIRECT ||
1033       instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE) {
1034     uint16_t callee_method_idx = (instr->Opcode() == Instruction::INVOKE_DIRECT_RANGE) ?
1035         instr->VRegB_3rc() : instr->VRegB_35c();
1036     return IsStringInit(caller->GetDexFile(), callee_method_idx);
1037   }
1038   return false;
1039 }
1040 
1041 // Set string value created from StringFactory.newStringFromXXX() into all aliases of
1042 // StringFactory.newEmptyString().
1043 void SetStringInitValueToAllAliases(ShadowFrame* shadow_frame,
1044                                     uint16_t this_obj_vreg,
1045                                     JValue result);
1046 
1047 }  // namespace interpreter
1048 }  // namespace art
1049 
1050 #endif  // ART_RUNTIME_INTERPRETER_INTERPRETER_COMMON_H_
1051