entrypoint_utils.cc revision 4fa0bcd2142793e1f105b24b658de3635652b957
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/art_field-inl.h"
23#include "mirror/art_method-inl.h"
24#include "mirror/class-inl.h"
25#include "mirror/object-inl.h"
26#include "object_utils.h"
27#include "mirror/object_array-inl.h"
28#include "mirror/proxy.h"
29#include "reflection.h"
30#include "scoped_thread_state_change.h"
31#include "ScopedLocalRef.h"
32#include "well_known_classes.h"
33
34namespace art {
35
36static inline mirror::Class* CheckFilledNewArrayAlloc(uint32_t type_idx, mirror::ArtMethod* referrer,
37                                                      int32_t component_count, Thread* self,
38                                                      bool access_check)
39    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
40  if (UNLIKELY(component_count < 0)) {
41    ThrowNegativeArraySizeException(component_count);
42    return nullptr;  // Failure
43  }
44  mirror::Class* klass = referrer->GetDexCacheResolvedTypes()->GetWithoutChecks(type_idx);
45  if (UNLIKELY(klass == NULL)) {  // Not in dex cache so try to resolve
46    klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, referrer);
47    if (klass == NULL) {  // Error
48      DCHECK(self->IsExceptionPending());
49      return nullptr;  // Failure
50    }
51  }
52  if (UNLIKELY(klass->IsPrimitive() && !klass->IsPrimitiveInt())) {
53    if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
54      ThrowRuntimeException("Bad filled array request for type %s",
55                            PrettyDescriptor(klass).c_str());
56    } else {
57      ThrowLocation throw_location = self->GetCurrentLocationForThrow();
58      DCHECK(throw_location.GetMethod() == referrer);
59      self->ThrowNewExceptionF(throw_location, "Ljava/lang/InternalError;",
60                               "Found type %s; filled-new-array not implemented for anything but 'int'",
61                               PrettyDescriptor(klass).c_str());
62    }
63    return nullptr;  // Failure
64  }
65  if (access_check) {
66    mirror::Class* referrer_klass = referrer->GetDeclaringClass();
67    if (UNLIKELY(!referrer_klass->CanAccess(klass))) {
68      ThrowIllegalAccessErrorClass(referrer_klass, klass);
69      return nullptr;  // Failure
70    }
71  }
72  DCHECK(klass->IsArrayClass()) << PrettyClass(klass);
73  return klass;
74}
75
76// Helper function to allocate array for FILLED_NEW_ARRAY.
77mirror::Array* CheckAndAllocArrayFromCode(uint32_t type_idx, mirror::ArtMethod* referrer,
78                                          int32_t component_count, Thread* self,
79                                          bool access_check,
80                                          gc::AllocatorType allocator_type) {
81  mirror::Class* klass = CheckFilledNewArrayAlloc(type_idx, referrer, component_count, self,
82                                                  access_check);
83  if (UNLIKELY(klass == nullptr)) {
84    return nullptr;
85  }
86  return mirror::Array::Alloc<false>(self, klass, component_count, allocator_type);
87}
88
89// Helper function to allocate array for FILLED_NEW_ARRAY.
90mirror::Array* CheckAndAllocArrayFromCodeInstrumented(uint32_t type_idx, mirror::ArtMethod* referrer,
91                                                      int32_t component_count, Thread* self,
92                                                      bool access_check,
93                                                      gc::AllocatorType allocator_type) {
94  mirror::Class* klass = CheckFilledNewArrayAlloc(type_idx, referrer, component_count, self,
95                                                  access_check);
96  if (UNLIKELY(klass == nullptr)) {
97    return nullptr;
98  }
99  return mirror::Array::Alloc<true>(self, klass, component_count, allocator_type);
100}
101
102void ThrowStackOverflowError(Thread* self) {
103  if (self->IsHandlingStackOverflow()) {
104      LOG(ERROR) << "Recursive stack overflow.";
105      // We don't fail here because SetStackEndForStackOverflow will print better diagnostics.
106  }
107
108  if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
109    // Remove extra entry pushed onto second stack during method tracing.
110    Runtime::Current()->GetInstrumentation()->PopMethodForUnwind(self, false);
111  }
112
113  self->SetStackEndForStackOverflow();  // Allow space on the stack for constructor to execute.
114  JNIEnvExt* env = self->GetJniEnv();
115  std::string msg("stack size ");
116  msg += PrettySize(self->GetStackSize());
117  // Use low-level JNI routine and pre-baked error class to avoid class linking operations that
118  // would consume more stack.
119  int rc = ::art::ThrowNewException(env, WellKnownClasses::java_lang_StackOverflowError,
120                                    msg.c_str(), NULL);
121  if (rc != JNI_OK) {
122    // TODO: ThrowNewException failed presumably because of an OOME, we continue to throw the OOME
123    //       or die in the CHECK below. We may want to throw a pre-baked StackOverflowError
124    //       instead.
125    LOG(ERROR) << "Couldn't throw new StackOverflowError because JNI ThrowNew failed.";
126    CHECK(self->IsExceptionPending());
127  }
128  self->ResetDefaultStackEnd();  // Return to default stack size.
129}
130
131JValue InvokeProxyInvocationHandler(ScopedObjectAccessUnchecked& soa, const char* shorty,
132                                    jobject rcvr_jobj, jobject interface_method_jobj,
133                                    std::vector<jvalue>& args) {
134  DCHECK(soa.Env()->IsInstanceOf(rcvr_jobj, WellKnownClasses::java_lang_reflect_Proxy));
135
136  // Build argument array possibly triggering GC.
137  soa.Self()->AssertThreadSuspensionIsAllowable();
138  jobjectArray args_jobj = NULL;
139  const JValue zero;
140  if (args.size() > 0) {
141    args_jobj = soa.Env()->NewObjectArray(args.size(), WellKnownClasses::java_lang_Object, NULL);
142    if (args_jobj == NULL) {
143      CHECK(soa.Self()->IsExceptionPending());
144      return zero;
145    }
146    for (size_t i = 0; i < args.size(); ++i) {
147      if (shorty[i + 1] == 'L') {
148        jobject val = args.at(i).l;
149        soa.Env()->SetObjectArrayElement(args_jobj, i, val);
150      } else {
151        JValue jv;
152        jv.SetJ(args.at(i).j);
153        mirror::Object* val = BoxPrimitive(Primitive::GetType(shorty[i + 1]), jv);
154        if (val == NULL) {
155          CHECK(soa.Self()->IsExceptionPending());
156          return zero;
157        }
158        soa.Decode<mirror::ObjectArray<mirror::Object>* >(args_jobj)->Set(i, val);
159      }
160    }
161  }
162
163  // Call Proxy.invoke(Proxy proxy, ArtMethod method, Object[] args).
164  jvalue invocation_args[3];
165  invocation_args[0].l = rcvr_jobj;
166  invocation_args[1].l = interface_method_jobj;
167  invocation_args[2].l = args_jobj;
168  jobject result =
169      soa.Env()->CallStaticObjectMethodA(WellKnownClasses::java_lang_reflect_Proxy,
170                                         WellKnownClasses::java_lang_reflect_Proxy_invoke,
171                                         invocation_args);
172
173  // Unbox result and handle error conditions.
174  if (LIKELY(!soa.Self()->IsExceptionPending())) {
175    if (shorty[0] == 'V' || (shorty[0] == 'L' && result == NULL)) {
176      // Do nothing.
177      return zero;
178    } else {
179      mirror::Object* result_ref = soa.Decode<mirror::Object*>(result);
180      mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
181      mirror::ArtMethod* interface_method =
182          soa.Decode<mirror::ArtMethod*>(interface_method_jobj);
183      mirror::Class* result_type = MethodHelper(interface_method).GetReturnType();
184      mirror::ArtMethod* proxy_method;
185      if (interface_method->GetDeclaringClass()->IsInterface()) {
186        proxy_method = rcvr->GetClass()->FindVirtualMethodForInterface(interface_method);
187      } else {
188        // Proxy dispatch to a method defined in Object.
189        DCHECK(interface_method->GetDeclaringClass()->IsObjectClass());
190        proxy_method = interface_method;
191      }
192      ThrowLocation throw_location(rcvr, proxy_method, -1);
193      JValue result_unboxed;
194      if (!UnboxPrimitiveForResult(throw_location, result_ref, result_type, result_unboxed)) {
195        DCHECK(soa.Self()->IsExceptionPending());
196        return zero;
197      }
198      return result_unboxed;
199    }
200  } else {
201    // In the case of checked exceptions that aren't declared, the exception must be wrapped by
202    // a UndeclaredThrowableException.
203    mirror::Throwable* exception = soa.Self()->GetException(NULL);
204    if (exception->IsCheckedException()) {
205      mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
206      mirror::SynthesizedProxyClass* proxy_class =
207          down_cast<mirror::SynthesizedProxyClass*>(rcvr->GetClass());
208      mirror::ArtMethod* interface_method =
209          soa.Decode<mirror::ArtMethod*>(interface_method_jobj);
210      mirror::ArtMethod* proxy_method =
211          rcvr->GetClass()->FindVirtualMethodForInterface(interface_method);
212      int throws_index = -1;
213      size_t num_virt_methods = proxy_class->NumVirtualMethods();
214      for (size_t i = 0; i < num_virt_methods; i++) {
215        if (proxy_class->GetVirtualMethod(i) == proxy_method) {
216          throws_index = i;
217          break;
218        }
219      }
220      CHECK_NE(throws_index, -1);
221      mirror::ObjectArray<mirror::Class>* declared_exceptions = proxy_class->GetThrows()->Get(throws_index);
222      mirror::Class* exception_class = exception->GetClass();
223      bool declares_exception = false;
224      for (int i = 0; i < declared_exceptions->GetLength() && !declares_exception; i++) {
225        mirror::Class* declared_exception = declared_exceptions->Get(i);
226        declares_exception = declared_exception->IsAssignableFrom(exception_class);
227      }
228      if (!declares_exception) {
229        ThrowLocation throw_location(rcvr, proxy_method, -1);
230        soa.Self()->ThrowNewWrappedException(throw_location,
231                                             "Ljava/lang/reflect/UndeclaredThrowableException;",
232                                             NULL);
233      }
234    }
235    return zero;
236  }
237}
238}  // namespace art
239