blob: 1294c0845fea35e0dfcddd4d81981d2a8b36091d [file] [log] [blame]
Elliott Hughes418d20f2011-09-22 14:00:39 -07001/*
2 * Copyright (C) 2011 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 "reflection.h"
18
19#include "class_linker.h"
20#include "jni_internal.h"
21#include "object.h"
22
23#include "JniConstants.h" // Last to avoid problems with LOG redefinition.
24
25namespace art {
26
27Method* gBoolean_valueOf;
28Method* gByte_valueOf;
29Method* gCharacter_valueOf;
30Method* gDouble_valueOf;
31Method* gFloat_valueOf;
32Method* gInteger_valueOf;
33Method* gLong_valueOf;
34Method* gShort_valueOf;
35
36void InitBoxingMethod(JNIEnv* env, Method*& m, jclass c, const char* method_signature) {
37 m = DecodeMethod(env->GetStaticMethodID(c, "valueOf", method_signature));
38}
39
40void InitBoxingMethods(JNIEnv* env) {
41 InitBoxingMethod(env, gBoolean_valueOf, JniConstants::booleanClass, "(Z)Ljava/lang/Boolean;");
42 InitBoxingMethod(env, gByte_valueOf, JniConstants::byteClass, "(B)Ljava/lang/Byte;");
43 InitBoxingMethod(env, gCharacter_valueOf, JniConstants::characterClass, "(C)Ljava/lang/Character;");
44 InitBoxingMethod(env, gDouble_valueOf, JniConstants::doubleClass, "(D)Ljava/lang/Double;");
45 InitBoxingMethod(env, gFloat_valueOf, JniConstants::floatClass, "(F)Ljava/lang/Float;");
46 InitBoxingMethod(env, gInteger_valueOf, JniConstants::integerClass, "(I)Ljava/lang/Integer;");
47 InitBoxingMethod(env, gLong_valueOf, JniConstants::longClass, "(J)Ljava/lang/Long;");
48 InitBoxingMethod(env, gShort_valueOf, JniConstants::shortClass, "(S)Ljava/lang/Short;");
49}
50
Elliott Hughes2a20cfd2011-09-23 19:30:41 -070051jobject InvokeMethod(JNIEnv* env, jobject javaMethod, jobject javaReceiver, jobject javaArgs, jobject javaParams) {
52 Thread* self = Thread::Current();
53 ScopedThreadStateChange tsc(self, Thread::kRunnable);
54
55 jmethodID mid = env->FromReflectedMethod(javaMethod);
56 Method* m = reinterpret_cast<Method*>(mid);
57
58 Class* declaring_class = m->GetDeclaringClass();
59 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(declaring_class, true)) {
60 return NULL;
61 }
62
63 Object* receiver = NULL;
64 if (!m->IsStatic()) {
65 // Check that the receiver is non-null and an instance of the field's declaring class.
66 receiver = Decode<Object*>(env, javaReceiver);
67 if (!VerifyObjectInClass(env, receiver, declaring_class)) {
68 return NULL;
69 }
70
71 // Find the actual implementation of the virtual method.
72 m = receiver->GetClass()->FindVirtualMethodForVirtualOrInterface(m);
73 }
74
75 // Get our arrays of arguments and their types, and check they're the same size.
76 ObjectArray<Object>* objects = Decode<ObjectArray<Object>*>(env, javaArgs);
77 ObjectArray<Class>* classes = Decode<ObjectArray<Class>*>(env, javaParams);
78 int32_t arg_count = (objects != NULL) ? objects->GetLength() : 0;
79 if (arg_count != classes->GetLength()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070080 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes2a20cfd2011-09-23 19:30:41 -070081 "wrong number of arguments; expected %d, got %d",
82 classes->GetLength(), arg_count);
83 return NULL;
84 }
85
86 // Translate javaArgs to a jvalue[].
87 UniquePtr<jvalue[]> args(new jvalue[arg_count]);
88 JValue* decoded_args = reinterpret_cast<JValue*>(args.get());
89 for (int32_t i = 0; i < arg_count; ++i) {
90 Object* arg = objects->Get(i);
91 Class* dst_class = classes->Get(i);
92 if (dst_class->IsPrimitive()) {
93 if (!UnboxPrimitive(env, arg, dst_class, decoded_args[i])) {
94 return NULL;
95 }
96 } else {
97 args[i].l = AddLocalReference<jobject>(env, arg);
98 }
99 }
100
101 // Invoke the method.
102 JValue value = InvokeWithJValues(env, javaReceiver, mid, args.get());
103
104 // Wrap any exception with "Ljava/lang/reflect/InvocationTargetException;" and return early.
105 if (self->IsExceptionPending()) {
106 jthrowable th = env->ExceptionOccurred();
107 env->ExceptionClear();
108 jclass exception_class = env->FindClass("java/lang/reflect/InvocationTargetException");
109 jmethodID mid = env->GetMethodID(exception_class, "<init>", "(Ljava/lang/Throwable;)V");
110 jobject exception_instance = env->NewObject(exception_class, mid, th);
111 env->Throw(reinterpret_cast<jthrowable>(exception_instance));
112 return NULL;
113 }
114
115 // Box if necessary and return.
116 BoxPrimitive(env, m->GetReturnType(), value);
117 return AddLocalReference<jobject>(env, value.l);
118}
119
Elliott Hughes418d20f2011-09-22 14:00:39 -0700120bool VerifyObjectInClass(JNIEnv* env, Object* o, Class* c) {
121 if (o == NULL) {
122 jniThrowNullPointerException(env, "receiver for non-static field access was null");
123 return false;
124 }
125 if (!o->InstanceOf(c)) {
126 std::string expectedClassName(PrettyDescriptor(c->GetDescriptor()));
127 std::string actualClassName(PrettyTypeOf(o));
128 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
129 "expected receiver of type %s, but got %s",
130 expectedClassName.c_str(), actualClassName.c_str());
131 return false;
132 }
133 return true;
134}
135
136/*
137 * Convert primitive, boxed data from "srcPtr" to "dstPtr".
138 *
139 * Section v2 2.6 lists the various conversions and promotions. We
140 * allow the "widening" and "identity" conversions, but don't allow the
141 * "narrowing" conversions.
142 *
143 * Allowed:
144 * byte to short, int, long, float, double
145 * short to int, long, float double
146 * char to int, long, float, double
147 * int to long, float, double
148 * long to float, double
149 * float to double
150 * Values of types byte, char, and short are "internally" widened to int.
151 *
152 * Returns the width in 32-bit words of the destination primitive, or
153 * -1 if the conversion is not allowed.
154 */
155bool ConvertPrimitiveValue(Class* src_class, Class* dst_class, const JValue& src, JValue& dst) {
156 Class::PrimitiveType srcType = src_class->GetPrimitiveType();
157 Class::PrimitiveType dstType = dst_class->GetPrimitiveType();
158 switch (dstType) {
159 case Class::kPrimBoolean:
160 case Class::kPrimChar:
161 case Class::kPrimByte:
162 if (srcType == dstType) {
163 dst.i = src.i;
164 return true;
165 }
166 break;
167 case Class::kPrimShort:
168 if (srcType == Class::kPrimByte || srcType == Class::kPrimShort) {
169 dst.i = src.i;
170 return true;
171 }
172 break;
173 case Class::kPrimInt:
174 if (srcType == Class::kPrimByte || srcType == Class::kPrimChar ||
175 srcType == Class::kPrimShort || srcType == Class::kPrimInt) {
176 dst.i = src.i;
177 return true;
178 }
179 break;
180 case Class::kPrimLong:
181 if (srcType == Class::kPrimByte || srcType == Class::kPrimChar ||
182 srcType == Class::kPrimShort || srcType == Class::kPrimInt) {
183 dst.j = src.i;
184 return true;
185 } else if (srcType == Class::kPrimLong) {
186 dst.j = src.j;
187 return true;
188 }
189 break;
190 case Class::kPrimFloat:
191 if (srcType == Class::kPrimByte || srcType == Class::kPrimChar ||
192 srcType == Class::kPrimShort || srcType == Class::kPrimInt) {
193 dst.f = src.i;
194 return true;
195 } else if (srcType == Class::kPrimLong) {
196 dst.f = src.j;
197 return true;
198 } else if (srcType == Class::kPrimFloat) {
199 dst.i = src.i;
200 return true;
201 }
202 break;
203 case Class::kPrimDouble:
204 if (srcType == Class::kPrimByte || srcType == Class::kPrimChar ||
205 srcType == Class::kPrimShort || srcType == Class::kPrimInt) {
206 dst.d = src.i;
207 return true;
208 } else if (srcType == Class::kPrimLong) {
209 dst.d = src.j;
210 return true;
211 } else if (srcType == Class::kPrimFloat) {
212 dst.d = src.f;
213 return true;
214 } else if (srcType == Class::kPrimDouble) {
215 dst.j = src.j;
216 return true;
217 }
218 break;
219 default:
220 break;
221 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700222 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700223 "invalid primitive conversion from %s to %s",
224 PrettyDescriptor(src_class->GetDescriptor()).c_str(),
225 PrettyDescriptor(dst_class->GetDescriptor()).c_str());
226 return false;
227}
228
229void BoxPrimitive(JNIEnv* env, Class* src_class, JValue& value) {
230 if (!src_class->IsPrimitive()) {
231 return;
232 }
233
234 Method* m = NULL;
235 UniquePtr<byte[]> args(new byte[8]);
236 memset(&args[0], 0, 8);
237 switch (src_class->GetPrimitiveType()) {
238 case Class::kPrimBoolean:
239 m = gBoolean_valueOf;
240 *reinterpret_cast<uint32_t*>(&args[0]) = value.z;
241 break;
242 case Class::kPrimByte:
243 m = gByte_valueOf;
244 *reinterpret_cast<uint32_t*>(&args[0]) = value.b;
245 break;
246 case Class::kPrimChar:
247 m = gCharacter_valueOf;
248 *reinterpret_cast<uint32_t*>(&args[0]) = value.c;
249 break;
250 case Class::kPrimDouble:
251 m = gDouble_valueOf;
252 *reinterpret_cast<double*>(&args[0]) = value.d;
253 break;
254 case Class::kPrimFloat:
255 m = gFloat_valueOf;
256 *reinterpret_cast<float*>(&args[0]) = value.f;
257 break;
258 case Class::kPrimInt:
259 m = gInteger_valueOf;
260 *reinterpret_cast<uint32_t*>(&args[0]) = value.i;
261 break;
262 case Class::kPrimLong:
263 m = gLong_valueOf;
264 *reinterpret_cast<uint64_t*>(&args[0]) = value.j;
265 break;
266 case Class::kPrimShort:
267 m = gShort_valueOf;
268 *reinterpret_cast<uint32_t*>(&args[0]) = value.s;
269 break;
270 case Class::kPrimVoid:
271 // There's no such thing as a void field, and void methods invoked via reflection return null.
272 value.l = NULL;
273 return;
274 default:
275 LOG(FATAL) << PrettyClass(src_class);
276 }
277
278 Thread* self = Thread::Current();
279 ScopedThreadStateChange tsc(self, Thread::kRunnable);
280 m->Invoke(self, NULL, args.get(), &value);
281}
282
283bool UnboxPrimitive(JNIEnv* env, Object* o, Class* dst_class, JValue& unboxed_value) {
284 if (dst_class->GetPrimitiveType() == Class::kPrimNot) {
285 if (o != NULL && !o->InstanceOf(dst_class)) {
286 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
287 "expected object of type %s, but got %s",
288 PrettyDescriptor(dst_class->GetDescriptor()).c_str(),
289 PrettyTypeOf(o).c_str());
290 return false;
291 }
292 unboxed_value.l = o;
293 return true;
294 } else if (dst_class->GetPrimitiveType() == Class::kPrimVoid) {
295 Thread::Current()->ThrowNewException("Ljava/lang/IllegalArgumentException;",
296 "can't unbox to void");
297 return false;
298 }
299
300 if (o == NULL) {
301 Thread::Current()->ThrowNewException("Ljava/lang/IllegalArgumentException;",
302 "null passed for boxed primitive type");
303 return false;
304 }
305
306 JValue boxed_value = { 0 };
307 const String* src_descriptor = o->GetClass()->GetDescriptor();
308 Class* src_class = NULL;
309 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
310 Field* primitive_field = o->GetClass()->GetIFields()->Get(0);
311 if (src_descriptor->Equals("Ljava/lang/Boolean;")) {
312 src_class = class_linker->FindPrimitiveClass('Z');
313 boxed_value.z = primitive_field->GetBoolean(o);
314 } else if (src_descriptor->Equals("Ljava/lang/Byte;")) {
315 src_class = class_linker->FindPrimitiveClass('B');
316 boxed_value.b = primitive_field->GetByte(o);
317 } else if (src_descriptor->Equals("Ljava/lang/Character;")) {
318 src_class = class_linker->FindPrimitiveClass('C');
319 boxed_value.c = primitive_field->GetChar(o);
320 } else if (src_descriptor->Equals("Ljava/lang/Float;")) {
321 src_class = class_linker->FindPrimitiveClass('F');
322 boxed_value.f = primitive_field->GetFloat(o);
323 } else if (src_descriptor->Equals("Ljava/lang/Double;")) {
324 src_class = class_linker->FindPrimitiveClass('D');
325 boxed_value.d = primitive_field->GetDouble(o);
326 } else if (src_descriptor->Equals("Ljava/lang/Integer;")) {
327 src_class = class_linker->FindPrimitiveClass('I');
328 boxed_value.i = primitive_field->GetInt(o);
329 } else if (src_descriptor->Equals("Ljava/lang/Long;")) {
330 src_class = class_linker->FindPrimitiveClass('J');
331 boxed_value.j = primitive_field->GetLong(o);
332 } else if (src_descriptor->Equals("Ljava/lang/Short;")) {
333 src_class = class_linker->FindPrimitiveClass('S');
334 boxed_value.s = primitive_field->GetShort(o);
335 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700336 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700337 "%s is not a boxed primitive type", PrettyDescriptor(src_descriptor).c_str());
338 return false;
339 }
340
341 return ConvertPrimitiveValue(src_class, dst_class, boxed_value, unboxed_value);
342}
343
344} // namespace art