• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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_Class.h"
18 
19 #include <iostream>
20 
21 #include "art_field-inl.h"
22 #include "class_linker.h"
23 #include "common_throws.h"
24 #include "dex_file-inl.h"
25 #include "jni_internal.h"
26 #include "nth_caller_visitor.h"
27 #include "mirror/class-inl.h"
28 #include "mirror/class_loader.h"
29 #include "mirror/field-inl.h"
30 #include "mirror/method.h"
31 #include "mirror/object-inl.h"
32 #include "mirror/object_array-inl.h"
33 #include "mirror/string-inl.h"
34 #include "reflection.h"
35 #include "scoped_thread_state_change.h"
36 #include "scoped_fast_native_object_access.h"
37 #include "ScopedLocalRef.h"
38 #include "ScopedUtfChars.h"
39 #include "utf.h"
40 #include "well_known_classes.h"
41 
42 namespace art {
43 
DecodeClass(const ScopedFastNativeObjectAccess & soa,jobject java_class)44 ALWAYS_INLINE static inline mirror::Class* DecodeClass(
45     const ScopedFastNativeObjectAccess& soa, jobject java_class)
46     SHARED_REQUIRES(Locks::mutator_lock_) {
47   mirror::Class* c = soa.Decode<mirror::Class*>(java_class);
48   DCHECK(c != nullptr);
49   DCHECK(c->IsClass());
50   // TODO: we could EnsureInitialized here, rather than on every reflective get/set or invoke .
51   // For now, we conservatively preserve the old dalvik behavior. A quick "IsInitialized" check
52   // every time probably doesn't make much difference to reflection performance anyway.
53   return c;
54 }
55 
56 // "name" is in "binary name" format, e.g. "dalvik.system.Debug$1".
Class_classForName(JNIEnv * env,jclass,jstring javaName,jboolean initialize,jobject javaLoader)57 static jclass Class_classForName(JNIEnv* env, jclass, jstring javaName, jboolean initialize,
58                                  jobject javaLoader) {
59   ScopedFastNativeObjectAccess soa(env);
60   ScopedUtfChars name(env, javaName);
61   if (name.c_str() == nullptr) {
62     return nullptr;
63   }
64 
65   // We need to validate and convert the name (from x.y.z to x/y/z).  This
66   // is especially handy for array types, since we want to avoid
67   // auto-generating bogus array classes.
68   if (!IsValidBinaryClassName(name.c_str())) {
69     soa.Self()->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
70                                    "Invalid name: %s", name.c_str());
71     return nullptr;
72   }
73 
74   std::string descriptor(DotToDescriptor(name.c_str()));
75   StackHandleScope<2> hs(soa.Self());
76   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(soa.Decode<mirror::ClassLoader*>(javaLoader)));
77   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
78   Handle<mirror::Class> c(
79       hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor.c_str(), class_loader)));
80   if (c.Get() == nullptr) {
81     ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
82     env->ExceptionClear();
83     jthrowable cnfe = reinterpret_cast<jthrowable>(env->NewObject(WellKnownClasses::java_lang_ClassNotFoundException,
84                                                                   WellKnownClasses::java_lang_ClassNotFoundException_init,
85                                                                   javaName, cause.get()));
86     if (cnfe != nullptr) {
87       // Make sure allocation didn't fail with an OOME.
88       env->Throw(cnfe);
89     }
90     return nullptr;
91   }
92   if (initialize) {
93     class_linker->EnsureInitialized(soa.Self(), c, true, true);
94   }
95   return soa.AddLocalReference<jclass>(c.Get());
96 }
97 
Class_getNameNative(JNIEnv * env,jobject javaThis)98 static jstring Class_getNameNative(JNIEnv* env, jobject javaThis) {
99   ScopedFastNativeObjectAccess soa(env);
100   StackHandleScope<1> hs(soa.Self());
101   mirror::Class* const c = DecodeClass(soa, javaThis);
102   return soa.AddLocalReference<jstring>(mirror::Class::ComputeName(hs.NewHandle(c)));
103 }
104 
Class_getProxyInterfaces(JNIEnv * env,jobject javaThis)105 static jobjectArray Class_getProxyInterfaces(JNIEnv* env, jobject javaThis) {
106   ScopedFastNativeObjectAccess soa(env);
107   mirror::Class* c = DecodeClass(soa, javaThis);
108   return soa.AddLocalReference<jobjectArray>(c->GetInterfaces()->Clone(soa.Self()));
109 }
110 
GetDeclaredFields(Thread * self,mirror::Class * klass,bool public_only,bool force_resolve)111 static mirror::ObjectArray<mirror::Field>* GetDeclaredFields(
112     Thread* self, mirror::Class* klass, bool public_only, bool force_resolve)
113       SHARED_REQUIRES(Locks::mutator_lock_) {
114   StackHandleScope<1> hs(self);
115   IterationRange<StrideIterator<ArtField>> ifields = klass->GetIFields();
116   IterationRange<StrideIterator<ArtField>> sfields = klass->GetSFields();
117   size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
118   if (public_only) {
119     // Lets go subtract all the non public fields.
120     for (ArtField& field : ifields) {
121       if (!field.IsPublic()) {
122         --array_size;
123       }
124     }
125     for (ArtField& field : sfields) {
126       if (!field.IsPublic()) {
127         --array_size;
128       }
129     }
130   }
131   size_t array_idx = 0;
132   auto object_array = hs.NewHandle(mirror::ObjectArray<mirror::Field>::Alloc(
133       self, mirror::Field::ArrayClass(), array_size));
134   if (object_array.Get() == nullptr) {
135     return nullptr;
136   }
137   for (ArtField& field : ifields) {
138     if (!public_only || field.IsPublic()) {
139       auto* reflect_field = mirror::Field::CreateFromArtField(self, &field, force_resolve);
140       if (reflect_field == nullptr) {
141         if (kIsDebugBuild) {
142           self->AssertPendingException();
143         }
144         // Maybe null due to OOME or type resolving exception.
145         return nullptr;
146       }
147       object_array->SetWithoutChecks<false>(array_idx++, reflect_field);
148     }
149   }
150   for (ArtField& field : sfields) {
151     if (!public_only || field.IsPublic()) {
152       auto* reflect_field = mirror::Field::CreateFromArtField(self, &field, force_resolve);
153       if (reflect_field == nullptr) {
154         if (kIsDebugBuild) {
155           self->AssertPendingException();
156         }
157         return nullptr;
158       }
159       object_array->SetWithoutChecks<false>(array_idx++, reflect_field);
160     }
161   }
162   DCHECK_EQ(array_idx, array_size);
163   return object_array.Get();
164 }
165 
Class_getDeclaredFieldsUnchecked(JNIEnv * env,jobject javaThis,jboolean publicOnly)166 static jobjectArray Class_getDeclaredFieldsUnchecked(JNIEnv* env, jobject javaThis,
167                                                      jboolean publicOnly) {
168   ScopedFastNativeObjectAccess soa(env);
169   return soa.AddLocalReference<jobjectArray>(
170       GetDeclaredFields(soa.Self(), DecodeClass(soa, javaThis), publicOnly != JNI_FALSE, false));
171 }
172 
Class_getDeclaredFields(JNIEnv * env,jobject javaThis)173 static jobjectArray Class_getDeclaredFields(JNIEnv* env, jobject javaThis) {
174   ScopedFastNativeObjectAccess soa(env);
175   return soa.AddLocalReference<jobjectArray>(
176       GetDeclaredFields(soa.Self(), DecodeClass(soa, javaThis), false, true));
177 }
178 
Class_getPublicDeclaredFields(JNIEnv * env,jobject javaThis)179 static jobjectArray Class_getPublicDeclaredFields(JNIEnv* env, jobject javaThis) {
180   ScopedFastNativeObjectAccess soa(env);
181   return soa.AddLocalReference<jobjectArray>(
182       GetDeclaredFields(soa.Self(), DecodeClass(soa, javaThis), true, true));
183 }
184 
185 // Performs a binary search through an array of fields, TODO: Is this fast enough if we don't use
186 // the dex cache for lookups? I think CompareModifiedUtf8ToUtf16AsCodePointValues should be fairly
187 // fast.
FindFieldByName(Thread * self ATTRIBUTE_UNUSED,mirror::String * name,LengthPrefixedArray<ArtField> * fields)188 ALWAYS_INLINE static inline ArtField* FindFieldByName(
189     Thread* self ATTRIBUTE_UNUSED, mirror::String* name, LengthPrefixedArray<ArtField>* fields)
190     SHARED_REQUIRES(Locks::mutator_lock_) {
191   if (fields == nullptr) {
192     return nullptr;
193   }
194   size_t low = 0;
195   size_t high = fields->size();
196   const uint16_t* const data = name->GetValue();
197   const size_t length = name->GetLength();
198   while (low < high) {
199     auto mid = (low + high) / 2;
200     ArtField& field = fields->At(mid);
201     int result = CompareModifiedUtf8ToUtf16AsCodePointValues(field.GetName(), data, length);
202     // Alternate approach, only a few % faster at the cost of more allocations.
203     // int result = field->GetStringName(self, true)->CompareTo(name);
204     if (result < 0) {
205       low = mid + 1;
206     } else if (result > 0) {
207       high = mid;
208     } else {
209       return &field;
210     }
211   }
212   if (kIsDebugBuild) {
213     for (ArtField& field : MakeIterationRangeFromLengthPrefixedArray(fields)) {
214       CHECK_NE(field.GetName(), name->ToModifiedUtf8());
215     }
216   }
217   return nullptr;
218 }
219 
GetDeclaredField(Thread * self,mirror::Class * c,mirror::String * name)220 ALWAYS_INLINE static inline mirror::Field* GetDeclaredField(
221     Thread* self, mirror::Class* c, mirror::String* name)
222     SHARED_REQUIRES(Locks::mutator_lock_) {
223   ArtField* art_field = FindFieldByName(self, name, c->GetIFieldsPtr());
224   if (art_field != nullptr) {
225     return mirror::Field::CreateFromArtField(self, art_field, true);
226   }
227   art_field = FindFieldByName(self, name, c->GetSFieldsPtr());
228   if (art_field != nullptr) {
229     return mirror::Field::CreateFromArtField(self, art_field, true);
230   }
231   return nullptr;
232 }
233 
GetPublicFieldRecursive(Thread * self,mirror::Class * clazz,mirror::String * name)234 static mirror::Field* GetPublicFieldRecursive(
235     Thread* self, mirror::Class* clazz, mirror::String* name)
236     SHARED_REQUIRES(Locks::mutator_lock_) {
237   DCHECK(clazz != nullptr);
238   DCHECK(name != nullptr);
239   DCHECK(self != nullptr);
240 
241   StackHandleScope<2> hs(self);
242   MutableHandle<mirror::Class> h_clazz(hs.NewHandle(clazz));
243   Handle<mirror::String> h_name(hs.NewHandle(name));
244 
245   // We search the current class, its direct interfaces then its superclass.
246   while (h_clazz.Get() != nullptr) {
247     mirror::Field* result = GetDeclaredField(self, h_clazz.Get(), h_name.Get());
248     if ((result != nullptr) && (result->GetAccessFlags() & kAccPublic)) {
249       return result;
250     } else if (UNLIKELY(self->IsExceptionPending())) {
251       // Something went wrong. Bail out.
252       return nullptr;
253     }
254 
255     uint32_t num_direct_interfaces = h_clazz->NumDirectInterfaces();
256     for (uint32_t i = 0; i < num_direct_interfaces; i++) {
257       mirror::Class *iface = mirror::Class::GetDirectInterface(self, h_clazz, i);
258       if (UNLIKELY(iface == nullptr)) {
259         self->AssertPendingException();
260         return nullptr;
261       }
262       result = GetPublicFieldRecursive(self, iface, h_name.Get());
263       if (result != nullptr) {
264         DCHECK(result->GetAccessFlags() & kAccPublic);
265         return result;
266       } else if (UNLIKELY(self->IsExceptionPending())) {
267         // Something went wrong. Bail out.
268         return nullptr;
269       }
270     }
271 
272     // We don't try the superclass if we are an interface.
273     if (h_clazz->IsInterface()) {
274       break;
275     }
276 
277     // Get the next class.
278     h_clazz.Assign(h_clazz->GetSuperClass());
279   }
280   return nullptr;
281 }
282 
Class_getPublicFieldRecursive(JNIEnv * env,jobject javaThis,jstring name)283 static jobject Class_getPublicFieldRecursive(JNIEnv* env, jobject javaThis, jstring name) {
284   ScopedFastNativeObjectAccess soa(env);
285   auto* name_string = soa.Decode<mirror::String*>(name);
286   if (UNLIKELY(name_string == nullptr)) {
287     ThrowNullPointerException("name == null");
288     return nullptr;
289   }
290   return soa.AddLocalReference<jobject>(
291       GetPublicFieldRecursive(soa.Self(), DecodeClass(soa, javaThis), name_string));
292 }
293 
Class_getDeclaredField(JNIEnv * env,jobject javaThis,jstring name)294 static jobject Class_getDeclaredField(JNIEnv* env, jobject javaThis, jstring name) {
295   ScopedFastNativeObjectAccess soa(env);
296   auto* name_string = soa.Decode<mirror::String*>(name);
297   if (name_string == nullptr) {
298     ThrowNullPointerException("name == null");
299     return nullptr;
300   }
301   auto* klass = DecodeClass(soa, javaThis);
302   mirror::Field* result = GetDeclaredField(soa.Self(), klass, name_string);
303   if (result == nullptr) {
304     std::string name_str = name_string->ToModifiedUtf8();
305     if (name_str == "value" && klass->IsStringClass()) {
306       // We log the error for this specific case, as the user might just swallow the exception.
307       // This helps diagnose crashes when applications rely on the String#value field being
308       // there.
309       // Also print on the error stream to test it through run-test.
310       std::string message("The String#value field is not present on Android versions >= 6.0");
311       LOG(ERROR) << message;
312       std::cerr << message << std::endl;
313     }
314     // We may have a pending exception if we failed to resolve.
315     if (!soa.Self()->IsExceptionPending()) {
316       ThrowNoSuchFieldException(DecodeClass(soa, javaThis), name_str.c_str());
317     }
318     return nullptr;
319   }
320   return soa.AddLocalReference<jobject>(result);
321 }
322 
Class_getDeclaredConstructorInternal(JNIEnv * env,jobject javaThis,jobjectArray args)323 static jobject Class_getDeclaredConstructorInternal(
324     JNIEnv* env, jobject javaThis, jobjectArray args) {
325   ScopedFastNativeObjectAccess soa(env);
326   mirror::Constructor* result = mirror::Class::GetDeclaredConstructorInternal(
327       soa.Self(),
328       DecodeClass(soa, javaThis),
329       soa.Decode<mirror::ObjectArray<mirror::Class>*>(args));
330   return soa.AddLocalReference<jobject>(result);
331 }
332 
MethodMatchesConstructor(ArtMethod * m,bool public_only)333 static ALWAYS_INLINE inline bool MethodMatchesConstructor(ArtMethod* m, bool public_only)
334     SHARED_REQUIRES(Locks::mutator_lock_) {
335   DCHECK(m != nullptr);
336   return (!public_only || m->IsPublic()) && !m->IsStatic() && m->IsConstructor();
337 }
338 
Class_getDeclaredConstructorsInternal(JNIEnv * env,jobject javaThis,jboolean publicOnly)339 static jobjectArray Class_getDeclaredConstructorsInternal(
340     JNIEnv* env, jobject javaThis, jboolean publicOnly) {
341   ScopedFastNativeObjectAccess soa(env);
342   StackHandleScope<2> hs(soa.Self());
343   Handle<mirror::Class> h_klass = hs.NewHandle(DecodeClass(soa, javaThis));
344   size_t constructor_count = 0;
345   // Two pass approach for speed.
346   for (auto& m : h_klass->GetDirectMethods(sizeof(void*))) {
347     constructor_count += MethodMatchesConstructor(&m, publicOnly != JNI_FALSE) ? 1u : 0u;
348   }
349   auto h_constructors = hs.NewHandle(mirror::ObjectArray<mirror::Constructor>::Alloc(
350       soa.Self(), mirror::Constructor::ArrayClass(), constructor_count));
351   if (UNLIKELY(h_constructors.Get() == nullptr)) {
352     soa.Self()->AssertPendingException();
353     return nullptr;
354   }
355   constructor_count = 0;
356   for (auto& m : h_klass->GetDirectMethods(sizeof(void*))) {
357     if (MethodMatchesConstructor(&m, publicOnly != JNI_FALSE)) {
358       auto* constructor = mirror::Constructor::CreateFromArtMethod(soa.Self(), &m);
359       if (UNLIKELY(constructor == nullptr)) {
360         soa.Self()->AssertPendingOOMException();
361         return nullptr;
362       }
363       h_constructors->SetWithoutChecks<false>(constructor_count++, constructor);
364     }
365   }
366   return soa.AddLocalReference<jobjectArray>(h_constructors.Get());
367 }
368 
Class_getDeclaredMethodInternal(JNIEnv * env,jobject javaThis,jobject name,jobjectArray args)369 static jobject Class_getDeclaredMethodInternal(JNIEnv* env, jobject javaThis,
370                                                jobject name, jobjectArray args) {
371   ScopedFastNativeObjectAccess soa(env);
372   mirror::Method* result = mirror::Class::GetDeclaredMethodInternal(
373       soa.Self(),
374       DecodeClass(soa, javaThis),
375       soa.Decode<mirror::String*>(name),
376       soa.Decode<mirror::ObjectArray<mirror::Class>*>(args));
377   return soa.AddLocalReference<jobject>(result);
378 }
379 
Class_getDeclaredMethodsUnchecked(JNIEnv * env,jobject javaThis,jboolean publicOnly)380 static jobjectArray Class_getDeclaredMethodsUnchecked(JNIEnv* env, jobject javaThis,
381                                                       jboolean publicOnly) {
382   ScopedFastNativeObjectAccess soa(env);
383   StackHandleScope<2> hs(soa.Self());
384   Handle<mirror::Class> klass = hs.NewHandle(DecodeClass(soa, javaThis));
385   size_t num_methods = 0;
386   for (auto& m : klass->GetDeclaredMethods(sizeof(void*))) {
387     auto modifiers = m.GetAccessFlags();
388     // Add non-constructor declared methods.
389     if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
390         (modifiers & kAccConstructor) == 0) {
391       ++num_methods;
392     }
393   }
394   auto ret = hs.NewHandle(mirror::ObjectArray<mirror::Method>::Alloc(
395       soa.Self(), mirror::Method::ArrayClass(), num_methods));
396   num_methods = 0;
397   for (auto& m : klass->GetDeclaredMethods(sizeof(void*))) {
398     auto modifiers = m.GetAccessFlags();
399     if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
400         (modifiers & kAccConstructor) == 0) {
401       auto* method = mirror::Method::CreateFromArtMethod(soa.Self(), &m);
402       if (method == nullptr) {
403         soa.Self()->AssertPendingException();
404         return nullptr;
405       }
406       ret->SetWithoutChecks<false>(num_methods++, method);
407     }
408   }
409   return soa.AddLocalReference<jobjectArray>(ret.Get());
410 }
411 
Class_getDeclaredAnnotation(JNIEnv * env,jobject javaThis,jclass annotationClass)412 static jobject Class_getDeclaredAnnotation(JNIEnv* env, jobject javaThis, jclass annotationClass) {
413   ScopedFastNativeObjectAccess soa(env);
414   StackHandleScope<2> hs(soa.Self());
415   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
416 
417   // Handle public contract to throw NPE if the "annotationClass" argument was null.
418   if (UNLIKELY(annotationClass == nullptr)) {
419     ThrowNullPointerException("annotationClass");
420     return nullptr;
421   }
422 
423   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
424     return nullptr;
425   }
426   Handle<mirror::Class> annotation_class(hs.NewHandle(soa.Decode<mirror::Class*>(annotationClass)));
427   return soa.AddLocalReference<jobject>(
428       klass->GetDexFile().GetAnnotationForClass(klass, annotation_class));
429 }
430 
Class_getDeclaredAnnotations(JNIEnv * env,jobject javaThis)431 static jobjectArray Class_getDeclaredAnnotations(JNIEnv* env, jobject javaThis) {
432   ScopedFastNativeObjectAccess soa(env);
433   StackHandleScope<1> hs(soa.Self());
434   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
435   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
436     // Return an empty array instead of a null pointer.
437     mirror::Class* annotation_array_class =
438         soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_annotation_Annotation__array);
439     mirror::ObjectArray<mirror::Object>* empty_array =
440         mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), annotation_array_class, 0);
441     return soa.AddLocalReference<jobjectArray>(empty_array);
442   }
443   return soa.AddLocalReference<jobjectArray>(klass->GetDexFile().GetAnnotationsForClass(klass));
444 }
445 
Class_getDeclaredClasses(JNIEnv * env,jobject javaThis)446 static jobjectArray Class_getDeclaredClasses(JNIEnv* env, jobject javaThis) {
447   ScopedFastNativeObjectAccess soa(env);
448   StackHandleScope<1> hs(soa.Self());
449   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
450   mirror::ObjectArray<mirror::Class>* classes = nullptr;
451   if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
452     classes = klass->GetDexFile().GetDeclaredClasses(klass);
453   }
454   if (classes == nullptr) {
455     // Return an empty array instead of a null pointer.
456     if (soa.Self()->IsExceptionPending()) {
457       // Pending exception from GetDeclaredClasses.
458       return nullptr;
459     }
460     mirror::Class* class_class = mirror::Class::GetJavaLangClass();
461     mirror::Class* class_array_class =
462         Runtime::Current()->GetClassLinker()->FindArrayClass(soa.Self(), &class_class);
463     if (class_array_class == nullptr) {
464       return nullptr;
465     }
466     mirror::ObjectArray<mirror::Class>* empty_array =
467         mirror::ObjectArray<mirror::Class>::Alloc(soa.Self(), class_array_class, 0);
468     return soa.AddLocalReference<jobjectArray>(empty_array);
469   }
470   return soa.AddLocalReference<jobjectArray>(classes);
471 }
472 
Class_getEnclosingClass(JNIEnv * env,jobject javaThis)473 static jclass Class_getEnclosingClass(JNIEnv* env, jobject javaThis) {
474   ScopedFastNativeObjectAccess soa(env);
475   StackHandleScope<1> hs(soa.Self());
476   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
477   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
478     return nullptr;
479   }
480   return soa.AddLocalReference<jclass>(klass->GetDexFile().GetEnclosingClass(klass));
481 }
482 
Class_getEnclosingConstructorNative(JNIEnv * env,jobject javaThis)483 static jobject Class_getEnclosingConstructorNative(JNIEnv* env, jobject javaThis) {
484   ScopedFastNativeObjectAccess soa(env);
485   StackHandleScope<1> hs(soa.Self());
486   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
487   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
488     return nullptr;
489   }
490   mirror::Object* method = klass->GetDexFile().GetEnclosingMethod(klass);
491   if (method != nullptr) {
492     if (method->GetClass() ==
493         soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_reflect_Constructor)) {
494       return soa.AddLocalReference<jobject>(method);
495     }
496   }
497   return nullptr;
498 }
499 
Class_getEnclosingMethodNative(JNIEnv * env,jobject javaThis)500 static jobject Class_getEnclosingMethodNative(JNIEnv* env, jobject javaThis) {
501   ScopedFastNativeObjectAccess soa(env);
502   StackHandleScope<1> hs(soa.Self());
503   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
504   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
505     return nullptr;
506   }
507   mirror::Object* method = klass->GetDexFile().GetEnclosingMethod(klass);
508   if (method != nullptr) {
509     if (method->GetClass() ==
510         soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_reflect_Method)) {
511       return soa.AddLocalReference<jobject>(method);
512     }
513   }
514   return nullptr;
515 }
516 
Class_getInnerClassFlags(JNIEnv * env,jobject javaThis,jint defaultValue)517 static jint Class_getInnerClassFlags(JNIEnv* env, jobject javaThis, jint defaultValue) {
518   ScopedFastNativeObjectAccess soa(env);
519   StackHandleScope<1> hs(soa.Self());
520   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
521   return mirror::Class::GetInnerClassFlags(klass, defaultValue);
522 }
523 
Class_getInnerClassName(JNIEnv * env,jobject javaThis)524 static jstring Class_getInnerClassName(JNIEnv* env, jobject javaThis) {
525   ScopedFastNativeObjectAccess soa(env);
526   StackHandleScope<1> hs(soa.Self());
527   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
528   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
529     return nullptr;
530   }
531   mirror::String* class_name = nullptr;
532   if (!klass->GetDexFile().GetInnerClass(klass, &class_name)) {
533     return nullptr;
534   }
535   return soa.AddLocalReference<jstring>(class_name);
536 }
537 
Class_getSignatureAnnotation(JNIEnv * env,jobject javaThis)538 static jobjectArray Class_getSignatureAnnotation(JNIEnv* env, jobject javaThis) {
539   ScopedFastNativeObjectAccess soa(env);
540   StackHandleScope<1> hs(soa.Self());
541   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
542   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
543     return nullptr;
544   }
545   return soa.AddLocalReference<jobjectArray>(
546       klass->GetDexFile().GetSignatureAnnotationForClass(klass));
547 }
548 
Class_isAnonymousClass(JNIEnv * env,jobject javaThis)549 static jboolean Class_isAnonymousClass(JNIEnv* env, jobject javaThis) {
550   ScopedFastNativeObjectAccess soa(env);
551   StackHandleScope<1> hs(soa.Self());
552   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
553   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
554     return false;
555   }
556   mirror::String* class_name = nullptr;
557   if (!klass->GetDexFile().GetInnerClass(klass, &class_name)) {
558     return false;
559   }
560   return class_name == nullptr;
561 }
562 
Class_isDeclaredAnnotationPresent(JNIEnv * env,jobject javaThis,jclass annotationType)563 static jboolean Class_isDeclaredAnnotationPresent(JNIEnv* env, jobject javaThis,
564                                                   jclass annotationType) {
565   ScopedFastNativeObjectAccess soa(env);
566   StackHandleScope<2> hs(soa.Self());
567   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
568   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
569     return false;
570   }
571   Handle<mirror::Class> annotation_class(hs.NewHandle(soa.Decode<mirror::Class*>(annotationType)));
572   return klass->GetDexFile().IsClassAnnotationPresent(klass, annotation_class);
573 }
574 
Class_getDeclaringClass(JNIEnv * env,jobject javaThis)575 static jclass Class_getDeclaringClass(JNIEnv* env, jobject javaThis) {
576   ScopedFastNativeObjectAccess soa(env);
577   StackHandleScope<1> hs(soa.Self());
578   Handle<mirror::Class> klass(hs.NewHandle(DecodeClass(soa, javaThis)));
579   if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
580     return nullptr;
581   }
582   // Return null for anonymous classes.
583   if (Class_isAnonymousClass(env, javaThis)) {
584     return nullptr;
585   }
586   return soa.AddLocalReference<jclass>(klass->GetDexFile().GetDeclaringClass(klass));
587 }
588 
Class_newInstance(JNIEnv * env,jobject javaThis)589 static jobject Class_newInstance(JNIEnv* env, jobject javaThis) {
590   ScopedFastNativeObjectAccess soa(env);
591   StackHandleScope<4> hs(soa.Self());
592   Handle<mirror::Class> klass = hs.NewHandle(DecodeClass(soa, javaThis));
593   if (UNLIKELY(klass->GetPrimitiveType() != 0 || klass->IsInterface() || klass->IsArrayClass() ||
594                klass->IsAbstract())) {
595     soa.Self()->ThrowNewExceptionF("Ljava/lang/InstantiationException;",
596                                    "%s cannot be instantiated", PrettyClass(klass.Get()).c_str());
597     return nullptr;
598   }
599   auto caller = hs.NewHandle<mirror::Class>(nullptr);
600   // Verify that we can access the class.
601   if (!klass->IsPublic()) {
602     caller.Assign(GetCallingClass(soa.Self(), 1));
603     if (caller.Get() != nullptr && !caller->CanAccess(klass.Get())) {
604       soa.Self()->ThrowNewExceptionF(
605           "Ljava/lang/IllegalAccessException;", "%s is not accessible from %s",
606           PrettyClass(klass.Get()).c_str(), PrettyClass(caller.Get()).c_str());
607       return nullptr;
608     }
609   }
610   auto* constructor = klass->GetDeclaredConstructor(
611       soa.Self(),
612       ScopedNullHandle<mirror::ObjectArray<mirror::Class>>(),
613       sizeof(void*));
614   if (UNLIKELY(constructor == nullptr)) {
615     soa.Self()->ThrowNewExceptionF("Ljava/lang/InstantiationException;",
616                                    "%s has no zero argument constructor",
617                                    PrettyClass(klass.Get()).c_str());
618     return nullptr;
619   }
620   // Invoke the string allocator to return an empty string for the string class.
621   if (klass->IsStringClass()) {
622     gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
623     mirror::SetStringCountVisitor visitor(0);
624     mirror::Object* obj = mirror::String::Alloc<true>(soa.Self(), 0, allocator_type, visitor);
625     if (UNLIKELY(soa.Self()->IsExceptionPending())) {
626       return nullptr;
627     } else {
628       return soa.AddLocalReference<jobject>(obj);
629     }
630   }
631   auto receiver = hs.NewHandle(klass->AllocObject(soa.Self()));
632   if (UNLIKELY(receiver.Get() == nullptr)) {
633     soa.Self()->AssertPendingOOMException();
634     return nullptr;
635   }
636   // Verify that we can access the constructor.
637   auto* declaring_class = constructor->GetDeclaringClass();
638   if (!constructor->IsPublic()) {
639     if (caller.Get() == nullptr) {
640       caller.Assign(GetCallingClass(soa.Self(), 1));
641     }
642     if (UNLIKELY(caller.Get() != nullptr && !VerifyAccess(
643         soa.Self(), receiver.Get(), declaring_class, constructor->GetAccessFlags(),
644         caller.Get()))) {
645       soa.Self()->ThrowNewExceptionF(
646           "Ljava/lang/IllegalAccessException;", "%s is not accessible from %s",
647           PrettyMethod(constructor).c_str(), PrettyClass(caller.Get()).c_str());
648       return nullptr;
649     }
650   }
651   // Ensure that we are initialized.
652   if (UNLIKELY(!declaring_class->IsInitialized())) {
653     if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(
654         soa.Self(), hs.NewHandle(declaring_class), true, true)) {
655       soa.Self()->AssertPendingException();
656       return nullptr;
657     }
658   }
659   // Invoke the constructor.
660   JValue result;
661   uint32_t args[1] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(receiver.Get())) };
662   constructor->Invoke(soa.Self(), args, sizeof(args), &result, "V");
663   if (UNLIKELY(soa.Self()->IsExceptionPending())) {
664     return nullptr;
665   }
666   // Constructors are ()V methods, so we shouldn't touch the result of InvokeMethod.
667   return soa.AddLocalReference<jobject>(receiver.Get());
668 }
669 
670 static JNINativeMethod gMethods[] = {
671   NATIVE_METHOD(Class, classForName,
672                 "!(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"),
673   NATIVE_METHOD(Class, getDeclaredAnnotation,
674                 "!(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;"),
675   NATIVE_METHOD(Class, getDeclaredAnnotations, "!()[Ljava/lang/annotation/Annotation;"),
676   NATIVE_METHOD(Class, getDeclaredClasses, "!()[Ljava/lang/Class;"),
677   NATIVE_METHOD(Class, getDeclaredConstructorInternal,
678                 "!([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;"),
679   NATIVE_METHOD(Class, getDeclaredConstructorsInternal, "!(Z)[Ljava/lang/reflect/Constructor;"),
680   NATIVE_METHOD(Class, getDeclaredField, "!(Ljava/lang/String;)Ljava/lang/reflect/Field;"),
681   NATIVE_METHOD(Class, getPublicFieldRecursive, "!(Ljava/lang/String;)Ljava/lang/reflect/Field;"),
682   NATIVE_METHOD(Class, getDeclaredFields, "!()[Ljava/lang/reflect/Field;"),
683   NATIVE_METHOD(Class, getDeclaredFieldsUnchecked, "!(Z)[Ljava/lang/reflect/Field;"),
684   NATIVE_METHOD(Class, getDeclaredMethodInternal,
685                 "!(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"),
686   NATIVE_METHOD(Class, getDeclaredMethodsUnchecked,
687                 "!(Z)[Ljava/lang/reflect/Method;"),
688   NATIVE_METHOD(Class, getDeclaringClass, "!()Ljava/lang/Class;"),
689   NATIVE_METHOD(Class, getEnclosingClass, "!()Ljava/lang/Class;"),
690   NATIVE_METHOD(Class, getEnclosingConstructorNative, "!()Ljava/lang/reflect/Constructor;"),
691   NATIVE_METHOD(Class, getEnclosingMethodNative, "!()Ljava/lang/reflect/Method;"),
692   NATIVE_METHOD(Class, getInnerClassFlags, "!(I)I"),
693   NATIVE_METHOD(Class, getInnerClassName, "!()Ljava/lang/String;"),
694   NATIVE_METHOD(Class, getNameNative, "!()Ljava/lang/String;"),
695   NATIVE_METHOD(Class, getProxyInterfaces, "!()[Ljava/lang/Class;"),
696   NATIVE_METHOD(Class, getPublicDeclaredFields, "!()[Ljava/lang/reflect/Field;"),
697   NATIVE_METHOD(Class, getSignatureAnnotation, "!()[Ljava/lang/String;"),
698   NATIVE_METHOD(Class, isAnonymousClass, "!()Z"),
699   NATIVE_METHOD(Class, isDeclaredAnnotationPresent, "!(Ljava/lang/Class;)Z"),
700   NATIVE_METHOD(Class, newInstance, "!()Ljava/lang/Object;"),
701 };
702 
register_java_lang_Class(JNIEnv * env)703 void register_java_lang_Class(JNIEnv* env) {
704   REGISTER_NATIVE_METHODS("java/lang/Class");
705 }
706 
707 }  // namespace art
708