entrypoint_utils.cc revision 834b394ee759ed31c5371d8093d7cd8cd90014a8
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 "entrypoints/entrypoint_utils.h"
18
19#include "class_linker-inl.h"
20#include "dex_file-inl.h"
21#include "gc/accounting/card_table-inl.h"
22#include "mirror/abstract_method-inl.h"
23#include "mirror/class-inl.h"
24#include "mirror/field-inl.h"
25#include "mirror/object-inl.h"
26#include "mirror/object_array-inl.h"
27#include "mirror/proxy.h"
28#include "reflection.h"
29#include "scoped_thread_state_change.h"
30#include "ScopedLocalRef.h"
31#include "well_known_classes.h"
32
33namespace art {
34
35// Helper function to allocate array for FILLED_NEW_ARRAY.
36mirror::Array* CheckAndAllocArrayFromCode(uint32_t type_idx, mirror::AbstractMethod* referrer,
37                                          int32_t component_count, Thread* self,
38                                          bool access_check) {
39  if (UNLIKELY(component_count < 0)) {
40    ThrowNegativeArraySizeException(component_count);
41    return NULL;  // Failure
42  }
43  mirror::Class* klass = referrer->GetDexCacheResolvedTypes()->Get(type_idx);
44  if (UNLIKELY(klass == NULL)) {  // Not in dex cache so try to resolve
45    klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, referrer);
46    if (klass == NULL) {  // Error
47      DCHECK(self->IsExceptionPending());
48      return NULL;  // Failure
49    }
50  }
51  if (UNLIKELY(klass->IsPrimitive() && !klass->IsPrimitiveInt())) {
52    if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
53      ThrowRuntimeException("Bad filled array request for type %s",
54                            PrettyDescriptor(klass).c_str());
55    } else {
56      ThrowLocation throw_location = self->GetCurrentLocationForThrow();
57      DCHECK(throw_location.GetMethod() == referrer);
58      self->ThrowNewExceptionF(throw_location, "Ljava/lang/InternalError;",
59                               "Found type %s; filled-new-array not implemented for anything but \'int\'",
60                               PrettyDescriptor(klass).c_str());
61    }
62    return NULL;  // Failure
63  } else {
64    if (access_check) {
65      mirror::Class* referrer_klass = referrer->GetDeclaringClass();
66      if (UNLIKELY(!referrer_klass->CanAccess(klass))) {
67        ThrowIllegalAccessErrorClass(referrer_klass, klass);
68        return NULL;  // Failure
69      }
70    }
71    DCHECK(klass->IsArrayClass()) << PrettyClass(klass);
72    return mirror::Array::Alloc(self, klass, component_count);
73  }
74}
75
76mirror::Field* FindFieldFromCode(uint32_t field_idx, const mirror::AbstractMethod* referrer,
77                                 Thread* self, FindFieldType type, size_t expected_size,
78                                 bool access_check) {
79  bool is_primitive;
80  bool is_set;
81  bool is_static;
82  switch (type) {
83    case InstanceObjectRead:     is_primitive = false; is_set = false; is_static = false; break;
84    case InstanceObjectWrite:    is_primitive = false; is_set = true;  is_static = false; break;
85    case InstancePrimitiveRead:  is_primitive = true;  is_set = false; is_static = false; break;
86    case InstancePrimitiveWrite: is_primitive = true;  is_set = true;  is_static = false; break;
87    case StaticObjectRead:       is_primitive = false; is_set = false; is_static = true;  break;
88    case StaticObjectWrite:      is_primitive = false; is_set = true;  is_static = true;  break;
89    case StaticPrimitiveRead:    is_primitive = true;  is_set = false; is_static = true;  break;
90    case StaticPrimitiveWrite:   // Keep GCC happy by having a default handler, fall-through.
91    default:                     is_primitive = true;  is_set = true;  is_static = true;  break;
92  }
93  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
94  mirror::Field* resolved_field = class_linker->ResolveField(field_idx, referrer, is_static);
95  if (UNLIKELY(resolved_field == NULL)) {
96    DCHECK(self->IsExceptionPending());  // Throw exception and unwind.
97    return NULL;  // Failure.
98  }
99  mirror::Class* fields_class = resolved_field->GetDeclaringClass();
100  if (access_check) {
101    if (UNLIKELY(resolved_field->IsStatic() != is_static)) {
102      ThrowIncompatibleClassChangeErrorField(resolved_field, is_static, referrer);
103      return NULL;
104    }
105    mirror::Class* referring_class = referrer->GetDeclaringClass();
106    if (UNLIKELY(!referring_class->CanAccess(fields_class) ||
107                 !referring_class->CanAccessMember(fields_class,
108                                                   resolved_field->GetAccessFlags()))) {
109      // The referring class can't access the resolved field, this may occur as a result of a
110      // protected field being made public by a sub-class. Resort to the dex file to determine
111      // the correct class for the access check.
112      const DexFile& dex_file = *referring_class->GetDexCache()->GetDexFile();
113      fields_class = class_linker->ResolveType(dex_file,
114                                               dex_file.GetFieldId(field_idx).class_idx_,
115                                               referring_class);
116      if (UNLIKELY(!referring_class->CanAccess(fields_class))) {
117        ThrowIllegalAccessErrorClass(referring_class, fields_class);
118        return NULL;  // failure
119      } else if (UNLIKELY(!referring_class->CanAccessMember(fields_class,
120                                                            resolved_field->GetAccessFlags()))) {
121        ThrowIllegalAccessErrorField(referring_class, resolved_field);
122        return NULL;  // failure
123      }
124    }
125    if (UNLIKELY(is_set && resolved_field->IsFinal() && (fields_class != referring_class))) {
126      ThrowIllegalAccessErrorFinalField(referrer, resolved_field);
127      return NULL;  // failure
128    } else {
129      FieldHelper fh(resolved_field);
130      if (UNLIKELY(fh.IsPrimitiveType() != is_primitive ||
131                   fh.FieldSize() != expected_size)) {
132        ThrowLocation throw_location = self->GetCurrentLocationForThrow();
133        DCHECK(throw_location.GetMethod() == referrer);
134        self->ThrowNewExceptionF(throw_location, "Ljava/lang/NoSuchFieldError;",
135                                 "Attempted read of %zd-bit %s on field '%s'",
136                                 expected_size * (32 / sizeof(int32_t)),
137                                 is_primitive ? "primitive" : "non-primitive",
138                                 PrettyField(resolved_field, true).c_str());
139        return NULL;  // failure
140      }
141    }
142  }
143  if (!is_static) {
144    // instance fields must be being accessed on an initialized class
145    return resolved_field;
146  } else {
147    // If the class is initialized we're done.
148    if (fields_class->IsInitialized()) {
149      return resolved_field;
150    } else if (Runtime::Current()->GetClassLinker()->EnsureInitialized(fields_class, true, true)) {
151      // Otherwise let's ensure the class is initialized before resolving the field.
152      return resolved_field;
153    } else {
154      DCHECK(self->IsExceptionPending());  // Throw exception and unwind
155      return NULL;  // failure
156    }
157  }
158}
159
160// Slow path method resolution
161mirror::AbstractMethod* FindMethodFromCode(uint32_t method_idx, mirror::Object* this_object,
162                                           mirror::AbstractMethod* referrer,
163                                           Thread* self, bool access_check, InvokeType type) {
164  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
165  bool is_direct = type == kStatic || type == kDirect;
166  mirror::AbstractMethod* resolved_method = class_linker->ResolveMethod(method_idx, referrer, type);
167  if (UNLIKELY(resolved_method == NULL)) {
168    DCHECK(self->IsExceptionPending());  // Throw exception and unwind.
169    return NULL;  // Failure.
170  } else if (UNLIKELY(this_object == NULL && type != kStatic)) {
171    // Maintain interpreter-like semantics where NullPointerException is thrown
172    // after potential NoSuchMethodError from class linker.
173    ThrowLocation throw_location = self->GetCurrentLocationForThrow();
174    DCHECK(referrer == throw_location.GetMethod());
175    ThrowNullPointerExceptionForMethodAccess(throw_location, method_idx, type);
176    return NULL;  // Failure.
177  } else {
178    if (!access_check) {
179      if (is_direct) {
180        return resolved_method;
181      } else if (type == kInterface) {
182        mirror::AbstractMethod* interface_method =
183            this_object->GetClass()->FindVirtualMethodForInterface(resolved_method);
184        if (UNLIKELY(interface_method == NULL)) {
185          ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(resolved_method, this_object,
186                                                                     referrer);
187          return NULL;  // Failure.
188        } else {
189          return interface_method;
190        }
191      } else {
192        mirror::ObjectArray<mirror::AbstractMethod>* vtable;
193        uint16_t vtable_index = resolved_method->GetMethodIndex();
194        if (type == kSuper) {
195          vtable = referrer->GetDeclaringClass()->GetSuperClass()->GetVTable();
196        } else {
197          vtable = this_object->GetClass()->GetVTable();
198        }
199        // TODO: eliminate bounds check?
200        return vtable->Get(vtable_index);
201      }
202    } else {
203      // Incompatible class change should have been handled in resolve method.
204      if (UNLIKELY(resolved_method->CheckIncompatibleClassChange(type))) {
205        ThrowIncompatibleClassChangeError(type, resolved_method->GetInvokeType(), resolved_method,
206                                          referrer);
207        return NULL;  // Failure.
208      }
209      mirror::Class* methods_class = resolved_method->GetDeclaringClass();
210      mirror::Class* referring_class = referrer->GetDeclaringClass();
211      if (UNLIKELY(!referring_class->CanAccess(methods_class) ||
212                   !referring_class->CanAccessMember(methods_class,
213                                                     resolved_method->GetAccessFlags()))) {
214        // The referring class can't access the resolved method, this may occur as a result of a
215        // protected method being made public by implementing an interface that re-declares the
216        // method public. Resort to the dex file to determine the correct class for the access check
217        const DexFile& dex_file = *referring_class->GetDexCache()->GetDexFile();
218        methods_class = class_linker->ResolveType(dex_file,
219                                                  dex_file.GetMethodId(method_idx).class_idx_,
220                                                  referring_class);
221        if (UNLIKELY(!referring_class->CanAccess(methods_class))) {
222          ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
223                                                        referrer, resolved_method, type);
224          return NULL;  // Failure.
225        } else if (UNLIKELY(!referring_class->CanAccessMember(methods_class,
226                                                              resolved_method->GetAccessFlags()))) {
227          ThrowIllegalAccessErrorMethod(referring_class, resolved_method);
228          return NULL;  // Failure.
229        }
230      }
231      if (is_direct) {
232        return resolved_method;
233      } else if (type == kInterface) {
234        mirror::AbstractMethod* interface_method =
235            this_object->GetClass()->FindVirtualMethodForInterface(resolved_method);
236        if (UNLIKELY(interface_method == NULL)) {
237          ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(resolved_method, this_object,
238                                                                     referrer);
239          return NULL;  // Failure.
240        } else {
241          return interface_method;
242        }
243      } else {
244        mirror::ObjectArray<mirror::AbstractMethod>* vtable;
245        uint16_t vtable_index = resolved_method->GetMethodIndex();
246        if (type == kSuper) {
247          mirror::Class* super_class = referring_class->GetSuperClass();
248          if (LIKELY(super_class != NULL)) {
249            vtable = referring_class->GetSuperClass()->GetVTable();
250          } else {
251            vtable = NULL;
252          }
253        } else {
254          vtable = this_object->GetClass()->GetVTable();
255        }
256        if (LIKELY(vtable != NULL &&
257                   vtable_index < static_cast<uint32_t>(vtable->GetLength()))) {
258          return vtable->GetWithoutChecks(vtable_index);
259        } else {
260          // Behavior to agree with that of the verifier.
261          MethodHelper mh(resolved_method);
262          ThrowNoSuchMethodError(type, resolved_method->GetDeclaringClass(), mh.GetName(),
263                                 mh.GetSignature());
264          return NULL;  // Failure.
265        }
266      }
267    }
268  }
269}
270
271void ThrowStackOverflowError(Thread* self) {
272  CHECK(!self->IsHandlingStackOverflow()) << "Recursive stack overflow.";
273
274  if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
275    // Remove extra entry pushed onto second stack during method tracing.
276    Runtime::Current()->GetInstrumentation()->PopMethodForUnwind(self, false);
277  }
278
279  self->SetStackEndForStackOverflow();  // Allow space on the stack for constructor to execute.
280  JNIEnvExt* env = self->GetJniEnv();
281  std::string msg("stack size ");
282  msg += PrettySize(self->GetStackSize());
283  // Use low-level JNI routine and pre-baked error class to avoid class linking operations that
284  // would consume more stack.
285  int rc = ::art::ThrowNewException(env, WellKnownClasses::java_lang_StackOverflowError,
286                                    msg.c_str(), NULL);
287  if (rc != JNI_OK) {
288    // TODO: ThrowNewException failed presumably because of an OOME, we continue to throw the OOME
289    //       or die in the CHECK below. We may want to throw a pre-baked StackOverflowError
290    //       instead.
291    LOG(ERROR) << "Couldn't throw new StackOverflowError because JNI ThrowNew failed.";
292    CHECK(self->IsExceptionPending());
293  }
294  self->ResetDefaultStackEnd();  // Return to default stack size.
295}
296
297JValue InvokeProxyInvocationHandler(ScopedObjectAccessUnchecked& soa, const char* shorty,
298                                    jobject rcvr_jobj, jobject interface_method_jobj,
299                                    std::vector<jvalue>& args) {
300  DCHECK(soa.Env()->IsInstanceOf(rcvr_jobj, WellKnownClasses::java_lang_reflect_Proxy));
301
302  // Build argument array possibly triggering GC.
303  soa.Self()->AssertThreadSuspensionIsAllowable();
304  jobjectArray args_jobj = NULL;
305  const JValue zero;
306  if (args.size() > 0) {
307    args_jobj = soa.Env()->NewObjectArray(args.size(), WellKnownClasses::java_lang_Object, NULL);
308    if (args_jobj == NULL) {
309      CHECK(soa.Self()->IsExceptionPending());
310      return zero;
311    }
312    for (size_t i = 0; i < args.size(); ++i) {
313      if (shorty[i + 1] == 'L') {
314        jobject val = args.at(i).l;
315        soa.Env()->SetObjectArrayElement(args_jobj, i, val);
316      } else {
317        JValue jv;
318        jv.SetJ(args.at(i).j);
319        mirror::Object* val = BoxPrimitive(Primitive::GetType(shorty[i + 1]), jv);
320        if (val == NULL) {
321          CHECK(soa.Self()->IsExceptionPending());
322          return zero;
323        }
324        soa.Decode<mirror::ObjectArray<mirror::Object>* >(args_jobj)->Set(i, val);
325      }
326    }
327  }
328
329  // Call InvocationHandler.invoke(Object proxy, Method method, Object[] args).
330  jobject inv_hand = soa.Env()->GetObjectField(rcvr_jobj,
331                                               WellKnownClasses::java_lang_reflect_Proxy_h);
332  jvalue invocation_args[3];
333  invocation_args[0].l = rcvr_jobj;
334  invocation_args[1].l = interface_method_jobj;
335  invocation_args[2].l = args_jobj;
336  jobject result =
337      soa.Env()->CallObjectMethodA(inv_hand,
338                                   WellKnownClasses::java_lang_reflect_InvocationHandler_invoke,
339                                   invocation_args);
340
341  // Unbox result and handle error conditions.
342  if (LIKELY(!soa.Self()->IsExceptionPending())) {
343    if (shorty[0] == 'V' || (shorty[0] == 'L' && result == NULL)) {
344      // Do nothing.
345      return zero;
346    } else {
347      mirror::Object* result_ref = soa.Decode<mirror::Object*>(result);
348      mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
349      mirror::AbstractMethod* interface_method =
350          soa.Decode<mirror::AbstractMethod*>(interface_method_jobj);
351      mirror::Class* result_type = MethodHelper(interface_method).GetReturnType();
352      mirror::AbstractMethod* proxy_method;
353      if (interface_method->GetDeclaringClass()->IsInterface()) {
354        proxy_method = rcvr->GetClass()->FindVirtualMethodForInterface(interface_method);
355      } else {
356        // Proxy dispatch to a method defined in Object.
357        DCHECK(interface_method->GetDeclaringClass()->IsObjectClass());
358        proxy_method = interface_method;
359      }
360      ThrowLocation throw_location(rcvr, proxy_method, -1);
361      JValue result_unboxed;
362      if (!UnboxPrimitiveForResult(throw_location, result_ref, result_type, result_unboxed)) {
363        DCHECK(soa.Self()->IsExceptionPending());
364        return zero;
365      }
366      return result_unboxed;
367    }
368  } else {
369    // In the case of checked exceptions that aren't declared, the exception must be wrapped by
370    // a UndeclaredThrowableException.
371    mirror::Throwable* exception = soa.Self()->GetException(NULL);
372    if (exception->IsCheckedException()) {
373      mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
374      mirror::SynthesizedProxyClass* proxy_class =
375          down_cast<mirror::SynthesizedProxyClass*>(rcvr->GetClass());
376      mirror::AbstractMethod* interface_method =
377          soa.Decode<mirror::AbstractMethod*>(interface_method_jobj);
378      mirror::AbstractMethod* proxy_method =
379          rcvr->GetClass()->FindVirtualMethodForInterface(interface_method);
380      int throws_index = -1;
381      size_t num_virt_methods = proxy_class->NumVirtualMethods();
382      for (size_t i = 0; i < num_virt_methods; i++) {
383        if (proxy_class->GetVirtualMethod(i) == proxy_method) {
384          throws_index = i;
385          break;
386        }
387      }
388      CHECK_NE(throws_index, -1);
389      mirror::ObjectArray<mirror::Class>* declared_exceptions = proxy_class->GetThrows()->Get(throws_index);
390      mirror::Class* exception_class = exception->GetClass();
391      bool declares_exception = false;
392      for (int i = 0; i < declared_exceptions->GetLength() && !declares_exception; i++) {
393        mirror::Class* declared_exception = declared_exceptions->Get(i);
394        declares_exception = declared_exception->IsAssignableFrom(exception_class);
395      }
396      if (!declares_exception) {
397        ThrowLocation throw_location(rcvr, proxy_method, -1);
398        soa.Self()->ThrowNewWrappedException(throw_location,
399                                             "Ljava/lang/reflect/UndeclaredThrowableException;",
400                                             NULL);
401      }
402    }
403    return zero;
404  }
405}
406
407}  // namespace art
408