blob: de5315ada88eaf847dd0e49ef377fa68fbe256d6 [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
17#include "jni_internal.h"
18#include "class_linker.h"
Brian Carlstromf91c8c32011-09-21 17:30:34 -070019#include "class_loader.h"
Elliott Hughesd369bb72011-09-12 14:41:14 -070020#include "object.h"
Elliott Hughes80609252011-09-23 17:24:51 -070021#include "ScopedLocalRef.h"
Brian Carlstromf91c8c32011-09-21 17:30:34 -070022#include "ScopedUtfChars.h"
Elliott Hughesd369bb72011-09-12 14:41:14 -070023
24#include "JniConstants.h" // Last to avoid problems with LOG redefinition.
25
26namespace art {
27
28namespace {
29
Brian Carlstromf91c8c32011-09-21 17:30:34 -070030// "name" is in "binary name" format, e.g. "dalvik.system.Debug$1".
31jclass Class_classForName(JNIEnv* env, jclass, jstring javaName, jboolean initialize, jobject javaLoader) {
32 ScopedUtfChars name(env, javaName);
33 if (name.c_str() == NULL) {
34 return NULL;
35 }
36
37 // We need to validate and convert the name (from x.y.z to x/y/z). This
38 // is especially handy for array types, since we want to avoid
39 // auto-generating bogus array classes.
40 if (!IsValidClassName(name.c_str(), true, true)) {
41 Thread::Current()->ThrowNewException("Ljava/lang/ClassNotFoundException;",
42 "Invalid name: %s", name.c_str());
43 return NULL;
44 }
45
46 std::string descriptor(DotToDescriptor(name.c_str()));
47 Object* loader = Decode<Object*>(env, javaLoader);
48 ClassLoader* class_loader = down_cast<ClassLoader*>(loader);
49 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
50 Class* c = class_linker->FindClass(descriptor.c_str(), class_loader);
Brian Carlstrom395520e2011-09-25 19:35:00 -070051 if (c == NULL) {
52 // Convert NoClassDefFoundError to ClassNotFoundException
53 // TODO: chain exceptions?
54 DCHECK(env->ExceptionCheck());
55 env->ExceptionClear();
56 Thread::Current()->ThrowNewException("Ljava/lang/ClassNotFoundException;",
57 "%s", name.c_str());
58 return NULL;
59 }
Brian Carlstromf91c8c32011-09-21 17:30:34 -070060 if (initialize) {
61 class_linker->EnsureInitialized(c, true);
62 }
63 return AddLocalReference<jclass>(env, c);
64}
65
Elliott Hughes80609252011-09-23 17:24:51 -070066template<typename T>
67jobjectArray ToArray(JNIEnv* env, const char* array_class_name, const std::vector<T*>& objects) {
68 jclass array_class = env->FindClass(array_class_name);
69 jobjectArray result = env->NewObjectArray(objects.size(), array_class, NULL);
70 for (size_t i = 0; i < objects.size(); ++i) {
71 ScopedLocalRef<jobject> object(env, AddLocalReference<jobject>(env, objects[i]));
72 env->SetObjectArrayElement(result, i, object.get());
73 }
74 return result;
75}
76
77bool IsVisibleConstructor(Method* m, bool public_only) {
78 if (public_only && !m->IsPublic()) {
79 return false;
80 }
81 if (m->IsMiranda() || m->IsStatic()) {
82 return false;
83 }
84 if (m->GetName()->CharAt(0) != '<') {
85 return false;
86 }
87 m->InitJavaFields();
88 return true;
89}
90
91jobjectArray Class_getDeclaredConstructors(JNIEnv* env, jclass, jclass javaClass, jboolean publicOnly) {
92 Class* c = Decode<Class*>(env, javaClass);
93
94 std::vector<Method*> constructors;
95 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
96 Method* m = c->GetDirectMethod(i);
97 if (IsVisibleConstructor(m, publicOnly)) {
98 constructors.push_back(m);
99 }
100 }
101
102 return ToArray(env, "java/lang/reflect/Constructor", constructors);
103}
104
105bool IsVisibleField(Field* f, bool public_only) {
Elliott Hughesc0dd3122011-09-26 10:15:43 -0700106 if (public_only && !f->IsPublic()) {
Elliott Hughes80609252011-09-23 17:24:51 -0700107 return false;
108 }
109 f->InitJavaFields();
110 return true;
111}
112
113jobjectArray Class_getDeclaredFields(JNIEnv* env, jclass, jclass javaClass, jboolean publicOnly) {
114 Class* c = Decode<Class*>(env, javaClass);
115
116 std::vector<Field*> fields;
117 for (size_t i = 0; i < c->NumInstanceFields(); ++i) {
118 Field* f = c->GetInstanceField(i);
119 if (IsVisibleField(f, publicOnly)) {
120 fields.push_back(f);
121 }
122 }
123 for (size_t i = 0; i < c->NumStaticFields(); ++i) {
124 Field* f = c->GetStaticField(i);
125 if (IsVisibleField(f, publicOnly)) {
126 fields.push_back(f);
127 }
128 }
129
130 return ToArray(env, "java/lang/reflect/Field", fields);
131}
132
133bool IsVisibleMethod(Method* m, bool public_only) {
134 if (public_only && !m->IsPublic()) {
135 return false;
136 }
137 if (m->IsMiranda()) {
138 return false;
139 }
140 if (m->GetName()->CharAt(0) == '<') {
141 return false;
142 }
143 m->InitJavaFields();
144 return true;
145}
146
147jobjectArray Class_getDeclaredMethods(JNIEnv* env, jclass, jclass javaClass, jboolean publicOnly) {
148 Class* c = Decode<Class*>(env, javaClass);
149
150 std::vector<Method*> methods;
151 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
152 Method* m = c->GetVirtualMethod(i);
153 if (IsVisibleMethod(m, publicOnly)) {
154 methods.push_back(m);
155 }
156 }
157 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
158 Method* m = c->GetDirectMethod(i);
159 if (IsVisibleMethod(m, publicOnly)) {
160 methods.push_back(m);
161 }
162 }
163
164 return ToArray(env, "java/lang/reflect/Method", methods);
165}
166
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700167jboolean Class_desiredAssertionStatus(JNIEnv* env, jobject javaThis) {
168 return JNI_FALSE;
169}
170
Jesse Wilson6bf19152011-09-29 13:12:33 -0400171jobject Class_getDex(JNIEnv* env, jobject javaClass) {
172 Class* c = Decode<Class*>(env, javaClass);
173
174 DexCache* dex_cache = c->GetDexCache();
175 if (dex_cache == NULL) {
176 return NULL;
177 }
178
179 return Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache).GetDexObject(env);
180}
181
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700182jobject Class_getClassLoader(JNIEnv* env, jclass, jobject javaClass) {
183 Class* c = Decode<Class*>(env, javaClass);
184 Object* result = reinterpret_cast<Object*>(const_cast<ClassLoader*>(c->GetClassLoader()));
185 return AddLocalReference<jobject>(env, result);
186}
187
Elliott Hughesd369bb72011-09-12 14:41:14 -0700188jclass Class_getComponentType(JNIEnv* env, jobject javaThis) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700189 return AddLocalReference<jclass>(env, Decode<Class*>(env, javaThis)->GetComponentType());
Elliott Hughesd369bb72011-09-12 14:41:14 -0700190}
191
Elliott Hughes418d20f2011-09-22 14:00:39 -0700192bool MethodMatches(Method* m, String* name, const std::string& signature) {
193 if (!m->GetName()->Equals(name)) {
194 return false;
195 }
196 std::string method_signature = m->GetSignature()->ToModifiedUtf8();
197 if (!StringPiece(method_signature).starts_with(signature)) {
198 return false;
199 }
200 m->InitJavaFields();
201 return true;
202}
203
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700204jobject Class_getDeclaredConstructorOrMethod(JNIEnv* env, jclass,
Elliott Hughes418d20f2011-09-22 14:00:39 -0700205 jclass javaClass, jstring javaName, jobjectArray javaSignature) {
206 Class* c = Decode<Class*>(env, javaClass);
207 String* name = Decode<String*>(env, javaName);
208 ObjectArray<Class>* signature_array = Decode<ObjectArray<Class>*>(env, javaSignature);
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700209
Elliott Hughes418d20f2011-09-22 14:00:39 -0700210 std::string signature;
211 signature += "(";
212 for (int i = 0; i < signature_array->GetLength(); i++) {
213 signature += signature_array->Get(i)->GetDescriptor()->ToModifiedUtf8();
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700214 }
Elliott Hughes418d20f2011-09-22 14:00:39 -0700215 signature += ")";
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700216
Elliott Hughes418d20f2011-09-22 14:00:39 -0700217 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
218 Method* m = c->GetVirtualMethod(i);
219 if (MethodMatches(m, name, signature)) {
220 return AddLocalReference<jobject>(env, m);
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700221 }
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700222 }
223
Elliott Hughes418d20f2011-09-22 14:00:39 -0700224 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
225 Method* m = c->GetDirectMethod(i);
226 if (MethodMatches(m, name, signature)) {
227 return AddLocalReference<jobject>(env, m);
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700228 }
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700229 }
230
231 return NULL;
232}
233
234jobject Class_getDeclaredField(JNIEnv* env, jclass, jclass jklass, jobject jname) {
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700235 Class* klass = Decode<Class*>(env, jklass);
236 DCHECK(klass->IsClass());
237 String* name = Decode<String*>(env, jname);
238 DCHECK(name->IsString());
239
Elliott Hughes80609252011-09-23 17:24:51 -0700240 for (size_t i = 0; i < klass->NumInstanceFields(); ++i) {
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700241 Field* f = klass->GetInstanceField(i);
242 if (f->GetName()->Equals(name)) {
Elliott Hughes80609252011-09-23 17:24:51 -0700243 f->InitJavaFields();
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700244 return AddLocalReference<jclass>(env, f);
245 }
246 }
247 for (size_t i = 0; i < klass->NumStaticFields(); ++i) {
248 Field* f = klass->GetStaticField(i);
249 if (f->GetName()->Equals(name)) {
Elliott Hughes80609252011-09-23 17:24:51 -0700250 f->InitJavaFields();
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700251 return AddLocalReference<jclass>(env, f);
252 }
253 }
254 return NULL;
255}
256
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700257jclass Class_getDeclaringClass(JNIEnv* env, jobject javaThis) {
258 UNIMPLEMENTED(WARNING) << "needs annotations";
259 return NULL;
260}
261
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700262/*
263 * private native String getNameNative()
264 *
265 * Return the class' name. The exact format is bizarre, but it's the specified
266 * behavior: keywords for primitive types, regular "[I" form for primitive
267 * arrays (so "int" but "[I"), and arrays of reference types written
268 * between "L" and ";" but with dots rather than slashes (so "java.lang.String"
269 * but "[Ljava.lang.String;"). Madness.
270 */
271jstring Class_getNameNative(JNIEnv* env, jobject javaThis) {
272 Class* c = Decode<Class*>(env, javaThis);
273 std::string descriptor(c->GetDescriptor()->ToModifiedUtf8());
274 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
275 // The descriptor indicates that this is the class for
276 // a primitive type; special-case the return value.
277 const char* name = NULL;
278 switch (descriptor[0]) {
279 case 'Z': name = "boolean"; break;
280 case 'B': name = "byte"; break;
281 case 'C': name = "char"; break;
282 case 'S': name = "short"; break;
283 case 'I': name = "int"; break;
284 case 'J': name = "long"; break;
285 case 'F': name = "float"; break;
286 case 'D': name = "double"; break;
287 case 'V': name = "void"; break;
288 default:
289 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
290 }
291 return env->NewStringUTF(name);
292 }
293
294 // Convert the UTF-8 name to a java.lang.String. The
295 // name must use '.' to separate package components.
296 if (descriptor.size() > 2 && descriptor[0] == 'L' && descriptor[descriptor.size() - 1] == ';') {
297 descriptor.erase(0, 1);
298 descriptor.erase(descriptor.size() - 1);
299 }
300 std::replace(descriptor.begin(), descriptor.end(), '/', '.');
301 return env->NewStringUTF(descriptor.c_str());
302}
303
304jclass Class_getSuperclass(JNIEnv* env, jobject javaThis) {
305 Class* c = Decode<Class*>(env, javaThis);
306 Class* result = c->GetSuperClass();
307 return AddLocalReference<jclass>(env, result);
308}
309
310jboolean Class_isAnonymousClass(JNIEnv* env, jobject javaThis) {
311 UNIMPLEMENTED(WARNING) << "needs annotations";
312 return JNI_FALSE;
313}
314
Elliott Hughesdd8df692011-09-23 14:42:41 -0700315jboolean Class_isAssignableFrom(JNIEnv* env, jobject javaLhs, jclass javaRhs) {
316 Class* lhs = Decode<Class*>(env, javaLhs);
317 Class* rhs = Decode<Class*>(env, javaRhs);
318 if (rhs == NULL) {
319 Thread::Current()->ThrowNewException("Ljava/lang/NullPointerException;", "class == null");
320 return JNI_FALSE;
321 }
322 return lhs->IsAssignableFrom(rhs) ? JNI_TRUE : JNI_FALSE;
323}
324
325jboolean Class_isInstance(JNIEnv* env, jobject javaClass, jobject javaObject) {
326 Class* c = Decode<Class*>(env, javaClass);
327 Object* o = Decode<Object*>(env, javaObject);
328 if (o == NULL) {
329 return JNI_FALSE;
330 }
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700331 return o->InstanceOf(c) ? JNI_TRUE : JNI_FALSE;
Elliott Hughesdd8df692011-09-23 14:42:41 -0700332}
333
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700334jboolean Class_isInterface(JNIEnv* env, jobject javaThis) {
335 Class* c = Decode<Class*>(env, javaThis);
336 return c->IsInterface();
337}
338
339jboolean Class_isPrimitive(JNIEnv* env, jobject javaThis) {
340 Class* c = Decode<Class*>(env, javaThis);
341 return c->IsPrimitive();
342}
343
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700344// Validate method/field access.
345bool CheckMemberAccess(const Class* access_from, const Class* access_to, uint32_t member_flags) {
346 // quick accept for public access */
347 if (member_flags & kAccPublic) {
348 return true;
349 }
350
351 // quick accept for access from same class
352 if (access_from == access_to) {
353 return true;
354 }
355
356 // quick reject for private access from another class
357 if (member_flags & kAccPrivate) {
358 return false;
359 }
360
361 // Semi-quick test for protected access from a sub-class, which may or
362 // may not be in the same package.
363 if (member_flags & kAccProtected) {
364 if (access_from->IsSubClass(access_to)) {
365 return true;
366 }
367 }
368
369 // Allow protected and private access from other classes in the same
370 return access_from->IsInSamePackage(access_to);
371}
372
373jobject Class_newInstanceImpl(JNIEnv* env, jobject javaThis) {
374 Class* c = Decode<Class*>(env, javaThis);
375 if (c->IsPrimitive() || c->IsInterface() || c->IsArrayClass() || c->IsAbstract()) {
376 Thread::Current()->ThrowNewException("Ljava/lang/InstantiationException;",
377 "Class %s can not be instantiated", PrettyDescriptor(c->GetDescriptor()).c_str());
378 return NULL;
379 }
380
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700381 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(c, true)) {
382 return NULL;
383 }
384
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700385 Method* init = c->FindDirectMethod("<init>", "()V");
386 if (init == NULL) {
387 Thread::Current()->ThrowNewException("Ljava/lang/InstantiationException;",
388 "Class %s has no default <init>()V constructor", PrettyDescriptor(c->GetDescriptor()).c_str());
389 return NULL;
390 }
391
392 // Verify access from the call site.
393 //
394 // First, make sure the method invoking Class.newInstance() has permission
395 // to access the class.
396 //
397 // Second, make sure it has permission to invoke the constructor. The
398 // constructor must be public or, if the caller is in the same package,
399 // have package scope.
400 // TODO: need SmartFrame (Thread::WalkStack-like iterator).
401 Frame frame = Thread::Current()->GetTopOfStack();
402 frame.Next();
403 frame.Next();
404 Method* caller_caller = frame.GetMethod();
405 Class* caller_class = caller_caller->GetDeclaringClass();
406
Brian Carlstrombc2f3e32011-09-22 17:16:54 -0700407 if (!caller_class->CanAccess(c)) {
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700408 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessException;",
409 "Class %s is not accessible from class %s",
410 PrettyDescriptor(c->GetDescriptor()).c_str(),
411 PrettyDescriptor(caller_class->GetDescriptor()).c_str());
412 return NULL;
413 }
414 if (!CheckMemberAccess(caller_class, init->GetDeclaringClass(), init->GetAccessFlags())) {
415 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessException;",
416 "%s is not accessible from class %s",
417 PrettyMethod(init).c_str(),
418 PrettyDescriptor(caller_class->GetDescriptor()).c_str());
419 return NULL;
420 }
421
422 Object* new_obj = c->AllocObject();
423 if (new_obj == NULL) {
424 DCHECK(Thread::Current()->IsExceptionPending());
425 return NULL;
426 }
427
428 // invoke constructor; unlike reflection calls, we don't wrap exceptions
429 jclass jklass = AddLocalReference<jclass>(env, c);
430 jmethodID mid = EncodeMethod(init);
431 return env->NewObject(jklass, mid);
432}
433
Elliott Hughesd369bb72011-09-12 14:41:14 -0700434static JNINativeMethod gMethods[] = {
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700435 NATIVE_METHOD(Class, classForName, "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700436 NATIVE_METHOD(Class, desiredAssertionStatus, "()Z"),
437 NATIVE_METHOD(Class, getClassLoader, "(Ljava/lang/Class;)Ljava/lang/ClassLoader;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700438 NATIVE_METHOD(Class, getComponentType, "()Ljava/lang/Class;"),
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700439 NATIVE_METHOD(Class, getDeclaredConstructorOrMethod, "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Member;"),
Elliott Hughes80609252011-09-23 17:24:51 -0700440 NATIVE_METHOD(Class, getDeclaredConstructors, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Constructor;"),
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700441 NATIVE_METHOD(Class, getDeclaredField, "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/reflect/Field;"),
Elliott Hughes80609252011-09-23 17:24:51 -0700442 NATIVE_METHOD(Class, getDeclaredFields, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Field;"),
443 NATIVE_METHOD(Class, getDeclaredMethods, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Method;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700444 NATIVE_METHOD(Class, getDeclaringClass, "()Ljava/lang/Class;"),
Jesse Wilson6bf19152011-09-29 13:12:33 -0400445 NATIVE_METHOD(Class, getDex, "()Lcom/android/dex/Dex;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700446 //NATIVE_METHOD(Class, getInnerClassName, "()Ljava/lang/String;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700447 //NATIVE_METHOD(Class, getModifiers, "(Ljava/lang/Class;Z)I"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700448 NATIVE_METHOD(Class, getNameNative, "()Ljava/lang/String;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700449 NATIVE_METHOD(Class, getSuperclass, "()Ljava/lang/Class;"),
450 NATIVE_METHOD(Class, isAnonymousClass, "()Z"),
Elliott Hughesdd8df692011-09-23 14:42:41 -0700451 NATIVE_METHOD(Class, isAssignableFrom, "(Ljava/lang/Class;)Z"),
452 NATIVE_METHOD(Class, isInstance, "(Ljava/lang/Object;)Z"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700453 NATIVE_METHOD(Class, isInterface, "()Z"),
454 NATIVE_METHOD(Class, isPrimitive, "()Z"),
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700455 NATIVE_METHOD(Class, newInstanceImpl, "()Ljava/lang/Object;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700456};
457
458} // namespace
459
460void register_java_lang_Class(JNIEnv* env) {
461 jniRegisterNativeMethods(env, "java/lang/Class", gMethods, NELEM(gMethods));
462}
463
464} // namespace art