blob: 207b12463b8a7f26c9e77e48a560ea97c5afc09d [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"
Brian Carlstromf91c8c32011-09-21 17:30:34 -070021#include "ScopedUtfChars.h"
Elliott Hughesd369bb72011-09-12 14:41:14 -070022
23#include "JniConstants.h" // Last to avoid problems with LOG redefinition.
24
25namespace art {
26
27namespace {
28
Brian Carlstromf91c8c32011-09-21 17:30:34 -070029// "name" is in "binary name" format, e.g. "dalvik.system.Debug$1".
30jclass Class_classForName(JNIEnv* env, jclass, jstring javaName, jboolean initialize, jobject javaLoader) {
31 ScopedUtfChars name(env, javaName);
32 if (name.c_str() == NULL) {
33 return NULL;
34 }
35
36 // We need to validate and convert the name (from x.y.z to x/y/z). This
37 // is especially handy for array types, since we want to avoid
38 // auto-generating bogus array classes.
39 if (!IsValidClassName(name.c_str(), true, true)) {
40 Thread::Current()->ThrowNewException("Ljava/lang/ClassNotFoundException;",
41 "Invalid name: %s", name.c_str());
42 return NULL;
43 }
44
45 std::string descriptor(DotToDescriptor(name.c_str()));
46 Object* loader = Decode<Object*>(env, javaLoader);
47 ClassLoader* class_loader = down_cast<ClassLoader*>(loader);
48 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
49 Class* c = class_linker->FindClass(descriptor.c_str(), class_loader);
50 if (initialize) {
51 class_linker->EnsureInitialized(c, true);
52 }
53 return AddLocalReference<jclass>(env, c);
54}
55
Elliott Hughes6bdc3b22011-09-16 19:24:10 -070056jboolean Class_desiredAssertionStatus(JNIEnv* env, jobject javaThis) {
57 return JNI_FALSE;
58}
59
60jobject Class_getClassLoader(JNIEnv* env, jclass, jobject javaClass) {
61 Class* c = Decode<Class*>(env, javaClass);
62 Object* result = reinterpret_cast<Object*>(const_cast<ClassLoader*>(c->GetClassLoader()));
63 return AddLocalReference<jobject>(env, result);
64}
65
Elliott Hughesd369bb72011-09-12 14:41:14 -070066jclass Class_getComponentType(JNIEnv* env, jobject javaThis) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -070067 return AddLocalReference<jclass>(env, Decode<Class*>(env, javaThis)->GetComponentType());
Elliott Hughesd369bb72011-09-12 14:41:14 -070068}
69
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -070070jobject Class_getDeclaredConstructorOrMethod(JNIEnv* env, jclass,
71 jclass jklass, jstring jname, jobjectArray jsignature) {
72 Class* klass = Decode<Class*>(env, jklass);
73 DCHECK(klass->IsClass());
74 String* name = Decode<String*>(env, jname);
75 DCHECK(name->IsString());
76 Object* signature_obj = Decode<Object*>(env, jsignature);
77 DCHECK(signature_obj->IsArrayInstance());
Brian Carlstrom03c99df2011-09-18 10:52:00 -070078 // check that this is a Class[] by checking that component type is Class
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -070079 // foo->GetClass()->GetClass() is an idiom for getting java.lang.Class from an arbitrary object
80 DCHECK(signature_obj->GetClass()->GetComponentType() == signature_obj->GetClass()->GetClass());
81 ObjectArray<Class>* signature = down_cast<ObjectArray<Class>*>(signature_obj);
82
83 std::string name_string = name->ToModifiedUtf8();
84 std::string signature_string;
85 signature_string += "(";
86 for (int i = 0; i < signature->GetLength(); i++) {
87 Class* argument_class = signature->Get(0);
88 if (argument_class == NULL) {
89 UNIMPLEMENTED(FATAL) << "throw null pointer exception?";
90 }
91 signature_string += argument_class->GetDescriptor()->ToModifiedUtf8();
92 }
93 signature_string += ")";
94
95 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
96 Method* method = klass->GetVirtualMethod(i);
97 if (!method->GetName()->Equals(name)) {
98 continue;
99 }
100 std::string method_signature = method->GetSignature()->ToModifiedUtf8();
101 if (!StringPiece(method_signature).starts_with(signature_string)) {
102 continue;
103 }
104 return AddLocalReference<jobject>(env, method);
105 }
106
Brian Carlstrom03c99df2011-09-18 10:52:00 -0700107 for (size_t i = 0; i < klass->NumDirectMethods(); ++i) {
108 Method* method = klass->GetDirectMethod(i);
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700109 if (!method->GetName()->Equals(name)) {
110 continue;
111 }
112 std::string method_signature = method->GetSignature()->ToModifiedUtf8();
113 if (!StringPiece(method_signature).starts_with(signature_string)) {
114 continue;
115 }
116 return AddLocalReference<jobject>(env, method);
117 }
118
119 return NULL;
120}
121
122jobject Class_getDeclaredField(JNIEnv* env, jclass, jclass jklass, jobject jname) {
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700123 Class* klass = Decode<Class*>(env, jklass);
124 DCHECK(klass->IsClass());
125 String* name = Decode<String*>(env, jname);
126 DCHECK(name->IsString());
127
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700128 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700129 Field* f = klass->GetInstanceField(i);
130 if (f->GetName()->Equals(name)) {
131 return AddLocalReference<jclass>(env, f);
132 }
133 }
134 for (size_t i = 0; i < klass->NumStaticFields(); ++i) {
135 Field* f = klass->GetStaticField(i);
136 if (f->GetName()->Equals(name)) {
137 return AddLocalReference<jclass>(env, f);
138 }
139 }
140 return NULL;
141}
142
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700143jclass Class_getDeclaringClass(JNIEnv* env, jobject javaThis) {
144 UNIMPLEMENTED(WARNING) << "needs annotations";
145 return NULL;
146}
147
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700148/*
149 * private native String getNameNative()
150 *
151 * Return the class' name. The exact format is bizarre, but it's the specified
152 * behavior: keywords for primitive types, regular "[I" form for primitive
153 * arrays (so "int" but "[I"), and arrays of reference types written
154 * between "L" and ";" but with dots rather than slashes (so "java.lang.String"
155 * but "[Ljava.lang.String;"). Madness.
156 */
157jstring Class_getNameNative(JNIEnv* env, jobject javaThis) {
158 Class* c = Decode<Class*>(env, javaThis);
159 std::string descriptor(c->GetDescriptor()->ToModifiedUtf8());
160 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
161 // The descriptor indicates that this is the class for
162 // a primitive type; special-case the return value.
163 const char* name = NULL;
164 switch (descriptor[0]) {
165 case 'Z': name = "boolean"; break;
166 case 'B': name = "byte"; break;
167 case 'C': name = "char"; break;
168 case 'S': name = "short"; break;
169 case 'I': name = "int"; break;
170 case 'J': name = "long"; break;
171 case 'F': name = "float"; break;
172 case 'D': name = "double"; break;
173 case 'V': name = "void"; break;
174 default:
175 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
176 }
177 return env->NewStringUTF(name);
178 }
179
180 // Convert the UTF-8 name to a java.lang.String. The
181 // name must use '.' to separate package components.
182 if (descriptor.size() > 2 && descriptor[0] == 'L' && descriptor[descriptor.size() - 1] == ';') {
183 descriptor.erase(0, 1);
184 descriptor.erase(descriptor.size() - 1);
185 }
186 std::replace(descriptor.begin(), descriptor.end(), '/', '.');
187 return env->NewStringUTF(descriptor.c_str());
188}
189
190jclass Class_getSuperclass(JNIEnv* env, jobject javaThis) {
191 Class* c = Decode<Class*>(env, javaThis);
192 Class* result = c->GetSuperClass();
193 return AddLocalReference<jclass>(env, result);
194}
195
196jboolean Class_isAnonymousClass(JNIEnv* env, jobject javaThis) {
197 UNIMPLEMENTED(WARNING) << "needs annotations";
198 return JNI_FALSE;
199}
200
201jboolean Class_isInterface(JNIEnv* env, jobject javaThis) {
202 Class* c = Decode<Class*>(env, javaThis);
203 return c->IsInterface();
204}
205
206jboolean Class_isPrimitive(JNIEnv* env, jobject javaThis) {
207 Class* c = Decode<Class*>(env, javaThis);
208 return c->IsPrimitive();
209}
210
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700211bool CheckClassAccess(const Class* access_from, const Class* klass) {
212 if (klass->IsPublic()) {
213 return true;
214 }
215 return access_from->IsInSamePackage(klass);
216}
217
218// Validate method/field access.
219bool CheckMemberAccess(const Class* access_from, const Class* access_to, uint32_t member_flags) {
220 // quick accept for public access */
221 if (member_flags & kAccPublic) {
222 return true;
223 }
224
225 // quick accept for access from same class
226 if (access_from == access_to) {
227 return true;
228 }
229
230 // quick reject for private access from another class
231 if (member_flags & kAccPrivate) {
232 return false;
233 }
234
235 // Semi-quick test for protected access from a sub-class, which may or
236 // may not be in the same package.
237 if (member_flags & kAccProtected) {
238 if (access_from->IsSubClass(access_to)) {
239 return true;
240 }
241 }
242
243 // Allow protected and private access from other classes in the same
244 return access_from->IsInSamePackage(access_to);
245}
246
247jobject Class_newInstanceImpl(JNIEnv* env, jobject javaThis) {
248 Class* c = Decode<Class*>(env, javaThis);
249 if (c->IsPrimitive() || c->IsInterface() || c->IsArrayClass() || c->IsAbstract()) {
250 Thread::Current()->ThrowNewException("Ljava/lang/InstantiationException;",
251 "Class %s can not be instantiated", PrettyDescriptor(c->GetDescriptor()).c_str());
252 return NULL;
253 }
254
255 Method* init = c->FindDirectMethod("<init>", "()V");
256 if (init == NULL) {
257 Thread::Current()->ThrowNewException("Ljava/lang/InstantiationException;",
258 "Class %s has no default <init>()V constructor", PrettyDescriptor(c->GetDescriptor()).c_str());
259 return NULL;
260 }
261
262 // Verify access from the call site.
263 //
264 // First, make sure the method invoking Class.newInstance() has permission
265 // to access the class.
266 //
267 // Second, make sure it has permission to invoke the constructor. The
268 // constructor must be public or, if the caller is in the same package,
269 // have package scope.
270 // TODO: need SmartFrame (Thread::WalkStack-like iterator).
271 Frame frame = Thread::Current()->GetTopOfStack();
272 frame.Next();
273 frame.Next();
274 Method* caller_caller = frame.GetMethod();
275 Class* caller_class = caller_caller->GetDeclaringClass();
276
277 if (!CheckClassAccess(c, caller_class)) {
278 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessException;",
279 "Class %s is not accessible from class %s",
280 PrettyDescriptor(c->GetDescriptor()).c_str(),
281 PrettyDescriptor(caller_class->GetDescriptor()).c_str());
282 return NULL;
283 }
284 if (!CheckMemberAccess(caller_class, init->GetDeclaringClass(), init->GetAccessFlags())) {
285 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessException;",
286 "%s is not accessible from class %s",
287 PrettyMethod(init).c_str(),
288 PrettyDescriptor(caller_class->GetDescriptor()).c_str());
289 return NULL;
290 }
291
292 Object* new_obj = c->AllocObject();
293 if (new_obj == NULL) {
294 DCHECK(Thread::Current()->IsExceptionPending());
295 return NULL;
296 }
297
298 // invoke constructor; unlike reflection calls, we don't wrap exceptions
299 jclass jklass = AddLocalReference<jclass>(env, c);
300 jmethodID mid = EncodeMethod(init);
301 return env->NewObject(jklass, mid);
302}
303
Elliott Hughesd369bb72011-09-12 14:41:14 -0700304static JNINativeMethod gMethods[] = {
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700305 NATIVE_METHOD(Class, classForName, "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700306 NATIVE_METHOD(Class, desiredAssertionStatus, "()Z"),
307 NATIVE_METHOD(Class, getClassLoader, "(Ljava/lang/Class;)Ljava/lang/ClassLoader;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700308 NATIVE_METHOD(Class, getComponentType, "()Ljava/lang/Class;"),
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700309 NATIVE_METHOD(Class, getDeclaredConstructorOrMethod, "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Member;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700310 //NATIVE_METHOD(Class, getDeclaredConstructors, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Constructor;"),
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700311 NATIVE_METHOD(Class, getDeclaredField, "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/reflect/Field;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700312 //NATIVE_METHOD(Class, getDeclaredFields, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Field;"),
313 //NATIVE_METHOD(Class, getDeclaredMethods, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Method;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700314 NATIVE_METHOD(Class, getDeclaringClass, "()Ljava/lang/Class;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700315 //NATIVE_METHOD(Class, getInnerClassName, "()Ljava/lang/String;"),
316 //NATIVE_METHOD(Class, getInterfaces, "()[Ljava/lang/Class;"),
317 //NATIVE_METHOD(Class, getModifiers, "(Ljava/lang/Class;Z)I"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700318 NATIVE_METHOD(Class, getNameNative, "()Ljava/lang/String;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700319 NATIVE_METHOD(Class, getSuperclass, "()Ljava/lang/Class;"),
320 NATIVE_METHOD(Class, isAnonymousClass, "()Z"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700321 //NATIVE_METHOD(Class, isAssignableFrom, "(Ljava/lang/Class;)Z"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700322 //NATIVE_METHOD(Class, isInstance, "(Ljava/lang/Object;)Z"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700323 NATIVE_METHOD(Class, isInterface, "()Z"),
324 NATIVE_METHOD(Class, isPrimitive, "()Z"),
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700325 NATIVE_METHOD(Class, newInstanceImpl, "()Ljava/lang/Object;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700326};
327
328} // namespace
329
330void register_java_lang_Class(JNIEnv* env) {
331 jniRegisterNativeMethods(env, "java/lang/Class", gMethods, NELEM(gMethods));
332}
333
334} // namespace art