OSDN Git Service

* java/lang/reflect/natMethod.cc (_Jv_CallAnyMethodA): Don't use
[pf3gnuchains/gcc-fork.git] / libjava / java / lang / reflect / natMethod.cc
1 // natMethod.cc - Native code for Method class.
2
3 /* Copyright (C) 1998, 1999, 2000, 2001 , 2002, 2003 Free Software Foundation
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 #include <config.h>
12
13 #include <gcj/cni.h>
14 #include <jvm.h>
15 #include <jni.h>
16
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>
21
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/IllegalAccessException.h>
32 #include <java/lang/IllegalArgumentException.h>
33 #include <java/lang/NullPointerException.h>
34 #include <java/lang/ArrayIndexOutOfBoundsException.h>
35 #include <java/lang/VirtualMachineError.h>
36 #include <java/lang/Class.h>
37 #include <gcj/method.h>
38 #include <gnu/gcj/RawData.h>
39
40 #include <stdlib.h>
41
42 #if USE_LIBFFI
43 #include <ffi.h>
44 #else
45 #include <java/lang/UnsupportedOperationException.h>
46 #endif
47
48 struct cpair
49 {
50   jclass prim;
51   jclass wrap;
52 };
53
54 // This is used to determine when a primitive widening conversion is
55 // allowed.
56 static cpair primitives[] =
57 {
58 #define BOOLEAN 0
59   { JvPrimClass (boolean), &java::lang::Boolean::class$ },
60   { JvPrimClass (byte), &java::lang::Byte::class$ },
61 #define SHORT 2
62   { JvPrimClass (short), &java::lang::Short::class$ },
63 #define CHAR 3
64   { JvPrimClass (char), &java::lang::Character::class$ },
65   { JvPrimClass (int), &java::lang::Integer::class$ },
66   { JvPrimClass (long), &java::lang::Long::class$ },
67   { JvPrimClass (float), &java::lang::Float::class$ },
68   { JvPrimClass (double), &java::lang::Double::class$ },
69   { NULL, NULL }
70 };
71
72 static inline jboolean
73 can_widen (jclass from, jclass to)
74 {
75   int fromx = -1, tox = -1;
76
77   for (int i = 0; primitives[i].prim; ++i)
78     {
79       if (primitives[i].wrap == from)
80         fromx = i;
81       if (primitives[i].prim == to)
82         tox = i;
83     }
84
85   // Can't handle a miss.
86   if (fromx == -1 || tox == -1)
87     return false;
88   // Boolean arguments may not be widened.
89   if (fromx == BOOLEAN && tox != BOOLEAN)
90     return false;
91   // Nothing promotes to char.
92   if (tox == CHAR && fromx != CHAR)
93     return false;
94
95   return fromx <= tox;
96 }
97
98 #ifdef USE_LIBFFI
99 static inline ffi_type *
100 get_ffi_type (jclass klass)
101 {
102   // A special case.
103   if (klass == NULL)
104     return &ffi_type_pointer;
105
106   ffi_type *r;
107   if (klass == JvPrimClass (byte))
108     r = &ffi_type_sint8;
109   else if (klass == JvPrimClass (short))
110     r = &ffi_type_sint16;
111   else if (klass == JvPrimClass (int))
112     r = &ffi_type_sint32;
113   else if (klass == JvPrimClass (long))
114     r = &ffi_type_sint64;
115   else if (klass == JvPrimClass (float))
116     r = &ffi_type_float;
117   else if (klass == JvPrimClass (double))
118     r = &ffi_type_double;
119   else if (klass == JvPrimClass (boolean))
120     {
121       // On some platforms a bool is a byte, on others an int.
122       if (sizeof (jboolean) == sizeof (jbyte))
123         r = &ffi_type_sint8;
124       else
125         {
126           JvAssert (sizeof (jboolean) == sizeof (jint));
127           r = &ffi_type_sint32;
128         }
129     }
130   else if (klass == JvPrimClass (char))
131     r = &ffi_type_uint16;
132   else
133     {
134       JvAssert (! klass->isPrimitive());
135       r = &ffi_type_pointer;
136     }
137
138   return r;
139 }
140 #endif // USE_LIBFFI
141
142 jobject
143 java::lang::reflect::Method::invoke (jobject obj, jobjectArray args)
144 {
145   using namespace java::lang::reflect;
146   
147   if (parameter_types == NULL)
148     getType ();
149     
150   jmethodID meth = _Jv_FromReflectedMethod (this);
151
152   jclass objClass;
153   
154   if (Modifier::isStatic(meth->accflags))
155     {
156       // We have to initialize a static class.  It is safe to do this
157       // here and not in _Jv_CallAnyMethodA because JNI initializes a
158       // class whenever a method lookup is done.
159       _Jv_InitClass (declaringClass);
160       objClass = declaringClass;
161     }
162   else
163     {
164       objClass = JV_CLASS (obj);
165      
166       if (! _Jv_IsAssignableFrom (declaringClass, objClass))
167         throw new java::lang::IllegalArgumentException;
168     }
169
170   // Check accessibility, if required.
171   if (! (Modifier::isPublic (meth->accflags) || this->isAccessible()))
172     {
173       gnu::gcj::runtime::StackTrace *t 
174         = new gnu::gcj::runtime::StackTrace(4);
175       Class *caller = NULL;
176       try
177         {
178           for (int i = 1; !caller; i++)
179             {
180               caller = t->classAt (i);
181             }
182         }
183       catch (::java::lang::ArrayIndexOutOfBoundsException *e)
184         {
185         }
186
187       if (! _Jv_CheckAccess(caller, objClass, meth->accflags))
188         throw new IllegalAccessException;
189     }
190
191   return _Jv_CallAnyMethodA (obj, return_type, meth, false,
192                              parameter_types, args);
193 }
194
195 jint
196 java::lang::reflect::Method::getModifiers ()
197 {
198   // Ignore all unknown flags.
199   return _Jv_FromReflectedMethod (this)->accflags & Modifier::ALL_FLAGS;
200 }
201
202 jstring
203 java::lang::reflect::Method::getName ()
204 {
205   if (name == NULL)
206     name = _Jv_NewStringUtf8Const (_Jv_FromReflectedMethod (this)->name);
207   return name;
208 }
209
210 /* Internal method to set return_type and parameter_types fields. */
211
212 void
213 java::lang::reflect::Method::getType ()
214 {
215   _Jv_Method *method = _Jv_FromReflectedMethod (this);
216   _Jv_GetTypesFromSignature (method,
217                              declaringClass,
218                              &parameter_types,
219                              &return_type);
220
221   int count = 0;
222   if (method->throws != NULL)
223     {
224       while (method->throws[count] != NULL)
225         ++count;
226     }
227
228   exception_types
229     = (JArray<jclass> *) JvNewObjectArray (count, &java::lang::Class::class$,
230                                            NULL);
231   jclass *elts = elements (exception_types);
232   for (int i = 0; i < count; ++i)
233     elts[i] = _Jv_FindClass (method->throws[i],
234                              declaringClass->getClassLoaderInternal ());
235 }
236
237 void
238 _Jv_GetTypesFromSignature (jmethodID method,
239                            jclass declaringClass,
240                            JArray<jclass> **arg_types_out,
241                            jclass *return_type_out)
242 {
243
244   _Jv_Utf8Const* sig = method->signature;
245   java::lang::ClassLoader *loader = declaringClass->getClassLoaderInternal();
246   char *ptr = sig->data;
247   int numArgs = 0;
248   /* First just count the number of parameters. */
249   for (; ; ptr++)
250     {
251       switch (*ptr)
252         {
253         case 0:
254         case ')':
255         case 'V':
256           break;
257         case '[':
258         case '(':
259           continue;
260         case 'B':
261         case 'C':
262         case 'D':
263         case 'F':
264         case 'S':
265         case 'I':
266         case 'J':
267         case 'Z':
268           numArgs++;
269           continue;
270         case 'L':
271           numArgs++;
272           do 
273             ptr++;
274           while (*ptr != ';' && ptr[1] != '\0');
275           continue;
276         }
277       break;
278     }
279
280   JArray<jclass> *args = (JArray<jclass> *)
281     JvNewObjectArray (numArgs, &java::lang::Class::class$, NULL);
282   jclass* argPtr = elements (args);
283   for (ptr = sig->data; *ptr != '\0'; ptr++)
284     {
285       int num_arrays = 0;
286       jclass type;
287       for (; *ptr == '[';  ptr++)
288         num_arrays++;
289       switch (*ptr)
290         {
291         default:
292           return;
293         case ')':
294           argPtr = return_type_out;
295           continue;
296         case '(':
297           continue;
298         case 'V':
299         case 'B':
300         case 'C':
301         case 'D':
302         case 'F':
303         case 'S':
304         case 'I':
305         case 'J':
306         case 'Z':
307           type = _Jv_FindClassFromSignature(ptr, loader);
308           break;
309         case 'L':
310           type = _Jv_FindClassFromSignature(ptr, loader);
311           do 
312             ptr++;
313           while (*ptr != ';' && ptr[1] != '\0');
314           break;
315         }
316
317       while (--num_arrays >= 0)
318         type = _Jv_GetArrayClass (type, loader);
319       // ARGPTR can be NULL if we are processing the return value of a
320       // call from Constructor.
321       if (argPtr)
322         *argPtr++ = type;
323     }
324   *arg_types_out = args;
325 }
326
327 // This is a very rough analog of the JNI CallNonvirtual<type>MethodA
328 // functions.  It handles both Methods and Constructors, and it can
329 // handle any return type.  In the Constructor case, the `obj'
330 // argument is unused and should be NULL; also, the `return_type' is
331 // the class that the constructor will construct.  RESULT is a pointer
332 // to a `jvalue' (see jni.h); for a void method this should be NULL.
333 // This function returns an exception (if one was thrown), or NULL if
334 // the call went ok.
335 void
336 _Jv_CallAnyMethodA (jobject obj,
337                     jclass return_type,
338                     jmethodID meth,
339                     jboolean is_constructor,
340                     jboolean is_virtual_call,
341                     JArray<jclass> *parameter_types,
342                     jvalue *args,
343                     jvalue *result,
344                     jboolean is_jni_call)
345 {
346   using namespace java::lang::reflect;
347   
348 #ifdef USE_LIBFFI
349   JvAssert (! is_constructor || ! obj);
350   JvAssert (! is_constructor || return_type);
351
352   // See whether call needs an object as the first argument.  A
353   // constructor does need a `this' argument, but it is one we create.
354   jboolean needs_this = false;
355   if (is_constructor
356       || ! Modifier::isStatic(meth->accflags))
357     needs_this = true;
358
359   int param_count = parameter_types->length;
360   if (needs_this)
361     ++param_count;
362
363   ffi_type *rtype;
364   // A constructor itself always returns void.
365   if (is_constructor || return_type == JvPrimClass (void))
366     rtype = &ffi_type_void;
367   else
368     rtype = get_ffi_type (return_type);
369   ffi_type **argtypes = (ffi_type **) __builtin_alloca (param_count
370                                                         * sizeof (ffi_type *));
371
372   jclass *paramelts = elements (parameter_types);
373
374   // Special case for the `this' argument of a constructor.  Note that
375   // the JDK 1.2 docs specify that the new object must be allocated
376   // before argument conversions are done.
377   if (is_constructor)
378     obj = JvAllocObject (return_type);
379
380   const int size_per_arg = sizeof(jvalue);
381   ffi_cif cif;
382
383   char *p = (char *) __builtin_alloca (param_count * size_per_arg);
384                 // Overallocate to get correct alignment.
385   void **values = (void **)
386                         __builtin_alloca (param_count * sizeof (void *));
387
388   int i = 0;
389   if (needs_this)
390     {
391       // The `NULL' type is `Object'.
392       argtypes[i] = get_ffi_type (NULL);
393       values[i] = p;
394       memcpy (p, &obj, sizeof (jobject));
395       p += size_per_arg;
396       ++i;
397     }
398
399   for (int arg = 0; i < param_count; ++i, ++arg)
400     {
401       int tsize;
402
403       argtypes[i] = get_ffi_type (paramelts[arg]);
404       if (paramelts[arg]->isPrimitive())
405         tsize = paramelts[arg]->size();
406       else
407         tsize = sizeof (jobject);
408
409       // Copy appropriate bits from the jvalue into the ffi array.
410       // FIXME: we could do this copying all in one loop, above, by
411       // over-allocating a bit.
412       // How do we do this without breaking big-endian platforms?
413       values[i] = p;
414       memcpy (p, &args[arg], tsize);
415       p += size_per_arg;
416     }
417
418   if (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, param_count,
419                     rtype, argtypes) != FFI_OK)
420     throw new java::lang::VirtualMachineError(JvNewStringLatin1("internal error: ffi_prep_cif failed"));
421
422   using namespace java::lang;
423   using namespace java::lang::reflect;
424
425   union
426   {
427     ffi_arg i;
428     jobject o;
429     jlong l;
430     jfloat f;
431     jdouble d;
432   } ffi_result;
433
434   switch (rtype->type)
435     {
436     case FFI_TYPE_VOID:
437       break;
438     case FFI_TYPE_SINT8:
439       result->b = 0;
440       break;
441     case FFI_TYPE_SINT16:
442       result->s = 0;
443       break;
444     case FFI_TYPE_UINT16:
445       result->c = 0;
446       break;
447     case FFI_TYPE_SINT32:
448       result->i = 0;
449       break;
450     case FFI_TYPE_SINT64:
451       result->j = 0;
452       break;
453     case FFI_TYPE_FLOAT:
454       result->f = 0;
455       break;
456     case FFI_TYPE_DOUBLE:
457       result->d = 0;
458       break;
459     case FFI_TYPE_POINTER:
460       result->l = 0;
461       break;
462     default:
463       JvFail ("Unknown ffi_call return type");
464       break;
465     }
466
467   void *ncode;
468
469   if (is_virtual_call && ! Modifier::isFinal (meth->accflags))
470     {
471       _Jv_VTable *vtable = *(_Jv_VTable **) obj;
472       ncode = vtable->get_method (meth->index);
473     }
474   else
475     {
476       ncode = meth->ncode;
477     }
478
479   try
480     {
481       ffi_call (&cif, (void (*)()) ncode, &ffi_result, values);
482     }
483   catch (Throwable *ex)
484     {
485       // For JNI we just throw the real error.  For reflection, we
486       // wrap the underlying method's exception in an
487       // InvocationTargetException.
488       if (! is_jni_call)
489         ex = new InvocationTargetException (ex);
490       throw ex;
491     }
492
493   // Since ffi_call returns integer values promoted to a word, use
494   // a narrowing conversion for jbyte, jchar, etc. results.
495   // Note that boolean is handled either by the FFI_TYPE_SINT8 or
496   // FFI_TYPE_SINT32 case.
497   if (is_constructor)
498     result->l = obj;
499   else
500     {
501       switch (rtype->type)
502         {
503         case FFI_TYPE_VOID:
504           break;
505         case FFI_TYPE_SINT8:
506           result->b = (jbyte)ffi_result.i;
507           break;
508         case FFI_TYPE_SINT16:
509           result->s = (jshort)ffi_result.i;
510           break;
511         case FFI_TYPE_UINT16:
512           result->c = (jchar)ffi_result.i;
513           break;
514         case FFI_TYPE_SINT32:
515           result->i = (jint)ffi_result.i;
516           break;
517         case FFI_TYPE_SINT64:
518           result->j = (jlong)ffi_result.l;
519           break;
520         case FFI_TYPE_FLOAT:
521           result->f = (jfloat)ffi_result.f;
522           break;
523         case FFI_TYPE_DOUBLE:
524           result->d = (jdouble)ffi_result.d;
525           break;
526         case FFI_TYPE_POINTER:
527           result->l = (jobject)ffi_result.o;
528           break;
529         default:
530           JvFail ("Unknown ffi_call return type");
531           break;
532         }
533     }
534 #else
535   throw new java::lang::UnsupportedOperationException(JvNewStringLatin1("reflection not available in this build"));
536 #endif // USE_LIBFFI
537 }
538
539 // This is another version of _Jv_CallAnyMethodA, but this one does
540 // more checking and is used by the reflection (and not JNI) code.
541 jobject
542 _Jv_CallAnyMethodA (jobject obj,
543                     jclass return_type,
544                     jmethodID meth,
545                     jboolean is_constructor,
546                     JArray<jclass> *parameter_types,
547                     jobjectArray args)
548 {
549   if (parameter_types->length == 0 && args == NULL)
550     {
551       // The JDK accepts this, so we do too.
552     }
553   else if (parameter_types->length != args->length)
554     throw new java::lang::IllegalArgumentException;
555
556   int param_count = parameter_types->length;
557
558   jclass *paramelts = elements (parameter_types);
559   jobject *argelts = args == NULL ? NULL : elements (args);
560   jvalue argvals[param_count];
561
562 #define COPY(Where, What, Type) \
563   do { \
564     Type val = (What); \
565     memcpy ((Where), &val, sizeof (Type)); \
566   } while (0)
567
568   for (int i = 0; i < param_count; ++i)
569     {
570       jclass k = argelts[i] ? argelts[i]->getClass() : NULL;
571       if (paramelts[i]->isPrimitive())
572         {
573           if (! argelts[i]
574               || ! k
575               || ! can_widen (k, paramelts[i]))
576             throw new java::lang::IllegalArgumentException;
577             
578           if (paramelts[i] == JvPrimClass (boolean))
579             COPY (&argvals[i],
580                   ((java::lang::Boolean *) argelts[i])->booleanValue(),
581                   jboolean);
582           else if (paramelts[i] == JvPrimClass (char))
583             COPY (&argvals[i],
584                   ((java::lang::Character *) argelts[i])->charValue(),
585                   jchar);
586           else
587             {
588               java::lang::Number *num = (java::lang::Number *) argelts[i];
589               if (paramelts[i] == JvPrimClass (byte))
590                 COPY (&argvals[i], num->byteValue(), jbyte);
591               else if (paramelts[i] == JvPrimClass (short))
592                 COPY (&argvals[i], num->shortValue(), jshort);
593               else if (paramelts[i] == JvPrimClass (int))
594                 COPY (&argvals[i], num->intValue(), jint);
595               else if (paramelts[i] == JvPrimClass (long))
596                 COPY (&argvals[i], num->longValue(), jlong);
597               else if (paramelts[i] == JvPrimClass (float))
598                 COPY (&argvals[i], num->floatValue(), jfloat);
599               else if (paramelts[i] == JvPrimClass (double))
600                 COPY (&argvals[i], num->doubleValue(), jdouble);
601             }
602         }
603       else
604         {
605           if (argelts[i] && ! paramelts[i]->isAssignableFrom (k))
606             throw new java::lang::IllegalArgumentException;
607           COPY (&argvals[i], argelts[i], jobject);
608         }
609     }
610
611   jvalue ret_value;
612   _Jv_CallAnyMethodA (obj, return_type, meth, is_constructor,
613                       _Jv_isVirtualMethod (meth),
614                       parameter_types, argvals, &ret_value,
615                       false);
616
617   jobject r;
618 #define VAL(Wrapper, Field)  (new Wrapper (ret_value.Field))
619   if (is_constructor)
620     r = ret_value.l;
621   else  if (return_type == JvPrimClass (byte))
622     r = VAL (java::lang::Byte, b);
623   else if (return_type == JvPrimClass (short))
624     r = VAL (java::lang::Short, s);
625   else if (return_type == JvPrimClass (int))
626     r = VAL (java::lang::Integer, i);
627   else if (return_type == JvPrimClass (long))
628     r = VAL (java::lang::Long, j);
629   else if (return_type == JvPrimClass (float))
630     r = VAL (java::lang::Float, f);
631   else if (return_type == JvPrimClass (double))
632     r = VAL (java::lang::Double, d);
633   else if (return_type == JvPrimClass (boolean))
634     r = VAL (java::lang::Boolean, z);
635   else if (return_type == JvPrimClass (char))
636     r = VAL (java::lang::Character, c);
637   else if (return_type == JvPrimClass (void))
638     r = NULL;
639   else
640     {
641       JvAssert (return_type == NULL || ! return_type->isPrimitive());
642       r = ret_value.l;
643     }
644
645   return r;
646 }