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
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>
48 #include <java/lang/UnsupportedOperationException.h>
57 // This is used to determine when a primitive widening conversion is
59 static cpair primitives[] =
62 { JvPrimClass (boolean), &java::lang::Boolean::class$ },
63 { JvPrimClass (byte), &java::lang::Byte::class$ },
65 { JvPrimClass (short), &java::lang::Short::class$ },
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$ },
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)
84 if (primitives[i].prim == to)
88 // Can't handle a miss.
89 if (fromx == -1 || tox == -1)
91 // Boolean arguments may not be widened.
92 if (fromx == BOOLEAN && tox != BOOLEAN)
94 // Nothing promotes to char.
95 if (tox == CHAR && fromx != CHAR)
102 static inline ffi_type *
103 get_ffi_type (jclass klass)
107 return &ffi_type_pointer;
110 if (klass == JvPrimClass (byte))
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))
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))
129 JvAssert (sizeof (jboolean) == sizeof (jint));
130 r = &ffi_type_sint32;
133 else if (klass == JvPrimClass (char))
134 r = &ffi_type_uint16;
137 JvAssert (! klass->isPrimitive());
138 r = &ffi_type_pointer;
146 java::lang::reflect::Method::invoke (jobject obj, jobjectArray args)
148 using namespace java::lang::reflect;
151 if (parameter_types == NULL)
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);
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);
186 java::lang::reflect::Method::getModifiersInternal ()
188 return _Jv_FromReflectedMethod (this)->accflags;
192 java::lang::reflect::Method::getName ()
195 name = _Jv_NewStringUtf8Const (_Jv_FromReflectedMethod (this)->name);
199 /* Internal method to set return_type and parameter_types fields. */
202 java::lang::reflect::Method::getType ()
204 _Jv_Method *method = _Jv_FromReflectedMethod (this);
205 _Jv_GetTypesFromSignature (method,
211 if (method->throws != NULL)
213 while (method->throws[count] != NULL)
218 = (JArray<jclass> *) JvNewObjectArray (count, &java::lang::Class::class$,
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 ());
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();
237 /* First just count the number of parameters. */
238 // FIXME: should do some validation here, e.g., that there is only
265 while (*ptr != ';' && ptr[1] != '\0');
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++)
280 argPtr = return_type_out;
285 jclass type = _Jv_FindClassFromSignature (ptr, loader, &end_ptr);
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.
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
309 _Jv_CallAnyMethodA (jobject obj,
312 jboolean is_constructor,
313 jboolean is_virtual_call,
314 JArray<jclass> *parameter_types,
317 jboolean is_jni_call,
320 using namespace java::lang::reflect;
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;
330 || ! Modifier::isStatic(meth->accflags))
333 int param_count = parameter_types->length;
338 // A constructor itself always returns void.
339 if (is_constructor || return_type == JvPrimClass (void))
340 rtype = &ffi_type_void;
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.
352 obj = _Jv_AllocObject (return_type);
354 const int size_per_arg = sizeof(jvalue);
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 *));
365 // The `NULL' type is `Object'.
366 argtypes[i] = get_ffi_type (NULL);
368 memcpy (p, &obj, sizeof (jobject));
373 for (int arg = 0; i < param_count; ++i, ++arg)
377 argtypes[i] = get_ffi_type (paramelts[arg]);
378 if (paramelts[arg]->isPrimitive())
379 tsize = paramelts[arg]->size();
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?
388 memcpy (p, &args[arg], tsize);
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;
415 case FFI_TYPE_SINT16:
418 case FFI_TYPE_UINT16:
421 case FFI_TYPE_SINT32:
424 case FFI_TYPE_SINT64:
430 case FFI_TYPE_DOUBLE:
433 case FFI_TYPE_POINTER:
437 JvFail ("Unknown ffi_call return type");
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
451 && ! Modifier::isFinal (meth->accflags)
452 && (_Jv_ushort)-1 != meth->index)
454 _Jv_VTable *vtable = *(_Jv_VTable **) obj;
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,
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;
475 ncode = vtable->get_method (meth->index);
478 ncode = _Jv_LookupInterfaceMethodIdx (vtable->clas, iface,
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.
496 ex = new InvocationTargetException (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.
513 result->b = (jbyte)ffi_result.i;
515 case FFI_TYPE_SINT16:
516 result->s = (jshort)ffi_result.i;
518 case FFI_TYPE_UINT16:
519 result->c = (jchar)ffi_result.i;
521 case FFI_TYPE_SINT32:
522 result->i = (jint)ffi_result.i;
524 case FFI_TYPE_SINT64:
525 result->j = (jlong)ffi_result.l;
528 result->f = (jfloat)ffi_result.f;
530 case FFI_TYPE_DOUBLE:
531 result->d = (jdouble)ffi_result.d;
533 case FFI_TYPE_POINTER:
534 result->l = (jobject)ffi_result.o;
537 JvFail ("Unknown ffi_call return type");
542 throw new java::lang::UnsupportedOperationException(JvNewStringLatin1("reflection not available in this build"));
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.
549 _Jv_CallAnyMethodA (jobject obj,
552 jboolean is_constructor,
553 JArray<jclass> *parameter_types,
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) \
573 memcpy ((Where), &val, sizeof (Type)); \
576 for (int i = 0; i < param_count; ++i)
578 jclass k = argelts[i] ? argelts[i]->getClass() : NULL;
579 if (paramelts[i]->isPrimitive())
583 || ! can_widen (k, paramelts[i]))
584 throw new java::lang::IllegalArgumentException;
586 if (paramelts[i] == JvPrimClass (boolean))
588 ((java::lang::Boolean *) argelts[i])->booleanValue(),
590 else if (paramelts[i] == JvPrimClass (char))
592 ((java::lang::Character *) argelts[i])->charValue(),
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);
613 if (argelts[i] && ! paramelts[i]->isAssignableFrom (k))
614 throw new java::lang::IllegalArgumentException;
615 COPY (&argvals[i], argelts[i], jobject);
620 _Jv_CallAnyMethodA (obj, return_type, meth, is_constructor,
621 _Jv_isVirtualMethod (meth),
622 parameter_types, argvals, &ret_value,
626 #define VAL(Wrapper, Field) (new Wrapper (ret_value.Field))
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))
649 JvAssert (return_type == NULL || ! return_type->isPrimitive());