OSDN Git Service

gcc/java:
[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, 2004, 2005, 2006 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 #include <java-stack.h>
17
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>
22
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>
42
43 #include <stdlib.h>
44
45 #if USE_LIBFFI
46 #include <ffi.h>
47 #else
48 #include <java/lang/UnsupportedOperationException.h>
49 #endif
50
51 struct cpair
52 {
53   jclass prim;
54   jclass wrap;
55 };
56
57 // This is used to determine when a primitive widening conversion is
58 // allowed.
59 static cpair primitives[] =
60 {
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 }
73 };
74
75 static inline jboolean
76 can_widen (jclass from, jclass to)
77 {
78   int fromx = -1, tox = -1;
79
80   for (int i = 0; primitives[i].prim; ++i)
81     {
82       if (primitives[i].wrap == from)
83         fromx = i;
84       if (primitives[i].prim == to)
85         tox = i;
86     }
87
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;
97
98   return fromx <= tox;
99 }
100
101 #ifdef USE_LIBFFI
102 static inline ffi_type *
103 get_ffi_type (jclass klass)
104 {
105   // A special case.
106   if (klass == NULL)
107     return &ffi_type_pointer;
108
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))
123     {
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
128         {
129           JvAssert (sizeof (jboolean) == sizeof (jint));
130           r = &ffi_type_sint32;
131         }
132     }
133   else if (klass == JvPrimClass (char))
134     r = &ffi_type_uint16;
135   else
136     {
137       JvAssert (! klass->isPrimitive());
138       r = &ffi_type_pointer;
139     }
140
141   return r;
142 }
143 #endif // USE_LIBFFI
144
145 jobject
146 java::lang::reflect::Method::invoke (jobject obj, jobjectArray args)
147 {
148   using namespace java::lang::reflect;
149   jclass iface = NULL;
150   
151   if (parameter_types == NULL)
152     getType ();
153     
154   jmethodID meth = _Jv_FromReflectedMethod (this);
155
156   if (Modifier::isStatic(meth->accflags))
157     {
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);
162     }
163   else
164     {
165       jclass objClass = JV_CLASS (obj);
166       if (! _Jv_IsAssignableFrom (objClass, declaringClass))
167         throw new java::lang::IllegalArgumentException;
168     }
169
170   // Check accessibility, if required.
171   if (! (Modifier::isPublic (meth->accflags) || this->isAccessible()))
172     {
173       Class *caller = _Jv_StackTrace::GetCallingClass (&Method::class$);
174       if (! _Jv_CheckAccess(caller, declaringClass, meth->accflags))
175         throw new IllegalAccessException;
176     }
177
178   if (declaringClass->isInterface())
179     iface = declaringClass;
180   
181   return _Jv_CallAnyMethodA (obj, return_type, meth, false,
182                              parameter_types, args, iface);
183 }
184
185 jint
186 java::lang::reflect::Method::getModifiersInternal ()
187 {
188   return _Jv_FromReflectedMethod (this)->accflags;
189 }
190
191 jstring
192 java::lang::reflect::Method::getName ()
193 {
194   if (name == NULL)
195     name = _Jv_NewStringUtf8Const (_Jv_FromReflectedMethod (this)->name);
196   return name;
197 }
198
199 /* Internal method to set return_type and parameter_types fields. */
200
201 void
202 java::lang::reflect::Method::getType ()
203 {
204   _Jv_Method *method = _Jv_FromReflectedMethod (this);
205   _Jv_GetTypesFromSignature (method,
206                              declaringClass,
207                              &parameter_types,
208                              &return_type);
209
210   int count = 0;
211   if (method->throws != NULL)
212     {
213       while (method->throws[count] != NULL)
214         ++count;
215     }
216
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 ());
224 }
225
226 void
227 _Jv_GetTypesFromSignature (jmethodID method,
228                            jclass declaringClass,
229                            JArray<jclass> **arg_types_out,
230                            jclass *return_type_out)
231 {
232
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++)
241     {
242       switch (*ptr)
243         {
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++;
263           do 
264             ptr++;
265           while (*ptr != ';' && ptr[1] != '\0');
266           continue;
267         }
268       break;
269     }
270
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++)
275     {
276       if (*ptr == '(')
277         continue;
278       if (*ptr == ')')
279         {
280           argPtr = return_type_out;
281           continue;
282         }
283
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());
289
290       // ARGPTR can be NULL if we are processing the return value of a
291       // call from Constructor.
292       if (argPtr)
293         *argPtr++ = type;
294
295       ptr = end_ptr;
296     }
297   *arg_types_out = args;
298 }
299
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)
319 {
320   using namespace java::lang::reflect;
321   
322 #ifdef USE_LIBFFI
323   JvAssert (! is_constructor || ! obj);
324   JvAssert (! is_constructor || return_type);
325
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;
332
333   int param_count = parameter_types->length;
334   if (needs_this)
335     ++param_count;
336
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 *));
345
346   jclass *paramelts = elements (parameter_types);
347
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);
353
354   const int size_per_arg = sizeof(jvalue);
355   ffi_cif cif;
356
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 *));
361
362   int i = 0;
363   if (needs_this)
364     {
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;
371     }
372
373   for (int arg = 0; i < param_count; ++i, ++arg)
374     {
375       int tsize;
376
377       argtypes[i] = get_ffi_type (paramelts[arg]);
378       if (paramelts[arg]->isPrimitive())
379         tsize = paramelts[arg]->size();
380       else
381         tsize = sizeof (jobject);
382
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;
390     }
391
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"));
395
396   using namespace java::lang;
397   using namespace java::lang::reflect;
398
399   union
400   {
401     ffi_arg i;
402     jobject o;
403     jlong l;
404     jfloat f;
405     jdouble d;
406   } ffi_result;
407
408   switch (rtype->type)
409     {
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;
439     }
440
441   void *ncode;
442
443   // FIXME: If a vtable index is -1 at this point it is invalid, so we
444   // have to use the ncode.  
445   //
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)
453     {
454       _Jv_VTable *vtable = *(_Jv_VTable **) obj;
455       if (iface == NULL)
456         {
457           if (is_jni_call && Modifier::isAbstract (meth->accflags))
458             {
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;
473             }
474           else
475             ncode = vtable->get_method (meth->index);
476         }
477       else
478         ncode = _Jv_LookupInterfaceMethodIdx (vtable->clas, iface,
479                                               meth->index);
480     }
481   else
482     {
483       ncode = meth->ncode;
484     }
485
486   try
487     {
488       ffi_call (&cif, (void (*)()) ncode, &ffi_result, values);
489     }
490   catch (Throwable *ex)
491     {
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;
498     }
499
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
507     {
508       switch (rtype->type)
509         {
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;
539         }
540     }
541 #else
542   throw new java::lang::UnsupportedOperationException(JvNewStringLatin1("reflection not available in this build"));
543 #endif // USE_LIBFFI
544 }
545
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)
556 {
557   if (parameter_types->length == 0 && args == NULL)
558     {
559       // The JDK accepts this, so we do too.
560     }
561   else if (parameter_types->length != args->length)
562     throw new java::lang::IllegalArgumentException;
563
564   int param_count = parameter_types->length;
565
566   jclass *paramelts = elements (parameter_types);
567   jobject *argelts = args == NULL ? NULL : elements (args);
568   jvalue argvals[param_count];
569
570 #define COPY(Where, What, Type) \
571   do { \
572     Type val = (What); \
573     memcpy ((Where), &val, sizeof (Type)); \
574   } while (0)
575
576   for (int i = 0; i < param_count; ++i)
577     {
578       jclass k = argelts[i] ? argelts[i]->getClass() : NULL;
579       if (paramelts[i]->isPrimitive())
580         {
581           if (! argelts[i]
582               || ! k
583               || ! can_widen (k, paramelts[i]))
584             throw new java::lang::IllegalArgumentException;
585             
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
595             {
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);
609             }
610         }
611       else
612         {
613           if (argelts[i] && ! paramelts[i]->isAssignableFrom (k))
614             throw new java::lang::IllegalArgumentException;
615           COPY (&argvals[i], argelts[i], jobject);
616         }
617     }
618
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);
624
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
648     {
649       JvAssert (return_type == NULL || ! return_type->isPrimitive());
650       r = ret_value.l;
651     }
652
653   return r;
654 }