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