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-alloc-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 WellKnownClasses::ToClass(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 WellKnownClasses::ToClass(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<6> 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 WellKnownClasses::ToClass(WellKnownClasses::java_lang_reflect_Parameter__array));
201 Handle<mirror::ObjectArray<mirror::Object>> parameter_array = hs.NewHandle(
202 mirror::ObjectArray<mirror::Object>::Alloc(self, parameter_array_class.Get(), names_count));
203 if (UNLIKELY(parameter_array == nullptr)) {
204 self->AssertPendingException();
205 return nullptr;
206 }
207
208 ArtMethod* parameter_init = WellKnownClasses::java_lang_reflect_Parameter_init;
209
210 // Mutable handles used in the loop below to ensure cleanup without scaling the number of
211 // handles by the number of parameters.
212 MutableHandle<mirror::String> name = hs.NewHandle<mirror::String>(nullptr);
213
214 // Populate the Parameter[] to return.
215 for (int32_t parameter_index = 0; parameter_index < names_count; parameter_index++) {
216 name.Assign(names.Get()->Get(parameter_index));
217 int32_t modifiers = access_flags.Get()->Get(parameter_index);
218
219 // Create the Parameter to add to parameter_array.
220 ObjPtr<mirror::Object> parameter = parameter_init->NewObject<'L', 'I', 'L', 'I'>(
221 self, name, modifiers, executable, parameter_index);
222 if (UNLIKELY(parameter == nullptr)) {
223 DCHECK(self->IsExceptionPending());
224 return nullptr;
225 }
226
227 // We're initializing a newly allocated array object, so we do not need to record that under
228 // a transaction. If the transaction is aborted, the whole object shall be unreachable.
229 parameter_array->SetWithoutChecks</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
230 parameter_index, parameter);
231 }
232 return soa.AddLocalReference<jobjectArray>(parameter_array.Get());
233 }
234
Executable_isAnnotationPresentNative(JNIEnv * env,jobject javaMethod,jclass annotationType)235 static jboolean Executable_isAnnotationPresentNative(JNIEnv* env,
236 jobject javaMethod,
237 jclass annotationType) {
238 ScopedFastNativeObjectAccess soa(env);
239 ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
240 if (method->GetDeclaringClass()->IsProxyClass()) {
241 return false;
242 }
243 StackHandleScope<1> hs(soa.Self());
244 Handle<mirror::Class> klass(hs.NewHandle(soa.Decode<mirror::Class>(annotationType)));
245 return annotations::IsMethodAnnotationPresent(method, klass);
246 }
247
Executable_compareMethodParametersInternal(JNIEnv * env,jobject thisMethod,jobject otherMethod)248 static jint Executable_compareMethodParametersInternal(JNIEnv* env,
249 jobject thisMethod,
250 jobject otherMethod) {
251 ScopedFastNativeObjectAccess soa(env);
252 ArtMethod* this_method = ArtMethod::FromReflectedMethod(soa, thisMethod);
253 ArtMethod* other_method = ArtMethod::FromReflectedMethod(soa, otherMethod);
254
255 this_method = this_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
256 other_method = other_method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
257
258 const dex::TypeList* this_list = this_method->GetParameterTypeList();
259 const dex::TypeList* other_list = other_method->GetParameterTypeList();
260
261 if (this_list == other_list) {
262 return 0;
263 }
264
265 if (this_list == nullptr && other_list != nullptr) {
266 return -1;
267 }
268
269 if (other_list == nullptr && this_list != nullptr) {
270 return 1;
271 }
272
273 const int32_t this_size = this_list->Size();
274 const int32_t other_size = other_list->Size();
275
276 if (this_size != other_size) {
277 return (this_size - other_size);
278 }
279
280 for (int32_t i = 0; i < this_size; ++i) {
281 const dex::TypeId& lhs = this_method->GetDexFile()->GetTypeId(
282 this_list->GetTypeItem(i).type_idx_);
283 const dex::TypeId& rhs = other_method->GetDexFile()->GetTypeId(
284 other_list->GetTypeItem(i).type_idx_);
285
286 uint32_t lhs_len, rhs_len;
287 const char* lhs_data = this_method->GetDexFile()->StringDataAndUtf16LengthByIdx(
288 lhs.descriptor_idx_, &lhs_len);
289 const char* rhs_data = other_method->GetDexFile()->StringDataAndUtf16LengthByIdx(
290 rhs.descriptor_idx_, &rhs_len);
291
292 int cmp = strcmp(lhs_data, rhs_data);
293 if (cmp != 0) {
294 return (cmp < 0) ? -1 : 1;
295 }
296 }
297
298 return 0;
299 }
300
Executable_getMethodNameInternal(JNIEnv * env,jobject javaMethod)301 static jstring Executable_getMethodNameInternal(JNIEnv* env, jobject javaMethod) {
302 ScopedFastNativeObjectAccess soa(env);
303 ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
304 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
305 return soa.AddLocalReference<jstring>(method->ResolveNameString());
306 }
307
Executable_getMethodReturnTypeInternal(JNIEnv * env,jobject javaMethod)308 static jclass Executable_getMethodReturnTypeInternal(JNIEnv* env, jobject javaMethod) {
309 ScopedFastNativeObjectAccess soa(env);
310 ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
311 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
312 ObjPtr<mirror::Class> return_type(method->ResolveReturnType());
313 if (return_type.IsNull()) {
314 CHECK(soa.Self()->IsExceptionPending());
315 return nullptr;
316 }
317
318 return soa.AddLocalReference<jclass>(return_type);
319 }
320
Executable_getParameterTypesInternal(JNIEnv * env,jobject javaMethod)321 static jobjectArray Executable_getParameterTypesInternal(JNIEnv* env, jobject javaMethod) {
322 ScopedFastNativeObjectAccess soa(env);
323 ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
324 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
325
326 const dex::TypeList* params = method->GetParameterTypeList();
327 if (params == nullptr) {
328 return nullptr;
329 }
330
331 const uint32_t num_params = params->Size();
332
333 StackHandleScope<2> hs(soa.Self());
334 ObjPtr<mirror::Class> class_array_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>();
335 Handle<mirror::ObjectArray<mirror::Class>> ptypes = hs.NewHandle(
336 mirror::ObjectArray<mirror::Class>::Alloc(soa.Self(), class_array_class, num_params));
337 if (ptypes.IsNull()) {
338 DCHECK(soa.Self()->IsExceptionPending());
339 return nullptr;
340 }
341
342 MutableHandle<mirror::Class> param(hs.NewHandle<mirror::Class>(nullptr));
343 for (uint32_t i = 0; i < num_params; ++i) {
344 const dex::TypeIndex type_idx = params->GetTypeItem(i).type_idx_;
345 param.Assign(Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method));
346 if (param.Get() == nullptr) {
347 DCHECK(soa.Self()->IsExceptionPending());
348 return nullptr;
349 }
350 ptypes->SetWithoutChecks<false>(i, param.Get());
351 }
352
353 return soa.AddLocalReference<jobjectArray>(ptypes.Get());
354 }
355
Executable_getParameterCountInternal(JNIEnv * env,jobject javaMethod)356 static jint Executable_getParameterCountInternal(JNIEnv* env, jobject javaMethod) {
357 ScopedFastNativeObjectAccess soa(env);
358 ArtMethod* method = ArtMethod::FromReflectedMethod(soa, javaMethod);
359 method = method->GetInterfaceMethodIfProxy(kRuntimePointerSize);
360
361 const dex::TypeList* params = method->GetParameterTypeList();
362 return (params == nullptr) ? 0 : params->Size();
363 }
364
365
366 static JNINativeMethod gMethods[] = {
367 FAST_NATIVE_METHOD(Executable, compareMethodParametersInternal,
368 "(Ljava/lang/reflect/Method;)I"),
369 FAST_NATIVE_METHOD(Executable, getAnnotationNative,
370 "(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;"),
371 FAST_NATIVE_METHOD(Executable, getDeclaredAnnotationsNative,
372 "()[Ljava/lang/annotation/Annotation;"),
373 FAST_NATIVE_METHOD(Executable, getParameterAnnotationsNative,
374 "()[[Ljava/lang/annotation/Annotation;"),
375 FAST_NATIVE_METHOD(Executable, getMethodNameInternal, "()Ljava/lang/String;"),
376 FAST_NATIVE_METHOD(Executable, getMethodReturnTypeInternal, "()Ljava/lang/Class;"),
377 FAST_NATIVE_METHOD(Executable, getParameterTypesInternal, "()[Ljava/lang/Class;"),
378 FAST_NATIVE_METHOD(Executable, getParameterCountInternal, "()I"),
379 FAST_NATIVE_METHOD(Executable, getParameters0, "()[Ljava/lang/reflect/Parameter;"),
380 FAST_NATIVE_METHOD(Executable, getSignatureAnnotation, "()[Ljava/lang/String;"),
381 FAST_NATIVE_METHOD(Executable, isAnnotationPresentNative, "(Ljava/lang/Class;)Z"),
382 };
383
register_java_lang_reflect_Executable(JNIEnv * env)384 void register_java_lang_reflect_Executable(JNIEnv* env) {
385 REGISTER_NATIVE_METHODS("java/lang/reflect/Executable");
386 }
387
388 } // namespace art
389