2006-07-15 Andrew John Hughes <gnu_andrew@member.fsf.org>
[official-gcc.git] / libjava / java / lang / reflect / natMethod.cc
blob26aa2a34a0e89472c49638b65e93f52393ae3da4
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 typedef JArray< ::java::lang::annotation::Annotation * > * anno_a_t;
52 typedef JArray< JArray< ::java::lang::annotation::Annotation * > *> * anno_aa_t;
56 struct cpair
58 jclass prim;
59 jclass wrap;
62 // This is used to determine when a primitive widening conversion is
63 // allowed.
64 static cpair primitives[] =
66 #define BOOLEAN 0
67 { JvPrimClass (boolean), &java::lang::Boolean::class$ },
68 { JvPrimClass (byte), &java::lang::Byte::class$ },
69 #define SHORT 2
70 { JvPrimClass (short), &java::lang::Short::class$ },
71 #define CHAR 3
72 { JvPrimClass (char), &java::lang::Character::class$ },
73 { JvPrimClass (int), &java::lang::Integer::class$ },
74 { JvPrimClass (long), &java::lang::Long::class$ },
75 { JvPrimClass (float), &java::lang::Float::class$ },
76 { JvPrimClass (double), &java::lang::Double::class$ },
77 { NULL, NULL }
80 static inline jboolean
81 can_widen (jclass from, jclass to)
83 int fromx = -1, tox = -1;
85 for (int i = 0; primitives[i].prim; ++i)
87 if (primitives[i].wrap == from)
88 fromx = i;
89 if (primitives[i].prim == to)
90 tox = i;
93 // Can't handle a miss.
94 if (fromx == -1 || tox == -1)
95 return false;
96 // Boolean arguments may not be widened.
97 if (fromx == BOOLEAN && tox != BOOLEAN)
98 return false;
99 // Nothing promotes to char.
100 if (tox == CHAR && fromx != CHAR)
101 return false;
103 return fromx <= tox;
106 #ifdef USE_LIBFFI
107 static inline ffi_type *
108 get_ffi_type (jclass klass)
110 // A special case.
111 if (klass == NULL)
112 return &ffi_type_pointer;
114 ffi_type *r;
115 if (klass == JvPrimClass (byte))
116 r = &ffi_type_sint8;
117 else if (klass == JvPrimClass (short))
118 r = &ffi_type_sint16;
119 else if (klass == JvPrimClass (int))
120 r = &ffi_type_sint32;
121 else if (klass == JvPrimClass (long))
122 r = &ffi_type_sint64;
123 else if (klass == JvPrimClass (float))
124 r = &ffi_type_float;
125 else if (klass == JvPrimClass (double))
126 r = &ffi_type_double;
127 else if (klass == JvPrimClass (boolean))
129 // On some platforms a bool is a byte, on others an int.
130 if (sizeof (jboolean) == sizeof (jbyte))
131 r = &ffi_type_sint8;
132 else
134 JvAssert (sizeof (jboolean) == sizeof (jint));
135 r = &ffi_type_sint32;
138 else if (klass == JvPrimClass (char))
139 r = &ffi_type_uint16;
140 else
142 JvAssert (! klass->isPrimitive());
143 r = &ffi_type_pointer;
146 return r;
148 #endif // USE_LIBFFI
150 jobject
151 java::lang::reflect::Method::invoke (jobject obj, jobjectArray args)
153 using namespace java::lang::reflect;
154 jclass iface = NULL;
156 if (parameter_types == NULL)
157 getType ();
159 jmethodID meth = _Jv_FromReflectedMethod (this);
161 if (Modifier::isStatic(meth->accflags))
163 // We have to initialize a static class. It is safe to do this
164 // here and not in _Jv_CallAnyMethodA because JNI initializes a
165 // class whenever a method lookup is done.
166 _Jv_InitClass (declaringClass);
168 else
170 jclass objClass = JV_CLASS (obj);
171 if (! _Jv_IsAssignableFrom (objClass, declaringClass))
172 throw new java::lang::IllegalArgumentException;
175 // Check accessibility, if required.
176 if (! (Modifier::isPublic (meth->accflags) || this->isAccessible()))
178 Class *caller = _Jv_StackTrace::GetCallingClass (&Method::class$);
179 if (! _Jv_CheckAccess(caller, declaringClass, meth->accflags))
180 throw new IllegalAccessException;
183 if (declaringClass->isInterface())
184 iface = declaringClass;
186 return _Jv_CallAnyMethodA (obj, return_type, meth, false,
187 parameter_types, args, iface);
190 jint
191 java::lang::reflect::Method::getModifiersInternal ()
193 return _Jv_FromReflectedMethod (this)->accflags;
196 jstring
197 java::lang::reflect::Method::getSignature()
199 return declaringClass->getReflectionSignature (this);
202 jobject
203 java::lang::reflect::Method::getDefaultValue()
205 return declaringClass->getMethodDefaultValue(this);
208 anno_a_t
209 java::lang::reflect::Method::getDeclaredAnnotationsInternal()
211 anno_a_t result;
212 return (anno_a_t) declaringClass->getDeclaredAnnotations(this, false);
215 anno_aa_t
216 java::lang::reflect::Method::getParameterAnnotationsInternal()
218 anno_aa_t result;
219 return (anno_aa_t) declaringClass->getDeclaredAnnotations(this, true);
222 jstring
223 java::lang::reflect::Method::getName ()
225 if (name == NULL)
226 name = _Jv_NewStringUtf8Const (_Jv_FromReflectedMethod (this)->name);
227 return name;
230 /* Internal method to set return_type and parameter_types fields. */
232 void
233 java::lang::reflect::Method::getType ()
235 _Jv_Method *method = _Jv_FromReflectedMethod (this);
236 _Jv_GetTypesFromSignature (method,
237 declaringClass,
238 &parameter_types,
239 &return_type);
241 int count = 0;
242 if (method->throws != NULL)
244 while (method->throws[count] != NULL)
245 ++count;
248 exception_types
249 = (JArray<jclass> *) JvNewObjectArray (count, &java::lang::Class::class$,
250 NULL);
251 jclass *elts = elements (exception_types);
252 for (int i = 0; i < count; ++i)
253 elts[i] = _Jv_FindClass (method->throws[i],
254 declaringClass->getClassLoaderInternal ());
257 void
258 _Jv_GetTypesFromSignature (jmethodID method,
259 jclass declaringClass,
260 JArray<jclass> **arg_types_out,
261 jclass *return_type_out)
264 _Jv_Utf8Const* sig = method->signature;
265 java::lang::ClassLoader *loader = declaringClass->getClassLoaderInternal();
266 char *ptr = sig->chars();
267 int numArgs = 0;
268 /* First just count the number of parameters. */
269 // FIXME: should do some validation here, e.g., that there is only
270 // one return type.
271 for (; ; ptr++)
273 switch (*ptr)
275 case 0:
276 case ')':
277 case 'V':
278 break;
279 case '[':
280 case '(':
281 continue;
282 case 'B':
283 case 'C':
284 case 'D':
285 case 'F':
286 case 'S':
287 case 'I':
288 case 'J':
289 case 'Z':
290 numArgs++;
291 continue;
292 case 'L':
293 numArgs++;
295 ptr++;
296 while (*ptr != ';' && ptr[1] != '\0');
297 continue;
299 break;
302 JArray<jclass> *args = (JArray<jclass> *)
303 JvNewObjectArray (numArgs, &java::lang::Class::class$, NULL);
304 jclass* argPtr = elements (args);
305 for (ptr = sig->chars(); *ptr != '\0'; ptr++)
307 if (*ptr == '(')
308 continue;
309 if (*ptr == ')')
311 argPtr = return_type_out;
312 continue;
315 char *end_ptr;
316 jclass type = _Jv_FindClassFromSignature (ptr, loader, &end_ptr);
317 if (type == NULL)
318 // FIXME: This isn't ideal.
319 throw new java::lang::NoClassDefFoundError (sig->toString());
321 // ARGPTR can be NULL if we are processing the return value of a
322 // call from Constructor.
323 if (argPtr)
324 *argPtr++ = type;
326 ptr = end_ptr;
328 *arg_types_out = args;
331 // This is a very rough analog of the JNI CallNonvirtual<type>MethodA
332 // functions. It handles both Methods and Constructors, and it can
333 // handle any return type. In the Constructor case, the `obj'
334 // argument is unused and should be NULL; also, the `return_type' is
335 // the class that the constructor will construct. RESULT is a pointer
336 // to a `jvalue' (see jni.h); for a void method this should be NULL.
337 // This function returns an exception (if one was thrown), or NULL if
338 // the call went ok.
339 void
340 _Jv_CallAnyMethodA (jobject obj,
341 jclass return_type,
342 jmethodID meth,
343 jboolean is_constructor,
344 jboolean is_virtual_call,
345 JArray<jclass> *parameter_types,
346 jvalue *args,
347 jvalue *result,
348 jboolean is_jni_call,
349 jclass iface)
351 using namespace java::lang::reflect;
353 #ifdef USE_LIBFFI
354 JvAssert (! is_constructor || ! obj);
355 JvAssert (! is_constructor || return_type);
357 // See whether call needs an object as the first argument. A
358 // constructor does need a `this' argument, but it is one we create.
359 jboolean needs_this = false;
360 if (is_constructor
361 || ! Modifier::isStatic(meth->accflags))
362 needs_this = true;
364 int param_count = parameter_types->length;
365 if (needs_this)
366 ++param_count;
368 ffi_type *rtype;
369 // A constructor itself always returns void.
370 if (is_constructor || return_type == JvPrimClass (void))
371 rtype = &ffi_type_void;
372 else
373 rtype = get_ffi_type (return_type);
374 ffi_type **argtypes = (ffi_type **) __builtin_alloca (param_count
375 * sizeof (ffi_type *));
377 jclass *paramelts = elements (parameter_types);
379 // Special case for the `this' argument of a constructor. Note that
380 // the JDK 1.2 docs specify that the new object must be allocated
381 // before argument conversions are done.
382 if (is_constructor)
383 obj = _Jv_AllocObject (return_type);
385 const int size_per_arg = sizeof(jvalue);
386 ffi_cif cif;
388 char *p = (char *) __builtin_alloca (param_count * size_per_arg);
389 // Overallocate to get correct alignment.
390 void **values = (void **)
391 __builtin_alloca (param_count * sizeof (void *));
393 int i = 0;
394 if (needs_this)
396 // The `NULL' type is `Object'.
397 argtypes[i] = get_ffi_type (NULL);
398 values[i] = p;
399 memcpy (p, &obj, sizeof (jobject));
400 p += size_per_arg;
401 ++i;
404 for (int arg = 0; i < param_count; ++i, ++arg)
406 int tsize;
408 argtypes[i] = get_ffi_type (paramelts[arg]);
409 if (paramelts[arg]->isPrimitive())
410 tsize = paramelts[arg]->size();
411 else
412 tsize = sizeof (jobject);
414 // Copy appropriate bits from the jvalue into the ffi array.
415 // FIXME: we could do this copying all in one loop, above, by
416 // over-allocating a bit.
417 // How do we do this without breaking big-endian platforms?
418 values[i] = p;
419 memcpy (p, &args[arg], tsize);
420 p += size_per_arg;
423 if (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, param_count,
424 rtype, argtypes) != FFI_OK)
425 throw new java::lang::VirtualMachineError(JvNewStringLatin1("internal error: ffi_prep_cif failed"));
427 using namespace java::lang;
428 using namespace java::lang::reflect;
430 union
432 ffi_arg i;
433 jobject o;
434 jlong l;
435 jfloat f;
436 jdouble d;
437 } ffi_result;
439 switch (rtype->type)
441 case FFI_TYPE_VOID:
442 break;
443 case FFI_TYPE_SINT8:
444 result->b = 0;
445 break;
446 case FFI_TYPE_SINT16:
447 result->s = 0;
448 break;
449 case FFI_TYPE_UINT16:
450 result->c = 0;
451 break;
452 case FFI_TYPE_SINT32:
453 result->i = 0;
454 break;
455 case FFI_TYPE_SINT64:
456 result->j = 0;
457 break;
458 case FFI_TYPE_FLOAT:
459 result->f = 0;
460 break;
461 case FFI_TYPE_DOUBLE:
462 result->d = 0;
463 break;
464 case FFI_TYPE_POINTER:
465 result->l = 0;
466 break;
467 default:
468 JvFail ("Unknown ffi_call return type");
469 break;
472 void *ncode;
474 // FIXME: If a vtable index is -1 at this point it is invalid, so we
475 // have to use the ncode.
477 // This can happen because methods in final classes don't have
478 // vtable entries, but _Jv_isVirtualMethod() doesn't know that. We
479 // could solve this problem by allocating a vtable index for methods
480 // in final classes.
481 if (is_virtual_call
482 && ! Modifier::isFinal (meth->accflags)
483 && (_Jv_ushort)-1 != meth->index)
485 _Jv_VTable *vtable = *(_Jv_VTable **) obj;
486 if (iface == NULL)
488 if (is_jni_call && Modifier::isAbstract (meth->accflags))
490 // With JNI we don't know if this is an interface call
491 // or a call to an abstract method. Look up the method
492 // by name, the slow way.
493 _Jv_Method *concrete_meth
494 = _Jv_LookupDeclaredMethod (vtable->clas,
495 meth->name,
496 meth->signature,
497 NULL);
498 if (concrete_meth == NULL
499 || concrete_meth->ncode == NULL
500 || Modifier::isAbstract(concrete_meth->accflags))
501 throw new java::lang::IncompatibleClassChangeError
502 (_Jv_GetMethodString (vtable->clas, meth));
503 ncode = concrete_meth->ncode;
505 else
506 ncode = vtable->get_method (meth->index);
508 else
509 ncode = _Jv_LookupInterfaceMethodIdx (vtable->clas, iface,
510 meth->index);
512 else
514 ncode = meth->ncode;
519 ffi_call (&cif, (void (*)()) ncode, &ffi_result, values);
521 catch (Throwable *ex)
523 // For JNI we just throw the real error. For reflection, we
524 // wrap the underlying method's exception in an
525 // InvocationTargetException.
526 if (! is_jni_call)
527 ex = new InvocationTargetException (ex);
528 throw ex;
531 // Since ffi_call returns integer values promoted to a word, use
532 // a narrowing conversion for jbyte, jchar, etc. results.
533 // Note that boolean is handled either by the FFI_TYPE_SINT8 or
534 // FFI_TYPE_SINT32 case.
535 if (is_constructor)
536 result->l = obj;
537 else
539 switch (rtype->type)
541 case FFI_TYPE_VOID:
542 break;
543 case FFI_TYPE_SINT8:
544 result->b = (jbyte)ffi_result.i;
545 break;
546 case FFI_TYPE_SINT16:
547 result->s = (jshort)ffi_result.i;
548 break;
549 case FFI_TYPE_UINT16:
550 result->c = (jchar)ffi_result.i;
551 break;
552 case FFI_TYPE_SINT32:
553 result->i = (jint)ffi_result.i;
554 break;
555 case FFI_TYPE_SINT64:
556 result->j = (jlong)ffi_result.l;
557 break;
558 case FFI_TYPE_FLOAT:
559 result->f = (jfloat)ffi_result.f;
560 break;
561 case FFI_TYPE_DOUBLE:
562 result->d = (jdouble)ffi_result.d;
563 break;
564 case FFI_TYPE_POINTER:
565 result->l = (jobject)ffi_result.o;
566 break;
567 default:
568 JvFail ("Unknown ffi_call return type");
569 break;
572 #else
573 throw new java::lang::UnsupportedOperationException(JvNewStringLatin1("reflection not available in this build"));
574 #endif // USE_LIBFFI
577 // This is another version of _Jv_CallAnyMethodA, but this one does
578 // more checking and is used by the reflection (and not JNI) code.
579 jobject
580 _Jv_CallAnyMethodA (jobject obj,
581 jclass return_type,
582 jmethodID meth,
583 jboolean is_constructor,
584 JArray<jclass> *parameter_types,
585 jobjectArray args,
586 jclass iface)
588 if (parameter_types->length == 0 && args == NULL)
590 // The JDK accepts this, so we do too.
592 else if (parameter_types->length != args->length)
593 throw new java::lang::IllegalArgumentException;
595 int param_count = parameter_types->length;
597 jclass *paramelts = elements (parameter_types);
598 jobject *argelts = args == NULL ? NULL : elements (args);
599 jvalue argvals[param_count];
601 #define COPY(Where, What, Type) \
602 do { \
603 Type val = (What); \
604 memcpy ((Where), &val, sizeof (Type)); \
605 } while (0)
607 for (int i = 0; i < param_count; ++i)
609 jclass k = argelts[i] ? argelts[i]->getClass() : NULL;
610 if (paramelts[i]->isPrimitive())
612 if (! argelts[i]
613 || ! k
614 || ! can_widen (k, paramelts[i]))
615 throw new java::lang::IllegalArgumentException;
617 if (paramelts[i] == JvPrimClass (boolean))
618 COPY (&argvals[i],
619 ((java::lang::Boolean *) argelts[i])->booleanValue(),
620 jboolean);
621 else if (paramelts[i] == JvPrimClass (char))
622 COPY (&argvals[i],
623 ((java::lang::Character *) argelts[i])->charValue(),
624 jchar);
625 else
627 java::lang::Number *num = (java::lang::Number *) argelts[i];
628 if (paramelts[i] == JvPrimClass (byte))
629 COPY (&argvals[i], num->byteValue(), jbyte);
630 else if (paramelts[i] == JvPrimClass (short))
631 COPY (&argvals[i], num->shortValue(), jshort);
632 else if (paramelts[i] == JvPrimClass (int))
633 COPY (&argvals[i], num->intValue(), jint);
634 else if (paramelts[i] == JvPrimClass (long))
635 COPY (&argvals[i], num->longValue(), jlong);
636 else if (paramelts[i] == JvPrimClass (float))
637 COPY (&argvals[i], num->floatValue(), jfloat);
638 else if (paramelts[i] == JvPrimClass (double))
639 COPY (&argvals[i], num->doubleValue(), jdouble);
642 else
644 if (argelts[i] && ! paramelts[i]->isAssignableFrom (k))
645 throw new java::lang::IllegalArgumentException;
646 COPY (&argvals[i], argelts[i], jobject);
650 jvalue ret_value;
651 _Jv_CallAnyMethodA (obj, return_type, meth, is_constructor,
652 _Jv_isVirtualMethod (meth),
653 parameter_types, argvals, &ret_value,
654 false, iface);
656 jobject r;
657 #define VAL(Wrapper, Field) (new Wrapper (ret_value.Field))
658 if (is_constructor)
659 r = ret_value.l;
660 else if (return_type == JvPrimClass (byte))
661 r = VAL (java::lang::Byte, b);
662 else if (return_type == JvPrimClass (short))
663 r = VAL (java::lang::Short, s);
664 else if (return_type == JvPrimClass (int))
665 r = VAL (java::lang::Integer, i);
666 else if (return_type == JvPrimClass (long))
667 r = VAL (java::lang::Long, j);
668 else if (return_type == JvPrimClass (float))
669 r = VAL (java::lang::Float, f);
670 else if (return_type == JvPrimClass (double))
671 r = VAL (java::lang::Double, d);
672 else if (return_type == JvPrimClass (boolean))
673 r = VAL (java::lang::Boolean, z);
674 else if (return_type == JvPrimClass (char))
675 r = VAL (java::lang::Character, c);
676 else if (return_type == JvPrimClass (void))
677 r = NULL;
678 else
680 JvAssert (return_type == NULL || ! return_type->isPrimitive());
681 r = ret_value.l;
684 return r;