• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 "java_lang_reflect_Executable.h"
18 
19 #include "android-base/stringprintf.h"
20 #include "nativehelper/jni_macros.h"
21 
22 #include "art_method-inl.h"
23 #include "dex/dex_file_annotations.h"
24 #include "handle.h"
25 #include "jni_internal.h"
26 #include "mirror/class-inl.h"
27 #include "mirror/method.h"
28 #include "mirror/object-inl.h"
29 #include "mirror/object_array-inl.h"
30 #include "native_util.h"
31 #include "reflection.h"
32 #include "scoped_fast_native_object_access-inl.h"
33 #include "well_known_classes.h"
34 
35 namespace art {
36 
37 using android::base::StringPrintf;
38 
Executable_getDeclaredAnnotationsNative(JNIEnv * env,jobject javaMethod)39 static jobjectArray Executable_getDeclaredAnnotationsNative(JNIEnv* env, jobject javaMethod) {
40   ScopedFastNativeObjectAccess soa(env);
41   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
42   if (method->GetDeclaringClass()->IsProxyClass()) {
43     // Return an empty array instead of a null pointer.
44     ObjPtr<mirror::Class> annotation_array_class =
45         soa.Decode<mirror::Class>(WellKnownClasses::java_lang_annotation_Annotation__array);
46     ObjPtr<mirror::ObjectArray<mirror::Object>> empty_array =
47         mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), annotation_array_class, 0);
48     return soa.AddLocalReference<jobjectArray>(empty_array);
49   }
50   return soa.AddLocalReference<jobjectArray>(annotations::GetAnnotationsForMethod(method));
51 }
52 
Executable_getAnnotationNative(JNIEnv * env,jobject javaMethod,jclass annotationType)53 static jobject Executable_getAnnotationNative(JNIEnv* env,
54                                               jobject javaMethod,
55                                               jclass annotationType) {
56   ScopedFastNativeObjectAccess soa(env);
57   StackHandleScope<1> hs(soa.Self());
58   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
59   if (method->IsProxyMethod()) {
60     return nullptr;
61   } else {
62     Handle<mirror::Class> klass(hs.NewHandle(soa.Decode<mirror::Class>(annotationType)));
63     return soa.AddLocalReference<jobject>(annotations::GetAnnotationForMethod(method, klass));
64   }
65 }
66 
Executable_getSignatureAnnotation(JNIEnv * env,jobject javaMethod)67 static jobjectArray Executable_getSignatureAnnotation(JNIEnv* env, jobject javaMethod) {
68   ScopedFastNativeObjectAccess soa(env);
69   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
70   if (method->GetDeclaringClass()->IsProxyClass()) {
71     return nullptr;
72   }
73   return soa.AddLocalReference<jobjectArray>(annotations::GetSignatureAnnotationForMethod(method));
74 }
75 
76 
Executable_getParameterAnnotationsNative(JNIEnv * env,jobject javaMethod)77 static jobjectArray Executable_getParameterAnnotationsNative(JNIEnv* env, jobject javaMethod) {
78   ScopedFastNativeObjectAccess soa(env);
79   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
80   if (method->IsProxyMethod()) {
81     return nullptr;
82   }
83 
84   StackHandleScope<4> hs(soa.Self());
85   Handle<mirror::ObjectArray<mirror::Object>> annotations =
86       hs.NewHandle(annotations::GetParameterAnnotations(method));
87   if (annotations.IsNull()) {
88     return nullptr;
89   }
90 
91   // If the method is not a constructor, or has parameter annotations
92   // for each parameter, then we can return those annotations
93   // unmodified. Otherwise, we need to look at whether the
94   // constructor has implicit parameters as these may need padding
95   // with empty parameter annotations.
96   if (!method->IsConstructor() ||
97       annotations->GetLength() == static_cast<int>(method->GetNumberOfParameters())) {
98     return soa.AddLocalReference<jobjectArray>(annotations.Get());
99   }
100 
101   // If declaring class is a local or an enum, do not pad parameter
102   // annotations, as the implicit constructor parameters are an implementation
103   // detail rather than required by JLS.
104   Handle<mirror::Class> declaring_class = hs.NewHandle(method->GetDeclaringClass());
105   if (annotations::GetEnclosingMethod(declaring_class) != nullptr ||
106       declaring_class->IsEnum()) {
107     return soa.AddLocalReference<jobjectArray>(annotations.Get());
108   }
109 
110   // Prepare to resize the annotations so there is 1:1 correspondence
111   // with the constructor parameters.
112   Handle<mirror::ObjectArray<mirror::Object>> resized_annotations = hs.NewHandle(
113       mirror::ObjectArray<mirror::Object>::Alloc(
114           soa.Self(),
115           annotations->GetClass(),
116           static_cast<int>(method->GetNumberOfParameters())));
117   if (resized_annotations.IsNull()) {
118     DCHECK(soa.Self()->IsExceptionPending());
119     return nullptr;
120   }
121 
122   static constexpr bool kTransactionActive = false;
123   const int32_t offset = resized_annotations->GetLength() - annotations->GetLength();
124   if (offset > 0) {
125     // Workaround for dexers (d8/dx) that do not insert annotations
126     // for implicit parameters (b/68033708).
127     ObjPtr<mirror::Class> annotation_array_class =
128         soa.Decode<mirror::Class>(WellKnownClasses::java_lang_annotation_Annotation__array);
129     Handle<mirror::ObjectArray<mirror::Object>> empty_annotations = hs.NewHandle(
130         mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), annotation_array_class, 0));
131     if (empty_annotations.IsNull()) {
132       DCHECK(soa.Self()->IsExceptionPending());
133       return nullptr;
134     }
135     for (int i = 0; i < offset; ++i) {
136       resized_annotations->SetWithoutChecks<kTransactionActive>(i, empty_annotations.Get());
137     }
138     for (int i = 0; i < annotations->GetLength(); ++i) {
139       ObjPtr<mirror::Object> annotation = annotations->GetWithoutChecks(i);
140       resized_annotations->SetWithoutChecks<kTransactionActive>(i + offset, annotation);
141     }
142   } else {
143     // Workaround for Jack (defunct) erroneously inserting annotations
144     // for local classes (b/68033708).
145     DCHECK_LT(offset, 0);
146     for (int i = 0; i < resized_annotations->GetLength(); ++i) {
147       ObjPtr<mirror::Object> annotation = annotations->GetWithoutChecks(i - offset);
148       resized_annotations->SetWithoutChecks<kTransactionActive>(i, annotation);
149     }
150   }
151   return soa.AddLocalReference<jobjectArray>(resized_annotations.Get());
152 }
153 
Executable_getParameters0(JNIEnv * env,jobject javaMethod)154 static jobjectArray Executable_getParameters0(JNIEnv* env, jobject javaMethod) {
155   ScopedFastNativeObjectAccess soa(env);
156   Thread* self = soa.Self();
157   StackHandleScope<8> hs(self);
158 
159   Handle<mirror::Method> executable = hs.NewHandle(soa.Decode<mirror::Method>(javaMethod));
160   ArtMethod* art_method = executable.Get()->GetArtMethod();
161   if (art_method->GetDeclaringClass()->IsProxyClass()) {
162     return nullptr;
163   }
164 
165   // Find the MethodParameters system annotation.
166   MutableHandle<mirror::ObjectArray<mirror::String>> names =
167       hs.NewHandle<mirror::ObjectArray<mirror::String>>(nullptr);
168   MutableHandle<mirror::IntArray> access_flags = hs.NewHandle<mirror::IntArray>(nullptr);
169   if (!annotations::GetParametersMetadataForMethod(art_method, &names, &access_flags)) {
170     return nullptr;
171   }
172 
173   // Validate the MethodParameters system annotation data.
174   if (UNLIKELY(names == nullptr || access_flags == nullptr)) {
175     ThrowIllegalArgumentException(
176         StringPrintf("Missing parameter metadata for names or access flags for %s",
177                      art_method->PrettyMethod().c_str()).c_str());
178     return nullptr;
179   }
180 
181   // Check array sizes match each other
182   int32_t names_count = names.Get()->GetLength();
183   int32_t access_flags_count = access_flags.Get()->GetLength();
184   if (names_count != access_flags_count) {
185     ThrowIllegalArgumentException(
186         StringPrintf(
187             "Inconsistent parameter metadata for %s. names length: %d, access flags length: %d",
188             art_method->PrettyMethod().c_str(),
189             names_count,
190             access_flags_count).c_str());
191     return nullptr;
192   }
193 
194   // Instantiate a Parameter[] to hold the result.
195   Handle<mirror::Class> parameter_array_class =
196       hs.NewHandle(
197           soa.Decode<mirror::Class>(WellKnownClasses::java_lang_reflect_Parameter__array));
198   Handle<mirror::ObjectArray<mirror::Object>> parameter_array =
199       hs.NewHandle(
200           mirror::ObjectArray<mirror::Object>::Alloc(self,
201                                                      parameter_array_class.Get(),
202                                                      names_count));
203   if (UNLIKELY(parameter_array == nullptr)) {
204     self->AssertPendingException();
205     return nullptr;
206   }
207 
208   Handle<mirror::Class> parameter_class =
209       hs.NewHandle(soa.Decode<mirror::Class>(WellKnownClasses::java_lang_reflect_Parameter));
210   ArtMethod* parameter_init =
211       jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Parameter_init);
212 
213   // Mutable handles used in the loop below to ensure cleanup without scaling the number of
214   // handles by the number of parameters.
215   MutableHandle<mirror::String> name = hs.NewHandle<mirror::String>(nullptr);
216   MutableHandle<mirror::Object> parameter = hs.NewHandle<mirror::Object>(nullptr);
217 
218   // Populate the Parameter[] to return.
219   for (int32_t parameter_index = 0; parameter_index < names_count; parameter_index++) {
220     name.Assign(names.Get()->Get(parameter_index));
221     int32_t modifiers = access_flags.Get()->Get(parameter_index);
222 
223     // Allocate / initialize the Parameter to add to parameter_array.
224     parameter.Assign(parameter_class->AllocObject(self));
225     if (UNLIKELY(parameter == nullptr)) {
226       self->AssertPendingOOMException();
227       return nullptr;
228     }
229 
230     uint32_t args[5] = { PointerToLowMemUInt32(parameter.Get()),
231                          PointerToLowMemUInt32(name.Get()),
232                          static_cast<uint32_t>(modifiers),
233                          PointerToLowMemUInt32(executable.Get()),
234                          static_cast<uint32_t>(parameter_index)
235     };
236     JValue result;
237     static const char* method_signature = "VLILI";  // return + parameter types
238     parameter_init->Invoke(self, args, sizeof(args), &result, method_signature);
239     if (UNLIKELY(self->IsExceptionPending())) {
240       return nullptr;
241     }
242 
243     // Store the Parameter in the Parameter[].
244     parameter_array.Get()->Set(parameter_index, parameter.Get());
245     if (UNLIKELY(self->IsExceptionPending())) {
246       return nullptr;
247     }
248   }
249   return soa.AddLocalReference<jobjectArray>(parameter_array.Get());
250 }
251 
Executable_isAnnotationPresentNative(JNIEnv * env,jobject javaMethod,jclass annotationType)252 static jboolean Executable_isAnnotationPresentNative(JNIEnv* env,
253                                                      jobject javaMethod,
254                                                      jclass annotationType) {
255   ScopedFastNativeObjectAccess soa(env);
256   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
257   if (method->GetDeclaringClass()->IsProxyClass()) {
258     return false;
259   }
260   StackHandleScope<1> hs(soa.Self());
261   Handle<mirror::Class> klass(hs.NewHandle(soa.Decode<mirror::Class>(annotationType)));
262   return annotations::IsMethodAnnotationPresent(method, klass);
263 }
264 
Executable_compareMethodParametersInternal(JNIEnv * env,jobject thisMethod,jobject otherMethod)265 static jint Executable_compareMethodParametersInternal(JNIEnv* env,
266                                                        jobject thisMethod,
267                                                        jobject otherMethod) {
268   ScopedFastNativeObjectAccess soa(env);
269   ArtMethod* this_method = ArtMethod::FromReflectedMethod(soa, thisMethod);
270   ArtMethod* other_method = ArtMethod::FromReflectedMethod(soa, otherMethod);
271 
272   this_method = this_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
273   other_method = other_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
274 
275   const DexFile::TypeList* this_list = this_method->GetParameterTypeList();
276   const DexFile::TypeList* other_list = other_method->GetParameterTypeList();
277 
278   if (this_list == other_list) {
279     return 0;
280   }
281 
282   if (this_list == nullptr && other_list != nullptr) {
283     return -1;
284   }
285 
286   if (other_list == nullptr && this_list != nullptr) {
287     return 1;
288   }
289 
290   const int32_t this_size = this_list->Size();
291   const int32_t other_size = other_list->Size();
292 
293   if (this_size != other_size) {
294     return (this_size - other_size);
295   }
296 
297   for (int32_t i = 0; i < this_size; ++i) {
298     const DexFile::TypeId& lhs = this_method->GetDexFile()->GetTypeId(
299         this_list->GetTypeItem(i).type_idx_);
300     const DexFile::TypeId& rhs = other_method->GetDexFile()->GetTypeId(
301         other_list->GetTypeItem(i).type_idx_);
302 
303     uint32_t lhs_len, rhs_len;
304     const char* lhs_data = this_method->GetDexFile()->StringDataAndUtf16LengthByIdx(
305         lhs.descriptor_idx_, &lhs_len);
306     const char* rhs_data = other_method->GetDexFile()->StringDataAndUtf16LengthByIdx(
307         rhs.descriptor_idx_, &rhs_len);
308 
309     int cmp = strcmp(lhs_data, rhs_data);
310     if (cmp != 0) {
311       return (cmp < 0) ? -1 : 1;
312     }
313   }
314 
315   return 0;
316 }
317 
Executable_getMethodNameInternal(JNIEnv * env,jobject javaMethod)318 static jstring Executable_getMethodNameInternal(JNIEnv* env, jobject javaMethod) {
319   ScopedFastNativeObjectAccess soa(env);
320   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
321   method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
322   return soa.AddLocalReference<jstring>(method->GetNameAsString(soa.Self()));
323 }
324 
Executable_getMethodReturnTypeInternal(JNIEnv * env,jobject javaMethod)325 static jclass Executable_getMethodReturnTypeInternal(JNIEnv* env, jobject javaMethod) {
326   ScopedFastNativeObjectAccess soa(env);
327   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
328   method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
329   ObjPtr<mirror::Class> return_type(method->ResolveReturnType());
330   if (return_type.IsNull()) {
331     CHECK(soa.Self()->IsExceptionPending());
332     return nullptr;
333   }
334 
335   return soa.AddLocalReference<jclass>(return_type);
336 }
337 
338 // TODO: Move this to mirror::Class ? Other mirror types that commonly appear
339 // as arrays have a GetArrayClass() method. This is duplicated in
340 // java_lang_Class.cc as well.
GetClassArrayClass(Thread * self)341 static ObjPtr<mirror::Class> GetClassArrayClass(Thread* self)
342     REQUIRES_SHARED(Locks::mutator_lock_) {
343   ObjPtr<mirror::Class> class_class = mirror::Class::GetJavaLangClass();
344   return Runtime::Current()->GetClassLinker()->FindArrayClass(self, &class_class);
345 }
346 
Executable_getParameterTypesInternal(JNIEnv * env,jobject javaMethod)347 static jobjectArray Executable_getParameterTypesInternal(JNIEnv* env, jobject javaMethod) {
348   ScopedFastNativeObjectAccess soa(env);
349   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
350   method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
351 
352   const DexFile::TypeList* params = method->GetParameterTypeList();
353   if (params == nullptr) {
354     return nullptr;
355   }
356 
357   const uint32_t num_params = params->Size();
358 
359   StackHandleScope<3> hs(soa.Self());
360   Handle<mirror::Class> class_array_class = hs.NewHandle(GetClassArrayClass(soa.Self()));
361   Handle<mirror::ObjectArray<mirror::Class>> ptypes = hs.NewHandle(
362       mirror::ObjectArray<mirror::Class>::Alloc(soa.Self(), class_array_class.Get(), num_params));
363   if (ptypes.IsNull()) {
364     DCHECK(soa.Self()->IsExceptionPending());
365     return nullptr;
366   }
367 
368   MutableHandle<mirror::Class> param(hs.NewHandle<mirror::Class>(nullptr));
369   for (uint32_t i = 0; i < num_params; ++i) {
370     const dex::TypeIndex type_idx = params->GetTypeItem(i).type_idx_;
371     param.Assign(Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method));
372     if (param.Get() == nullptr) {
373       DCHECK(soa.Self()->IsExceptionPending());
374       return nullptr;
375     }
376     ptypes->SetWithoutChecks<false>(i, param.Get());
377   }
378 
379   return soa.AddLocalReference<jobjectArray>(ptypes.Get());
380 }
381 
Executable_getParameterCountInternal(JNIEnv * env,jobject javaMethod)382 static jint Executable_getParameterCountInternal(JNIEnv* env, jobject javaMethod) {
383   ScopedFastNativeObjectAccess soa(env);
384   ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
385   method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
386 
387   const DexFile::TypeList* params = method->GetParameterTypeList();
388   return (params == nullptr) ? 0 : params->Size();
389 }
390 
391 
392 static JNINativeMethod gMethods[] = {
393   FAST_NATIVE_METHOD(Executable, compareMethodParametersInternal,
394                      "(Ljava/lang/reflect/Method;)I"),
395   FAST_NATIVE_METHOD(Executable, getAnnotationNative,
396                      "(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;"),
397   FAST_NATIVE_METHOD(Executable, getDeclaredAnnotationsNative,
398                      "()[Ljava/lang/annotation/Annotation;"),
399   FAST_NATIVE_METHOD(Executable, getParameterAnnotationsNative,
400                      "()[[Ljava/lang/annotation/Annotation;"),
401   FAST_NATIVE_METHOD(Executable, getMethodNameInternal, "()Ljava/lang/String;"),
402   FAST_NATIVE_METHOD(Executable, getMethodReturnTypeInternal, "()Ljava/lang/Class;"),
403   FAST_NATIVE_METHOD(Executable, getParameterTypesInternal, "()[Ljava/lang/Class;"),
404   FAST_NATIVE_METHOD(Executable, getParameterCountInternal, "()I"),
405   FAST_NATIVE_METHOD(Executable, getParameters0, "()[Ljava/lang/reflect/Parameter;"),
406   FAST_NATIVE_METHOD(Executable, getSignatureAnnotation, "()[Ljava/lang/String;"),
407   FAST_NATIVE_METHOD(Executable, isAnnotationPresentNative, "(Ljava/lang/Class;)Z"),
408 };
409 
register_java_lang_reflect_Executable(JNIEnv * env)410 void register_java_lang_reflect_Executable(JNIEnv* env) {
411   REGISTER_NATIVE_METHODS("java/lang/reflect/Executable");
412 }
413 
414 }  // namespace art
415