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/enums.h"
22 #include "base/mutex.h"
23 #include "base/sdk_version.h"
24 #include "class_linker-inl.h"
25 #include "dex/dex_file-inl.h"
26 #include "dex/method_reference.h"
27 #include "entrypoints/entrypoint_utils-inl.h"
28 #include "entrypoints/quick/callee_save_frame.h"
29 #include "entrypoints/runtime_asm_entrypoints.h"
30 #include "gc/accounting/card_table-inl.h"
31 #include "index_bss_mapping.h"
32 #include "jni/java_vm_ext.h"
33 #include "mirror/class-inl.h"
34 #include "mirror/method.h"
35 #include "mirror/object-inl.h"
36 #include "mirror/object_array-inl.h"
37 #include "nth_caller_visitor.h"
38 #include "oat_file.h"
39 #include "oat_file-inl.h"
40 #include "oat_quick_method_header.h"
41 #include "reflection.h"
42 #include "scoped_thread_state_change-inl.h"
43 #include "well_known_classes.h"
44
45 namespace art {
46
CheckReferenceResult(Handle<mirror::Object> o,Thread * self)47 void CheckReferenceResult(Handle<mirror::Object> o, Thread* self) {
48 if (o == nullptr) {
49 return;
50 }
51 // Make sure that the result is an instance of the type this method was expected to return.
52 ArtMethod* method = self->GetCurrentMethod(nullptr);
53 ObjPtr<mirror::Class> return_type = method->ResolveReturnType();
54
55 if (!o->InstanceOf(return_type)) {
56 Runtime::Current()->GetJavaVM()->JniAbortF(nullptr,
57 "attempt to return an instance of %s from %s",
58 o->PrettyTypeOf().c_str(),
59 method->PrettyMethod().c_str());
60 }
61 }
62
InvokeProxyInvocationHandler(ScopedObjectAccessAlreadyRunnable & soa,const char * shorty,jobject rcvr_jobj,jobject interface_method_jobj,std::vector<jvalue> & args)63 JValue InvokeProxyInvocationHandler(ScopedObjectAccessAlreadyRunnable& soa,
64 const char* shorty,
65 jobject rcvr_jobj,
66 jobject interface_method_jobj,
67 std::vector<jvalue>& args) {
68 DCHECK(soa.Env()->IsInstanceOf(rcvr_jobj, WellKnownClasses::java_lang_reflect_Proxy));
69
70 // Build argument array possibly triggering GC.
71 soa.Self()->AssertThreadSuspensionIsAllowable();
72 jobjectArray args_jobj = nullptr;
73 const JValue zero;
74 uint32_t target_sdk_version = Runtime::Current()->GetTargetSdkVersion();
75 // Do not create empty arrays unless needed to maintain Dalvik bug compatibility.
76 if (args.size() > 0 || IsSdkVersionSetAndAtMost(target_sdk_version, SdkVersion::kL)) {
77 args_jobj = soa.Env()->NewObjectArray(args.size(), WellKnownClasses::java_lang_Object, nullptr);
78 if (args_jobj == nullptr) {
79 CHECK(soa.Self()->IsExceptionPending());
80 return zero;
81 }
82 for (size_t i = 0; i < args.size(); ++i) {
83 if (shorty[i + 1] == 'L') {
84 jobject val = args[i].l;
85 soa.Env()->SetObjectArrayElement(args_jobj, i, val);
86 } else {
87 JValue jv;
88 jv.SetJ(args[i].j);
89 ObjPtr<mirror::Object> val = BoxPrimitive(Primitive::GetType(shorty[i + 1]), jv);
90 if (val == nullptr) {
91 CHECK(soa.Self()->IsExceptionPending());
92 return zero;
93 }
94 soa.Decode<mirror::ObjectArray<mirror::Object>>(args_jobj)->Set<false>(i, val);
95 }
96 }
97 }
98
99 // Call Proxy.invoke(Proxy proxy, Method method, Object[] args).
100 jvalue invocation_args[3];
101 invocation_args[0].l = rcvr_jobj;
102 invocation_args[1].l = interface_method_jobj;
103 invocation_args[2].l = args_jobj;
104 jobject result =
105 soa.Env()->CallStaticObjectMethodA(WellKnownClasses::java_lang_reflect_Proxy,
106 WellKnownClasses::java_lang_reflect_Proxy_invoke,
107 invocation_args);
108
109 // Unbox result and handle error conditions.
110 if (LIKELY(!soa.Self()->IsExceptionPending())) {
111 if (shorty[0] == 'V' || (shorty[0] == 'L' && result == nullptr)) {
112 // Do nothing.
113 return zero;
114 } else {
115 ArtMethod* interface_method =
116 soa.Decode<mirror::Method>(interface_method_jobj)->GetArtMethod();
117 // This can cause thread suspension.
118 ObjPtr<mirror::Class> result_type = interface_method->ResolveReturnType();
119 ObjPtr<mirror::Object> result_ref = soa.Decode<mirror::Object>(result);
120 JValue result_unboxed;
121 if (!UnboxPrimitiveForResult(result_ref, result_type, &result_unboxed)) {
122 DCHECK(soa.Self()->IsExceptionPending());
123 return zero;
124 }
125 return result_unboxed;
126 }
127 } else {
128 // In the case of checked exceptions that aren't declared, the exception must be wrapped by
129 // a UndeclaredThrowableException.
130 ObjPtr<mirror::Throwable> exception = soa.Self()->GetException();
131 if (exception->IsCheckedException()) {
132 bool declares_exception = false;
133 {
134 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
135 ObjPtr<mirror::Object> rcvr = soa.Decode<mirror::Object>(rcvr_jobj);
136 ObjPtr<mirror::Class> proxy_class = rcvr->GetClass();
137 ObjPtr<mirror::Method> interface_method = soa.Decode<mirror::Method>(interface_method_jobj);
138 ArtMethod* proxy_method = rcvr->GetClass()->FindVirtualMethodForInterface(
139 interface_method->GetArtMethod(), kRuntimePointerSize);
140 auto virtual_methods = proxy_class->GetVirtualMethodsSlice(kRuntimePointerSize);
141 size_t num_virtuals = proxy_class->NumVirtualMethods();
142 size_t method_size = ArtMethod::Size(kRuntimePointerSize);
143 // Rely on the fact that the methods are contiguous to determine the index of the method in
144 // the slice.
145 int throws_index = (reinterpret_cast<uintptr_t>(proxy_method) -
146 reinterpret_cast<uintptr_t>(&virtual_methods[0])) / method_size;
147 CHECK_LT(throws_index, static_cast<int>(num_virtuals));
148 ObjPtr<mirror::ObjectArray<mirror::Class>> declared_exceptions =
149 proxy_class->GetProxyThrows()->Get(throws_index);
150 ObjPtr<mirror::Class> exception_class = exception->GetClass();
151 for (int32_t i = 0; i < declared_exceptions->GetLength() && !declares_exception; i++) {
152 ObjPtr<mirror::Class> declared_exception = declared_exceptions->Get(i);
153 declares_exception = declared_exception->IsAssignableFrom(exception_class);
154 }
155 }
156 if (!declares_exception) {
157 soa.Self()->ThrowNewWrappedException("Ljava/lang/reflect/UndeclaredThrowableException;",
158 nullptr);
159 }
160 }
161 return zero;
162 }
163 }
164
FillArrayData(ObjPtr<mirror::Object> obj,const Instruction::ArrayDataPayload * payload)165 bool FillArrayData(ObjPtr<mirror::Object> obj, const Instruction::ArrayDataPayload* payload) {
166 DCHECK_EQ(payload->ident, static_cast<uint16_t>(Instruction::kArrayDataSignature));
167 if (UNLIKELY(obj == nullptr)) {
168 ThrowNullPointerException("null array in FILL_ARRAY_DATA");
169 return false;
170 }
171 ObjPtr<mirror::Array> array = obj->AsArray();
172 DCHECK(!array->IsObjectArray());
173 if (UNLIKELY(static_cast<int32_t>(payload->element_count) > array->GetLength())) {
174 Thread* self = Thread::Current();
175 self->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
176 "failed FILL_ARRAY_DATA; length=%d, index=%d",
177 array->GetLength(), payload->element_count);
178 return false;
179 }
180 // Copy data from dex file to memory assuming both are little endian.
181 uint32_t size_in_bytes = payload->element_count * payload->element_width;
182 memcpy(array->GetRawData(payload->element_width, 0), payload->data, size_in_bytes);
183 return true;
184 }
185
DoGetCalleeSaveMethodOuterCallerAndPc(ArtMethod ** sp,CalleeSaveType type)186 static inline std::pair<ArtMethod*, uintptr_t> DoGetCalleeSaveMethodOuterCallerAndPc(
187 ArtMethod** sp, CalleeSaveType type) REQUIRES_SHARED(Locks::mutator_lock_) {
188 DCHECK_EQ(*sp, Runtime::Current()->GetCalleeSaveMethod(type));
189
190 const size_t callee_frame_size = RuntimeCalleeSaveFrame::GetFrameSize(type);
191 auto** caller_sp = reinterpret_cast<ArtMethod**>(
192 reinterpret_cast<uintptr_t>(sp) + callee_frame_size);
193 const size_t callee_return_pc_offset = RuntimeCalleeSaveFrame::GetReturnPcOffset(type);
194 uintptr_t caller_pc = *reinterpret_cast<uintptr_t*>(
195 (reinterpret_cast<uint8_t*>(sp) + callee_return_pc_offset));
196 ArtMethod* outer_method = *caller_sp;
197 return std::make_pair(outer_method, caller_pc);
198 }
199
DoGetCalleeSaveMethodCaller(ArtMethod * outer_method,uintptr_t caller_pc,bool do_caller_check)200 static inline ArtMethod* DoGetCalleeSaveMethodCaller(ArtMethod* outer_method,
201 uintptr_t caller_pc,
202 bool do_caller_check)
203 REQUIRES_SHARED(Locks::mutator_lock_) {
204 ArtMethod* caller = outer_method;
205 if (LIKELY(caller_pc != reinterpret_cast<uintptr_t>(GetQuickInstrumentationExitPc()))) {
206 if (outer_method != nullptr) {
207 const OatQuickMethodHeader* current_code = outer_method->GetOatQuickMethodHeader(caller_pc);
208 DCHECK(current_code != nullptr);
209 if (current_code->IsOptimized() &&
210 CodeInfo::HasInlineInfo(current_code->GetOptimizedCodeInfoPtr())) {
211 uintptr_t native_pc_offset = current_code->NativeQuickPcOffset(caller_pc);
212 CodeInfo code_info = CodeInfo::DecodeInlineInfoOnly(current_code);
213 StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
214 DCHECK(stack_map.IsValid());
215 BitTableRange<InlineInfo> inline_infos = code_info.GetInlineInfosOf(stack_map);
216 if (!inline_infos.empty()) {
217 caller = GetResolvedMethod(outer_method, code_info, inline_infos);
218 }
219 }
220 }
221 if (kIsDebugBuild && do_caller_check) {
222 // Note that do_caller_check is optional, as this method can be called by
223 // stubs, and tests without a proper call stack.
224 NthCallerVisitor visitor(Thread::Current(), 1, true);
225 visitor.WalkStack();
226 CHECK_EQ(caller, visitor.caller);
227 }
228 } else {
229 // We're instrumenting, just use the StackVisitor which knows how to
230 // handle instrumented frames.
231 NthCallerVisitor visitor(Thread::Current(), 1, true);
232 visitor.WalkStack();
233 caller = visitor.caller;
234 }
235 return caller;
236 }
237
GetCalleeSaveMethodCaller(ArtMethod ** sp,CalleeSaveType type,bool do_caller_check)238 ArtMethod* GetCalleeSaveMethodCaller(ArtMethod** sp, CalleeSaveType type, bool do_caller_check)
239 REQUIRES_SHARED(Locks::mutator_lock_) {
240 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
241 auto outer_caller_and_pc = DoGetCalleeSaveMethodOuterCallerAndPc(sp, type);
242 ArtMethod* outer_method = outer_caller_and_pc.first;
243 uintptr_t caller_pc = outer_caller_and_pc.second;
244 ArtMethod* caller = DoGetCalleeSaveMethodCaller(outer_method, caller_pc, do_caller_check);
245 return caller;
246 }
247
GetCalleeSaveMethodCallerAndOuterMethod(Thread * self,CalleeSaveType type)248 CallerAndOuterMethod GetCalleeSaveMethodCallerAndOuterMethod(Thread* self, CalleeSaveType type) {
249 CallerAndOuterMethod result;
250 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
251 ArtMethod** sp = self->GetManagedStack()->GetTopQuickFrameKnownNotTagged();
252 auto outer_caller_and_pc = DoGetCalleeSaveMethodOuterCallerAndPc(sp, type);
253 result.outer_method = outer_caller_and_pc.first;
254 uintptr_t caller_pc = outer_caller_and_pc.second;
255 result.caller =
256 DoGetCalleeSaveMethodCaller(result.outer_method, caller_pc, /* do_caller_check= */ true);
257 return result;
258 }
259
GetCalleeSaveOuterMethod(Thread * self,CalleeSaveType type)260 ArtMethod* GetCalleeSaveOuterMethod(Thread* self, CalleeSaveType type) {
261 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
262 ArtMethod** sp = self->GetManagedStack()->GetTopQuickFrameKnownNotTagged();
263 return DoGetCalleeSaveMethodOuterCallerAndPc(sp, type).first;
264 }
265
ResolveMethodHandleFromCode(ArtMethod * referrer,uint32_t method_handle_idx)266 ObjPtr<mirror::MethodHandle> ResolveMethodHandleFromCode(ArtMethod* referrer,
267 uint32_t method_handle_idx) {
268 Thread::PoisonObjectPointersIfDebug();
269 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
270 return class_linker->ResolveMethodHandle(Thread::Current(), method_handle_idx, referrer);
271 }
272
ResolveMethodTypeFromCode(ArtMethod * referrer,dex::ProtoIndex proto_idx)273 ObjPtr<mirror::MethodType> ResolveMethodTypeFromCode(ArtMethod* referrer,
274 dex::ProtoIndex proto_idx) {
275 Thread::PoisonObjectPointersIfDebug();
276 ObjPtr<mirror::MethodType> method_type =
277 referrer->GetDexCache()->GetResolvedMethodType(proto_idx);
278 if (UNLIKELY(method_type == nullptr)) {
279 StackHandleScope<2> hs(Thread::Current());
280 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
281 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
282 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
283 method_type = class_linker->ResolveMethodType(hs.Self(), proto_idx, dex_cache, class_loader);
284 }
285 return method_type;
286 }
287
MaybeUpdateBssMethodEntry(ArtMethod * callee,MethodReference callee_reference,ArtMethod * outer_method)288 void MaybeUpdateBssMethodEntry(ArtMethod* callee,
289 MethodReference callee_reference,
290 ArtMethod* outer_method) {
291 DCHECK_NE(callee, nullptr);
292 if (outer_method->GetDexFile()->GetOatDexFile() == nullptr ||
293 outer_method->GetDexFile()->GetOatDexFile()->GetOatFile() == nullptr) {
294 // No OatFile to update.
295 return;
296 }
297 const OatFile* outer_oat_file = outer_method->GetDexFile()->GetOatDexFile()->GetOatFile();
298
299 const DexFile* dex_file = callee_reference.dex_file;
300 const OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
301 const IndexBssMapping* mapping = nullptr;
302 if (oat_dex_file != nullptr && oat_dex_file->GetOatFile() == outer_oat_file) {
303 // DexFiles compiled together to an oat file case.
304 mapping = oat_dex_file->GetMethodBssMapping();
305 } else {
306 // Try to find the DexFile in the BCP of the outer_method.
307 const OatFile::BssMappingInfo* mapping_info = outer_oat_file->FindBcpMappingInfo(dex_file);
308 if (mapping_info != nullptr) {
309 mapping = mapping_info->method_bss_mapping;
310 }
311 }
312
313 // Perform the update if we found a mapping.
314 if (mapping != nullptr) {
315 size_t bss_offset =
316 IndexBssMappingLookup::GetBssOffset(mapping,
317 callee_reference.index,
318 dex_file->NumMethodIds(),
319 static_cast<size_t>(kRuntimePointerSize));
320 if (bss_offset != IndexBssMappingLookup::npos) {
321 DCHECK_ALIGNED(bss_offset, static_cast<size_t>(kRuntimePointerSize));
322 DCHECK_NE(outer_oat_file, nullptr);
323 ArtMethod** method_entry = reinterpret_cast<ArtMethod**>(
324 const_cast<uint8_t*>(outer_oat_file->BssBegin() + bss_offset));
325 DCHECK_GE(method_entry, outer_oat_file->GetBssMethods().data());
326 DCHECK_LT(method_entry,
327 outer_oat_file->GetBssMethods().data() + outer_oat_file->GetBssMethods().size());
328 std::atomic<ArtMethod*>* atomic_entry =
329 reinterpret_cast<std::atomic<ArtMethod*>*>(method_entry);
330 if (kIsDebugBuild) {
331 ArtMethod* existing = atomic_entry->load(std::memory_order_acquire);
332 CHECK(existing->IsRuntimeMethod() || existing == callee);
333 }
334 static_assert(sizeof(*method_entry) == sizeof(*atomic_entry), "Size check.");
335 atomic_entry->store(callee, std::memory_order_release);
336 }
337 }
338 }
339
340 } // namespace art
341