interpreter_common.cc revision f832284dd847ff077577bb5712225430bbbb3b67
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_common.h"
18#include "mirror/array-inl.h"
19
20namespace art {
21namespace interpreter {
22
23static void UnstartedRuntimeInvoke(Thread* self, MethodHelper& mh,
24                                   const DexFile::CodeItem* code_item, ShadowFrame* shadow_frame,
25                                   JValue* result, size_t arg_offset)
26    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
27
28// Assign register 'src_reg' from shadow_frame to register 'dest_reg' into new_shadow_frame.
29static inline void AssignRegister(ShadowFrame* new_shadow_frame, const ShadowFrame& shadow_frame,
30                                  size_t dest_reg, size_t src_reg)
31    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
32  // If both register locations contains the same value, the register probably holds a reference.
33  // Uint required, so that sign extension does not make this wrong on 64b systems
34  uint32_t src_value = shadow_frame.GetVReg(src_reg);
35  mirror::Object* o = shadow_frame.GetVRegReference<kVerifyNone>(src_reg);
36  if (src_value == reinterpret_cast<uintptr_t>(o)) {
37    new_shadow_frame->SetVRegReference(dest_reg, o);
38  } else {
39    new_shadow_frame->SetVReg(dest_reg, src_value);
40  }
41}
42
43void AbortTransaction(Thread* self, const char* fmt, ...) {
44  CHECK(Runtime::Current()->IsActiveTransaction());
45  // Throw an exception so we can abort the transaction and undo every change.
46  va_list args;
47  va_start(args, fmt);
48  self->ThrowNewExceptionV(self->GetCurrentLocationForThrow(), "Ljava/lang/InternalError;", fmt,
49                           args);
50  va_end(args);
51}
52
53template<bool is_range, bool do_assignability_check>
54bool DoCall(ArtMethod* method, Thread* self, ShadowFrame& shadow_frame,
55            const Instruction* inst, uint16_t inst_data, JValue* result) {
56  // Compute method information.
57  MethodHelper mh(method);
58  const DexFile::CodeItem* code_item = mh.GetCodeItem();
59  const uint16_t num_ins = (is_range) ? inst->VRegA_3rc(inst_data) : inst->VRegA_35c(inst_data);
60  uint16_t num_regs;
61  if (LIKELY(code_item != NULL)) {
62    num_regs = code_item->registers_size_;
63    DCHECK_EQ(num_ins, code_item->ins_size_);
64  } else {
65    DCHECK(method->IsNative() || method->IsProxyMethod());
66    num_regs = num_ins;
67  }
68
69  // Allocate shadow frame on the stack.
70  const char* old_cause = self->StartAssertNoThreadSuspension("DoCall");
71  void* memory = alloca(ShadowFrame::ComputeSize(num_regs));
72  ShadowFrame* new_shadow_frame(ShadowFrame::Create(num_regs, &shadow_frame, method, 0, memory));
73
74  // Initialize new shadow frame.
75  const size_t first_dest_reg = num_regs - num_ins;
76  if (do_assignability_check) {
77    // Slow path: we need to do runtime check on reference assignment. We need to load the shorty
78    // to get the exact type of each reference argument.
79    const DexFile::TypeList* params = mh.GetParameterTypeList();
80    const char* shorty = mh.GetShorty();
81
82    // TODO: find a cleaner way to separate non-range and range information without duplicating code.
83    uint32_t arg[5];  // only used in invoke-XXX.
84    uint32_t vregC;   // only used in invoke-XXX-range.
85    if (is_range) {
86      vregC = inst->VRegC_3rc();
87    } else {
88      inst->GetVarArgs(arg, inst_data);
89    }
90
91    // Handle receiver apart since it's not part of the shorty.
92    size_t dest_reg = first_dest_reg;
93    size_t arg_offset = 0;
94    if (!method->IsStatic()) {
95      size_t receiver_reg = (is_range) ? vregC : arg[0];
96      new_shadow_frame->SetVRegReference(dest_reg, shadow_frame.GetVRegReference(receiver_reg));
97      ++dest_reg;
98      ++arg_offset;
99    }
100    for (uint32_t shorty_pos = 0; dest_reg < num_regs; ++shorty_pos, ++dest_reg, ++arg_offset) {
101      DCHECK_LT(shorty_pos + 1, mh.GetShortyLength());
102      const size_t src_reg = (is_range) ? vregC + arg_offset : arg[arg_offset];
103      switch (shorty[shorty_pos + 1]) {
104        case 'L': {
105          Object* o = shadow_frame.GetVRegReference(src_reg);
106          if (do_assignability_check && o != NULL) {
107            Class* arg_type = mh.GetClassFromTypeIdx(params->GetTypeItem(shorty_pos).type_idx_);
108            if (arg_type == NULL) {
109              CHECK(self->IsExceptionPending());
110              self->EndAssertNoThreadSuspension(old_cause);
111              return false;
112            }
113            if (!o->VerifierInstanceOf(arg_type)) {
114              self->EndAssertNoThreadSuspension(old_cause);
115              // This should never happen.
116              self->ThrowNewExceptionF(self->GetCurrentLocationForThrow(),
117                                       "Ljava/lang/VirtualMachineError;",
118                                       "Invoking %s with bad arg %d, type '%s' not instance of '%s'",
119                                       mh.GetName(), shorty_pos,
120                                       o->GetClass()->GetDescriptor().c_str(),
121                                       arg_type->GetDescriptor().c_str());
122              return false;
123            }
124          }
125          new_shadow_frame->SetVRegReference(dest_reg, o);
126          break;
127        }
128        case 'J': case 'D': {
129          uint64_t wide_value = (static_cast<uint64_t>(shadow_frame.GetVReg(src_reg + 1)) << 32) |
130                                static_cast<uint32_t>(shadow_frame.GetVReg(src_reg));
131          new_shadow_frame->SetVRegLong(dest_reg, wide_value);
132          ++dest_reg;
133          ++arg_offset;
134          break;
135        }
136        default:
137          new_shadow_frame->SetVReg(dest_reg, shadow_frame.GetVReg(src_reg));
138          break;
139      }
140    }
141  } else {
142    // Fast path: no extra checks.
143    if (is_range) {
144      const uint16_t first_src_reg = inst->VRegC_3rc();
145      for (size_t src_reg = first_src_reg, dest_reg = first_dest_reg; dest_reg < num_regs;
146          ++dest_reg, ++src_reg) {
147        AssignRegister(new_shadow_frame, shadow_frame, dest_reg, src_reg);
148      }
149    } else {
150      DCHECK_LE(num_ins, 5U);
151      uint16_t regList = inst->Fetch16(2);
152      uint16_t count = num_ins;
153      if (count == 5) {
154        AssignRegister(new_shadow_frame, shadow_frame, first_dest_reg + 4U, (inst_data >> 8) & 0x0f);
155        --count;
156       }
157      for (size_t arg_index = 0; arg_index < count; ++arg_index, regList >>= 4) {
158        AssignRegister(new_shadow_frame, shadow_frame, first_dest_reg + arg_index, regList & 0x0f);
159      }
160    }
161  }
162  self->EndAssertNoThreadSuspension(old_cause);
163
164  // Do the call now.
165  if (LIKELY(Runtime::Current()->IsStarted())) {
166    if (kIsDebugBuild && method->GetEntryPointFromInterpreter() == nullptr) {
167      LOG(FATAL) << "Attempt to invoke non-executable method: " << PrettyMethod(method);
168    }
169    if (kIsDebugBuild && Runtime::Current()->GetInstrumentation()->IsForcedInterpretOnly() &&
170        !method->IsNative() && !method->IsProxyMethod() &&
171        method->GetEntryPointFromInterpreter() == artInterpreterToCompiledCodeBridge) {
172      LOG(FATAL) << "Attempt to call compiled code when -Xint: " << PrettyMethod(method);
173    }
174    (method->GetEntryPointFromInterpreter())(self, mh, code_item, new_shadow_frame, result);
175  } else {
176    UnstartedRuntimeInvoke(self, mh, code_item, new_shadow_frame, result, first_dest_reg);
177  }
178  return !self->IsExceptionPending();
179}
180
181template <bool is_range, bool do_access_check, bool transaction_active>
182bool DoFilledNewArray(const Instruction* inst, const ShadowFrame& shadow_frame,
183                      Thread* self, JValue* result) {
184  DCHECK(inst->Opcode() == Instruction::FILLED_NEW_ARRAY ||
185         inst->Opcode() == Instruction::FILLED_NEW_ARRAY_RANGE);
186  const int32_t length = is_range ? inst->VRegA_3rc() : inst->VRegA_35c();
187  if (!is_range) {
188    // Checks FILLED_NEW_ARRAY's length does not exceed 5 arguments.
189    CHECK_LE(length, 5);
190  }
191  if (UNLIKELY(length < 0)) {
192    ThrowNegativeArraySizeException(length);
193    return false;
194  }
195  uint16_t type_idx = is_range ? inst->VRegB_3rc() : inst->VRegB_35c();
196  Class* arrayClass = ResolveVerifyAndClinit(type_idx, shadow_frame.GetMethod(),
197                                             self, false, do_access_check);
198  if (UNLIKELY(arrayClass == NULL)) {
199    DCHECK(self->IsExceptionPending());
200    return false;
201  }
202  CHECK(arrayClass->IsArrayClass());
203  Class* componentClass = arrayClass->GetComponentType();
204  if (UNLIKELY(componentClass->IsPrimitive() && !componentClass->IsPrimitiveInt())) {
205    if (componentClass->IsPrimitiveLong() || componentClass->IsPrimitiveDouble()) {
206      ThrowRuntimeException("Bad filled array request for type %s",
207                            PrettyDescriptor(componentClass).c_str());
208    } else {
209      self->ThrowNewExceptionF(shadow_frame.GetCurrentLocationForThrow(),
210                               "Ljava/lang/InternalError;",
211                               "Found type %s; filled-new-array not implemented for anything but 'int'",
212                               PrettyDescriptor(componentClass).c_str());
213    }
214    return false;
215  }
216  Object* newArray = Array::Alloc<true>(self, arrayClass, length, arrayClass->GetComponentSize(),
217                                        Runtime::Current()->GetHeap()->GetCurrentAllocator());
218  if (UNLIKELY(newArray == NULL)) {
219    DCHECK(self->IsExceptionPending());
220    return false;
221  }
222  uint32_t arg[5];  // only used in filled-new-array.
223  uint32_t vregC;   // only used in filled-new-array-range.
224  if (is_range) {
225    vregC = inst->VRegC_3rc();
226  } else {
227    inst->GetVarArgs(arg);
228  }
229  const bool is_primitive_int_component = componentClass->IsPrimitiveInt();
230  for (int32_t i = 0; i < length; ++i) {
231    size_t src_reg = is_range ? vregC + i : arg[i];
232    if (is_primitive_int_component) {
233      newArray->AsIntArray()->SetWithoutChecks<transaction_active>(i, shadow_frame.GetVReg(src_reg));
234    } else {
235      newArray->AsObjectArray<Object>()->SetWithoutChecks<transaction_active>(i, shadow_frame.GetVRegReference(src_reg));
236    }
237  }
238
239  result->SetL(newArray);
240  return true;
241}
242
243// TODO fix thread analysis: should be SHARED_LOCKS_REQUIRED(Locks::mutator_lock_).
244template<typename T>
245static void RecordArrayElementsInTransactionImpl(mirror::PrimitiveArray<T>* array, int32_t count)
246    NO_THREAD_SAFETY_ANALYSIS {
247  Runtime* runtime = Runtime::Current();
248  for (int32_t i = 0; i < count; ++i) {
249    runtime->RecordWriteArray(array, i, array->GetWithoutChecks(i));
250  }
251}
252
253void RecordArrayElementsInTransaction(mirror::Array* array, int32_t count)
254    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
255  DCHECK(Runtime::Current()->IsActiveTransaction());
256  DCHECK(array != nullptr);
257  DCHECK_LE(count, array->GetLength());
258  Primitive::Type primitive_component_type = array->GetClass()->GetComponentType()->GetPrimitiveType();
259  switch (primitive_component_type) {
260    case Primitive::kPrimBoolean:
261      RecordArrayElementsInTransactionImpl(array->AsBooleanArray(), count);
262      break;
263    case Primitive::kPrimByte:
264      RecordArrayElementsInTransactionImpl(array->AsByteArray(), count);
265      break;
266    case Primitive::kPrimChar:
267      RecordArrayElementsInTransactionImpl(array->AsCharArray(), count);
268      break;
269    case Primitive::kPrimShort:
270      RecordArrayElementsInTransactionImpl(array->AsShortArray(), count);
271      break;
272    case Primitive::kPrimInt:
273    case Primitive::kPrimFloat:
274      RecordArrayElementsInTransactionImpl(array->AsIntArray(), count);
275      break;
276    case Primitive::kPrimLong:
277    case Primitive::kPrimDouble:
278      RecordArrayElementsInTransactionImpl(array->AsLongArray(), count);
279      break;
280    default:
281      LOG(FATAL) << "Unsupported primitive type " << primitive_component_type
282                 << " in fill-array-data";
283      break;
284  }
285}
286
287static void UnstartedRuntimeInvoke(Thread* self, MethodHelper& mh,
288                                   const DexFile::CodeItem* code_item, ShadowFrame* shadow_frame,
289                                   JValue* result, size_t arg_offset) {
290  // In a runtime that's not started we intercept certain methods to avoid complicated dependency
291  // problems in core libraries.
292  std::string name(PrettyMethod(shadow_frame->GetMethod()));
293  if (name == "java.lang.Class java.lang.Class.forName(java.lang.String)"
294      || name == "java.lang.Class java.lang.VMClassLoader.loadClass(java.lang.String, boolean)") {
295    // TODO Class#forName should actually call Class::EnsureInitialized always. Support for the
296    // other variants that take more arguments should also be added.
297    std::string descriptor(DotToDescriptor(shadow_frame->GetVRegReference(arg_offset)->AsString()->ToModifiedUtf8().c_str()));
298
299    StackHandleScope<1> hs(self);
300    // shadow_frame.GetMethod()->GetDeclaringClass()->GetClassLoader();
301    auto class_loader = hs.NewHandle<ClassLoader>(nullptr);
302    Class* found = Runtime::Current()->GetClassLinker()->FindClass(self, descriptor.c_str(),
303                                                                   class_loader);
304    CHECK(found != NULL) << "Class.forName failed in un-started runtime for class: "
305        << PrettyDescriptor(descriptor);
306    result->SetL(found);
307  } else if (name == "java.lang.Class java.lang.Void.lookupType()") {
308    result->SetL(Runtime::Current()->GetClassLinker()->FindPrimitiveClass('V'));
309  } else if (name == "java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String)") {
310    StackHandleScope<1> hs(self);
311    Handle<ClassLoader> class_loader(
312        hs.NewHandle(down_cast<mirror::ClassLoader*>(shadow_frame->GetVRegReference(arg_offset))));
313    std::string descriptor(DotToDescriptor(shadow_frame->GetVRegReference(arg_offset + 1)->AsString()->ToModifiedUtf8().c_str()));
314
315    Class* found = Runtime::Current()->GetClassLinker()->FindClass(self, descriptor.c_str(),
316                                                                   class_loader);
317    result->SetL(found);
318  } else if (name == "java.lang.Object java.lang.Class.newInstance()") {
319    Class* klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
320    ArtMethod* c = klass->FindDeclaredDirectMethod("<init>", "()V");
321    CHECK(c != NULL);
322    StackHandleScope<1> hs(self);
323    Handle<Object> obj(hs.NewHandle(klass->AllocObject(self)));
324    CHECK(obj.Get() != NULL);
325    EnterInterpreterFromInvoke(self, c, obj.Get(), NULL, NULL);
326    result->SetL(obj.Get());
327  } else if (name == "java.lang.reflect.Field java.lang.Class.getDeclaredField(java.lang.String)") {
328    // Special managed code cut-out to allow field lookup in a un-started runtime that'd fail
329    // going the reflective Dex way.
330    Class* klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
331    String* name = shadow_frame->GetVRegReference(arg_offset + 1)->AsString();
332    ArtField* found = NULL;
333    FieldHelper fh;
334    ObjectArray<ArtField>* fields = klass->GetIFields();
335    for (int32_t i = 0; i < fields->GetLength() && found == NULL; ++i) {
336      ArtField* f = fields->Get(i);
337      fh.ChangeField(f);
338      if (name->Equals(fh.GetName())) {
339        found = f;
340      }
341    }
342    if (found == NULL) {
343      fields = klass->GetSFields();
344      for (int32_t i = 0; i < fields->GetLength() && found == NULL; ++i) {
345        ArtField* f = fields->Get(i);
346        fh.ChangeField(f);
347        if (name->Equals(fh.GetName())) {
348          found = f;
349        }
350      }
351    }
352    CHECK(found != NULL)
353      << "Failed to find field in Class.getDeclaredField in un-started runtime. name="
354      << name->ToModifiedUtf8() << " class=" << PrettyDescriptor(klass);
355    // TODO: getDeclaredField calls GetType once the field is found to ensure a
356    //       NoClassDefFoundError is thrown if the field's type cannot be resolved.
357    Class* jlr_Field = self->DecodeJObject(WellKnownClasses::java_lang_reflect_Field)->AsClass();
358    StackHandleScope<1> hs(self);
359    Handle<Object> field(hs.NewHandle(jlr_Field->AllocNonMovableObject(self)));
360    CHECK(field.Get() != NULL);
361    ArtMethod* c = jlr_Field->FindDeclaredDirectMethod("<init>", "(Ljava/lang/reflect/ArtField;)V");
362    uint32_t args[1];
363    args[0] = StackReference<mirror::Object>::FromMirrorPtr(found).AsVRegValue();
364    EnterInterpreterFromInvoke(self, c, field.Get(), args, NULL);
365    result->SetL(field.Get());
366  } else if (name == "int java.lang.Object.hashCode()") {
367    Object* obj = shadow_frame->GetVRegReference(arg_offset);
368    result->SetI(obj->IdentityHashCode());
369  } else if (name == "java.lang.String java.lang.reflect.ArtMethod.getMethodName(java.lang.reflect.ArtMethod)") {
370    ArtMethod* method = shadow_frame->GetVRegReference(arg_offset)->AsArtMethod();
371    result->SetL(MethodHelper(method).GetNameAsString());
372  } else if (name == "void java.lang.System.arraycopy(java.lang.Object, int, java.lang.Object, int, int)" ||
373             name == "void java.lang.System.arraycopy(char[], int, char[], int, int)") {
374    // Special case array copying without initializing System.
375    Class* ctype = shadow_frame->GetVRegReference(arg_offset)->GetClass()->GetComponentType();
376    jint srcPos = shadow_frame->GetVReg(arg_offset + 1);
377    jint dstPos = shadow_frame->GetVReg(arg_offset + 3);
378    jint length = shadow_frame->GetVReg(arg_offset + 4);
379    if (!ctype->IsPrimitive()) {
380      ObjectArray<Object>* src = shadow_frame->GetVRegReference(arg_offset)->AsObjectArray<Object>();
381      ObjectArray<Object>* dst = shadow_frame->GetVRegReference(arg_offset + 2)->AsObjectArray<Object>();
382      for (jint i = 0; i < length; ++i) {
383        dst->Set(dstPos + i, src->Get(srcPos + i));
384      }
385    } else if (ctype->IsPrimitiveChar()) {
386      CharArray* src = shadow_frame->GetVRegReference(arg_offset)->AsCharArray();
387      CharArray* dst = shadow_frame->GetVRegReference(arg_offset + 2)->AsCharArray();
388      for (jint i = 0; i < length; ++i) {
389        dst->Set(dstPos + i, src->Get(srcPos + i));
390      }
391    } else if (ctype->IsPrimitiveInt()) {
392      IntArray* src = shadow_frame->GetVRegReference(arg_offset)->AsIntArray();
393      IntArray* dst = shadow_frame->GetVRegReference(arg_offset + 2)->AsIntArray();
394      for (jint i = 0; i < length; ++i) {
395        dst->Set(dstPos + i, src->Get(srcPos + i));
396      }
397    } else {
398      self->ThrowNewExceptionF(self->GetCurrentLocationForThrow(), "Ljava/lang/InternalError;",
399                               "Unimplemented System.arraycopy for type '%s'",
400                               PrettyDescriptor(ctype).c_str());
401    }
402  } else  if (name == "java.lang.Object java.lang.ThreadLocal.get()") {
403    std::string caller(PrettyMethod(shadow_frame->GetLink()->GetMethod()));
404    if (caller == "java.lang.String java.lang.IntegralToString.convertInt(java.lang.AbstractStringBuilder, int)") {
405      // Allocate non-threadlocal buffer.
406      result->SetL(mirror::CharArray::Alloc(self, 11));
407    } else {
408      self->ThrowNewException(self->GetCurrentLocationForThrow(), "Ljava/lang/InternalError;",
409                              "Unimplemented ThreadLocal.get");
410    }
411  } else {
412    // Not special, continue with regular interpreter execution.
413    artInterpreterToInterpreterBridge(self, mh, code_item, shadow_frame, result);
414  }
415}
416
417// Explicit DoCall template function declarations.
418#define EXPLICIT_DO_CALL_TEMPLATE_DECL(_is_range, _do_assignability_check)                      \
419  template SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)                                          \
420  bool DoCall<_is_range, _do_assignability_check>(ArtMethod* method, Thread* self,              \
421                                                  ShadowFrame& shadow_frame,                    \
422                                                  const Instruction* inst, uint16_t inst_data,  \
423                                                  JValue* result)
424EXPLICIT_DO_CALL_TEMPLATE_DECL(false, false);
425EXPLICIT_DO_CALL_TEMPLATE_DECL(false, true);
426EXPLICIT_DO_CALL_TEMPLATE_DECL(true, false);
427EXPLICIT_DO_CALL_TEMPLATE_DECL(true, true);
428#undef EXPLICIT_DO_CALL_TEMPLATE_DECL
429
430// Explicit DoFilledNewArray template function declarations.
431#define EXPLICIT_DO_FILLED_NEW_ARRAY_TEMPLATE_DECL(_is_range_, _check, _transaction_active)       \
432  template SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)                                            \
433  bool DoFilledNewArray<_is_range_, _check, _transaction_active>(const Instruction* inst,         \
434                                                                 const ShadowFrame& shadow_frame, \
435                                                                 Thread* self, JValue* result)
436#define EXPLICIT_DO_FILLED_NEW_ARRAY_ALL_TEMPLATE_DECL(_transaction_active)       \
437  EXPLICIT_DO_FILLED_NEW_ARRAY_TEMPLATE_DECL(false, false, _transaction_active);  \
438  EXPLICIT_DO_FILLED_NEW_ARRAY_TEMPLATE_DECL(false, true, _transaction_active);   \
439  EXPLICIT_DO_FILLED_NEW_ARRAY_TEMPLATE_DECL(true, false, _transaction_active);   \
440  EXPLICIT_DO_FILLED_NEW_ARRAY_TEMPLATE_DECL(true, true, _transaction_active)
441EXPLICIT_DO_FILLED_NEW_ARRAY_ALL_TEMPLATE_DECL(false);
442EXPLICIT_DO_FILLED_NEW_ARRAY_ALL_TEMPLATE_DECL(true);
443#undef EXPLICIT_DO_FILLED_NEW_ARRAY_ALL_TEMPLATE_DECL
444#undef EXPLICIT_DO_FILLED_NEW_ARRAY_TEMPLATE_DECL
445
446}  // namespace interpreter
447}  // namespace art
448