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