gcc/java:
[official-gcc.git] / libjava / java / lang / reflect / natMethod.cc
blobeb7170a02be83d357ccec238584a1722da49b0af
1 // natMethod.cc - Native code for Method class.
3 /* Copyright (C) 1998, 1999, 2000, 2001 , 2002, 2003, 2004, 2005, 2006 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>
16 #include <java-stack.h>
18 #include <java/lang/reflect/Method.h>
19 #include <java/lang/reflect/Constructor.h>
20 #include <java/lang/reflect/InvocationTargetException.h>
21 #include <java/lang/reflect/Modifier.h>
23 #include <java/lang/Void.h>
24 #include <java/lang/Byte.h>
25 #include <java/lang/Boolean.h>
26 #include <java/lang/Character.h>
27 #include <java/lang/Short.h>
28 #include <java/lang/Integer.h>
29 #include <java/lang/Long.h>
30 #include <java/lang/Float.h>
31 #include <java/lang/Double.h>
32 #include <java/lang/IllegalAccessException.h>
33 #include <java/lang/IllegalArgumentException.h>
34 #include <java/lang/IncompatibleClassChangeError.h>
35 #include <java/lang/NullPointerException.h>
36 #include <java/lang/ArrayIndexOutOfBoundsException.h>
37 #include <java/lang/VirtualMachineError.h>
38 #include <java/lang/Class.h>
39 #include <gcj/method.h>
40 #include <gnu/gcj/RawData.h>
41 #include <java/lang/NoClassDefFoundError.h>
43 #include <stdlib.h>
45 #if USE_LIBFFI
46 #include <ffi.h>
47 #else
48 #include <java/lang/UnsupportedOperationException.h>
49 #endif
51 struct cpair
53 jclass prim;
54 jclass wrap;
57 // This is used to determine when a primitive widening conversion is
58 // allowed.
59 static cpair primitives[] =
61 #define BOOLEAN 0
62 { JvPrimClass (boolean), &java::lang::Boolean::class$ },
63 { JvPrimClass (byte), &java::lang::Byte::class$ },
64 #define SHORT 2
65 { JvPrimClass (short), &java::lang::Short::class$ },
66 #define CHAR 3
67 { JvPrimClass (char), &java::lang::Character::class$ },
68 { JvPrimClass (int), &java::lang::Integer::class$ },
69 { JvPrimClass (long), &java::lang::Long::class$ },
70 { JvPrimClass (float), &java::lang::Float::class$ },
71 { JvPrimClass (double), &java::lang::Double::class$ },
72 { NULL, NULL }
75 static inline jboolean
76 can_widen (jclass from, jclass to)
78 int fromx = -1, tox = -1;
80 for (int i = 0; primitives[i].prim; ++i)
82 if (primitives[i].wrap == from)
83 fromx = i;
84 if (primitives[i].prim == to)
85 tox = i;
88 // Can't handle a miss.
89 if (fromx == -1 || tox == -1)
90 return false;
91 // Boolean arguments may not be widened.
92 if (fromx == BOOLEAN && tox != BOOLEAN)
93 return false;
94 // Nothing promotes to char.
95 if (tox == CHAR && fromx != CHAR)
96 return false;
98 return fromx <= tox;
101 #ifdef USE_LIBFFI
102 static inline ffi_type *
103 get_ffi_type (jclass klass)
105 // A special case.
106 if (klass == NULL)
107 return &ffi_type_pointer;
109 ffi_type *r;
110 if (klass == JvPrimClass (byte))
111 r = &ffi_type_sint8;
112 else if (klass == JvPrimClass (short))
113 r = &ffi_type_sint16;
114 else if (klass == JvPrimClass (int))
115 r = &ffi_type_sint32;
116 else if (klass == JvPrimClass (long))
117 r = &ffi_type_sint64;
118 else if (klass == JvPrimClass (float))
119 r = &ffi_type_float;
120 else if (klass == JvPrimClass (double))
121 r = &ffi_type_double;
122 else if (klass == JvPrimClass (boolean))
124 // On some platforms a bool is a byte, on others an int.
125 if (sizeof (jboolean) == sizeof (jbyte))
126 r = &ffi_type_sint8;
127 else
129 JvAssert (sizeof (jboolean) == sizeof (jint));
130 r = &ffi_type_sint32;
133 else if (klass == JvPrimClass (char))
134 r = &ffi_type_uint16;
135 else
137 JvAssert (! klass->isPrimitive());
138 r = &ffi_type_pointer;
141 return r;
143 #endif // USE_LIBFFI
145 jobject
146 java::lang::reflect::Method::invoke (jobject obj, jobjectArray args)
148 using namespace java::lang::reflect;
149 jclass iface = NULL;
151 if (parameter_types == NULL)
152 getType ();
154 jmethodID meth = _Jv_FromReflectedMethod (this);
156 if (Modifier::isStatic(meth->accflags))
158 // We have to initialize a static class. It is safe to do this
159 // here and not in _Jv_CallAnyMethodA because JNI initializes a
160 // class whenever a method lookup is done.
161 _Jv_InitClass (declaringClass);
163 else
165 jclass objClass = JV_CLASS (obj);
166 if (! _Jv_IsAssignableFrom (objClass, declaringClass))
167 throw new java::lang::IllegalArgumentException;
170 // Check accessibility, if required.
171 if (! (Modifier::isPublic (meth->accflags) || this->isAccessible()))
173 Class *caller = _Jv_StackTrace::GetCallingClass (&Method::class$);
174 if (! _Jv_CheckAccess(caller, declaringClass, meth->accflags))
175 throw new IllegalAccessException;
178 if (declaringClass->isInterface())
179 iface = declaringClass;
181 return _Jv_CallAnyMethodA (obj, return_type, meth, false,
182 parameter_types, args, iface);
185 jint
186 java::lang::reflect::Method::getModifiersInternal ()
188 return _Jv_FromReflectedMethod (this)->accflags;
191 jstring
192 java::lang::reflect::Method::getName ()
194 if (name == NULL)
195 name = _Jv_NewStringUtf8Const (_Jv_FromReflectedMethod (this)->name);
196 return name;
199 /* Internal method to set return_type and parameter_types fields. */
201 void
202 java::lang::reflect::Method::getType ()
204 _Jv_Method *method = _Jv_FromReflectedMethod (this);
205 _Jv_GetTypesFromSignature (method,
206 declaringClass,
207 &parameter_types,
208 &return_type);
210 int count = 0;
211 if (method->throws != NULL)
213 while (method->throws[count] != NULL)
214 ++count;
217 exception_types
218 = (JArray<jclass> *) JvNewObjectArray (count, &java::lang::Class::class$,
219 NULL);
220 jclass *elts = elements (exception_types);
221 for (int i = 0; i < count; ++i)
222 elts[i] = _Jv_FindClass (method->throws[i],
223 declaringClass->getClassLoaderInternal ());
226 void
227 _Jv_GetTypesFromSignature (jmethodID method,
228 jclass declaringClass,
229 JArray<jclass> **arg_types_out,
230 jclass *return_type_out)
233 _Jv_Utf8Const* sig = method->signature;
234 java::lang::ClassLoader *loader = declaringClass->getClassLoaderInternal();
235 char *ptr = sig->chars();
236 int numArgs = 0;
237 /* First just count the number of parameters. */
238 // FIXME: should do some validation here, e.g., that there is only
239 // one return type.
240 for (; ; ptr++)
242 switch (*ptr)
244 case 0:
245 case ')':
246 case 'V':
247 break;
248 case '[':
249 case '(':
250 continue;
251 case 'B':
252 case 'C':
253 case 'D':
254 case 'F':
255 case 'S':
256 case 'I':
257 case 'J':
258 case 'Z':
259 numArgs++;
260 continue;
261 case 'L':
262 numArgs++;
264 ptr++;
265 while (*ptr != ';' && ptr[1] != '\0');
266 continue;
268 break;
271 JArray<jclass> *args = (JArray<jclass> *)
272 JvNewObjectArray (numArgs, &java::lang::Class::class$, NULL);
273 jclass* argPtr = elements (args);
274 for (ptr = sig->chars(); *ptr != '\0'; ptr++)
276 if (*ptr == '(')
277 continue;
278 if (*ptr == ')')
280 argPtr = return_type_out;
281 continue;
284 char *end_ptr;
285 jclass type = _Jv_FindClassFromSignature (ptr, loader, &end_ptr);
286 if (type == NULL)
287 // FIXME: This isn't ideal.
288 throw new java::lang::NoClassDefFoundError (sig->toString());
290 // ARGPTR can be NULL if we are processing the return value of a
291 // call from Constructor.
292 if (argPtr)
293 *argPtr++ = type;
295 ptr = end_ptr;
297 *arg_types_out = args;
300 // This is a very rough analog of the JNI CallNonvirtual<type>MethodA
301 // functions. It handles both Methods and Constructors, and it can
302 // handle any return type. In the Constructor case, the `obj'
303 // argument is unused and should be NULL; also, the `return_type' is
304 // the class that the constructor will construct. RESULT is a pointer
305 // to a `jvalue' (see jni.h); for a void method this should be NULL.
306 // This function returns an exception (if one was thrown), or NULL if
307 // the call went ok.
308 void
309 _Jv_CallAnyMethodA (jobject obj,
310 jclass return_type,
311 jmethodID meth,
312 jboolean is_constructor,
313 jboolean is_virtual_call,
314 JArray<jclass> *parameter_types,
315 jvalue *args,
316 jvalue *result,
317 jboolean is_jni_call,
318 jclass iface)
320 using namespace java::lang::reflect;
322 #ifdef USE_LIBFFI
323 JvAssert (! is_constructor || ! obj);
324 JvAssert (! is_constructor || return_type);
326 // See whether call needs an object as the first argument. A
327 // constructor does need a `this' argument, but it is one we create.
328 jboolean needs_this = false;
329 if (is_constructor
330 || ! Modifier::isStatic(meth->accflags))
331 needs_this = true;
333 int param_count = parameter_types->length;
334 if (needs_this)
335 ++param_count;
337 ffi_type *rtype;
338 // A constructor itself always returns void.
339 if (is_constructor || return_type == JvPrimClass (void))
340 rtype = &ffi_type_void;
341 else
342 rtype = get_ffi_type (return_type);
343 ffi_type **argtypes = (ffi_type **) __builtin_alloca (param_count
344 * sizeof (ffi_type *));
346 jclass *paramelts = elements (parameter_types);
348 // Special case for the `this' argument of a constructor. Note that
349 // the JDK 1.2 docs specify that the new object must be allocated
350 // before argument conversions are done.
351 if (is_constructor)
352 obj = _Jv_AllocObject (return_type);
354 const int size_per_arg = sizeof(jvalue);
355 ffi_cif cif;
357 char *p = (char *) __builtin_alloca (param_count * size_per_arg);
358 // Overallocate to get correct alignment.
359 void **values = (void **)
360 __builtin_alloca (param_count * sizeof (void *));
362 int i = 0;
363 if (needs_this)
365 // The `NULL' type is `Object'.
366 argtypes[i] = get_ffi_type (NULL);
367 values[i] = p;
368 memcpy (p, &obj, sizeof (jobject));
369 p += size_per_arg;
370 ++i;
373 for (int arg = 0; i < param_count; ++i, ++arg)
375 int tsize;
377 argtypes[i] = get_ffi_type (paramelts[arg]);
378 if (paramelts[arg]->isPrimitive())
379 tsize = paramelts[arg]->size();
380 else
381 tsize = sizeof (jobject);
383 // Copy appropriate bits from the jvalue into the ffi array.
384 // FIXME: we could do this copying all in one loop, above, by
385 // over-allocating a bit.
386 // How do we do this without breaking big-endian platforms?
387 values[i] = p;
388 memcpy (p, &args[arg], tsize);
389 p += size_per_arg;
392 if (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, param_count,
393 rtype, argtypes) != FFI_OK)
394 throw new java::lang::VirtualMachineError(JvNewStringLatin1("internal error: ffi_prep_cif failed"));
396 using namespace java::lang;
397 using namespace java::lang::reflect;
399 union
401 ffi_arg i;
402 jobject o;
403 jlong l;
404 jfloat f;
405 jdouble d;
406 } ffi_result;
408 switch (rtype->type)
410 case FFI_TYPE_VOID:
411 break;
412 case FFI_TYPE_SINT8:
413 result->b = 0;
414 break;
415 case FFI_TYPE_SINT16:
416 result->s = 0;
417 break;
418 case FFI_TYPE_UINT16:
419 result->c = 0;
420 break;
421 case FFI_TYPE_SINT32:
422 result->i = 0;
423 break;
424 case FFI_TYPE_SINT64:
425 result->j = 0;
426 break;
427 case FFI_TYPE_FLOAT:
428 result->f = 0;
429 break;
430 case FFI_TYPE_DOUBLE:
431 result->d = 0;
432 break;
433 case FFI_TYPE_POINTER:
434 result->l = 0;
435 break;
436 default:
437 JvFail ("Unknown ffi_call return type");
438 break;
441 void *ncode;
443 // FIXME: If a vtable index is -1 at this point it is invalid, so we
444 // have to use the ncode.
446 // This can happen because methods in final classes don't have
447 // vtable entries, but _Jv_isVirtualMethod() doesn't know that. We
448 // could solve this problem by allocating a vtable index for methods
449 // in final classes.
450 if (is_virtual_call
451 && ! Modifier::isFinal (meth->accflags)
452 && (_Jv_ushort)-1 != meth->index)
454 _Jv_VTable *vtable = *(_Jv_VTable **) obj;
455 if (iface == NULL)
457 if (is_jni_call && Modifier::isAbstract (meth->accflags))
459 // With JNI we don't know if this is an interface call
460 // or a call to an abstract method. Look up the method
461 // by name, the slow way.
462 _Jv_Method *concrete_meth
463 = _Jv_LookupDeclaredMethod (vtable->clas,
464 meth->name,
465 meth->signature,
466 NULL);
467 if (concrete_meth == NULL
468 || concrete_meth->ncode == NULL
469 || Modifier::isAbstract(concrete_meth->accflags))
470 throw new java::lang::IncompatibleClassChangeError
471 (_Jv_GetMethodString (vtable->clas, meth));
472 ncode = concrete_meth->ncode;
474 else
475 ncode = vtable->get_method (meth->index);
477 else
478 ncode = _Jv_LookupInterfaceMethodIdx (vtable->clas, iface,
479 meth->index);
481 else
483 ncode = meth->ncode;
488 ffi_call (&cif, (void (*)()) ncode, &ffi_result, values);
490 catch (Throwable *ex)
492 // For JNI we just throw the real error. For reflection, we
493 // wrap the underlying method's exception in an
494 // InvocationTargetException.
495 if (! is_jni_call)
496 ex = new InvocationTargetException (ex);
497 throw ex;
500 // Since ffi_call returns integer values promoted to a word, use
501 // a narrowing conversion for jbyte, jchar, etc. results.
502 // Note that boolean is handled either by the FFI_TYPE_SINT8 or
503 // FFI_TYPE_SINT32 case.
504 if (is_constructor)
505 result->l = obj;
506 else
508 switch (rtype->type)
510 case FFI_TYPE_VOID:
511 break;
512 case FFI_TYPE_SINT8:
513 result->b = (jbyte)ffi_result.i;
514 break;
515 case FFI_TYPE_SINT16:
516 result->s = (jshort)ffi_result.i;
517 break;
518 case FFI_TYPE_UINT16:
519 result->c = (jchar)ffi_result.i;
520 break;
521 case FFI_TYPE_SINT32:
522 result->i = (jint)ffi_result.i;
523 break;
524 case FFI_TYPE_SINT64:
525 result->j = (jlong)ffi_result.l;
526 break;
527 case FFI_TYPE_FLOAT:
528 result->f = (jfloat)ffi_result.f;
529 break;
530 case FFI_TYPE_DOUBLE:
531 result->d = (jdouble)ffi_result.d;
532 break;
533 case FFI_TYPE_POINTER:
534 result->l = (jobject)ffi_result.o;
535 break;
536 default:
537 JvFail ("Unknown ffi_call return type");
538 break;
541 #else
542 throw new java::lang::UnsupportedOperationException(JvNewStringLatin1("reflection not available in this build"));
543 #endif // USE_LIBFFI
546 // This is another version of _Jv_CallAnyMethodA, but this one does
547 // more checking and is used by the reflection (and not JNI) code.
548 jobject
549 _Jv_CallAnyMethodA (jobject obj,
550 jclass return_type,
551 jmethodID meth,
552 jboolean is_constructor,
553 JArray<jclass> *parameter_types,
554 jobjectArray args,
555 jclass iface)
557 if (parameter_types->length == 0 && args == NULL)
559 // The JDK accepts this, so we do too.
561 else if (parameter_types->length != args->length)
562 throw new java::lang::IllegalArgumentException;
564 int param_count = parameter_types->length;
566 jclass *paramelts = elements (parameter_types);
567 jobject *argelts = args == NULL ? NULL : elements (args);
568 jvalue argvals[param_count];
570 #define COPY(Where, What, Type) \
571 do { \
572 Type val = (What); \
573 memcpy ((Where), &val, sizeof (Type)); \
574 } while (0)
576 for (int i = 0; i < param_count; ++i)
578 jclass k = argelts[i] ? argelts[i]->getClass() : NULL;
579 if (paramelts[i]->isPrimitive())
581 if (! argelts[i]
582 || ! k
583 || ! can_widen (k, paramelts[i]))
584 throw new java::lang::IllegalArgumentException;
586 if (paramelts[i] == JvPrimClass (boolean))
587 COPY (&argvals[i],
588 ((java::lang::Boolean *) argelts[i])->booleanValue(),
589 jboolean);
590 else if (paramelts[i] == JvPrimClass (char))
591 COPY (&argvals[i],
592 ((java::lang::Character *) argelts[i])->charValue(),
593 jchar);
594 else
596 java::lang::Number *num = (java::lang::Number *) argelts[i];
597 if (paramelts[i] == JvPrimClass (byte))
598 COPY (&argvals[i], num->byteValue(), jbyte);
599 else if (paramelts[i] == JvPrimClass (short))
600 COPY (&argvals[i], num->shortValue(), jshort);
601 else if (paramelts[i] == JvPrimClass (int))
602 COPY (&argvals[i], num->intValue(), jint);
603 else if (paramelts[i] == JvPrimClass (long))
604 COPY (&argvals[i], num->longValue(), jlong);
605 else if (paramelts[i] == JvPrimClass (float))
606 COPY (&argvals[i], num->floatValue(), jfloat);
607 else if (paramelts[i] == JvPrimClass (double))
608 COPY (&argvals[i], num->doubleValue(), jdouble);
611 else
613 if (argelts[i] && ! paramelts[i]->isAssignableFrom (k))
614 throw new java::lang::IllegalArgumentException;
615 COPY (&argvals[i], argelts[i], jobject);
619 jvalue ret_value;
620 _Jv_CallAnyMethodA (obj, return_type, meth, is_constructor,
621 _Jv_isVirtualMethod (meth),
622 parameter_types, argvals, &ret_value,
623 false, iface);
625 jobject r;
626 #define VAL(Wrapper, Field) (new Wrapper (ret_value.Field))
627 if (is_constructor)
628 r = ret_value.l;
629 else if (return_type == JvPrimClass (byte))
630 r = VAL (java::lang::Byte, b);
631 else if (return_type == JvPrimClass (short))
632 r = VAL (java::lang::Short, s);
633 else if (return_type == JvPrimClass (int))
634 r = VAL (java::lang::Integer, i);
635 else if (return_type == JvPrimClass (long))
636 r = VAL (java::lang::Long, j);
637 else if (return_type == JvPrimClass (float))
638 r = VAL (java::lang::Float, f);
639 else if (return_type == JvPrimClass (double))
640 r = VAL (java::lang::Double, d);
641 else if (return_type == JvPrimClass (boolean))
642 r = VAL (java::lang::Boolean, z);
643 else if (return_type == JvPrimClass (char))
644 r = VAL (java::lang::Character, c);
645 else if (return_type == JvPrimClass (void))
646 r = NULL;
647 else
649 JvAssert (return_type == NULL || ! return_type->isPrimitive());
650 r = ret_value.l;
653 return r;