FSF GCC merge 02/23/03
[official-gcc.git] / libjava / java / lang / reflect / natMethod.cc
blob9b697d25024bbb0be83d0c561049c572a2707e78
1 // natMethod.cc - Native code for Method class.
3 /* Copyright (C) 1998, 1999, 2000, 2001 , 2002 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 #include <config.h>
13 #include <gcj/cni.h>
14 #include <jvm.h>
15 #include <jni.h>
17 #include <java/lang/reflect/Method.h>
18 #include <java/lang/reflect/Constructor.h>
19 #include <java/lang/reflect/InvocationTargetException.h>
20 #include <java/lang/reflect/Modifier.h>
22 #include <java/lang/Void.h>
23 #include <java/lang/Byte.h>
24 #include <java/lang/Boolean.h>
25 #include <java/lang/Character.h>
26 #include <java/lang/Short.h>
27 #include <java/lang/Integer.h>
28 #include <java/lang/Long.h>
29 #include <java/lang/Float.h>
30 #include <java/lang/Double.h>
31 #include <java/lang/IllegalArgumentException.h>
32 #include <java/lang/NullPointerException.h>
33 #include <java/lang/Class.h>
34 #include <gcj/method.h>
35 #include <gnu/gcj/RawData.h>
37 #include <stdlib.h>
39 #if USE_LIBFFI
40 #include <ffi.h>
41 #else
42 #include <java/lang/UnsupportedOperationException.h>
43 #endif
45 struct cpair
47 jclass prim;
48 jclass wrap;
51 // This is used to determine when a primitive widening conversion is
52 // allowed.
53 static cpair primitives[] =
55 #define BOOLEAN 0
56 { JvPrimClass (boolean), &java::lang::Boolean::class$ },
57 { JvPrimClass (byte), &java::lang::Byte::class$ },
58 #define SHORT 2
59 { JvPrimClass (short), &java::lang::Short::class$ },
60 #define CHAR 3
61 { JvPrimClass (char), &java::lang::Character::class$ },
62 { JvPrimClass (int), &java::lang::Integer::class$ },
63 { JvPrimClass (long), &java::lang::Long::class$ },
64 { JvPrimClass (float), &java::lang::Float::class$ },
65 { JvPrimClass (double), &java::lang::Double::class$ },
66 { NULL, NULL }
69 static inline jboolean
70 can_widen (jclass from, jclass to)
72 int fromx = -1, tox = -1;
74 for (int i = 0; primitives[i].prim; ++i)
76 if (primitives[i].wrap == from)
77 fromx = i;
78 if (primitives[i].prim == to)
79 tox = i;
82 // Can't handle a miss.
83 if (fromx == -1 || tox == -1)
84 return false;
85 // Boolean arguments may not be widened.
86 if (fromx == BOOLEAN && tox != BOOLEAN)
87 return false;
88 // Nothing promotes to char.
89 if (tox == CHAR && fromx != CHAR)
90 return false;
92 return fromx <= tox;
95 #ifdef USE_LIBFFI
96 static inline ffi_type *
97 get_ffi_type (jclass klass)
99 // A special case.
100 if (klass == NULL)
101 return &ffi_type_pointer;
103 ffi_type *r;
104 if (klass == JvPrimClass (byte))
105 r = &ffi_type_sint8;
106 else if (klass == JvPrimClass (short))
107 r = &ffi_type_sint16;
108 else if (klass == JvPrimClass (int))
109 r = &ffi_type_sint32;
110 else if (klass == JvPrimClass (long))
111 r = &ffi_type_sint64;
112 else if (klass == JvPrimClass (float))
113 r = &ffi_type_float;
114 else if (klass == JvPrimClass (double))
115 r = &ffi_type_double;
116 else if (klass == JvPrimClass (boolean))
118 // On some platforms a bool is a byte, on others an int.
119 if (sizeof (jboolean) == sizeof (jbyte))
120 r = &ffi_type_sint8;
121 else
123 JvAssert (sizeof (jboolean) == sizeof (jint));
124 r = &ffi_type_sint32;
127 else if (klass == JvPrimClass (char))
128 r = &ffi_type_uint16;
129 else
131 JvAssert (! klass->isPrimitive());
132 r = &ffi_type_pointer;
135 return r;
137 #endif // USE_LIBFFI
139 jobject
140 java::lang::reflect::Method::invoke (jobject obj, jobjectArray args)
142 if (parameter_types == NULL)
143 getType ();
145 jmethodID meth = _Jv_FromReflectedMethod (this);
146 if (! java::lang::reflect::Modifier::isStatic(meth->accflags))
148 jclass k = obj ? obj->getClass() : NULL;
149 if (! obj)
150 throw new java::lang::NullPointerException;
151 if (! declaringClass->isAssignableFrom(k))
152 throw new java::lang::IllegalArgumentException;
153 // FIXME: access checks.
155 // Find the possibly overloaded method based on the runtime type
156 // of the object.
157 meth = _Jv_LookupDeclaredMethod (k, meth->name, meth->signature);
159 else
161 // We have to initialize a static class. It is safe to do this
162 // here and not in _Jv_CallAnyMethodA because JNI initializes a
163 // class whenever a method lookup is done.
164 _Jv_InitClass (declaringClass);
167 return _Jv_CallAnyMethodA (obj, return_type, meth, false,
168 parameter_types, args);
171 jint
172 java::lang::reflect::Method::getModifiers ()
174 // Ignore all unknown flags.
175 return _Jv_FromReflectedMethod (this)->accflags & Modifier::ALL_FLAGS;
178 jstring
179 java::lang::reflect::Method::getName ()
181 if (name == NULL)
182 name = _Jv_NewStringUtf8Const (_Jv_FromReflectedMethod (this)->name);
183 return name;
186 /* Internal method to set return_type and parameter_types fields. */
188 void
189 java::lang::reflect::Method::getType ()
191 _Jv_Method *method = _Jv_FromReflectedMethod (this);
192 _Jv_GetTypesFromSignature (method,
193 declaringClass,
194 &parameter_types,
195 &return_type);
197 int count = 0;
198 if (method->throws != NULL)
200 while (method->throws[count] != NULL)
201 ++count;
204 exception_types
205 = (JArray<jclass> *) JvNewObjectArray (count, &java::lang::Class::class$,
206 NULL);
207 jclass *elts = elements (exception_types);
208 for (int i = 0; i < count; ++i)
209 elts[i] = _Jv_FindClass (method->throws[i],
210 declaringClass->getClassLoader ());
213 void
214 _Jv_GetTypesFromSignature (jmethodID method,
215 jclass declaringClass,
216 JArray<jclass> **arg_types_out,
217 jclass *return_type_out)
220 _Jv_Utf8Const* sig = method->signature;
221 java::lang::ClassLoader *loader = declaringClass->getClassLoader();
222 char *ptr = sig->data;
223 int numArgs = 0;
224 /* First just count the number of parameters. */
225 for (; ; ptr++)
227 switch (*ptr)
229 case 0:
230 case ')':
231 case 'V':
232 break;
233 case '[':
234 case '(':
235 continue;
236 case 'B':
237 case 'C':
238 case 'D':
239 case 'F':
240 case 'S':
241 case 'I':
242 case 'J':
243 case 'Z':
244 numArgs++;
245 continue;
246 case 'L':
247 numArgs++;
249 ptr++;
250 while (*ptr != ';' && ptr[1] != '\0');
251 continue;
253 break;
256 JArray<jclass> *args = (JArray<jclass> *)
257 JvNewObjectArray (numArgs, &java::lang::Class::class$, NULL);
258 jclass* argPtr = elements (args);
259 for (ptr = sig->data; *ptr != '\0'; ptr++)
261 int num_arrays = 0;
262 jclass type;
263 for (; *ptr == '['; ptr++)
264 num_arrays++;
265 switch (*ptr)
267 default:
268 return;
269 case ')':
270 argPtr = return_type_out;
271 continue;
272 case '(':
273 continue;
274 case 'V':
275 case 'B':
276 case 'C':
277 case 'D':
278 case 'F':
279 case 'S':
280 case 'I':
281 case 'J':
282 case 'Z':
283 type = _Jv_FindClassFromSignature(ptr, loader);
284 break;
285 case 'L':
286 type = _Jv_FindClassFromSignature(ptr, loader);
288 ptr++;
289 while (*ptr != ';' && ptr[1] != '\0');
290 break;
293 // FIXME: 2'nd argument should be "current loader"
294 while (--num_arrays >= 0)
295 type = _Jv_GetArrayClass (type, 0);
296 // ARGPTR can be NULL if we are processing the return value of a
297 // call from Constructor.
298 if (argPtr)
299 *argPtr++ = type;
301 *arg_types_out = args;
304 // This is a very rough analog of the JNI CallNonvirtual<type>MethodA
305 // functions. It handles both Methods and Constructors, and it can
306 // handle any return type. In the Constructor case, the `obj'
307 // argument is unused and should be NULL; also, the `return_type' is
308 // the class that the constructor will construct. RESULT is a pointer
309 // to a `jvalue' (see jni.h); for a void method this should be NULL.
310 // This function returns an exception (if one was thrown), or NULL if
311 // the call went ok.
312 jthrowable
313 _Jv_CallAnyMethodA (jobject obj,
314 jclass return_type,
315 jmethodID meth,
316 jboolean is_constructor,
317 JArray<jclass> *parameter_types,
318 jvalue *args,
319 jvalue *result)
321 #ifdef USE_LIBFFI
322 JvAssert (! is_constructor || ! obj);
323 JvAssert (! is_constructor || return_type);
325 // See whether call needs an object as the first argument. A
326 // constructor does need a `this' argument, but it is one we create.
327 jboolean needs_this = false;
328 if (is_constructor
329 || ! java::lang::reflect::Modifier::isStatic(meth->accflags))
330 needs_this = true;
332 int param_count = parameter_types->length;
333 if (needs_this)
334 ++param_count;
336 ffi_type *rtype;
337 // A constructor itself always returns void.
338 if (is_constructor || return_type == JvPrimClass (void))
339 rtype = &ffi_type_void;
340 else
341 rtype = get_ffi_type (return_type);
342 ffi_type **argtypes = (ffi_type **) __builtin_alloca (param_count
343 * sizeof (ffi_type *));
345 jclass *paramelts = elements (parameter_types);
347 // FIXME: at some point the compiler is going to add extra arguments
348 // to some functions. In particular we are going to do this for
349 // handling access checks in reflection. We must add these hidden
350 // arguments here.
352 // Special case for the `this' argument of a constructor. Note that
353 // the JDK 1.2 docs specify that the new object must be allocated
354 // before argument conversions are done.
355 if (is_constructor)
357 // FIXME: must special-case String, arrays, maybe others here.
358 obj = JvAllocObject (return_type);
361 int i = 0;
362 int size = 0;
363 if (needs_this)
365 // The `NULL' type is `Object'.
366 argtypes[i++] = get_ffi_type (NULL);
367 size += sizeof (jobject);
370 for (int arg = 0; i < param_count; ++i, ++arg)
372 argtypes[i] = get_ffi_type (paramelts[arg]);
373 if (paramelts[arg]->isPrimitive())
374 size += paramelts[arg]->size();
375 else
376 size += sizeof (jobject);
379 ffi_cif cif;
380 if (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, param_count,
381 rtype, argtypes) != FFI_OK)
383 // FIXME: throw some kind of VirtualMachineError here.
386 char *p = (char *) __builtin_alloca (size);
387 void **values = (void **) __builtin_alloca (param_count * sizeof (void *));
389 i = 0;
390 if (needs_this)
392 values[i] = p;
393 memcpy (p, &obj, sizeof (jobject));
394 p += sizeof (jobject);
395 ++i;
398 for (int arg = 0; i < param_count; ++i, ++arg)
400 int tsize;
401 if (paramelts[arg]->isPrimitive())
402 tsize = paramelts[arg]->size();
403 else
404 tsize = sizeof (jobject);
406 // Copy appropriate bits from the jvalue into the ffi array.
407 // FIXME: we could do this copying all in one loop, above, by
408 // over-allocating a bit.
409 values[i] = p;
410 memcpy (p, &args[arg], tsize);
411 p += tsize;
414 using namespace java::lang;
415 using namespace java::lang::reflect;
417 Throwable *ex = NULL;
419 union
421 ffi_arg i;
422 jobject o;
423 jlong l;
424 jfloat f;
425 jdouble d;
426 } ffi_result;
430 ffi_call (&cif, (void (*)()) meth->ncode, &ffi_result, values);
432 catch (Throwable *ex2)
434 // FIXME: this is wrong for JNI. But if we just return the
435 // exception, then the non-JNI cases won't be able to
436 // distinguish it from exceptions we might generate ourselves.
437 // Sigh.
438 ex = new InvocationTargetException (ex2);
441 // Since ffi_call returns integer values promoted to a word, use
442 // a narrowing conversion for jbyte, jchar, etc. results.
443 // Note that boolean is handled either by the FFI_TYPE_SINT8 or
444 // FFI_TYPE_SINT32 case.
445 if (is_constructor)
446 result->l = obj;
447 else
449 switch (rtype->type)
451 case FFI_TYPE_VOID:
452 break;
453 case FFI_TYPE_SINT8:
454 result->b = (jbyte)ffi_result.i;
455 break;
456 case FFI_TYPE_SINT16:
457 result->s = (jshort)ffi_result.i;
458 break;
459 case FFI_TYPE_UINT16:
460 result->c = (jchar)ffi_result.i;
461 break;
462 case FFI_TYPE_SINT32:
463 result->i = (jint)ffi_result.i;
464 break;
465 case FFI_TYPE_SINT64:
466 result->j = (jlong)ffi_result.l;
467 break;
468 case FFI_TYPE_FLOAT:
469 result->f = (jfloat)ffi_result.f;
470 break;
471 case FFI_TYPE_DOUBLE:
472 result->d = (jdouble)ffi_result.d;
473 break;
474 case FFI_TYPE_POINTER:
475 result->l = (jobject)ffi_result.o;
476 break;
477 default:
478 JvFail ("Unknown ffi_call return type");
479 break;
483 return ex;
484 #else
485 throw new java::lang::UnsupportedOperationException;
486 return 0;
487 #endif // USE_LIBFFI
490 // This is another version of _Jv_CallAnyMethodA, but this one does
491 // more checking and is used by the reflection (and not JNI) code.
492 jobject
493 _Jv_CallAnyMethodA (jobject obj,
494 jclass return_type,
495 jmethodID meth,
496 jboolean is_constructor,
497 JArray<jclass> *parameter_types,
498 jobjectArray args)
500 // FIXME: access checks.
502 if (parameter_types->length == 0 && args == NULL)
504 // The JDK accepts this, so we do too.
506 else if (parameter_types->length != args->length)
507 throw new java::lang::IllegalArgumentException;
509 int param_count = parameter_types->length;
511 jclass *paramelts = elements (parameter_types);
512 jobject *argelts = args == NULL ? NULL : elements (args);
513 jvalue argvals[param_count];
515 #define COPY(Where, What, Type) \
516 do { \
517 Type val = (What); \
518 memcpy ((Where), &val, sizeof (Type)); \
519 } while (0)
521 for (int i = 0; i < param_count; ++i)
523 jclass k = argelts[i] ? argelts[i]->getClass() : NULL;
524 if (paramelts[i]->isPrimitive())
526 if (! argelts[i]
527 || ! k
528 || ! can_widen (k, paramelts[i]))
529 throw new java::lang::IllegalArgumentException;
531 if (paramelts[i] == JvPrimClass (boolean))
532 COPY (&argvals[i],
533 ((java::lang::Boolean *) argelts[i])->booleanValue(),
534 jboolean);
535 else if (paramelts[i] == JvPrimClass (char))
536 COPY (&argvals[i],
537 ((java::lang::Character *) argelts[i])->charValue(),
538 jchar);
539 else
541 java::lang::Number *num = (java::lang::Number *) argelts[i];
542 if (paramelts[i] == JvPrimClass (byte))
543 COPY (&argvals[i], num->byteValue(), jbyte);
544 else if (paramelts[i] == JvPrimClass (short))
545 COPY (&argvals[i], num->shortValue(), jshort);
546 else if (paramelts[i] == JvPrimClass (int))
547 COPY (&argvals[i], num->intValue(), jint);
548 else if (paramelts[i] == JvPrimClass (long))
549 COPY (&argvals[i], num->longValue(), jlong);
550 else if (paramelts[i] == JvPrimClass (float))
551 COPY (&argvals[i], num->floatValue(), jfloat);
552 else if (paramelts[i] == JvPrimClass (double))
553 COPY (&argvals[i], num->doubleValue(), jdouble);
556 else
558 if (argelts[i] && ! paramelts[i]->isAssignableFrom (k))
559 throw new java::lang::IllegalArgumentException;
560 COPY (&argvals[i], argelts[i], jobject);
564 jvalue ret_value;
565 java::lang::Throwable *ex = _Jv_CallAnyMethodA (obj,
566 return_type,
567 meth,
568 is_constructor,
569 parameter_types,
570 argvals,
571 &ret_value);
573 if (ex)
574 throw ex;
576 jobject r;
577 #define VAL(Wrapper, Field) (new Wrapper (ret_value.Field))
578 if (is_constructor)
579 r = ret_value.l;
580 else if (return_type == JvPrimClass (byte))
581 r = VAL (java::lang::Byte, b);
582 else if (return_type == JvPrimClass (short))
583 r = VAL (java::lang::Short, s);
584 else if (return_type == JvPrimClass (int))
585 r = VAL (java::lang::Integer, i);
586 else if (return_type == JvPrimClass (long))
587 r = VAL (java::lang::Long, j);
588 else if (return_type == JvPrimClass (float))
589 r = VAL (java::lang::Float, f);
590 else if (return_type == JvPrimClass (double))
591 r = VAL (java::lang::Double, d);
592 else if (return_type == JvPrimClass (boolean))
593 r = VAL (java::lang::Boolean, z);
594 else if (return_type == JvPrimClass (char))
595 r = VAL (java::lang::Character, c);
596 else if (return_type == JvPrimClass (void))
597 r = NULL;
598 else
600 JvAssert (return_type == NULL || ! return_type->isPrimitive());
601 r = ret_value.l;
604 return r;