entrypoint_utils.cc revision 7ea6f79bbddd69d5db86a8656a31aaaf64ae2582
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
127  // Avoid running Java code for exception initialization.
128  // TODO: Checks to make this a bit less brittle.
129
130  std::string error_msg;
131
132  // Allocate an uninitialized object.
133  ScopedLocalRef<jobject> exc(env,
134                              env->AllocObject(WellKnownClasses::java_lang_StackOverflowError));
135  if (exc.get() != nullptr) {
136    // "Initialize".
137    // StackOverflowError -> VirtualMachineError -> Error -> Throwable -> Object.
138    // Only Throwable has "custom" fields:
139    //   String detailMessage.
140    //   Throwable cause (= this).
141    //   List<Throwable> suppressedExceptions (= Collections.emptyList()).
142    //   Object stackState;
143    //   StackTraceElement[] stackTrace;
144    // Only Throwable has a non-empty constructor:
145    //   this.stackTrace = EmptyArray.STACK_TRACE_ELEMENT;
146    //   fillInStackTrace();
147
148    // detailMessage.
149    // TODO: Use String::FromModifiedUTF...?
150    ScopedLocalRef<jstring> s(env, env->NewStringUTF(msg.c_str()));
151    if (s.get() != nullptr) {
152      jfieldID detail_message_id = env->GetFieldID(WellKnownClasses::java_lang_Throwable,
153                                                   "detailMessage", "Ljava/lang/String;");
154      env->SetObjectField(exc.get(), detail_message_id, s.get());
155
156      // cause.
157      jfieldID cause_id = env->GetFieldID(WellKnownClasses::java_lang_Throwable,
158                                          "cause", "Ljava/lang/Throwable;");
159      env->SetObjectField(exc.get(), cause_id, exc.get());
160
161      // suppressedExceptions.
162      jfieldID emptylist_id = env->GetStaticFieldID(WellKnownClasses::java_util_Collections,
163                                                    "EMPTY_LIST", "Ljava/util/List;");
164      ScopedLocalRef<jobject> emptylist(env, env->GetStaticObjectField(
165              WellKnownClasses::java_util_Collections, emptylist_id));
166      CHECK(emptylist.get() != nullptr);
167      jfieldID suppressed_id = env->GetFieldID(WellKnownClasses::java_lang_Throwable,
168                                               "suppressedExceptions", "Ljava/util/List;");
169      env->SetObjectField(exc.get(), suppressed_id, emptylist.get());
170
171      // stackState is set as result of fillInStackTrace. fillInStackTrace calls
172      // nativeFillInStackTrace.
173      ScopedLocalRef<jobject> stack_state_val(env, nullptr);
174      {
175        ScopedObjectAccessUnchecked soa(env);
176        stack_state_val.reset(soa.Self()->CreateInternalStackTrace<false>(soa));
177      }
178      if (stack_state_val.get() != nullptr) {
179        jfieldID stackstateID = env->GetFieldID(WellKnownClasses::java_lang_Throwable,
180            "stackState", "Ljava/lang/Object;");
181        env->SetObjectField(exc.get(), stackstateID, stack_state_val.get());
182
183        // stackTrace.
184        jfieldID stack_trace_elem_id = env->GetStaticFieldID(
185            WellKnownClasses::libcore_util_EmptyArray, "STACK_TRACE_ELEMENT",
186            "[Ljava/lang/StackTraceElement;");
187        ScopedLocalRef<jobject> stack_trace_elem(env, env->GetStaticObjectField(
188                WellKnownClasses::libcore_util_EmptyArray, stack_trace_elem_id));
189        jfieldID stacktrace_id = env->GetFieldID(
190            WellKnownClasses::java_lang_Throwable, "stackTrace", "[Ljava/lang/StackTraceElement;");
191        env->SetObjectField(exc.get(), stacktrace_id, stack_trace_elem.get());
192
193        // Throw the exception.
194        ThrowLocation throw_location = self->GetCurrentLocationForThrow();
195        self->SetException(throw_location,
196            reinterpret_cast<mirror::Throwable*>(self->DecodeJObject(exc.get())));
197      } else {
198        error_msg = "Could not create stack trace.";
199      }
200    } else {
201      // Could not allocate a string object.
202      error_msg = "Couldn't throw new StackOverflowError because JNI NewStringUTF failed.";
203    }
204  } else {
205    error_msg = "Could not allocate StackOverflowError object.";
206  }
207
208  if (!error_msg.empty()) {
209    LOG(ERROR) << error_msg;
210    CHECK(self->IsExceptionPending());
211  }
212
213  bool explicit_overflow_check = Runtime::Current()->ExplicitStackOverflowChecks();
214  self->ResetDefaultStackEnd(!explicit_overflow_check);  // Return to default stack size.
215}
216
217void CheckReferenceResult(mirror::Object* o, Thread* self) {
218  if (o == NULL) {
219    return;
220  }
221  mirror::ArtMethod* m = self->GetCurrentMethod(NULL);
222  if (o == kInvalidIndirectRefObject) {
223    JniAbortF(NULL, "invalid reference returned from %s", PrettyMethod(m).c_str());
224  }
225  // Make sure that the result is an instance of the type this method was expected to return.
226  StackHandleScope<1> hs(self);
227  Handle<mirror::ArtMethod> h_m(hs.NewHandle(m));
228  mirror::Class* return_type = MethodHelper(h_m).GetReturnType();
229
230  if (!o->InstanceOf(return_type)) {
231    JniAbortF(NULL, "attempt to return an instance of %s from %s", PrettyTypeOf(o).c_str(),
232              PrettyMethod(h_m.Get()).c_str());
233  }
234}
235
236JValue InvokeProxyInvocationHandler(ScopedObjectAccessAlreadyRunnable& soa, const char* shorty,
237                                    jobject rcvr_jobj, jobject interface_method_jobj,
238                                    std::vector<jvalue>& args) {
239  DCHECK(soa.Env()->IsInstanceOf(rcvr_jobj, WellKnownClasses::java_lang_reflect_Proxy));
240
241  // Build argument array possibly triggering GC.
242  soa.Self()->AssertThreadSuspensionIsAllowable();
243  jobjectArray args_jobj = NULL;
244  const JValue zero;
245  int32_t target_sdk_version = Runtime::Current()->GetTargetSdkVersion();
246  // Do not create empty arrays unless needed to maintain Dalvik bug compatibility.
247  if (args.size() > 0 || (target_sdk_version > 0 && target_sdk_version <= 21)) {
248    args_jobj = soa.Env()->NewObjectArray(args.size(), WellKnownClasses::java_lang_Object, NULL);
249    if (args_jobj == NULL) {
250      CHECK(soa.Self()->IsExceptionPending());
251      return zero;
252    }
253    for (size_t i = 0; i < args.size(); ++i) {
254      if (shorty[i + 1] == 'L') {
255        jobject val = args.at(i).l;
256        soa.Env()->SetObjectArrayElement(args_jobj, i, val);
257      } else {
258        JValue jv;
259        jv.SetJ(args.at(i).j);
260        mirror::Object* val = BoxPrimitive(Primitive::GetType(shorty[i + 1]), jv);
261        if (val == NULL) {
262          CHECK(soa.Self()->IsExceptionPending());
263          return zero;
264        }
265        soa.Decode<mirror::ObjectArray<mirror::Object>* >(args_jobj)->Set<false>(i, val);
266      }
267    }
268  }
269
270  // Call Proxy.invoke(Proxy proxy, ArtMethod method, Object[] args).
271  jvalue invocation_args[3];
272  invocation_args[0].l = rcvr_jobj;
273  invocation_args[1].l = interface_method_jobj;
274  invocation_args[2].l = args_jobj;
275  jobject result =
276      soa.Env()->CallStaticObjectMethodA(WellKnownClasses::java_lang_reflect_Proxy,
277                                         WellKnownClasses::java_lang_reflect_Proxy_invoke,
278                                         invocation_args);
279
280  // Unbox result and handle error conditions.
281  if (LIKELY(!soa.Self()->IsExceptionPending())) {
282    if (shorty[0] == 'V' || (shorty[0] == 'L' && result == NULL)) {
283      // Do nothing.
284      return zero;
285    } else {
286      StackHandleScope<1> hs(soa.Self());
287      MethodHelper mh_interface_method(
288          hs.NewHandle(soa.Decode<mirror::ArtMethod*>(interface_method_jobj)));
289      // This can cause thread suspension.
290      mirror::Class* result_type = mh_interface_method.GetReturnType();
291      mirror::Object* result_ref = soa.Decode<mirror::Object*>(result);
292      mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
293      mirror::ArtMethod* proxy_method;
294      if (mh_interface_method.GetMethod()->GetDeclaringClass()->IsInterface()) {
295        proxy_method = rcvr->GetClass()->FindVirtualMethodForInterface(
296            mh_interface_method.GetMethod());
297      } else {
298        // Proxy dispatch to a method defined in Object.
299        DCHECK(mh_interface_method.GetMethod()->GetDeclaringClass()->IsObjectClass());
300        proxy_method = mh_interface_method.GetMethod();
301      }
302      ThrowLocation throw_location(rcvr, proxy_method, -1);
303      JValue result_unboxed;
304      if (!UnboxPrimitiveForResult(throw_location, result_ref, result_type, &result_unboxed)) {
305        DCHECK(soa.Self()->IsExceptionPending());
306        return zero;
307      }
308      return result_unboxed;
309    }
310  } else {
311    // In the case of checked exceptions that aren't declared, the exception must be wrapped by
312    // a UndeclaredThrowableException.
313    mirror::Throwable* exception = soa.Self()->GetException(NULL);
314    if (exception->IsCheckedException()) {
315      mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
316      mirror::Class* proxy_class = rcvr->GetClass();
317      mirror::ArtMethod* interface_method =
318          soa.Decode<mirror::ArtMethod*>(interface_method_jobj);
319      mirror::ArtMethod* proxy_method =
320          rcvr->GetClass()->FindVirtualMethodForInterface(interface_method);
321      int throws_index = -1;
322      size_t num_virt_methods = proxy_class->NumVirtualMethods();
323      for (size_t i = 0; i < num_virt_methods; i++) {
324        if (proxy_class->GetVirtualMethod(i) == proxy_method) {
325          throws_index = i;
326          break;
327        }
328      }
329      CHECK_NE(throws_index, -1);
330      mirror::ObjectArray<mirror::Class>* declared_exceptions = proxy_class->GetThrows()->Get(throws_index);
331      mirror::Class* exception_class = exception->GetClass();
332      bool declares_exception = false;
333      for (int i = 0; i < declared_exceptions->GetLength() && !declares_exception; i++) {
334        mirror::Class* declared_exception = declared_exceptions->Get(i);
335        declares_exception = declared_exception->IsAssignableFrom(exception_class);
336      }
337      if (!declares_exception) {
338        ThrowLocation throw_location(rcvr, proxy_method, -1);
339        soa.Self()->ThrowNewWrappedException(throw_location,
340                                             "Ljava/lang/reflect/UndeclaredThrowableException;",
341                                             NULL);
342      }
343    }
344    return zero;
345  }
346}
347}  // namespace art
348