OSDN Git Service

* resolve.cc (METHOD_NOT_THERE, METHOD_INACCESSIBLE): Remove.
[pf3gnuchains/gcc-fork.git] / libjava / resolve.cc
1 // resolve.cc - Code for linking and resolving classes and pool entries.
2
3 /* Copyright (C) 1999, 2000, 2001 , 2002 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 /* Author: Kresten Krab Thorup <krab@gnu.org>  */
12
13 #include <config.h>
14
15 #include <java-interp.h>
16
17 #include <jvm.h>
18 #include <gcj/cni.h>
19 #include <string.h>
20 #include <java-cpool.h>
21 #include <java/lang/Class.h>
22 #include <java/lang/String.h>
23 #include <java/lang/StringBuffer.h>
24 #include <java/lang/Thread.h>
25 #include <java/lang/InternalError.h>
26 #include <java/lang/VirtualMachineError.h>
27 #include <java/lang/NoSuchFieldError.h>
28 #include <java/lang/NoSuchMethodError.h>
29 #include <java/lang/ClassFormatError.h>
30 #include <java/lang/IllegalAccessError.h>
31 #include <java/lang/AbstractMethodError.h>
32 #include <java/lang/NoClassDefFoundError.h>
33 #include <java/lang/IncompatibleClassChangeError.h>
34 #include <java/lang/reflect/Modifier.h>
35
36 using namespace gcj;
37
38 void
39 _Jv_ResolveField (_Jv_Field *field, java::lang::ClassLoader *loader)
40 {
41   if (! field->isResolved ())
42     {
43       _Jv_Utf8Const *sig = (_Jv_Utf8Const*)field->type;
44       field->type = _Jv_FindClassFromSignature (sig->data, loader);
45       field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
46     }
47 }
48
49 #ifdef INTERPRETER
50
51 static void throw_internal_error (char *msg)
52         __attribute__ ((__noreturn__));
53 static void throw_class_format_error (jstring msg)
54         __attribute__ ((__noreturn__));
55 static void throw_class_format_error (char *msg)
56         __attribute__ ((__noreturn__));
57
58 static int get_alignment_from_class (jclass);
59
60 static _Jv_ResolvedMethod* 
61 _Jv_BuildResolvedMethod (_Jv_Method*,
62                          jclass,
63                          jboolean,
64                          jint);
65
66
67 static void throw_incompatible_class_change_error (jstring msg)
68 {
69   throw new java::lang::IncompatibleClassChangeError (msg);
70 }
71
72 _Jv_word
73 _Jv_ResolvePoolEntry (jclass klass, int index)
74 {
75   using namespace java::lang::reflect;
76
77   _Jv_Constants *pool = &klass->constants;
78
79   if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
80     return pool->data[index];
81
82   switch (pool->tags[index]) {
83   case JV_CONSTANT_Class:
84     {
85       _Jv_Utf8Const *name = pool->data[index].utf8;
86
87       jclass found;
88       if (name->data[0] == '[')
89         found = _Jv_FindClassFromSignature (&name->data[0],
90                                             klass->loader);
91       else
92         found = _Jv_FindClass (name, klass->loader);
93
94       if (! found)
95         {
96           jstring str = _Jv_NewStringUTF (name->data);
97           // This exception is specified in JLS 2nd Ed, section 5.1.
98           throw new java::lang::NoClassDefFoundError (str);
99         }
100
101       if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
102           || (_Jv_ClassNameSamePackage (found->name,
103                                         klass->name)))
104         {
105           pool->data[index].clazz = found;
106           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
107         }
108       else
109         {
110           throw new java::lang::IllegalAccessError (found->getName());
111         }
112     }
113     break;
114
115   case JV_CONSTANT_String:
116     {
117       jstring str;
118       str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
119       pool->data[index].o = str;
120       pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
121     }
122     break;
123
124
125   case JV_CONSTANT_Fieldref:
126     {
127       _Jv_ushort class_index, name_and_type_index;
128       _Jv_loadIndexes (&pool->data[index],
129                        class_index,
130                        name_and_type_index);
131       jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
132
133       if (owner != klass)
134         _Jv_InitClass (owner);
135
136       _Jv_ushort name_index, type_index;
137       _Jv_loadIndexes (&pool->data[name_and_type_index],
138                        name_index,
139                        type_index);
140
141       _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
142       _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
143
144       // FIXME: The implementation of this function
145       // (_Jv_FindClassFromSignature) will generate an instance of
146       // _Jv_Utf8Const for each call if the field type is a class name
147       // (Lxx.yy.Z;).  This may be too expensive to do for each and
148       // every fieldref being resolved.  For now, we fix the problem by
149       // only doing it when we have a loader different from the class
150       // declaring the field.
151
152       jclass field_type = 0;
153
154       if (owner->loader != klass->loader)
155         field_type = _Jv_FindClassFromSignature (field_type_name->data,
156                                                  klass->loader);
157       
158       _Jv_Field* the_field = 0;
159
160       for (jclass cls = owner; cls != 0; cls = cls->getSuperclass ())
161         {
162           for (int i = 0;  i < cls->field_count;  i++)
163             {
164               _Jv_Field *field = &cls->fields[i];
165               if (! _Jv_equalUtf8Consts (field->name, field_name))
166                 continue;
167
168               // now, check field access. 
169
170               if (   (cls == klass)
171                   || ((field->flags & Modifier::PUBLIC) != 0)
172                   || (((field->flags & Modifier::PROTECTED) != 0)
173                       && cls->isAssignableFrom (klass))
174                   || (((field->flags & Modifier::PRIVATE) == 0)
175                       && _Jv_ClassNameSamePackage (cls->name,
176                                                    klass->name)))
177                 {
178                   /* resove the field using the class' own loader
179                      if necessary */
180
181                   if (!field->isResolved ())
182                     _Jv_ResolveField (field, cls->loader);
183
184                   if (field_type != 0 && field->type != field_type)
185                     throw new java::lang::LinkageError
186                       (JvNewStringLatin1 
187                        ("field type mismatch with different loaders"));
188
189                   the_field = field;
190                   goto end_of_field_search;
191                 }
192               else
193                 {
194                   throw new java::lang::IllegalAccessError;
195                 }
196             }
197         }
198
199     end_of_field_search:
200       if (the_field == 0)
201         {
202           java::lang::StringBuffer *sb = new java::lang::StringBuffer();
203           sb->append(JvNewStringLatin1("field "));
204           sb->append(owner->getName());
205           sb->append(JvNewStringLatin1("."));
206           sb->append(_Jv_NewStringUTF(field_name->data));
207           sb->append(JvNewStringLatin1(" was not found."));
208           throw_incompatible_class_change_error(sb->toString());
209         }
210
211       pool->data[index].field = the_field;
212       pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
213     }
214     break;
215
216   case JV_CONSTANT_Methodref:
217   case JV_CONSTANT_InterfaceMethodref:
218     {
219       _Jv_ushort class_index, name_and_type_index;
220       _Jv_loadIndexes (&pool->data[index],
221                        class_index,
222                        name_and_type_index);
223       jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
224
225       if (owner != klass)
226         _Jv_InitClass (owner);
227
228       _Jv_ushort name_index, type_index;
229       _Jv_loadIndexes (&pool->data[name_and_type_index],
230                        name_index,
231                        type_index);
232
233       _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
234       _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
235
236       _Jv_Method *the_method = 0;
237       jclass found_class = 0;
238
239       // First search the class itself.
240       the_method = _Jv_SearchMethodInClass (owner, klass, 
241                    method_name, method_signature);
242
243       if (the_method != 0)
244         {
245           found_class = owner;
246           goto end_of_method_search;
247         }
248
249       // If we are resolving an interface method, search the interface's 
250       // superinterfaces (A superinterface is not an interface's superclass - 
251       // a superinterface is implemented by the interface).
252       if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
253         {
254           _Jv_ifaces ifaces;
255           ifaces.count = 0;
256           ifaces.len = 4;
257           ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
258
259           _Jv_GetInterfaces (owner, &ifaces);     
260           
261           for (int i=0; i < ifaces.count; i++)
262             {
263               jclass cls = ifaces.list[i];
264               the_method = _Jv_SearchMethodInClass (cls, klass, method_name, 
265                                                     method_signature);
266               if (the_method != 0)
267                 {
268                   found_class = cls;
269                   break;
270                 }
271             }
272           
273           _Jv_Free (ifaces.list);
274           
275           if (the_method != 0)
276             goto end_of_method_search;
277         }
278
279       // Finally, search superclasses. 
280       for (jclass cls = owner->getSuperclass (); cls != 0; 
281            cls = cls->getSuperclass ())
282         {
283           the_method = _Jv_SearchMethodInClass (cls, klass, 
284                        method_name, method_signature);
285           if (the_method != 0)
286             {
287               found_class = cls;
288               break;
289             }
290         }
291
292     end_of_method_search:
293     
294       // FIXME: if (cls->loader != klass->loader), then we
295       // must actually check that the types of arguments
296       // correspond.  That is, for each argument type, and
297       // the return type, doing _Jv_FindClassFromSignature
298       // with either loader should produce the same result,
299       // i.e., exactly the same jclass object. JVMS 5.4.3.3    
300     
301       if (the_method == 0)
302         {
303           java::lang::StringBuffer *sb = new java::lang::StringBuffer();
304           sb->append(JvNewStringLatin1("method "));
305           sb->append(owner->getName());
306           sb->append(JvNewStringLatin1("."));
307           sb->append(_Jv_NewStringUTF(method_name->data));
308           sb->append(JvNewStringLatin1(" was not found."));
309           throw new java::lang::NoSuchMethodError (sb->toString());
310         }
311       
312       int vtable_index = -1;
313       if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
314         vtable_index = (jshort)the_method->index;
315
316       pool->data[index].rmethod = 
317         _Jv_BuildResolvedMethod(the_method,
318                                 found_class,
319                                 (the_method->accflags & Modifier::STATIC) != 0,
320                                 vtable_index);
321       pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
322     }
323     break;
324
325   }
326
327   return pool->data[index];
328 }
329
330 // Find a method declared in the cls that is referenced from klass and
331 // perform access checks.
332 _Jv_Method *
333 _Jv_SearchMethodInClass (jclass cls, jclass klass, 
334                          _Jv_Utf8Const *method_name, 
335                          _Jv_Utf8Const *method_signature)
336 {
337   using namespace java::lang::reflect;
338
339   for (int i = 0;  i < cls->method_count;  i++)
340     {
341       _Jv_Method *method = &cls->methods[i];
342       if (   (!_Jv_equalUtf8Consts (method->name,
343                                     method_name))
344           || (!_Jv_equalUtf8Consts (method->signature,
345                                     method_signature)))
346         continue;
347
348       if (cls == klass 
349           || ((method->accflags & Modifier::PUBLIC) != 0)
350           || (((method->accflags & Modifier::PROTECTED) != 0)
351               && cls->isAssignableFrom (klass))
352           || (((method->accflags & Modifier::PRIVATE) == 0)
353               && _Jv_ClassNameSamePackage (cls->name,
354                                            klass->name)))
355         {
356           return method;
357         }
358       else
359         {
360           throw new java::lang::IllegalAccessError;
361         }
362     }
363   return 0;
364 }
365
366 /* this is installed in place of abstract methods */
367 static void
368 _Jv_abstractMethodError ()
369 {
370   throw new java::lang::AbstractMethodError;
371 }
372
373 void 
374 _Jv_PrepareClass(jclass klass)
375 {
376   using namespace java::lang::reflect;
377
378  /*
379   * The job of this function is to: 1) assign storage to fields, and 2)
380   * build the vtable.  static fields are assigned real memory, instance
381   * fields are assigned offsets.
382   *
383   * NOTE: we have a contract with the garbage collector here.  Static
384   * reference fields must not be resolved, until after they have storage
385   * assigned which is the check used by the collector to see if it
386   * should indirect the static field reference and mark the object
387   * pointed to. 
388   *
389   * Most fields are resolved lazily (i.e. have their class-type
390   * assigned) when they are accessed the first time by calling as part
391   * of _Jv_ResolveField, which is allways called after _Jv_PrepareClass.
392   * Static fields with initializers are resolved as part of this
393   * function, as are fields with primitive types.
394   */
395
396   if (! _Jv_IsInterpretedClass (klass))
397     return;
398
399   if (klass->state >= JV_STATE_PREPARED)
400     return;
401
402   // Make sure super-class is linked.  This involves taking a lock on
403   // the super class, so we use the Java method resolveClass, which
404   // will unlock it properly, should an exception happen.  If there's
405   // no superclass, do nothing -- Object will already have been
406   // resolved.
407
408   if (klass->superclass)
409     java::lang::ClassLoader::resolveClass0 (klass->superclass);
410
411   _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
412
413   /************ PART ONE: OBJECT LAYOUT ***************/
414
415   int instance_size;
416   int static_size;
417
418   // Although java.lang.Object is never interpreted, an interface can
419   // have a null superclass.
420   if (clz->superclass)
421     instance_size = clz->superclass->size();
422   else
423     instance_size = java::lang::Object::class$.size();
424   static_size   = 0;
425
426   for (int i = 0; i < clz->field_count; i++)
427     {
428       int field_size;
429       int field_align;
430
431       _Jv_Field *field = &clz->fields[i];
432
433       if (! field->isRef ())
434         {
435           // it's safe to resolve the field here, since it's 
436           // a primitive class, which does not cause loading to happen.
437           _Jv_ResolveField (field, clz->loader);
438
439           field_size = field->type->size ();
440           field_align = get_alignment_from_class (field->type);
441         }
442       else 
443         {
444           field_size = sizeof (jobject);
445           field_align = __alignof__ (jobject);
446         }
447
448 #ifndef COMPACT_FIELDS
449       field->bsize = field_size;
450 #endif
451
452       if (field->flags & Modifier::STATIC)
453         {
454           /* this computes an offset into a region we'll allocate 
455              shortly, and then add this offset to the start address */
456
457           static_size        = ROUND (static_size, field_align);
458           field->u.boffset   = static_size;
459           static_size       += field_size;
460         }
461       else
462         {
463           instance_size      = ROUND (instance_size, field_align);
464           field->u.boffset   = instance_size;
465           instance_size     += field_size;
466         }
467     }
468
469   // set the instance size for the class
470   clz->size_in_bytes = instance_size;
471
472   // allocate static memory
473   if (static_size != 0)
474     {
475       char *static_data = (char*)_Jv_AllocBytes (static_size);
476
477       memset (static_data, 0, static_size);
478
479       for (int i = 0; i < clz->field_count; i++)
480         {
481           _Jv_Field *field = &clz->fields[i];
482
483           if ((field->flags & Modifier::STATIC) != 0)
484             {
485               field->u.addr  = static_data + field->u.boffset;
486                             
487               if (clz->field_initializers[i] != 0)
488                 {
489                   _Jv_ResolveField (field, clz->loader);
490                   _Jv_InitField (0, clz, i);
491                 }
492             }
493         }
494
495       // now we don't need the field_initializers anymore, so let the
496       // collector get rid of it!
497
498       clz->field_initializers = 0;
499     }
500
501   /************ PART TWO: VTABLE LAYOUT ***************/
502
503   /* preparation: build the vtable stubs (even interfaces can)
504      have code -- for static constructors. */
505   for (int i = 0; i < clz->method_count; i++)
506     {
507       _Jv_MethodBase *imeth = clz->interpreted_methods[i];
508
509       if ((clz->methods[i].accflags & Modifier::NATIVE) != 0)
510         {
511           // You might think we could use a virtual `ncode' method in
512           // the _Jv_MethodBase and unify the native and non-native
513           // cases.  Well, we can't, because we don't allocate these
514           // objects using `new', and thus they don't get a vtable.
515           _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
516           clz->methods[i].ncode = jnim->ncode ();
517         }
518       else if (imeth != 0)              // it could be abstract
519         {
520           _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
521           _Jv_VerifyMethod (im);
522           clz->methods[i].ncode = im->ncode ();
523         }
524     }
525
526   if (clz->accflags & Modifier::INTERFACE)
527     {
528       clz->state = JV_STATE_PREPARED;
529       clz->notifyAll ();
530       return;
531     }
532
533   clz->vtable_method_count = -1;
534   _Jv_MakeVTable (clz);
535
536   /* wooha! we're done. */
537   clz->state = JV_STATE_PREPARED;
538   clz->notifyAll ();
539 }
540
541 /** Do static initialization for fields with a constant initializer */
542 void
543 _Jv_InitField (jobject obj, jclass klass, int index)
544 {
545   using namespace java::lang::reflect;
546
547   if (obj != 0 && klass == 0)
548     klass = obj->getClass ();
549
550   if (!_Jv_IsInterpretedClass (klass))
551     return;
552
553   _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
554
555   _Jv_Field * field = (&clz->fields[0]) + index;
556
557   if (index > clz->field_count)
558     throw_internal_error ("field out of range");
559
560   int init = clz->field_initializers[index];
561   if (init == 0)
562     return;
563
564   _Jv_Constants *pool = &clz->constants;
565   int tag = pool->tags[init];
566
567   if (! field->isResolved ())
568     throw_internal_error ("initializing unresolved field");
569
570   if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
571     throw_internal_error ("initializing non-static field with no object");
572
573   void *addr = 0;
574
575   if ((field->flags & Modifier::STATIC) != 0)
576     addr = (void*) field->u.addr;
577   else
578     addr = (void*) (((char*)obj) + field->u.boffset);
579
580   switch (tag)
581     {
582     case JV_CONSTANT_String:
583       {
584         _Jv_MonitorEnter (clz);
585         jstring str;
586         str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
587         pool->data[init].string = str;
588         pool->tags[init] = JV_CONSTANT_ResolvedString;
589         _Jv_MonitorExit (clz);
590       }
591       /* fall through */
592
593     case JV_CONSTANT_ResolvedString:
594       if (! (field->type == &StringClass
595              || field->type == &java::lang::Class::class$))
596         throw_class_format_error ("string initialiser to non-string field");
597
598       *(jstring*)addr = pool->data[init].string;
599       break;
600
601     case JV_CONSTANT_Integer:
602       {
603         int value = pool->data[init].i;
604
605         if (field->type == JvPrimClass (boolean))
606           *(jboolean*)addr = (jboolean)value;
607         
608         else if (field->type == JvPrimClass (byte))
609           *(jbyte*)addr = (jbyte)value;
610         
611         else if (field->type == JvPrimClass (char))
612           *(jchar*)addr = (jchar)value;
613
614         else if (field->type == JvPrimClass (short))
615           *(jshort*)addr = (jshort)value;
616         
617         else if (field->type == JvPrimClass (int))
618           *(jint*)addr = (jint)value;
619
620         else
621           throw_class_format_error ("erroneous field initializer");
622       }  
623       break;
624
625     case JV_CONSTANT_Long:
626       if (field->type != JvPrimClass (long))
627         throw_class_format_error ("erroneous field initializer");
628
629       *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
630       break;
631
632     case JV_CONSTANT_Float:
633       if (field->type != JvPrimClass (float))
634         throw_class_format_error ("erroneous field initializer");
635
636       *(jfloat*)addr = pool->data[init].f;
637       break;
638
639     case JV_CONSTANT_Double:
640       if (field->type != JvPrimClass (double))
641         throw_class_format_error ("erroneous field initializer");
642
643       *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
644       break;
645
646     default:
647       throw_class_format_error ("erroneous field initializer");
648     }
649 }
650
651 static int
652 get_alignment_from_class (jclass klass)
653 {
654   if (klass == JvPrimClass (byte))
655     return  __alignof__ (jbyte);
656   else if (klass == JvPrimClass (short))
657     return  __alignof__ (jshort);
658   else if (klass == JvPrimClass (int)) 
659     return  __alignof__ (jint);
660   else if (klass == JvPrimClass (long))
661     return  __alignof__ (jlong);
662   else if (klass == JvPrimClass (boolean))
663     return  __alignof__ (jboolean);
664   else if (klass == JvPrimClass (char))
665     return  __alignof__ (jchar);
666   else if (klass == JvPrimClass (float))
667     return  __alignof__ (jfloat);
668   else if (klass == JvPrimClass (double))
669     return  __alignof__ (jdouble);
670   else
671     return __alignof__ (jobject);
672 }
673
674
675 inline static unsigned char*
676 skip_one_type (unsigned char* ptr)
677 {
678   int ch = *ptr++;
679
680   while (ch == '[')
681     { 
682       ch = *ptr++;
683     }
684   
685   if (ch == 'L')
686     {
687       do { ch = *ptr++; } while (ch != ';');
688     }
689
690   return ptr;
691 }
692
693 static ffi_type*
694 get_ffi_type_from_signature (unsigned char* ptr)
695 {
696   switch (*ptr) 
697     {
698     case 'L':
699     case '[':
700       return &ffi_type_pointer;
701       break;
702
703     case 'Z':
704       // On some platforms a bool is a byte, on others an int.
705       if (sizeof (jboolean) == sizeof (jbyte))
706         return &ffi_type_sint8;
707       else
708         {
709           JvAssert (sizeof (jbyte) == sizeof (jint));
710           return &ffi_type_sint32;
711         }
712       break;
713
714     case 'B':
715       return &ffi_type_sint8;
716       break;
717       
718     case 'C':
719       return &ffi_type_uint16;
720       break;
721           
722     case 'S': 
723       return &ffi_type_sint16;
724       break;
725           
726     case 'I':
727       return &ffi_type_sint32;
728       break;
729           
730     case 'J':
731       return &ffi_type_sint64;
732       break;
733           
734     case 'F':
735       return &ffi_type_float;
736       break;
737           
738     case 'D':
739       return &ffi_type_double;
740       break;
741
742     case 'V':
743       return &ffi_type_void;
744       break;
745     }
746
747   throw_internal_error ("unknown type in signature");
748 }
749
750 /* this function yields the number of actual arguments, that is, if the
751  * function is non-static, then one is added to the number of elements
752  * found in the signature */
753
754 int 
755 _Jv_count_arguments (_Jv_Utf8Const *signature,
756                      jboolean staticp)
757 {
758   unsigned char *ptr = (unsigned char*) signature->data;
759   int arg_count = staticp ? 0 : 1;
760
761   /* first, count number of arguments */
762
763   // skip '('
764   ptr++;
765
766   // count args
767   while (*ptr != ')')
768     {
769       ptr = skip_one_type (ptr);
770       arg_count += 1;
771     }
772
773   return arg_count;
774 }
775
776 /* This beast will build a cif, given the signature.  Memory for
777  * the cif itself and for the argument types must be allocated by the
778  * caller.
779  */
780
781 static int 
782 init_cif (_Jv_Utf8Const* signature,
783           int arg_count,
784           jboolean staticp,
785           ffi_cif *cif,
786           ffi_type **arg_types,
787           ffi_type **rtype_p)
788 {
789   unsigned char *ptr = (unsigned char*) signature->data;
790
791   int arg_index = 0;            // arg number
792   int item_count = 0;           // stack-item count
793
794   // setup receiver
795   if (!staticp)
796     {
797       arg_types[arg_index++] = &ffi_type_pointer;
798       item_count += 1;
799     }
800
801   // skip '('
802   ptr++;
803
804   // assign arg types
805   while (*ptr != ')')
806     {
807       arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
808
809       if (*ptr == 'J' || *ptr == 'D')
810         item_count += 2;
811       else
812         item_count += 1;
813
814       ptr = skip_one_type (ptr);
815     }
816
817   // skip ')'
818   ptr++;
819   ffi_type *rtype = get_ffi_type_from_signature (ptr);
820
821   ptr = skip_one_type (ptr);
822   if (ptr != (unsigned char*)signature->data + signature->length)
823     throw_internal_error ("did not find end of signature");
824
825   if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
826                     arg_count, rtype, arg_types) != FFI_OK)
827     throw_internal_error ("ffi_prep_cif failed");
828
829   if (rtype_p != NULL)
830     *rtype_p = rtype;
831
832   return item_count;
833 }
834
835 #if FFI_NATIVE_RAW_API
836 #   define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure
837 #   define FFI_RAW_SIZE ffi_raw_size
838 #else
839 #   define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure
840 #   define FFI_RAW_SIZE ffi_java_raw_size
841 #endif
842
843 /* we put this one here, and not in interpret.cc because it
844  * calls the utility routines _Jv_count_arguments 
845  * which are static to this module.  The following struct defines the
846  * layout we use for the stubs, it's only used in the ncode method. */
847
848 typedef struct {
849   ffi_raw_closure  closure;
850   ffi_cif   cif;
851   ffi_type *arg_types[0];
852 } ncode_closure;
853
854 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
855
856 void *
857 _Jv_InterpMethod::ncode ()
858 {
859   using namespace java::lang::reflect;
860
861   if (self->ncode != 0)
862     return self->ncode;
863
864   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
865   int arg_count = _Jv_count_arguments (self->signature, staticp);
866
867   ncode_closure *closure =
868     (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
869                                         + arg_count * sizeof (ffi_type*));
870
871   init_cif (self->signature,
872             arg_count,
873             staticp,
874             &closure->cif,
875             &closure->arg_types[0],
876             NULL);
877
878   ffi_closure_fun fun;
879
880   args_raw_size = FFI_RAW_SIZE (&closure->cif);
881
882   JvAssert ((self->accflags & Modifier::NATIVE) == 0);
883
884   if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
885     {
886       if (staticp)
887         fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
888       else
889         fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object; 
890     }
891   else
892     {
893       fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
894     }
895
896   FFI_PREP_RAW_CLOSURE (&closure->closure,
897                         &closure->cif, 
898                         fun,
899                         (void*)this);
900
901   self->ncode = (void*)closure;
902   return self->ncode;
903 }
904
905
906 void *
907 _Jv_JNIMethod::ncode ()
908 {
909   using namespace java::lang::reflect;
910
911   if (self->ncode != 0)
912     return self->ncode;
913
914   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
915   int arg_count = _Jv_count_arguments (self->signature, staticp);
916
917   ncode_closure *closure =
918     (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
919                                     + arg_count * sizeof (ffi_type*));
920
921   ffi_type *rtype;
922   init_cif (self->signature,
923             arg_count,
924             staticp,
925             &closure->cif,
926             &closure->arg_types[0],
927             &rtype);
928
929   ffi_closure_fun fun;
930
931   args_raw_size = FFI_RAW_SIZE (&closure->cif);
932
933   // Initialize the argument types and CIF that represent the actual
934   // underlying JNI function.
935   int extra_args = 1;
936   if ((self->accflags & Modifier::STATIC))
937     ++extra_args;
938   jni_arg_types = (ffi_type **) _Jv_Malloc ((extra_args + arg_count)
939                                             * sizeof (ffi_type *));
940   int offset = 0;
941   jni_arg_types[offset++] = &ffi_type_pointer;
942   if ((self->accflags & Modifier::STATIC))
943     jni_arg_types[offset++] = &ffi_type_pointer;
944   memcpy (&jni_arg_types[offset], &closure->arg_types[0],
945           arg_count * sizeof (ffi_type *));
946
947   if (ffi_prep_cif (&jni_cif, FFI_DEFAULT_ABI,
948                     extra_args + arg_count, rtype,
949                     jni_arg_types) != FFI_OK)
950     throw_internal_error ("ffi_prep_cif failed for JNI function");
951
952   JvAssert ((self->accflags & Modifier::NATIVE) != 0);
953
954   // FIXME: for now we assume that all native methods for
955   // interpreted code use JNI.
956   fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
957
958   FFI_PREP_RAW_CLOSURE (&closure->closure,
959                         &closure->cif, 
960                         fun,
961                         (void*) this);
962
963   self->ncode = (void *) closure;
964   return self->ncode;
965 }
966
967
968 /* A _Jv_ResolvedMethod is what is put in the constant pool for a
969  * MethodRef or InterfacemethodRef.  */
970 static _Jv_ResolvedMethod*
971 _Jv_BuildResolvedMethod (_Jv_Method* method,
972                          jclass      klass,
973                          jboolean staticp,
974                          jint vtable_index)
975 {
976   int arg_count = _Jv_count_arguments (method->signature, staticp);
977
978   _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
979     _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
980                     + arg_count*sizeof (ffi_type*));
981
982   result->stack_item_count
983     = init_cif (method->signature,
984                 arg_count,
985                 staticp,
986                 &result->cif,
987                 &result->arg_types[0],
988                 NULL);
989
990   result->vtable_index        = vtable_index;
991   result->method              = method;
992   result->klass               = klass;
993
994   return result;
995 }
996
997
998 static void
999 throw_class_format_error (jstring msg)
1000 {
1001   throw (msg
1002          ? new java::lang::ClassFormatError (msg)
1003          : new java::lang::ClassFormatError);
1004 }
1005
1006 static void
1007 throw_class_format_error (char *msg)
1008 {
1009   throw_class_format_error (JvNewStringLatin1 (msg));
1010 }
1011
1012 static void
1013 throw_internal_error (char *msg)
1014 {
1015   throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1016 }
1017
1018
1019 #endif /* INTERPRETER */