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 "art_field-inl.h"
20 #include "art_method-inl.h"
21 #include "base/mutex.h"
22 #include "class_linker-inl.h"
23 #include "dex_file-inl.h"
24 #include "gc/accounting/card_table-inl.h"
25 #include "mirror/class-inl.h"
26 #include "mirror/method.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 
34 namespace art {
35 
CheckFilledNewArrayAlloc(uint32_t type_idx,int32_t component_count,ArtMethod * referrer,Thread * self,bool access_check)36 static inline mirror::Class* CheckFilledNewArrayAlloc(uint32_t type_idx,
37                                                       int32_t component_count,
38                                                       ArtMethod* referrer,
39                                                       Thread* self,
40                                                       bool access_check)
41     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
42   if (UNLIKELY(component_count < 0)) {
43     ThrowNegativeArraySizeException(component_count);
44     return nullptr;  // Failure
45   }
46   mirror::Class* klass = referrer->GetDexCacheResolvedType<false>(type_idx);
47   if (UNLIKELY(klass == nullptr)) {  // Not in dex cache so try to resolve
48     klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, referrer);
49     if (klass == nullptr) {  // Error
50       DCHECK(self->IsExceptionPending());
51       return nullptr;  // Failure
52     }
53   }
54   if (UNLIKELY(klass->IsPrimitive() && !klass->IsPrimitiveInt())) {
55     if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
56       ThrowRuntimeException("Bad filled array request for type %s",
57                             PrettyDescriptor(klass).c_str());
58     } else {
59       self->ThrowNewExceptionF(
60           "Ljava/lang/InternalError;",
61           "Found type %s; filled-new-array not implemented for anything but 'int'",
62           PrettyDescriptor(klass).c_str());
63     }
64     return nullptr;  // Failure
65   }
66   if (access_check) {
67     mirror::Class* referrer_klass = referrer->GetDeclaringClass();
68     if (UNLIKELY(!referrer_klass->CanAccess(klass))) {
69       ThrowIllegalAccessErrorClass(referrer_klass, klass);
70       return nullptr;  // Failure
71     }
72   }
73   DCHECK(klass->IsArrayClass()) << PrettyClass(klass);
74   return klass;
75 }
76 
77 // Helper function to allocate array for FILLED_NEW_ARRAY.
CheckAndAllocArrayFromCode(uint32_t type_idx,int32_t component_count,ArtMethod * referrer,Thread * self,bool access_check,gc::AllocatorType)78 mirror::Array* CheckAndAllocArrayFromCode(uint32_t type_idx, int32_t component_count,
79                                           ArtMethod* referrer, Thread* self,
80                                           bool access_check,
81                                           gc::AllocatorType /* allocator_type */) {
82   mirror::Class* klass = CheckFilledNewArrayAlloc(type_idx, component_count, referrer, self,
83                                                   access_check);
84   if (UNLIKELY(klass == nullptr)) {
85     return nullptr;
86   }
87   // Always go slow path for now, filled new array is not common.
88   gc::Heap* heap = Runtime::Current()->GetHeap();
89   // Use the current allocator type in case CheckFilledNewArrayAlloc caused us to suspend and then
90   // the heap switched the allocator type while we were suspended.
91   return mirror::Array::Alloc<false>(self, klass, component_count,
92                                      klass->GetComponentSizeShift(),
93                                      heap->GetCurrentAllocator());
94 }
95 
96 // Helper function to allocate array for FILLED_NEW_ARRAY.
CheckAndAllocArrayFromCodeInstrumented(uint32_t type_idx,int32_t component_count,ArtMethod * referrer,Thread * self,bool access_check,gc::AllocatorType)97 mirror::Array* CheckAndAllocArrayFromCodeInstrumented(uint32_t type_idx,
98                                                       int32_t component_count,
99                                                       ArtMethod* referrer,
100                                                       Thread* self,
101                                                       bool access_check,
102                                                       gc::AllocatorType /* allocator_type */) {
103   mirror::Class* klass = CheckFilledNewArrayAlloc(type_idx, component_count, referrer, self,
104                                                   access_check);
105   if (UNLIKELY(klass == nullptr)) {
106     return nullptr;
107   }
108   gc::Heap* heap = Runtime::Current()->GetHeap();
109   // Use the current allocator type in case CheckFilledNewArrayAlloc caused us to suspend and then
110   // the heap switched the allocator type while we were suspended.
111   return mirror::Array::Alloc<true>(self, klass, component_count,
112                                     klass->GetComponentSizeShift(),
113                                     heap->GetCurrentAllocator());
114 }
115 
ThrowStackOverflowError(Thread * self)116 void ThrowStackOverflowError(Thread* self) {
117   if (self->IsHandlingStackOverflow()) {
118     LOG(ERROR) << "Recursive stack overflow.";
119     // We don't fail here because SetStackEndForStackOverflow will print better diagnostics.
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       env->SetObjectField(exc.get(), WellKnownClasses::java_lang_Throwable_detailMessage, s.get());
153 
154       // cause.
155       env->SetObjectField(exc.get(), WellKnownClasses::java_lang_Throwable_cause, exc.get());
156 
157       // suppressedExceptions.
158       ScopedLocalRef<jobject> emptylist(env, env->GetStaticObjectField(
159           WellKnownClasses::java_util_Collections,
160           WellKnownClasses::java_util_Collections_EMPTY_LIST));
161       CHECK(emptylist.get() != nullptr);
162       env->SetObjectField(exc.get(),
163                           WellKnownClasses::java_lang_Throwable_suppressedExceptions,
164                           emptylist.get());
165 
166       // stackState is set as result of fillInStackTrace. fillInStackTrace calls
167       // nativeFillInStackTrace.
168       ScopedLocalRef<jobject> stack_state_val(env, nullptr);
169       {
170         ScopedObjectAccessUnchecked soa(env);
171         stack_state_val.reset(soa.Self()->CreateInternalStackTrace<false>(soa));
172       }
173       if (stack_state_val.get() != nullptr) {
174         env->SetObjectField(exc.get(),
175                             WellKnownClasses::java_lang_Throwable_stackState,
176                             stack_state_val.get());
177 
178         // stackTrace.
179         ScopedLocalRef<jobject> stack_trace_elem(env, env->GetStaticObjectField(
180             WellKnownClasses::libcore_util_EmptyArray,
181             WellKnownClasses::libcore_util_EmptyArray_STACK_TRACE_ELEMENT));
182         env->SetObjectField(exc.get(),
183                             WellKnownClasses::java_lang_Throwable_stackTrace,
184                             stack_trace_elem.get());
185       } else {
186         error_msg = "Could not create stack trace.";
187       }
188       // Throw the exception.
189       self->SetException(reinterpret_cast<mirror::Throwable*>(self->DecodeJObject(exc.get())));
190     } else {
191       // Could not allocate a string object.
192       error_msg = "Couldn't throw new StackOverflowError because JNI NewStringUTF failed.";
193     }
194   } else {
195     error_msg = "Could not allocate StackOverflowError object.";
196   }
197 
198   if (!error_msg.empty()) {
199     LOG(WARNING) << error_msg;
200     CHECK(self->IsExceptionPending());
201   }
202 
203   bool explicit_overflow_check = Runtime::Current()->ExplicitStackOverflowChecks();
204   self->ResetDefaultStackEnd();  // Return to default stack size.
205 
206   // And restore protection if implicit checks are on.
207   if (!explicit_overflow_check) {
208     self->ProtectStack();
209   }
210 }
211 
CheckReferenceResult(mirror::Object * o,Thread * self)212 void CheckReferenceResult(mirror::Object* o, Thread* self) {
213   if (o == nullptr) {
214     return;
215   }
216   // Make sure that the result is an instance of the type this method was expected to return.
217   mirror::Class* return_type = self->GetCurrentMethod(nullptr)->GetReturnType();
218 
219   if (!o->InstanceOf(return_type)) {
220     Runtime::Current()->GetJavaVM()->JniAbortF(nullptr,
221                                                "attempt to return an instance of %s from %s",
222                                                PrettyTypeOf(o).c_str(),
223                                                PrettyMethod(self->GetCurrentMethod(nullptr)).c_str());
224   }
225 }
226 
InvokeProxyInvocationHandler(ScopedObjectAccessAlreadyRunnable & soa,const char * shorty,jobject rcvr_jobj,jobject interface_method_jobj,std::vector<jvalue> & args)227 JValue InvokeProxyInvocationHandler(ScopedObjectAccessAlreadyRunnable& soa, const char* shorty,
228                                     jobject rcvr_jobj, jobject interface_method_jobj,
229                                     std::vector<jvalue>& args) {
230   DCHECK(soa.Env()->IsInstanceOf(rcvr_jobj, WellKnownClasses::java_lang_reflect_Proxy));
231 
232   // Build argument array possibly triggering GC.
233   soa.Self()->AssertThreadSuspensionIsAllowable();
234   jobjectArray args_jobj = nullptr;
235   const JValue zero;
236   int32_t target_sdk_version = Runtime::Current()->GetTargetSdkVersion();
237   // Do not create empty arrays unless needed to maintain Dalvik bug compatibility.
238   if (args.size() > 0 || (target_sdk_version > 0 && target_sdk_version <= 21)) {
239     args_jobj = soa.Env()->NewObjectArray(args.size(), WellKnownClasses::java_lang_Object, nullptr);
240     if (args_jobj == nullptr) {
241       CHECK(soa.Self()->IsExceptionPending());
242       return zero;
243     }
244     for (size_t i = 0; i < args.size(); ++i) {
245       if (shorty[i + 1] == 'L') {
246         jobject val = args.at(i).l;
247         soa.Env()->SetObjectArrayElement(args_jobj, i, val);
248       } else {
249         JValue jv;
250         jv.SetJ(args.at(i).j);
251         mirror::Object* val = BoxPrimitive(Primitive::GetType(shorty[i + 1]), jv);
252         if (val == nullptr) {
253           CHECK(soa.Self()->IsExceptionPending());
254           return zero;
255         }
256         soa.Decode<mirror::ObjectArray<mirror::Object>* >(args_jobj)->Set<false>(i, val);
257       }
258     }
259   }
260 
261   // Call Proxy.invoke(Proxy proxy, Method method, Object[] args).
262   jvalue invocation_args[3];
263   invocation_args[0].l = rcvr_jobj;
264   invocation_args[1].l = interface_method_jobj;
265   invocation_args[2].l = args_jobj;
266   jobject result =
267       soa.Env()->CallStaticObjectMethodA(WellKnownClasses::java_lang_reflect_Proxy,
268                                          WellKnownClasses::java_lang_reflect_Proxy_invoke,
269                                          invocation_args);
270 
271   // Unbox result and handle error conditions.
272   if (LIKELY(!soa.Self()->IsExceptionPending())) {
273     if (shorty[0] == 'V' || (shorty[0] == 'L' && result == nullptr)) {
274       // Do nothing.
275       return zero;
276     } else {
277       StackHandleScope<1> hs(soa.Self());
278       auto h_interface_method(hs.NewHandle(soa.Decode<mirror::Method*>(interface_method_jobj)));
279       // This can cause thread suspension.
280       mirror::Class* result_type = h_interface_method->GetArtMethod()->GetReturnType();
281       mirror::Object* result_ref = soa.Decode<mirror::Object*>(result);
282       JValue result_unboxed;
283       if (!UnboxPrimitiveForResult(result_ref, result_type, &result_unboxed)) {
284         DCHECK(soa.Self()->IsExceptionPending());
285         return zero;
286       }
287       return result_unboxed;
288     }
289   } else {
290     // In the case of checked exceptions that aren't declared, the exception must be wrapped by
291     // a UndeclaredThrowableException.
292     mirror::Throwable* exception = soa.Self()->GetException();
293     if (exception->IsCheckedException()) {
294       mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
295       mirror::Class* proxy_class = rcvr->GetClass();
296       mirror::Method* interface_method = soa.Decode<mirror::Method*>(interface_method_jobj);
297       ArtMethod* proxy_method = rcvr->GetClass()->FindVirtualMethodForInterface(
298           interface_method->GetArtMethod(), sizeof(void*));
299       auto* virtual_methods = proxy_class->GetVirtualMethodsPtr();
300       size_t num_virtuals = proxy_class->NumVirtualMethods();
301       size_t method_size = ArtMethod::ObjectSize(sizeof(void*));
302       int throws_index = (reinterpret_cast<uintptr_t>(proxy_method) -
303           reinterpret_cast<uintptr_t>(virtual_methods)) / method_size;
304       CHECK_LT(throws_index, static_cast<int>(num_virtuals));
305       mirror::ObjectArray<mirror::Class>* declared_exceptions =
306           proxy_class->GetThrows()->Get(throws_index);
307       mirror::Class* exception_class = exception->GetClass();
308       bool declares_exception = false;
309       for (int32_t i = 0; i < declared_exceptions->GetLength() && !declares_exception; i++) {
310         mirror::Class* declared_exception = declared_exceptions->Get(i);
311         declares_exception = declared_exception->IsAssignableFrom(exception_class);
312       }
313       if (!declares_exception) {
314         soa.Self()->ThrowNewWrappedException("Ljava/lang/reflect/UndeclaredThrowableException;",
315                                              nullptr);
316       }
317     }
318     return zero;
319   }
320 }
321 
FillArrayData(mirror::Object * obj,const Instruction::ArrayDataPayload * payload)322 bool FillArrayData(mirror::Object* obj, const Instruction::ArrayDataPayload* payload) {
323   DCHECK_EQ(payload->ident, static_cast<uint16_t>(Instruction::kArrayDataSignature));
324   if (UNLIKELY(obj == nullptr)) {
325     ThrowNullPointerException("null array in FILL_ARRAY_DATA");
326     return false;
327   }
328   mirror::Array* array = obj->AsArray();
329   DCHECK(!array->IsObjectArray());
330   if (UNLIKELY(static_cast<int32_t>(payload->element_count) > array->GetLength())) {
331     Thread* self = Thread::Current();
332     self->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
333                              "failed FILL_ARRAY_DATA; length=%d, index=%d",
334                              array->GetLength(), payload->element_count);
335     return false;
336   }
337   // Copy data from dex file to memory assuming both are little endian.
338   uint32_t size_in_bytes = payload->element_count * payload->element_width;
339   memcpy(array->GetRawData(payload->element_width, 0), payload->data, size_in_bytes);
340   return true;
341 }
342 
343 }  // namespace art
344