entrypoint_utils.cc revision e5877a12c30afe10a5c6a1afaff7a47ef44a2a5f
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 "base/mutex.h"
20#include "class_linker-inl.h"
21#include "dex_file-inl.h"
22#include "gc/accounting/card_table-inl.h"
23#include "method_helper-inl.h"
24#include "mirror/art_field-inl.h"
25#include "mirror/art_method-inl.h"
26#include "mirror/class-inl.h"
27#include "mirror/object-inl.h"
28#include "mirror/object_array-inl.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  // Always go slow path for now, filled new array is not common.
87  gc::Heap* heap = Runtime::Current()->GetHeap();
88  // Use the current allocator type in case CheckFilledNewArrayAlloc caused us to suspend and then
89  // the heap switched the allocator type while we were suspended.
90  return mirror::Array::Alloc<false>(self, klass, component_count, klass->GetComponentSize(),
91                                     heap->GetCurrentAllocator());
92}
93
94// Helper function to allocate array for FILLED_NEW_ARRAY.
95mirror::Array* CheckAndAllocArrayFromCodeInstrumented(uint32_t type_idx, mirror::ArtMethod* referrer,
96                                                      int32_t component_count, Thread* self,
97                                                      bool access_check,
98                                                      gc::AllocatorType /* allocator_type */) {
99  mirror::Class* klass = CheckFilledNewArrayAlloc(type_idx, referrer, component_count, self,
100                                                  access_check);
101  if (UNLIKELY(klass == nullptr)) {
102    return nullptr;
103  }
104  gc::Heap* heap = Runtime::Current()->GetHeap();
105  // Use the current allocator type in case CheckFilledNewArrayAlloc caused us to suspend and then
106  // the heap switched the allocator type while we were suspended.
107  return mirror::Array::Alloc<true>(self, klass, component_count, klass->GetComponentSize(),
108                                    heap->GetCurrentAllocator());
109}
110
111void ThrowStackOverflowError(Thread* self) {
112  if (self->IsHandlingStackOverflow()) {
113      LOG(ERROR) << "Recursive stack overflow.";
114      // We don't fail here because SetStackEndForStackOverflow will print better diagnostics.
115  }
116
117  if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
118    // Remove extra entry pushed onto second stack during method tracing.
119    Runtime::Current()->GetInstrumentation()->PopMethodForUnwind(self, false);
120  }
121
122  self->SetStackEndForStackOverflow();  // Allow space on the stack for constructor to execute.
123  JNIEnvExt* env = self->GetJniEnv();
124  std::string msg("stack size ");
125  msg += PrettySize(self->GetStackSize());
126  // Use low-level JNI routine and pre-baked error class to avoid class linking operations that
127  // would consume more stack.
128  int rc = ::art::ThrowNewException(env, WellKnownClasses::java_lang_StackOverflowError,
129                                    msg.c_str(), NULL);
130  if (rc != JNI_OK) {
131    // TODO: ThrowNewException failed presumably because of an OOME, we continue to throw the OOME
132    //       or die in the CHECK below. We may want to throw a pre-baked StackOverflowError
133    //       instead.
134    LOG(ERROR) << "Couldn't throw new StackOverflowError because JNI ThrowNew failed.";
135    CHECK(self->IsExceptionPending());
136  }
137
138  bool explicit_overflow_check = Runtime::Current()->ExplicitStackOverflowChecks();
139  self->ResetDefaultStackEnd(!explicit_overflow_check);  // Return to default stack size.
140}
141
142void CheckReferenceResult(mirror::Object* o, Thread* self) {
143  if (o == NULL) {
144    return;
145  }
146  mirror::ArtMethod* m = self->GetCurrentMethod(NULL);
147  if (o == kInvalidIndirectRefObject) {
148    JniAbortF(NULL, "invalid reference returned from %s", PrettyMethod(m).c_str());
149  }
150  // Make sure that the result is an instance of the type this method was expected to return.
151  StackHandleScope<1> hs(self);
152  Handle<mirror::ArtMethod> h_m(hs.NewHandle(m));
153  mirror::Class* return_type = MethodHelper(h_m).GetReturnType();
154
155  if (!o->InstanceOf(return_type)) {
156    JniAbortF(NULL, "attempt to return an instance of %s from %s", PrettyTypeOf(o).c_str(),
157              PrettyMethod(h_m.Get()).c_str());
158  }
159}
160
161JValue InvokeProxyInvocationHandler(ScopedObjectAccessAlreadyRunnable& soa, const char* shorty,
162                                    jobject rcvr_jobj, jobject interface_method_jobj,
163                                    std::vector<jvalue>& args) {
164  DCHECK(soa.Env()->IsInstanceOf(rcvr_jobj, WellKnownClasses::java_lang_reflect_Proxy));
165
166  // Build argument array possibly triggering GC.
167  soa.Self()->AssertThreadSuspensionIsAllowable();
168  jobjectArray args_jobj = NULL;
169  const JValue zero;
170  int32_t target_sdk_version = Runtime::Current()->GetTargetSdkVersion();
171  // Do not create empty arrays unless needed to maintain Dalvik bug compatibility.
172  if (args.size() > 0 || (target_sdk_version > 0 && target_sdk_version <= 21)) {
173    args_jobj = soa.Env()->NewObjectArray(args.size(), WellKnownClasses::java_lang_Object, NULL);
174    if (args_jobj == NULL) {
175      CHECK(soa.Self()->IsExceptionPending());
176      return zero;
177    }
178    for (size_t i = 0; i < args.size(); ++i) {
179      if (shorty[i + 1] == 'L') {
180        jobject val = args.at(i).l;
181        soa.Env()->SetObjectArrayElement(args_jobj, i, val);
182      } else {
183        JValue jv;
184        jv.SetJ(args.at(i).j);
185        mirror::Object* val = BoxPrimitive(Primitive::GetType(shorty[i + 1]), jv);
186        if (val == NULL) {
187          CHECK(soa.Self()->IsExceptionPending());
188          return zero;
189        }
190        soa.Decode<mirror::ObjectArray<mirror::Object>* >(args_jobj)->Set<false>(i, val);
191      }
192    }
193  }
194
195  // Call Proxy.invoke(Proxy proxy, ArtMethod method, Object[] args).
196  jvalue invocation_args[3];
197  invocation_args[0].l = rcvr_jobj;
198  invocation_args[1].l = interface_method_jobj;
199  invocation_args[2].l = args_jobj;
200  jobject result =
201      soa.Env()->CallStaticObjectMethodA(WellKnownClasses::java_lang_reflect_Proxy,
202                                         WellKnownClasses::java_lang_reflect_Proxy_invoke,
203                                         invocation_args);
204
205  // Unbox result and handle error conditions.
206  if (LIKELY(!soa.Self()->IsExceptionPending())) {
207    if (shorty[0] == 'V' || (shorty[0] == 'L' && result == NULL)) {
208      // Do nothing.
209      return zero;
210    } else {
211      StackHandleScope<1> hs(soa.Self());
212      MethodHelper mh_interface_method(
213          hs.NewHandle(soa.Decode<mirror::ArtMethod*>(interface_method_jobj)));
214      // This can cause thread suspension.
215      mirror::Class* result_type = mh_interface_method.GetReturnType();
216      mirror::Object* result_ref = soa.Decode<mirror::Object*>(result);
217      mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
218      mirror::ArtMethod* proxy_method;
219      if (mh_interface_method.GetMethod()->GetDeclaringClass()->IsInterface()) {
220        proxy_method = rcvr->GetClass()->FindVirtualMethodForInterface(
221            mh_interface_method.GetMethod());
222      } else {
223        // Proxy dispatch to a method defined in Object.
224        DCHECK(mh_interface_method.GetMethod()->GetDeclaringClass()->IsObjectClass());
225        proxy_method = mh_interface_method.GetMethod();
226      }
227      ThrowLocation throw_location(rcvr, proxy_method, -1);
228      JValue result_unboxed;
229      if (!UnboxPrimitiveForResult(throw_location, result_ref, result_type, &result_unboxed)) {
230        DCHECK(soa.Self()->IsExceptionPending());
231        return zero;
232      }
233      return result_unboxed;
234    }
235  } else {
236    // In the case of checked exceptions that aren't declared, the exception must be wrapped by
237    // a UndeclaredThrowableException.
238    mirror::Throwable* exception = soa.Self()->GetException(NULL);
239    if (exception->IsCheckedException()) {
240      mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
241      mirror::Class* proxy_class = rcvr->GetClass();
242      mirror::ArtMethod* interface_method =
243          soa.Decode<mirror::ArtMethod*>(interface_method_jobj);
244      mirror::ArtMethod* proxy_method =
245          rcvr->GetClass()->FindVirtualMethodForInterface(interface_method);
246      int throws_index = -1;
247      size_t num_virt_methods = proxy_class->NumVirtualMethods();
248      for (size_t i = 0; i < num_virt_methods; i++) {
249        if (proxy_class->GetVirtualMethod(i) == proxy_method) {
250          throws_index = i;
251          break;
252        }
253      }
254      CHECK_NE(throws_index, -1);
255      mirror::ObjectArray<mirror::Class>* declared_exceptions = proxy_class->GetThrows()->Get(throws_index);
256      mirror::Class* exception_class = exception->GetClass();
257      bool declares_exception = false;
258      for (int i = 0; i < declared_exceptions->GetLength() && !declares_exception; i++) {
259        mirror::Class* declared_exception = declared_exceptions->Get(i);
260        declares_exception = declared_exception->IsAssignableFrom(exception_class);
261      }
262      if (!declares_exception) {
263        ThrowLocation throw_location(rcvr, proxy_method, -1);
264        soa.Self()->ThrowNewWrappedException(throw_location,
265                                             "Ljava/lang/reflect/UndeclaredThrowableException;",
266                                             NULL);
267      }
268    }
269    return zero;
270  }
271}
272}  // namespace art
273