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