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