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
34 namespace art {
35
CheckFilledNewArrayAlloc(uint32_t type_idx,mirror::ArtMethod * referrer,int32_t component_count,Thread * self,bool access_check)36 static inline mirror::Class* CheckFilledNewArrayAlloc(uint32_t type_idx,
37 mirror::ArtMethod* referrer,
38 int32_t component_count,
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 == NULL)) { // Not in dex cache so try to resolve
48 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, referrer);
49 if (klass == NULL) { // 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 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
60 DCHECK(throw_location.GetMethod() == referrer);
61 self->ThrowNewExceptionF(
62 throw_location, "Ljava/lang/InternalError;",
63 "Found type %s; filled-new-array not implemented for anything but 'int'",
64 PrettyDescriptor(klass).c_str());
65 }
66 return nullptr; // Failure
67 }
68 if (access_check) {
69 mirror::Class* referrer_klass = referrer->GetDeclaringClass();
70 if (UNLIKELY(!referrer_klass->CanAccess(klass))) {
71 ThrowIllegalAccessErrorClass(referrer_klass, klass);
72 return nullptr; // Failure
73 }
74 }
75 DCHECK(klass->IsArrayClass()) << PrettyClass(klass);
76 return klass;
77 }
78
79 // Helper function to allocate array for FILLED_NEW_ARRAY.
CheckAndAllocArrayFromCode(uint32_t type_idx,mirror::ArtMethod * referrer,int32_t component_count,Thread * self,bool access_check,gc::AllocatorType)80 mirror::Array* CheckAndAllocArrayFromCode(uint32_t type_idx, mirror::ArtMethod* referrer,
81 int32_t component_count, Thread* self,
82 bool access_check,
83 gc::AllocatorType /* allocator_type */) {
84 mirror::Class* klass = CheckFilledNewArrayAlloc(type_idx, referrer, component_count, self,
85 access_check);
86 if (UNLIKELY(klass == nullptr)) {
87 return nullptr;
88 }
89 // Always go slow path for now, filled new array is not common.
90 gc::Heap* heap = Runtime::Current()->GetHeap();
91 // Use the current allocator type in case CheckFilledNewArrayAlloc caused us to suspend and then
92 // the heap switched the allocator type while we were suspended.
93 return mirror::Array::Alloc<false>(self, klass, component_count, klass->GetComponentSize(),
94 heap->GetCurrentAllocator());
95 }
96
97 // Helper function to allocate array for FILLED_NEW_ARRAY.
CheckAndAllocArrayFromCodeInstrumented(uint32_t type_idx,mirror::ArtMethod * referrer,int32_t component_count,Thread * self,bool access_check,gc::AllocatorType)98 mirror::Array* CheckAndAllocArrayFromCodeInstrumented(uint32_t type_idx,
99 mirror::ArtMethod* referrer,
100 int32_t component_count,
101 Thread* self,
102 bool access_check,
103 gc::AllocatorType /* allocator_type */) {
104 mirror::Class* klass = CheckFilledNewArrayAlloc(type_idx, referrer, component_count, self,
105 access_check);
106 if (UNLIKELY(klass == nullptr)) {
107 return nullptr;
108 }
109 gc::Heap* heap = Runtime::Current()->GetHeap();
110 // Use the current allocator type in case CheckFilledNewArrayAlloc caused us to suspend and then
111 // the heap switched the allocator type while we were suspended.
112 return mirror::Array::Alloc<true>(self, klass, component_count, klass->GetComponentSize(),
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
186 // Throw the exception.
187 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
188 self->SetException(throw_location,
189 reinterpret_cast<mirror::Throwable*>(self->DecodeJObject(exc.get())));
190 } else {
191 error_msg = "Could not create stack trace.";
192 }
193 } else {
194 // Could not allocate a string object.
195 error_msg = "Couldn't throw new StackOverflowError because JNI NewStringUTF failed.";
196 }
197 } else {
198 error_msg = "Could not allocate StackOverflowError object.";
199 }
200
201 if (!error_msg.empty()) {
202 LOG(ERROR) << error_msg;
203 CHECK(self->IsExceptionPending());
204 }
205
206 bool explicit_overflow_check = Runtime::Current()->ExplicitStackOverflowChecks();
207 self->ResetDefaultStackEnd(); // Return to default stack size.
208
209 // And restore protection if implicit checks are on.
210 if (!explicit_overflow_check) {
211 self->ProtectStack();
212 }
213 }
214
CheckReferenceResult(mirror::Object * o,Thread * self)215 void CheckReferenceResult(mirror::Object* o, Thread* self) {
216 if (o == NULL) {
217 return;
218 }
219 mirror::ArtMethod* m = self->GetCurrentMethod(NULL);
220 if (o == kInvalidIndirectRefObject) {
221 JniAbortF(NULL, "invalid reference returned from %s", PrettyMethod(m).c_str());
222 }
223 // Make sure that the result is an instance of the type this method was expected to return.
224 StackHandleScope<1> hs(self);
225 Handle<mirror::ArtMethod> h_m(hs.NewHandle(m));
226 mirror::Class* return_type = MethodHelper(h_m).GetReturnType();
227
228 if (!o->InstanceOf(return_type)) {
229 JniAbortF(NULL, "attempt to return an instance of %s from %s", PrettyTypeOf(o).c_str(),
230 PrettyMethod(h_m.Get()).c_str());
231 }
232 }
233
InvokeProxyInvocationHandler(ScopedObjectAccessAlreadyRunnable & soa,const char * shorty,jobject rcvr_jobj,jobject interface_method_jobj,std::vector<jvalue> & args)234 JValue InvokeProxyInvocationHandler(ScopedObjectAccessAlreadyRunnable& soa, const char* shorty,
235 jobject rcvr_jobj, jobject interface_method_jobj,
236 std::vector<jvalue>& args) {
237 DCHECK(soa.Env()->IsInstanceOf(rcvr_jobj, WellKnownClasses::java_lang_reflect_Proxy));
238
239 // Build argument array possibly triggering GC.
240 soa.Self()->AssertThreadSuspensionIsAllowable();
241 jobjectArray args_jobj = NULL;
242 const JValue zero;
243 int32_t target_sdk_version = Runtime::Current()->GetTargetSdkVersion();
244 // Do not create empty arrays unless needed to maintain Dalvik bug compatibility.
245 if (args.size() > 0 || (target_sdk_version > 0 && target_sdk_version <= 21)) {
246 args_jobj = soa.Env()->NewObjectArray(args.size(), WellKnownClasses::java_lang_Object, NULL);
247 if (args_jobj == NULL) {
248 CHECK(soa.Self()->IsExceptionPending());
249 return zero;
250 }
251 for (size_t i = 0; i < args.size(); ++i) {
252 if (shorty[i + 1] == 'L') {
253 jobject val = args.at(i).l;
254 soa.Env()->SetObjectArrayElement(args_jobj, i, val);
255 } else {
256 JValue jv;
257 jv.SetJ(args.at(i).j);
258 mirror::Object* val = BoxPrimitive(Primitive::GetType(shorty[i + 1]), jv);
259 if (val == NULL) {
260 CHECK(soa.Self()->IsExceptionPending());
261 return zero;
262 }
263 soa.Decode<mirror::ObjectArray<mirror::Object>* >(args_jobj)->Set<false>(i, val);
264 }
265 }
266 }
267
268 // Call Proxy.invoke(Proxy proxy, ArtMethod method, Object[] args).
269 jvalue invocation_args[3];
270 invocation_args[0].l = rcvr_jobj;
271 invocation_args[1].l = interface_method_jobj;
272 invocation_args[2].l = args_jobj;
273 jobject result =
274 soa.Env()->CallStaticObjectMethodA(WellKnownClasses::java_lang_reflect_Proxy,
275 WellKnownClasses::java_lang_reflect_Proxy_invoke,
276 invocation_args);
277
278 // Unbox result and handle error conditions.
279 if (LIKELY(!soa.Self()->IsExceptionPending())) {
280 if (shorty[0] == 'V' || (shorty[0] == 'L' && result == NULL)) {
281 // Do nothing.
282 return zero;
283 } else {
284 StackHandleScope<1> hs(soa.Self());
285 MethodHelper mh_interface_method(
286 hs.NewHandle(soa.Decode<mirror::ArtMethod*>(interface_method_jobj)));
287 // This can cause thread suspension.
288 mirror::Class* result_type = mh_interface_method.GetReturnType();
289 mirror::Object* result_ref = soa.Decode<mirror::Object*>(result);
290 mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
291 mirror::ArtMethod* proxy_method;
292 if (mh_interface_method.GetMethod()->GetDeclaringClass()->IsInterface()) {
293 proxy_method = rcvr->GetClass()->FindVirtualMethodForInterface(
294 mh_interface_method.GetMethod());
295 } else {
296 // Proxy dispatch to a method defined in Object.
297 DCHECK(mh_interface_method.GetMethod()->GetDeclaringClass()->IsObjectClass());
298 proxy_method = mh_interface_method.GetMethod();
299 }
300 ThrowLocation throw_location(rcvr, proxy_method, -1);
301 JValue result_unboxed;
302 if (!UnboxPrimitiveForResult(throw_location, result_ref, result_type, &result_unboxed)) {
303 DCHECK(soa.Self()->IsExceptionPending());
304 return zero;
305 }
306 return result_unboxed;
307 }
308 } else {
309 // In the case of checked exceptions that aren't declared, the exception must be wrapped by
310 // a UndeclaredThrowableException.
311 mirror::Throwable* exception = soa.Self()->GetException(NULL);
312 if (exception->IsCheckedException()) {
313 mirror::Object* rcvr = soa.Decode<mirror::Object*>(rcvr_jobj);
314 mirror::Class* proxy_class = rcvr->GetClass();
315 mirror::ArtMethod* interface_method =
316 soa.Decode<mirror::ArtMethod*>(interface_method_jobj);
317 mirror::ArtMethod* proxy_method =
318 rcvr->GetClass()->FindVirtualMethodForInterface(interface_method);
319 int throws_index = -1;
320 size_t num_virt_methods = proxy_class->NumVirtualMethods();
321 for (size_t i = 0; i < num_virt_methods; i++) {
322 if (proxy_class->GetVirtualMethod(i) == proxy_method) {
323 throws_index = i;
324 break;
325 }
326 }
327 CHECK_NE(throws_index, -1);
328 mirror::ObjectArray<mirror::Class>* declared_exceptions =
329 proxy_class->GetThrows()->Get(throws_index);
330 mirror::Class* exception_class = exception->GetClass();
331 bool declares_exception = false;
332 for (int i = 0; i < declared_exceptions->GetLength() && !declares_exception; i++) {
333 mirror::Class* declared_exception = declared_exceptions->Get(i);
334 declares_exception = declared_exception->IsAssignableFrom(exception_class);
335 }
336 if (!declares_exception) {
337 ThrowLocation throw_location(rcvr, proxy_method, -1);
338 soa.Self()->ThrowNewWrappedException(throw_location,
339 "Ljava/lang/reflect/UndeclaredThrowableException;",
340 NULL);
341 }
342 }
343 return zero;
344 }
345 }
346 } // namespace art
347