blob: a779e97a3b829488670d6ceafb814824c6c9e153 [file] [log] [blame]
Elliott Hughesd369bb72011-09-12 14:41:14 -07001/*
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
Andreas Gampe277ccbd2014-11-03 21:36:10 -080017#include "java_lang_Class.h"
18
Mathieu Chartierc7853442015-03-27 14:35:38 -070019#include "art_field-inl.h"
Elliott Hughesd369bb72011-09-12 14:41:14 -070020#include "class_linker.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070021#include "common_throws.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070022#include "dex_file-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070023#include "jni_internal.h"
Elliott Hughes6a144332012-04-03 13:07:11 -070024#include "nth_caller_visitor.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080026#include "mirror/class_loader.h"
Hiroshi Yamauchi02d2f292015-04-03 13:35:16 -070027#include "mirror/field-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070028#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "mirror/object-inl.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070030#include "mirror/object_array-inl.h"
31#include "mirror/string-inl.h"
Mathieu Chartierf36cb5f2015-04-24 16:55:16 -070032#include "reflection.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070033#include "scoped_thread_state_change.h"
Ian Rogers1eb512d2013-10-18 15:42:20 -070034#include "scoped_fast_native_object_access.h"
Elliott Hughes80609252011-09-23 17:24:51 -070035#include "ScopedLocalRef.h"
Brian Carlstromf91c8c32011-09-21 17:30:34 -070036#include "ScopedUtfChars.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070037#include "utf.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070038#include "well_known_classes.h"
Elliott Hughesd369bb72011-09-12 14:41:14 -070039
40namespace art {
41
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070042ALWAYS_INLINE static inline mirror::Class* DecodeClass(
43 const ScopedFastNativeObjectAccess& soa, jobject java_class)
Ian Rogersb726dcb2012-09-05 08:57:23 -070044 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045 mirror::Class* c = soa.Decode<mirror::Class*>(java_class);
Mathieu Chartier2cebb242015-04-21 16:50:40 -070046 DCHECK(c != nullptr);
Elliott Hughes15216932012-03-21 21:53:06 -070047 DCHECK(c->IsClass());
Elliott Hughes923e8b82012-03-23 11:44:07 -070048 // 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;
Elliott Hughes15216932012-03-21 21:53:06 -070052}
53
Brian Carlstromf91c8c32011-09-21 17:30:34 -070054// "name" is in "binary name" format, e.g. "dalvik.system.Debug$1".
Ian Rogers98379392014-02-24 16:53:16 -080055static jclass Class_classForName(JNIEnv* env, jclass, jstring javaName, jboolean initialize,
56 jobject javaLoader) {
Ian Rogers53b8b092014-03-13 23:45:53 -070057 ScopedFastNativeObjectAccess soa(env);
Brian Carlstromf91c8c32011-09-21 17:30:34 -070058 ScopedUtfChars name(env, javaName);
Mathieu Chartierc528dba2013-11-26 12:00:11 -080059 if (name.c_str() == nullptr) {
60 return nullptr;
Brian Carlstromf91c8c32011-09-21 17:30:34 -070061 }
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.
Elliott Hughes906e6852011-10-28 14:52:10 -070066 if (!IsValidBinaryClassName(name.c_str())) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +000067 soa.Self()->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
Ian Rogers62d6c772013-02-27 08:32:07 -080068 "Invalid name: %s", name.c_str());
Mathieu Chartierc528dba2013-11-26 12:00:11 -080069 return nullptr;
Brian Carlstromf91c8c32011-09-21 17:30:34 -070070 }
71
72 std::string descriptor(DotToDescriptor(name.c_str()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070073 StackHandleScope<2> hs(soa.Self());
74 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(soa.Decode<mirror::ClassLoader*>(javaLoader)));
Brian Carlstromf91c8c32011-09-21 17:30:34 -070075 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070076 Handle<mirror::Class> c(
77 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor.c_str(), class_loader)));
78 if (c.Get() == nullptr) {
Elliott Hughes844f9a02012-01-24 20:19:58 -080079 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Brian Carlstrom395520e2011-09-25 19:35:00 -070080 env->ExceptionClear();
Elliott Hugheseac76672012-05-24 21:56:51 -070081 jthrowable cnfe = reinterpret_cast<jthrowable>(env->NewObject(WellKnownClasses::java_lang_ClassNotFoundException,
82 WellKnownClasses::java_lang_ClassNotFoundException_init,
83 javaName, cause.get()));
Ian Rogersc114b5f2014-07-21 08:55:01 -070084 if (cnfe != nullptr) {
85 // Make sure allocation didn't fail with an OOME.
86 env->Throw(cnfe);
87 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -080088 return nullptr;
Brian Carlstrom395520e2011-09-25 19:35:00 -070089 }
Brian Carlstromf91c8c32011-09-21 17:30:34 -070090 if (initialize) {
Ian Rogers7b078e82014-09-10 14:44:24 -070091 class_linker->EnsureInitialized(soa.Self(), c, true, true);
Brian Carlstromf91c8c32011-09-21 17:30:34 -070092 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070093 return soa.AddLocalReference<jclass>(c.Get());
Brian Carlstromf91c8c32011-09-21 17:30:34 -070094}
95
Elliott Hughes0512f022012-03-15 22:10:52 -070096static jstring Class_getNameNative(JNIEnv* env, jobject javaThis) {
Ian Rogers1eb512d2013-10-18 15:42:20 -070097 ScopedFastNativeObjectAccess soa(env);
Mathieu Chartierf8322842014-05-16 10:59:25 -070098 StackHandleScope<1> hs(soa.Self());
99 mirror::Class* const c = DecodeClass(soa, javaThis);
100 return soa.AddLocalReference<jstring>(mirror::Class::ComputeName(hs.NewHandle(c)));
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700101}
102
Elliott Hughes2ed52c42012-03-21 16:56:56 -0700103static jobjectArray Class_getProxyInterfaces(JNIEnv* env, jobject javaThis) {
Ian Rogers1eb512d2013-10-18 15:42:20 -0700104 ScopedFastNativeObjectAccess soa(env);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700105 mirror::Class* c = DecodeClass(soa, javaThis);
Ian Rogers50b35e22012-10-04 10:09:15 -0700106 return soa.AddLocalReference<jobjectArray>(c->GetInterfaces()->Clone(soa.Self()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -0700107}
108
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700109static mirror::ObjectArray<mirror::Field>* GetDeclaredFields(
110 Thread* self, mirror::Class* klass, bool public_only, bool force_resolve)
111 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700112 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;
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700118 if (public_only) {
119 // Lets go subtract all the non public fields.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700120 for (size_t i = 0; i < num_ifields; ++i) {
121 if (!ifields[i].IsPublic()) {
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700122 --array_size;
123 }
124 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700125 for (size_t i = 0; i < num_sfields; ++i) {
126 if (!sfields[i].IsPublic()) {
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700127 --array_size;
128 }
129 }
130 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700131 size_t array_idx = 0;
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700132 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 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700137 for (size_t i = 0; i < num_ifields; ++i) {
138 auto* art_field = &ifields[i];
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700139 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 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700151 for (size_t i = 0; i < num_sfields; ++i) {
152 auto* art_field = &sfields[i];
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700153 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
168static 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
175static 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
181static 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.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700190ALWAYS_INLINE static inline ArtField* FindFieldByName(
191 Thread* self ATTRIBUTE_UNUSED, mirror::String* name, ArtField* fields, size_t num_fields)
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700192 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700193 size_t low = 0;
194 size_t high = num_fields;
Jeff Hao848f70a2014-01-15 13:49:50 -0800195 const uint16_t* const data = name->GetValue();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700196 const size_t length = name->GetLength();
197 while (low < high) {
198 auto mid = (low + high) / 2;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700199 ArtField* const field = &fields[mid];
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700200 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) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700212 for (size_t i = 0; i < num_fields; ++i) {
213 CHECK_NE(fields[i].GetName(), name->ToModifiedUtf8());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700214 }
215 }
216 return nullptr;
217}
218
219ALWAYS_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();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700223 auto* art_field = FindFieldByName(self, name, instance_fields, c->NumInstanceFields());
224 if (art_field != nullptr) {
225 return mirror::Field::CreateFromArtField(self, art_field, true);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700226 }
227 auto* static_fields = c->GetSFields();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700228 art_field = FindFieldByName(self, name, static_fields, c->NumStaticFields());
229 if (art_field != nullptr) {
230 return mirror::Field::CreateFromArtField(self, art_field, true);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700231 }
232 return nullptr;
233}
234
235static 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
242static jobject Class_getDeclaredField(JNIEnv* env, jobject javaThis, jstring name) {
243 ScopedFastNativeObjectAccess soa(env);
244 auto* name_string = soa.Decode<mirror::String*>(name);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700245 if (name_string == nullptr) {
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700246 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();
Mathieu Chartierca239af2015-03-29 18:27:50 -0700253 // We may have a pending exception if we failed to resolve.
254 if (!soa.Self()->IsExceptionPending()) {
255 soa.Self()->ThrowNewException("Ljava/lang/NoSuchFieldException;", name_str.c_str());
256 }
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700257 return nullptr;
258 }
259 return soa.AddLocalReference<jobject>(result);
260}
261
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700262static 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
276static ALWAYS_INLINE inline bool MethodMatchesConstructor(mirror::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
282static jobjectArray Class_getDeclaredConstructorsInternal(
283 JNIEnv* env, jobject javaThis, jboolean publicOnly) {
284 ScopedFastNativeObjectAccess soa(env);
285 auto* klass = DecodeClass(soa, javaThis);
286 StackHandleScope<2> hs(soa.Self());
287 auto h_direct_methods = hs.NewHandle(klass->GetDirectMethods());
288 size_t constructor_count = 0;
289 auto count = h_direct_methods.Get() != nullptr ? h_direct_methods->GetLength() : 0u;
290 // Two pass approach for speed.
291 for (size_t i = 0; i < count; ++i) {
292 constructor_count += MethodMatchesConstructor(h_direct_methods->GetWithoutChecks(i),
293 publicOnly != JNI_FALSE) ? 1u : 0u;
294 }
295 auto h_constructors = hs.NewHandle(mirror::ObjectArray<mirror::Constructor>::Alloc(
296 soa.Self(), mirror::Constructor::ArrayClass(), constructor_count));
297 if (UNLIKELY(h_constructors.Get() == nullptr)) {
298 soa.Self()->AssertPendingException();
299 return nullptr;
300 }
301 constructor_count = 0;
302 for (size_t i = 0; i < count; ++i) {
303 auto* method = h_direct_methods->GetWithoutChecks(i);
304 if (MethodMatchesConstructor(method, publicOnly != JNI_FALSE)) {
305 auto* constructor = mirror::Constructor::CreateFromArtMethod(soa.Self(), method);
306 if (UNLIKELY(constructor == nullptr)) {
307 soa.Self()->AssertPendingException();
308 return nullptr;
309 }
310 h_constructors->SetWithoutChecks<false>(constructor_count++, constructor);
311 }
312 }
313 return soa.AddLocalReference<jobjectArray>(h_constructors.Get());
314}
315
316static jobject Class_getDeclaredMethodInternal(JNIEnv* env, jobject javaThis,
317 jobject name, jobjectArray args) {
318 // Covariant return types permit the class to define multiple
319 // methods with the same name and parameter types. Prefer to
320 // return a non-synthetic method in such situations. We may
321 // still return a synthetic method to handle situations like
322 // escalated visibility. We never return miranda methods that
323 // were synthesized by the runtime.
324 constexpr uint32_t kSkipModifiers = kAccMiranda | kAccSynthetic;
325 ScopedFastNativeObjectAccess soa(env);
326 StackHandleScope<5> hs(soa.Self());
327 auto h_method_name = hs.NewHandle(soa.Decode<mirror::String*>(name));
328 if (UNLIKELY(h_method_name.Get() == nullptr)) {
329 ThrowNullPointerException("name == null");
330 return nullptr;
331 }
332 auto h_args = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(args));
333 auto* klass = DecodeClass(soa, javaThis);
334 mirror::ArtMethod* result = nullptr;
335 auto* virtual_methods = klass->GetVirtualMethods();
336 if (virtual_methods != nullptr) {
337 auto h_virtual_methods = hs.NewHandle(virtual_methods);
338 for (size_t i = 0, count = virtual_methods->GetLength(); i < count; ++i) {
339 auto* m = h_virtual_methods->GetWithoutChecks(i);
340 auto* np_method = m->GetInterfaceMethodIfProxy();
341 // May cause thread suspension.
342 mirror::String* np_name = np_method->GetNameAsString(soa.Self());
343 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
344 if (UNLIKELY(soa.Self()->IsExceptionPending())) {
345 return nullptr;
346 }
347 continue;
348 }
349 auto modifiers = m->GetAccessFlags();
350 if ((modifiers & kSkipModifiers) == 0) {
351 return soa.AddLocalReference<jobject>(mirror::Method::CreateFromArtMethod(soa.Self(), m));
352 }
353 if ((modifiers & kAccMiranda) == 0) {
354 result = m; // Remember as potential result if it's not a miranda method.
355 }
356 }
357 }
358 if (result == nullptr) {
359 auto* direct_methods = klass->GetDirectMethods();
360 if (direct_methods != nullptr) {
361 auto h_direct_methods = hs.NewHandle(direct_methods);
362 for (size_t i = 0, count = direct_methods->GetLength(); i < count; ++i) {
363 auto* m = h_direct_methods->GetWithoutChecks(i);
364 auto modifiers = m->GetAccessFlags();
365 if ((modifiers & kAccConstructor) != 0) {
366 continue;
367 }
368 auto* np_method = m->GetInterfaceMethodIfProxy();
369 // May cause thread suspension.
370 mirror::String* np_name = np_method ->GetNameAsString(soa.Self());
371 if (np_name == nullptr) {
372 soa.Self()->AssertPendingException();
373 return nullptr;
374 }
375 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
376 if (UNLIKELY(soa.Self()->IsExceptionPending())) {
377 return nullptr;
378 }
379 continue;
380 }
381 if ((modifiers & kSkipModifiers) == 0) {
382 return soa.AddLocalReference<jobject>(mirror::Method::CreateFromArtMethod(
383 soa.Self(), m));
384 }
385 // Direct methods cannot be miranda methods, so this potential result must be synthetic.
386 result = m;
387 }
388 }
389 }
390 return result != nullptr ?
391 soa.AddLocalReference<jobject>(mirror::Method::CreateFromArtMethod(soa.Self(), result)) :
392 nullptr;
393}
394
Mathieu Chartierf36cb5f2015-04-24 16:55:16 -0700395static jobjectArray Class_getDeclaredMethodsUnchecked(JNIEnv* env, jobject javaThis,
396 jboolean publicOnly) {
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700397 ScopedFastNativeObjectAccess soa(env);
398 StackHandleScope<5> hs(soa.Self());
399 auto* klass = DecodeClass(soa, javaThis);
400 auto virtual_methods = hs.NewHandle(klass->GetVirtualMethods());
401 auto direct_methods = hs.NewHandle(klass->GetDirectMethods());
402 size_t num_methods = 0;
403 if (virtual_methods.Get() != nullptr) {
404 for (size_t i = 0, count = virtual_methods->GetLength(); i < count; ++i) {
405 auto* m = virtual_methods->GetWithoutChecks(i);
406 auto modifiers = m->GetAccessFlags();
407 if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
408 (modifiers & kAccMiranda) == 0) {
409 ++num_methods;
410 }
411 }
412 }
413 if (direct_methods.Get() != nullptr) {
414 for (size_t i = 0, count = direct_methods->GetLength(); i < count; ++i) {
415 auto* m = direct_methods->GetWithoutChecks(i);
416 auto modifiers = m->GetAccessFlags();
417 // Add non-constructor direct/static methods.
418 if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
419 (modifiers & kAccConstructor) == 0) {
420 ++num_methods;
421 }
422 }
423 }
424 auto ret = hs.NewHandle(mirror::ObjectArray<mirror::Method>::Alloc(
425 soa.Self(), mirror::Method::ArrayClass(), num_methods));
426 num_methods = 0;
427 if (virtual_methods.Get() != nullptr) {
428 for (size_t i = 0, count = virtual_methods->GetLength(); i < count; ++i) {
429 auto* m = virtual_methods->GetWithoutChecks(i);
430 auto modifiers = m->GetAccessFlags();
431 if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
432 (modifiers & kAccMiranda) == 0) {
433 auto* method = mirror::Method::CreateFromArtMethod(soa.Self(), m);
434 if (method == nullptr) {
435 soa.Self()->AssertPendingException();
436 return nullptr;
437 }
438 ret->SetWithoutChecks<false>(num_methods++, method);
439 }
440 }
441 }
442 if (direct_methods.Get() != nullptr) {
443 for (size_t i = 0, count = direct_methods->GetLength(); i < count; ++i) {
444 auto* m = direct_methods->GetWithoutChecks(i);
445 auto modifiers = m->GetAccessFlags();
446 // Add non-constructor direct/static methods.
447 if ((publicOnly == JNI_FALSE || (modifiers & kAccPublic) != 0) &&
448 (modifiers & kAccConstructor) == 0) {
449 auto* method = mirror::Method::CreateFromArtMethod(soa.Self(), m);
450 if (method == nullptr) {
451 soa.Self()->AssertPendingException();
452 return nullptr;
453 }
454 ret->SetWithoutChecks<false>(num_methods++, method);
455 }
456 }
457 }
458 return soa.AddLocalReference<jobjectArray>(ret.Get());
459}
460
Mathieu Chartierf36cb5f2015-04-24 16:55:16 -0700461static jobject Class_newInstance(JNIEnv* env, jobject javaThis) {
462 ScopedFastNativeObjectAccess soa(env);
463 StackHandleScope<4> hs(soa.Self());
464 auto klass = hs.NewHandle(DecodeClass(soa, javaThis));
465 if (UNLIKELY(klass->GetPrimitiveType() != 0 || klass->IsInterface() || klass->IsArrayClass() ||
466 klass->IsAbstract())) {
467 soa.Self()->ThrowNewExceptionF("Ljava/lang/InstantiationException;",
468 "%s cannot be instantiated", PrettyClass(klass.Get()).c_str());
469 return nullptr;
470 }
471 auto caller = hs.NewHandle<mirror::Class>(nullptr);
472 // Verify that we can access the class.
473 if (!klass->IsPublic()) {
474 caller.Assign(GetCallingClass(soa.Self(), 1));
475 if (caller.Get() != nullptr && !caller->CanAccess(klass.Get())) {
476 soa.Self()->ThrowNewExceptionF(
477 "Ljava/lang/IllegalAccessException;", "%s is not accessible from %s",
478 PrettyClass(klass.Get()).c_str(), PrettyClass(caller.Get()).c_str());
479 return nullptr;
480 }
481 }
482 auto* constructor = klass->GetDeclaredConstructor(
483 soa.Self(), NullHandle<mirror::ObjectArray<mirror::Class>>());
484 if (UNLIKELY(constructor == nullptr)) {
485 soa.Self()->ThrowNewExceptionF("Ljava/lang/InstantiationException;",
486 "%s has no zero argument constructor",
487 PrettyClass(klass.Get()).c_str());
488 return nullptr;
489 }
Jeff Hao69bdcb22015-04-27 20:54:07 -0700490 // Invoke the string allocator to return an empty string for the string class.
491 if (klass->IsStringClass()) {
492 gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
493 mirror::SetStringCountVisitor visitor(0);
494 mirror::Object* obj = mirror::String::Alloc<true>(soa.Self(), 0, allocator_type, visitor);
495 if (UNLIKELY(soa.Self()->IsExceptionPending())) {
496 return nullptr;
497 } else {
498 return soa.AddLocalReference<jobject>(obj);
499 }
500 }
Mathieu Chartierf36cb5f2015-04-24 16:55:16 -0700501 auto receiver = hs.NewHandle(klass->AllocObject(soa.Self()));
502 if (UNLIKELY(receiver.Get() == nullptr)) {
503 soa.Self()->AssertPendingOOMException();
504 return nullptr;
505 }
506 // Verify that we can access the constructor.
507 auto* declaring_class = constructor->GetDeclaringClass();
508 if (!constructor->IsPublic()) {
509 if (caller.Get() == nullptr) {
510 caller.Assign(GetCallingClass(soa.Self(), 1));
511 }
512 if (UNLIKELY(caller.Get() != nullptr && !VerifyAccess(
513 soa.Self(), receiver.Get(), declaring_class, constructor->GetAccessFlags(),
514 caller.Get()))) {
515 soa.Self()->ThrowNewExceptionF(
516 "Ljava/lang/IllegalAccessException;", "%s is not accessible from %s",
517 PrettyMethod(constructor).c_str(), PrettyClass(caller.Get()).c_str());
518 return nullptr;
519 }
520 }
521 // Ensure that we are initialized.
522 if (UNLIKELY(!declaring_class->IsInitialized())) {
523 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(
524 soa.Self(), hs.NewHandle(declaring_class), true, true)) {
525 soa.Self()->AssertPendingException();
526 return nullptr;
527 }
528 }
529 // Invoke the constructor.
530 JValue result;
531 uint32_t args[1] = { static_cast<uint32_t>(reinterpret_cast<uintptr_t>(receiver.Get())) };
532 constructor->Invoke(soa.Self(), args, sizeof(args), &result, "V");
533 if (UNLIKELY(soa.Self()->IsExceptionPending())) {
534 return nullptr;
535 }
536 // Constructors are ()V methods, so we shouldn't touch the result of InvokeMethod.
537 return soa.AddLocalReference<jobject>(receiver.Get());
538}
539
Elliott Hughesd369bb72011-09-12 14:41:14 -0700540static JNINativeMethod gMethods[] = {
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700541 NATIVE_METHOD(Class, classForName,
542 "!(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"),
543 NATIVE_METHOD(Class, getDeclaredConstructorInternal,
544 "!([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;"),
545 NATIVE_METHOD(Class, getDeclaredConstructorsInternal, "!(Z)[Ljava/lang/reflect/Constructor;"),
546 NATIVE_METHOD(Class, getDeclaredField, "!(Ljava/lang/String;)Ljava/lang/reflect/Field;"),
547 NATIVE_METHOD(Class, getDeclaredFieldInternal, "!(Ljava/lang/String;)Ljava/lang/reflect/Field;"),
548 NATIVE_METHOD(Class, getDeclaredFields, "!()[Ljava/lang/reflect/Field;"),
549 NATIVE_METHOD(Class, getDeclaredFieldsUnchecked, "!(Z)[Ljava/lang/reflect/Field;"),
550 NATIVE_METHOD(Class, getDeclaredMethodInternal,
551 "!(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"),
552 NATIVE_METHOD(Class, getDeclaredMethodsUnchecked,
553 "!(Z)[Ljava/lang/reflect/Method;"),
Ian Rogers1eb512d2013-10-18 15:42:20 -0700554 NATIVE_METHOD(Class, getNameNative, "!()Ljava/lang/String;"),
555 NATIVE_METHOD(Class, getProxyInterfaces, "!()[Ljava/lang/Class;"),
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700556 NATIVE_METHOD(Class, getPublicDeclaredFields, "!()[Ljava/lang/reflect/Field;"),
Mathieu Chartierf36cb5f2015-04-24 16:55:16 -0700557 NATIVE_METHOD(Class, newInstance, "!()Ljava/lang/Object;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700558};
559
Elliott Hughesd369bb72011-09-12 14:41:14 -0700560void register_java_lang_Class(JNIEnv* env) {
Elliott Hugheseac76672012-05-24 21:56:51 -0700561 REGISTER_NATIVE_METHODS("java/lang/Class");
Elliott Hughesd369bb72011-09-12 14:41:14 -0700562}
563
564} // namespace art