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 "art_field-inl.h"
20 #include "class_linker.h"
21 #include "common_throws.h"
22 #include "dex_file-inl.h"
23 #include "jni_internal.h"
24 #include "nth_caller_visitor.h"
25 #include "mirror/class-inl.h"
26 #include "mirror/class_loader.h"
27 #include "mirror/field-inl.h"
28 #include "mirror/method.h"
29 #include "mirror/object-inl.h"
30 #include "mirror/object_array-inl.h"
31 #include "mirror/string-inl.h"
32 #include "reflection.h"
33 #include "scoped_thread_state_change.h"
34 #include "scoped_fast_native_object_access.h"
35 #include "ScopedLocalRef.h"
36 #include "ScopedUtfChars.h"
37 #include "utf.h"
38 #include "well_known_classes.h"
39 
40 namespace art {
41 
DecodeClass(const ScopedFastNativeObjectAccess & soa,jobject java_class)42 ALWAYS_INLINE static inline mirror::Class* DecodeClass(
43     const ScopedFastNativeObjectAccess& soa, jobject java_class)
44     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
45   mirror::Class* c = soa.Decode<mirror::Class*>(java_class);
46   DCHECK(c != nullptr);
47   DCHECK(c->IsClass());
48   // TODO: we could EnsureInitialized here, rather than on every reflective get/set or invoke .
49   // For now, we conservatively preserve the old dalvik behavior. A quick "IsInitialized" check
50   // every time probably doesn't make much difference to reflection performance anyway.
51   return c;
52 }
53 
54 // "name" is in "binary name" format, e.g. "dalvik.system.Debug$1".
Class_classForName(JNIEnv * env,jclass,jstring javaName,jboolean initialize,jobject javaLoader)55 static jclass Class_classForName(JNIEnv* env, jclass, jstring javaName, jboolean initialize,
56                                  jobject javaLoader) {
57   ScopedFastNativeObjectAccess soa(env);
58   ScopedUtfChars name(env, javaName);
59   if (name.c_str() == nullptr) {
60     return nullptr;
61   }
62 
63   // We need to validate and convert the name (from x.y.z to x/y/z).  This
64   // is especially handy for array types, since we want to avoid
65   // auto-generating bogus array classes.
66   if (!IsValidBinaryClassName(name.c_str())) {
67     soa.Self()->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
68                                    "Invalid name: %s", name.c_str());
69     return nullptr;
70   }
71 
72   std::string descriptor(DotToDescriptor(name.c_str()));
73   StackHandleScope<2> hs(soa.Self());
74   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(soa.Decode<mirror::ClassLoader*>(javaLoader)));
75   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
76   Handle<mirror::Class> c(
77       hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor.c_str(), class_loader)));
78   if (c.Get() == nullptr) {
79     ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
80     env->ExceptionClear();
81     jthrowable cnfe = reinterpret_cast<jthrowable>(env->NewObject(WellKnownClasses::java_lang_ClassNotFoundException,
82                                                                   WellKnownClasses::java_lang_ClassNotFoundException_init,
83                                                                   javaName, cause.get()));
84     if (cnfe != nullptr) {
85       // Make sure allocation didn't fail with an OOME.
86       env->Throw(cnfe);
87     }
88     return nullptr;
89   }
90   if (initialize) {
91     class_linker->EnsureInitialized(soa.Self(), c, true, true);
92   }
93   return soa.AddLocalReference<jclass>(c.Get());
94 }
95 
Class_getNameNative(JNIEnv * env,jobject javaThis)96 static jstring Class_getNameNative(JNIEnv* env, jobject javaThis) {
97   ScopedFastNativeObjectAccess soa(env);
98   StackHandleScope<1> hs(soa.Self());
99   mirror::Class* const c = DecodeClass(soa, javaThis);
100   return soa.AddLocalReference<jstring>(mirror::Class::ComputeName(hs.NewHandle(c)));
101 }
102 
Class_getProxyInterfaces(JNIEnv * env,jobject javaThis)103 static jobjectArray Class_getProxyInterfaces(JNIEnv* env, jobject javaThis) {
104   ScopedFastNativeObjectAccess soa(env);
105   mirror::Class* c = DecodeClass(soa, javaThis);
106   return soa.AddLocalReference<jobjectArray>(c->GetInterfaces()->Clone(soa.Self()));
107 }
108 
GetDeclaredFields(Thread * self,mirror::Class * klass,bool public_only,bool force_resolve)109 static mirror::ObjectArray<mirror::Field>* GetDeclaredFields(
110     Thread* self, mirror::Class* klass, bool public_only, bool force_resolve)
111       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
112   StackHandleScope<1> hs(self);
113   auto* ifields = klass->GetIFields();
114   auto* sfields = klass->GetSFields();
115   const auto num_ifields = klass->NumInstanceFields();
116   const auto num_sfields = klass->NumStaticFields();
117   size_t array_size = num_ifields + num_sfields;
118   if (public_only) {
119     // Lets go subtract all the non public fields.
120     for (size_t i = 0; i < num_ifields; ++i) {
121       if (!ifields[i].IsPublic()) {
122         --array_size;
123       }
124     }
125     for (size_t i = 0; i < num_sfields; ++i) {
126       if (!sfields[i].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 (size_t i = 0; i < num_ifields; ++i) {
138     auto* art_field = &ifields[i];
139     if (!public_only || art_field->IsPublic()) {
140       auto* field = mirror::Field::CreateFromArtField(self, art_field, force_resolve);
141       if (field == nullptr) {
142         if (kIsDebugBuild) {
143           self->AssertPendingException();
144         }
145         // Maybe null due to OOME or type resolving exception.
146         return nullptr;
147       }
148       object_array->SetWithoutChecks<false>(array_idx++, field);
149     }
150   }
151   for (size_t i = 0; i < num_sfields; ++i) {
152     auto* art_field = &sfields[i];
153     if (!public_only || art_field->IsPublic()) {
154       auto* field = mirror::Field::CreateFromArtField(self, art_field, force_resolve);
155       if (field == nullptr) {
156         if (kIsDebugBuild) {
157           self->AssertPendingException();
158         }
159         return nullptr;
160       }
161       object_array->SetWithoutChecks<false>(array_idx++, field);
162     }
163   }
164   CHECK_EQ(array_idx, array_size);
165   return object_array.Get();
166 }
167 
Class_getDeclaredFieldsUnchecked(JNIEnv * env,jobject javaThis,jboolean publicOnly)168 static jobjectArray Class_getDeclaredFieldsUnchecked(JNIEnv* env, jobject javaThis,
169                                                      jboolean publicOnly) {
170   ScopedFastNativeObjectAccess soa(env);
171   return soa.AddLocalReference<jobjectArray>(
172       GetDeclaredFields(soa.Self(), DecodeClass(soa, javaThis), publicOnly != JNI_FALSE, false));
173 }
174 
Class_getDeclaredFields(JNIEnv * env,jobject javaThis)175 static jobjectArray Class_getDeclaredFields(JNIEnv* env, jobject javaThis) {
176   ScopedFastNativeObjectAccess soa(env);
177   return soa.AddLocalReference<jobjectArray>(
178       GetDeclaredFields(soa.Self(), DecodeClass(soa, javaThis), false, true));
179 }
180 
Class_getPublicDeclaredFields(JNIEnv * env,jobject javaThis)181 static jobjectArray Class_getPublicDeclaredFields(JNIEnv* env, jobject javaThis) {
182   ScopedFastNativeObjectAccess soa(env);
183   return soa.AddLocalReference<jobjectArray>(
184       GetDeclaredFields(soa.Self(), DecodeClass(soa, javaThis), true, true));
185 }
186 
187 // Performs a binary search through an array of fields, TODO: Is this fast enough if we don't use
188 // the dex cache for lookups? I think CompareModifiedUtf8ToUtf16AsCodePointValues should be fairly
189 // fast.
FindFieldByName(Thread * self ATTRIBUTE_UNUSED,mirror::String * name,ArtField * fields,size_t num_fields)190 ALWAYS_INLINE static inline ArtField* FindFieldByName(
191     Thread* self ATTRIBUTE_UNUSED, mirror::String* name, ArtField* fields, size_t num_fields)
192     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
193   size_t low = 0;
194   size_t high = num_fields;
195   const uint16_t* const data = name->GetValue();
196   const size_t length = name->GetLength();
197   while (low < high) {
198     auto mid = (low + high) / 2;
199     ArtField* const field = &fields[mid];
200     int result = CompareModifiedUtf8ToUtf16AsCodePointValues(field->GetName(), data, length);
201     // Alternate approach, only a few % faster at the cost of more allocations.
202     // int result = field->GetStringName(self, true)->CompareTo(name);
203     if (result < 0) {
204       low = mid + 1;
205     } else if (result > 0) {
206       high = mid;
207     } else {
208       return field;
209     }
210   }
211   if (kIsDebugBuild) {
212     for (size_t i = 0; i < num_fields; ++i) {
213       CHECK_NE(fields[i].GetName(), name->ToModifiedUtf8());
214     }
215   }
216   return nullptr;
217 }
218 
GetDeclaredField(Thread * self,mirror::Class * c,mirror::String * name)219 ALWAYS_INLINE static inline mirror::Field* GetDeclaredField(
220     Thread* self, mirror::Class* c, mirror::String* name)
221     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
222   auto* instance_fields = c->GetIFields();
223   auto* art_field = FindFieldByName(self, name, instance_fields, c->NumInstanceFields());
224   if (art_field != nullptr) {
225     return mirror::Field::CreateFromArtField(self, art_field, true);
226   }
227   auto* static_fields = c->GetSFields();
228   art_field = FindFieldByName(self, name, static_fields, c->NumStaticFields());
229   if (art_field != nullptr) {
230     return mirror::Field::CreateFromArtField(self, art_field, true);
231   }
232   return nullptr;
233 }
234 
Class_getDeclaredFieldInternal(JNIEnv * env,jobject javaThis,jstring name)235 static jobject Class_getDeclaredFieldInternal(JNIEnv* env, jobject javaThis, jstring name) {
236   ScopedFastNativeObjectAccess soa(env);
237   auto* name_string = soa.Decode<mirror::String*>(name);
238   return soa.AddLocalReference<jobject>(
239       GetDeclaredField(soa.Self(), DecodeClass(soa, javaThis), name_string));
240 }
241 
Class_getDeclaredField(JNIEnv * env,jobject javaThis,jstring name)242 static jobject Class_getDeclaredField(JNIEnv* env, jobject javaThis, jstring name) {
243   ScopedFastNativeObjectAccess soa(env);
244   auto* name_string = soa.Decode<mirror::String*>(name);
245   if (name_string == nullptr) {
246     ThrowNullPointerException("name == null");
247     return nullptr;
248   }
249   auto* klass = DecodeClass(soa, javaThis);
250   mirror::Field* result = GetDeclaredField(soa.Self(), klass, name_string);
251   if (result == nullptr) {
252     std::string name_str = name_string->ToModifiedUtf8();
253     // We may have a pending exception if we failed to resolve.
254     if (!soa.Self()->IsExceptionPending()) {
255       ThrowNoSuchFieldException(DecodeClass(soa, javaThis), name_str.c_str());
256     }
257     return nullptr;
258   }
259   return soa.AddLocalReference<jobject>(result);
260 }
261 
Class_getDeclaredConstructorInternal(JNIEnv * env,jobject javaThis,jobjectArray args)262 static jobject Class_getDeclaredConstructorInternal(
263     JNIEnv* env, jobject javaThis, jobjectArray args) {
264   ScopedFastNativeObjectAccess soa(env);
265   auto* klass = DecodeClass(soa, javaThis);
266   auto* params = soa.Decode<mirror::ObjectArray<mirror::Class>*>(args);
267   StackHandleScope<1> hs(soa.Self());
268   auto* declared_constructor = klass->GetDeclaredConstructor(soa.Self(), hs.NewHandle(params));
269   if (declared_constructor != nullptr) {
270     return soa.AddLocalReference<jobject>(
271         mirror::Constructor::CreateFromArtMethod(soa.Self(), declared_constructor));
272   }
273   return nullptr;
274 }
275 
MethodMatchesConstructor(ArtMethod * m,bool public_only)276 static ALWAYS_INLINE inline bool MethodMatchesConstructor(ArtMethod* m, bool public_only)
277     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
278   DCHECK(m != nullptr);
279   return (!public_only || m->IsPublic()) && !m->IsStatic() && m->IsConstructor();
280 }
281 
Class_getDeclaredConstructorsInternal(JNIEnv * env,jobject javaThis,jboolean publicOnly)282 static jobjectArray Class_getDeclaredConstructorsInternal(
283     JNIEnv* env, jobject javaThis, jboolean publicOnly) {
284   ScopedFastNativeObjectAccess soa(env);
285   StackHandleScope<2> hs(soa.Self());
286   Handle<mirror::Class> h_klass = hs.NewHandle(DecodeClass(soa, javaThis));
287   size_t constructor_count = 0;
288   // Two pass approach for speed.
289   for (auto& m : h_klass->GetDirectMethods(sizeof(void*))) {
290     constructor_count += MethodMatchesConstructor(&m, publicOnly != JNI_FALSE) ? 1u : 0u;
291   }
292   auto h_constructors = hs.NewHandle(mirror::ObjectArray<mirror::Constructor>::Alloc(
293       soa.Self(), mirror::Constructor::ArrayClass(), constructor_count));
294   if (UNLIKELY(h_constructors.Get() == nullptr)) {
295     soa.Self()->AssertPendingException();
296     return nullptr;
297   }
298   constructor_count = 0;
299   for (auto& m : h_klass->GetDirectMethods(sizeof(void*))) {
300     if (MethodMatchesConstructor(&m, publicOnly != JNI_FALSE)) {
301       auto* constructor = mirror::Constructor::CreateFromArtMethod(soa.Self(), &m);
302       if (UNLIKELY(constructor == nullptr)) {
303         soa.Self()->AssertPendingOOMException();
304         return nullptr;
305       }
306       h_constructors->SetWithoutChecks<false>(constructor_count++, constructor);
307     }
308   }
309   return soa.AddLocalReference<jobjectArray>(h_constructors.Get());
310 }
311 
Class_getDeclaredMethodInternal(JNIEnv * env,jobject javaThis,jobject name,jobjectArray args)312 static jobject Class_getDeclaredMethodInternal(JNIEnv* env, jobject javaThis,
313                                                jobject name, jobjectArray args) {
314   // Covariant return types permit the class to define multiple
315   // methods with the same name and parameter types. Prefer to
316   // return a non-synthetic method in such situations. We may
317   // still return a synthetic method to handle situations like
318   // escalated visibility. We never return miranda methods that
319   // were synthesized by the runtime.
320   constexpr uint32_t kSkipModifiers = kAccMiranda | kAccSynthetic;
321   ScopedFastNativeObjectAccess soa(env);
322   StackHandleScope<3> hs(soa.Self());
323   auto h_method_name = hs.NewHandle(soa.Decode<mirror::String*>(name));
324   if (UNLIKELY(h_method_name.Get() == nullptr)) {
325     ThrowNullPointerException("name == null");
326     return nullptr;
327   }
328   auto h_args = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(args));
329   Handle<mirror::Class> h_klass = hs.NewHandle(DecodeClass(soa, javaThis));
330   ArtMethod* result = nullptr;
331   for (auto& m : h_klass->GetVirtualMethods(sizeof(void*))) {
332     auto* np_method = m.GetInterfaceMethodIfProxy(sizeof(void*));
333     // May cause thread suspension.
334     mirror::String* np_name = np_method->GetNameAsString(soa.Self());
335     if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
336       if (UNLIKELY(soa.Self()->IsExceptionPending())) {
337         return nullptr;
338       }
339       continue;
340     }
341     auto modifiers = m.GetAccessFlags();
342     if ((modifiers & kSkipModifiers) == 0) {
343       return soa.AddLocalReference<jobject>(mirror::Method::CreateFromArtMethod(soa.Self(), &m));
344     }
345     if ((modifiers & kAccMiranda) == 0) {
346       result = &m;  // Remember as potential result if it's not a miranda method.
347     }
348   }
349   if (result == nullptr) {
350     for (auto& m : h_klass->GetDirectMethods(sizeof(void*))) {
351       auto modifiers = m.GetAccessFlags();
352       if ((modifiers & kAccConstructor) != 0) {
353         continue;
354       }
355       auto* np_method = m.GetInterfaceMethodIfProxy(sizeof(void*));
356       // May cause thread suspension.
357       mirror::String* np_name = np_method->GetNameAsString(soa.Self());
358       if (np_name == nullptr) {
359         soa.Self()->AssertPendingException();
360         return nullptr;
361       }
362       if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
363         if (UNLIKELY(soa.Self()->IsExceptionPending())) {
364           return nullptr;
365         }
366         continue;
367       }
368       if ((modifiers & kSkipModifiers) == 0) {
369         return soa.AddLocalReference<jobject>(mirror::Method::CreateFromArtMethod(soa.Self(), &m));
370       }
371       // Direct methods cannot be miranda methods, so this potential result must be synthetic.
372       result = &m;
373     }
374   }
375   return result != nullptr ?
376       soa.AddLocalReference<jobject>(mirror::Method::CreateFromArtMethod(soa.Self(), result)) :
377       nullptr;
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->GetVirtualMethods(sizeof(void*))) {
387     auto modifiers = m.GetAccessFlags();
388     if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
389         (modifiers & kAccMiranda) == 0) {
390       ++num_methods;
391     }
392   }
393   for (auto& m : klass->GetDirectMethods(sizeof(void*))) {
394     auto modifiers = m.GetAccessFlags();
395     // Add non-constructor direct/static methods.
396     if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
397         (modifiers & kAccConstructor) == 0) {
398       ++num_methods;
399     }
400   }
401   auto ret = hs.NewHandle(mirror::ObjectArray<mirror::Method>::Alloc(
402       soa.Self(), mirror::Method::ArrayClass(), num_methods));
403   num_methods = 0;
404   for (auto& m : klass->GetVirtualMethods(sizeof(void*))) {
405     auto modifiers = m.GetAccessFlags();
406     if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
407         (modifiers & kAccMiranda) == 0) {
408       auto* method = mirror::Method::CreateFromArtMethod(soa.Self(), &m);
409       if (method == nullptr) {
410         soa.Self()->AssertPendingException();
411         return nullptr;
412       }
413       ret->SetWithoutChecks<false>(num_methods++, method);
414     }
415   }
416   for (auto& m : klass->GetDirectMethods(sizeof(void*))) {
417     auto modifiers = m.GetAccessFlags();
418     // Add non-constructor direct/static methods.
419     if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
420         (modifiers & kAccConstructor) == 0) {
421       auto* method = mirror::Method::CreateFromArtMethod(soa.Self(), &m);
422       if (method == nullptr) {
423         soa.Self()->AssertPendingException();
424         return nullptr;
425       }
426       ret->SetWithoutChecks<false>(num_methods++, method);
427     }
428   }
429   return soa.AddLocalReference<jobjectArray>(ret.Get());
430 }
431 
Class_newInstance(JNIEnv * env,jobject javaThis)432 static jobject Class_newInstance(JNIEnv* env, jobject javaThis) {
433   ScopedFastNativeObjectAccess soa(env);
434   StackHandleScope<4> hs(soa.Self());
435   Handle<mirror::Class> klass = hs.NewHandle(DecodeClass(soa, javaThis));
436   if (UNLIKELY(klass->GetPrimitiveType() != 0 || klass->IsInterface() || klass->IsArrayClass() ||
437                klass->IsAbstract())) {
438     soa.Self()->ThrowNewExceptionF("Ljava/lang/InstantiationException;",
439                                    "%s cannot be instantiated", PrettyClass(klass.Get()).c_str());
440     return nullptr;
441   }
442   auto caller = hs.NewHandle<mirror::Class>(nullptr);
443   // Verify that we can access the class.
444   if (!klass->IsPublic()) {
445     caller.Assign(GetCallingClass(soa.Self(), 1));
446     if (caller.Get() != nullptr && !caller->CanAccess(klass.Get())) {
447       soa.Self()->ThrowNewExceptionF(
448           "Ljava/lang/IllegalAccessException;", "%s is not accessible from %s",
449           PrettyClass(klass.Get()).c_str(), PrettyClass(caller.Get()).c_str());
450       return nullptr;
451     }
452   }
453   auto* constructor = klass->GetDeclaredConstructor(
454       soa.Self(), NullHandle<mirror::ObjectArray<mirror::Class>>());
455   if (UNLIKELY(constructor == nullptr)) {
456     soa.Self()->ThrowNewExceptionF("Ljava/lang/InstantiationException;",
457                                    "%s has no zero argument constructor",
458                                    PrettyClass(klass.Get()).c_str());
459     return nullptr;
460   }
461   // Invoke the string allocator to return an empty string for the string class.
462   if (klass->IsStringClass()) {
463     gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
464     mirror::SetStringCountVisitor visitor(0);
465     mirror::Object* obj = mirror::String::Alloc<true>(soa.Self(), 0, allocator_type, visitor);
466     if (UNLIKELY(soa.Self()->IsExceptionPending())) {
467       return nullptr;
468     } else {
469       return soa.AddLocalReference<jobject>(obj);
470     }
471   }
472   auto receiver = hs.NewHandle(klass->AllocObject(soa.Self()));
473   if (UNLIKELY(receiver.Get() == nullptr)) {
474     soa.Self()->AssertPendingOOMException();
475     return nullptr;
476   }
477   // Verify that we can access the constructor.
478   auto* declaring_class = constructor->GetDeclaringClass();
479   if (!constructor->IsPublic()) {
480     if (caller.Get() == nullptr) {
481       caller.Assign(GetCallingClass(soa.Self(), 1));
482     }
483     if (UNLIKELY(caller.Get() != nullptr && !VerifyAccess(
484         soa.Self(), receiver.Get(), declaring_class, constructor->GetAccessFlags(),
485         caller.Get()))) {
486       soa.Self()->ThrowNewExceptionF(
487           "Ljava/lang/IllegalAccessException;", "%s is not accessible from %s",
488           PrettyMethod(constructor).c_str(), PrettyClass(caller.Get()).c_str());
489       return nullptr;
490     }
491   }
492   // Ensure that we are initialized.
493   if (UNLIKELY(!declaring_class->IsInitialized())) {
494     if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(
495         soa.Self(), hs.NewHandle(declaring_class), true, true)) {
496       soa.Self()->AssertPendingException();
497       return nullptr;
498     }
499   }
500   // Invoke the constructor.
501   JValue result;
502   uint32_t args[1] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(receiver.Get())) };
503   constructor->Invoke(soa.Self(), args, sizeof(args), &result, "V");
504   if (UNLIKELY(soa.Self()->IsExceptionPending())) {
505     return nullptr;
506   }
507   // Constructors are ()V methods, so we shouldn't touch the result of InvokeMethod.
508   return soa.AddLocalReference<jobject>(receiver.Get());
509 }
510 
511 static JNINativeMethod gMethods[] = {
512   NATIVE_METHOD(Class, classForName,
513                 "!(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"),
514   NATIVE_METHOD(Class, getDeclaredConstructorInternal,
515                 "!([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;"),
516   NATIVE_METHOD(Class, getDeclaredConstructorsInternal, "!(Z)[Ljava/lang/reflect/Constructor;"),
517   NATIVE_METHOD(Class, getDeclaredField, "!(Ljava/lang/String;)Ljava/lang/reflect/Field;"),
518   NATIVE_METHOD(Class, getDeclaredFieldInternal, "!(Ljava/lang/String;)Ljava/lang/reflect/Field;"),
519   NATIVE_METHOD(Class, getDeclaredFields, "!()[Ljava/lang/reflect/Field;"),
520   NATIVE_METHOD(Class, getDeclaredFieldsUnchecked, "!(Z)[Ljava/lang/reflect/Field;"),
521   NATIVE_METHOD(Class, getDeclaredMethodInternal,
522                 "!(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"),
523   NATIVE_METHOD(Class, getDeclaredMethodsUnchecked,
524                   "!(Z)[Ljava/lang/reflect/Method;"),
525   NATIVE_METHOD(Class, getNameNative, "!()Ljava/lang/String;"),
526   NATIVE_METHOD(Class, getProxyInterfaces, "!()[Ljava/lang/Class;"),
527   NATIVE_METHOD(Class, getPublicDeclaredFields, "!()[Ljava/lang/reflect/Field;"),
528   NATIVE_METHOD(Class, newInstance, "!()Ljava/lang/Object;"),
529 };
530 
register_java_lang_Class(JNIEnv * env)531 void register_java_lang_Class(JNIEnv* env) {
532   REGISTER_NATIVE_METHODS("java/lang/Class");
533 }
534 
535 }  // namespace art
536