blob: 9ca171b71759e0090b0fec4c3d7c5c8eec2c9fe4 [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
Brian Carlstrom53d6ff42011-09-23 10:45:07 -0700148jobject Class_getEnclosingConstructor(JNIEnv* env, jobject javaThis) {
149 UNIMPLEMENTED(WARNING) << "needs annotations";
150 return NULL;
151}
152
153jobject Class_getEnclosingMethod(JNIEnv* env, jobject javaThis) {
154 UNIMPLEMENTED(WARNING) << "needs annotations";
155 return NULL;
156}
157
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700158/*
159 * private native String getNameNative()
160 *
161 * Return the class' name. The exact format is bizarre, but it's the specified
162 * behavior: keywords for primitive types, regular "[I" form for primitive
163 * arrays (so "int" but "[I"), and arrays of reference types written
164 * between "L" and ";" but with dots rather than slashes (so "java.lang.String"
165 * but "[Ljava.lang.String;"). Madness.
166 */
167jstring Class_getNameNative(JNIEnv* env, jobject javaThis) {
168 Class* c = Decode<Class*>(env, javaThis);
169 std::string descriptor(c->GetDescriptor()->ToModifiedUtf8());
170 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
171 // The descriptor indicates that this is the class for
172 // a primitive type; special-case the return value.
173 const char* name = NULL;
174 switch (descriptor[0]) {
175 case 'Z': name = "boolean"; break;
176 case 'B': name = "byte"; break;
177 case 'C': name = "char"; break;
178 case 'S': name = "short"; break;
179 case 'I': name = "int"; break;
180 case 'J': name = "long"; break;
181 case 'F': name = "float"; break;
182 case 'D': name = "double"; break;
183 case 'V': name = "void"; break;
184 default:
185 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
186 }
187 return env->NewStringUTF(name);
188 }
189
190 // Convert the UTF-8 name to a java.lang.String. The
191 // name must use '.' to separate package components.
192 if (descriptor.size() > 2 && descriptor[0] == 'L' && descriptor[descriptor.size() - 1] == ';') {
193 descriptor.erase(0, 1);
194 descriptor.erase(descriptor.size() - 1);
195 }
196 std::replace(descriptor.begin(), descriptor.end(), '/', '.');
197 return env->NewStringUTF(descriptor.c_str());
198}
199
200jclass Class_getSuperclass(JNIEnv* env, jobject javaThis) {
201 Class* c = Decode<Class*>(env, javaThis);
202 Class* result = c->GetSuperClass();
203 return AddLocalReference<jclass>(env, result);
204}
205
206jboolean Class_isAnonymousClass(JNIEnv* env, jobject javaThis) {
207 UNIMPLEMENTED(WARNING) << "needs annotations";
208 return JNI_FALSE;
209}
210
211jboolean Class_isInterface(JNIEnv* env, jobject javaThis) {
212 Class* c = Decode<Class*>(env, javaThis);
213 return c->IsInterface();
214}
215
216jboolean Class_isPrimitive(JNIEnv* env, jobject javaThis) {
217 Class* c = Decode<Class*>(env, javaThis);
218 return c->IsPrimitive();
219}
220
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700221bool CheckClassAccess(const Class* access_from, const Class* klass) {
222 if (klass->IsPublic()) {
223 return true;
224 }
225 return access_from->IsInSamePackage(klass);
226}
227
228// Validate method/field access.
229bool CheckMemberAccess(const Class* access_from, const Class* access_to, uint32_t member_flags) {
230 // quick accept for public access */
231 if (member_flags & kAccPublic) {
232 return true;
233 }
234
235 // quick accept for access from same class
236 if (access_from == access_to) {
237 return true;
238 }
239
240 // quick reject for private access from another class
241 if (member_flags & kAccPrivate) {
242 return false;
243 }
244
245 // Semi-quick test for protected access from a sub-class, which may or
246 // may not be in the same package.
247 if (member_flags & kAccProtected) {
248 if (access_from->IsSubClass(access_to)) {
249 return true;
250 }
251 }
252
253 // Allow protected and private access from other classes in the same
254 return access_from->IsInSamePackage(access_to);
255}
256
257jobject Class_newInstanceImpl(JNIEnv* env, jobject javaThis) {
258 Class* c = Decode<Class*>(env, javaThis);
259 if (c->IsPrimitive() || c->IsInterface() || c->IsArrayClass() || c->IsAbstract()) {
260 Thread::Current()->ThrowNewException("Ljava/lang/InstantiationException;",
261 "Class %s can not be instantiated", PrettyDescriptor(c->GetDescriptor()).c_str());
262 return NULL;
263 }
264
265 Method* init = c->FindDirectMethod("<init>", "()V");
266 if (init == NULL) {
267 Thread::Current()->ThrowNewException("Ljava/lang/InstantiationException;",
268 "Class %s has no default <init>()V constructor", PrettyDescriptor(c->GetDescriptor()).c_str());
269 return NULL;
270 }
271
272 // Verify access from the call site.
273 //
274 // First, make sure the method invoking Class.newInstance() has permission
275 // to access the class.
276 //
277 // Second, make sure it has permission to invoke the constructor. The
278 // constructor must be public or, if the caller is in the same package,
279 // have package scope.
280 // TODO: need SmartFrame (Thread::WalkStack-like iterator).
281 Frame frame = Thread::Current()->GetTopOfStack();
282 frame.Next();
283 frame.Next();
284 Method* caller_caller = frame.GetMethod();
285 Class* caller_class = caller_caller->GetDeclaringClass();
286
287 if (!CheckClassAccess(c, caller_class)) {
288 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessException;",
289 "Class %s is not accessible from class %s",
290 PrettyDescriptor(c->GetDescriptor()).c_str(),
291 PrettyDescriptor(caller_class->GetDescriptor()).c_str());
292 return NULL;
293 }
294 if (!CheckMemberAccess(caller_class, init->GetDeclaringClass(), init->GetAccessFlags())) {
295 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessException;",
296 "%s is not accessible from class %s",
297 PrettyMethod(init).c_str(),
298 PrettyDescriptor(caller_class->GetDescriptor()).c_str());
299 return NULL;
300 }
301
302 Object* new_obj = c->AllocObject();
303 if (new_obj == NULL) {
304 DCHECK(Thread::Current()->IsExceptionPending());
305 return NULL;
306 }
307
308 // invoke constructor; unlike reflection calls, we don't wrap exceptions
309 jclass jklass = AddLocalReference<jclass>(env, c);
310 jmethodID mid = EncodeMethod(init);
311 return env->NewObject(jklass, mid);
312}
313
Elliott Hughesd369bb72011-09-12 14:41:14 -0700314static JNINativeMethod gMethods[] = {
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700315 NATIVE_METHOD(Class, classForName, "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700316 NATIVE_METHOD(Class, desiredAssertionStatus, "()Z"),
317 NATIVE_METHOD(Class, getClassLoader, "(Ljava/lang/Class;)Ljava/lang/ClassLoader;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700318 NATIVE_METHOD(Class, getComponentType, "()Ljava/lang/Class;"),
Brian Carlstrom3a7b4f22011-09-17 15:01:57 -0700319 NATIVE_METHOD(Class, getDeclaredConstructorOrMethod, "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Member;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700320 //NATIVE_METHOD(Class, getDeclaredConstructors, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Constructor;"),
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700321 NATIVE_METHOD(Class, getDeclaredField, "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/reflect/Field;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700322 //NATIVE_METHOD(Class, getDeclaredFields, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Field;"),
323 //NATIVE_METHOD(Class, getDeclaredMethods, "(Ljava/lang/Class;Z)[Ljava/lang/reflect/Method;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700324 NATIVE_METHOD(Class, getDeclaringClass, "()Ljava/lang/Class;"),
Brian Carlstrom53d6ff42011-09-23 10:45:07 -0700325 //NATIVE_METHOD(Class, getEnclosingClass, "()Ljava/lang/Class;"),
326 NATIVE_METHOD(Class, getEnclosingConstructor, "()Ljava/lang/reflect/Constructor;"),
327 NATIVE_METHOD(Class, getEnclosingMethod, "()Ljava/lang/reflect/Method;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700328 //NATIVE_METHOD(Class, getInnerClassName, "()Ljava/lang/String;"),
329 //NATIVE_METHOD(Class, getInterfaces, "()[Ljava/lang/Class;"),
330 //NATIVE_METHOD(Class, getModifiers, "(Ljava/lang/Class;Z)I"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700331 NATIVE_METHOD(Class, getNameNative, "()Ljava/lang/String;"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700332 NATIVE_METHOD(Class, getSuperclass, "()Ljava/lang/Class;"),
333 NATIVE_METHOD(Class, isAnonymousClass, "()Z"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700334 //NATIVE_METHOD(Class, isAssignableFrom, "(Ljava/lang/Class;)Z"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700335 //NATIVE_METHOD(Class, isInstance, "(Ljava/lang/Object;)Z"),
Elliott Hughes6bdc3b22011-09-16 19:24:10 -0700336 NATIVE_METHOD(Class, isInterface, "()Z"),
337 NATIVE_METHOD(Class, isPrimitive, "()Z"),
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700338 NATIVE_METHOD(Class, newInstanceImpl, "()Ljava/lang/Object;"),
Elliott Hughesd369bb72011-09-12 14:41:14 -0700339};
340
341} // namespace
342
343void register_java_lang_Class(JNIEnv* env) {
344 jniRegisterNativeMethods(env, "java/lang/Class", gMethods, NELEM(gMethods));
345}
346
347} // namespace art