OSDN Git Service

* java/lang/Class.h (_Jv_SetVTableEntries): Updated declaration.
[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 void 
367 _Jv_PrepareClass(jclass klass)
368 {
369   using namespace java::lang::reflect;
370
371  /*
372   * The job of this function is to: 1) assign storage to fields, and 2)
373   * build the vtable.  static fields are assigned real memory, instance
374   * fields are assigned offsets.
375   *
376   * NOTE: we have a contract with the garbage collector here.  Static
377   * reference fields must not be resolved, until after they have storage
378   * assigned which is the check used by the collector to see if it
379   * should indirect the static field reference and mark the object
380   * pointed to. 
381   *
382   * Most fields are resolved lazily (i.e. have their class-type
383   * assigned) when they are accessed the first time by calling as part
384   * of _Jv_ResolveField, which is allways called after _Jv_PrepareClass.
385   * Static fields with initializers are resolved as part of this
386   * function, as are fields with primitive types.
387   */
388
389   if (! _Jv_IsInterpretedClass (klass))
390     return;
391
392   if (klass->state >= JV_STATE_PREPARED)
393     return;
394
395   // Make sure super-class is linked.  This involves taking a lock on
396   // the super class, so we use the Java method resolveClass, which
397   // will unlock it properly, should an exception happen.  If there's
398   // no superclass, do nothing -- Object will already have been
399   // resolved.
400
401   if (klass->superclass)
402     java::lang::ClassLoader::resolveClass0 (klass->superclass);
403
404   _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
405
406   /************ PART ONE: OBJECT LAYOUT ***************/
407
408   int instance_size;
409   int static_size;
410
411   // Although java.lang.Object is never interpreted, an interface can
412   // have a null superclass.
413   if (clz->superclass)
414     instance_size = clz->superclass->size();
415   else
416     instance_size = java::lang::Object::class$.size();
417   static_size   = 0;
418
419   for (int i = 0; i < clz->field_count; i++)
420     {
421       int field_size;
422       int field_align;
423
424       _Jv_Field *field = &clz->fields[i];
425
426       if (! field->isRef ())
427         {
428           // it's safe to resolve the field here, since it's 
429           // a primitive class, which does not cause loading to happen.
430           _Jv_ResolveField (field, clz->loader);
431
432           field_size = field->type->size ();
433           field_align = get_alignment_from_class (field->type);
434         }
435       else 
436         {
437           field_size = sizeof (jobject);
438           field_align = __alignof__ (jobject);
439         }
440
441 #ifndef COMPACT_FIELDS
442       field->bsize = field_size;
443 #endif
444
445       if (field->flags & Modifier::STATIC)
446         {
447           /* this computes an offset into a region we'll allocate 
448              shortly, and then add this offset to the start address */
449
450           static_size        = ROUND (static_size, field_align);
451           field->u.boffset   = static_size;
452           static_size       += field_size;
453         }
454       else
455         {
456           instance_size      = ROUND (instance_size, field_align);
457           field->u.boffset   = instance_size;
458           instance_size     += field_size;
459         }
460     }
461
462   // set the instance size for the class
463   clz->size_in_bytes = instance_size;
464
465   // allocate static memory
466   if (static_size != 0)
467     {
468       char *static_data = (char*)_Jv_AllocBytes (static_size);
469
470       memset (static_data, 0, static_size);
471
472       for (int i = 0; i < clz->field_count; i++)
473         {
474           _Jv_Field *field = &clz->fields[i];
475
476           if ((field->flags & Modifier::STATIC) != 0)
477             {
478               field->u.addr  = static_data + field->u.boffset;
479                             
480               if (clz->field_initializers[i] != 0)
481                 {
482                   _Jv_ResolveField (field, clz->loader);
483                   _Jv_InitField (0, clz, i);
484                 }
485             }
486         }
487
488       // now we don't need the field_initializers anymore, so let the
489       // collector get rid of it!
490
491       clz->field_initializers = 0;
492     }
493
494   /************ PART TWO: VTABLE LAYOUT ***************/
495
496   /* preparation: build the vtable stubs (even interfaces can)
497      have code -- for static constructors. */
498   for (int i = 0; i < clz->method_count; i++)
499     {
500       _Jv_MethodBase *imeth = clz->interpreted_methods[i];
501
502       if ((clz->methods[i].accflags & Modifier::NATIVE) != 0)
503         {
504           // You might think we could use a virtual `ncode' method in
505           // the _Jv_MethodBase and unify the native and non-native
506           // cases.  Well, we can't, because we don't allocate these
507           // objects using `new', and thus they don't get a vtable.
508           _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
509           clz->methods[i].ncode = jnim->ncode ();
510         }
511       else if (imeth != 0)              // it could be abstract
512         {
513           _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
514           _Jv_VerifyMethod (im);
515           clz->methods[i].ncode = im->ncode ();
516         }
517     }
518
519   if (clz->accflags & Modifier::INTERFACE)
520     {
521       clz->state = JV_STATE_PREPARED;
522       clz->notifyAll ();
523       return;
524     }
525
526   clz->vtable_method_count = -1;
527   _Jv_MakeVTable (clz);
528
529   /* wooha! we're done. */
530   clz->state = JV_STATE_PREPARED;
531   clz->notifyAll ();
532 }
533
534 /** Do static initialization for fields with a constant initializer */
535 void
536 _Jv_InitField (jobject obj, jclass klass, int index)
537 {
538   using namespace java::lang::reflect;
539
540   if (obj != 0 && klass == 0)
541     klass = obj->getClass ();
542
543   if (!_Jv_IsInterpretedClass (klass))
544     return;
545
546   _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
547
548   _Jv_Field * field = (&clz->fields[0]) + index;
549
550   if (index > clz->field_count)
551     throw_internal_error ("field out of range");
552
553   int init = clz->field_initializers[index];
554   if (init == 0)
555     return;
556
557   _Jv_Constants *pool = &clz->constants;
558   int tag = pool->tags[init];
559
560   if (! field->isResolved ())
561     throw_internal_error ("initializing unresolved field");
562
563   if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
564     throw_internal_error ("initializing non-static field with no object");
565
566   void *addr = 0;
567
568   if ((field->flags & Modifier::STATIC) != 0)
569     addr = (void*) field->u.addr;
570   else
571     addr = (void*) (((char*)obj) + field->u.boffset);
572
573   switch (tag)
574     {
575     case JV_CONSTANT_String:
576       {
577         _Jv_MonitorEnter (clz);
578         jstring str;
579         str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
580         pool->data[init].string = str;
581         pool->tags[init] = JV_CONSTANT_ResolvedString;
582         _Jv_MonitorExit (clz);
583       }
584       /* fall through */
585
586     case JV_CONSTANT_ResolvedString:
587       if (! (field->type == &StringClass
588              || field->type == &java::lang::Class::class$))
589         throw_class_format_error ("string initialiser to non-string field");
590
591       *(jstring*)addr = pool->data[init].string;
592       break;
593
594     case JV_CONSTANT_Integer:
595       {
596         int value = pool->data[init].i;
597
598         if (field->type == JvPrimClass (boolean))
599           *(jboolean*)addr = (jboolean)value;
600         
601         else if (field->type == JvPrimClass (byte))
602           *(jbyte*)addr = (jbyte)value;
603         
604         else if (field->type == JvPrimClass (char))
605           *(jchar*)addr = (jchar)value;
606
607         else if (field->type == JvPrimClass (short))
608           *(jshort*)addr = (jshort)value;
609         
610         else if (field->type == JvPrimClass (int))
611           *(jint*)addr = (jint)value;
612
613         else
614           throw_class_format_error ("erroneous field initializer");
615       }  
616       break;
617
618     case JV_CONSTANT_Long:
619       if (field->type != JvPrimClass (long))
620         throw_class_format_error ("erroneous field initializer");
621
622       *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
623       break;
624
625     case JV_CONSTANT_Float:
626       if (field->type != JvPrimClass (float))
627         throw_class_format_error ("erroneous field initializer");
628
629       *(jfloat*)addr = pool->data[init].f;
630       break;
631
632     case JV_CONSTANT_Double:
633       if (field->type != JvPrimClass (double))
634         throw_class_format_error ("erroneous field initializer");
635
636       *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
637       break;
638
639     default:
640       throw_class_format_error ("erroneous field initializer");
641     }
642 }
643
644 static int
645 get_alignment_from_class (jclass klass)
646 {
647   if (klass == JvPrimClass (byte))
648     return  __alignof__ (jbyte);
649   else if (klass == JvPrimClass (short))
650     return  __alignof__ (jshort);
651   else if (klass == JvPrimClass (int)) 
652     return  __alignof__ (jint);
653   else if (klass == JvPrimClass (long))
654     return  __alignof__ (jlong);
655   else if (klass == JvPrimClass (boolean))
656     return  __alignof__ (jboolean);
657   else if (klass == JvPrimClass (char))
658     return  __alignof__ (jchar);
659   else if (klass == JvPrimClass (float))
660     return  __alignof__ (jfloat);
661   else if (klass == JvPrimClass (double))
662     return  __alignof__ (jdouble);
663   else
664     return __alignof__ (jobject);
665 }
666
667
668 inline static unsigned char*
669 skip_one_type (unsigned char* ptr)
670 {
671   int ch = *ptr++;
672
673   while (ch == '[')
674     { 
675       ch = *ptr++;
676     }
677   
678   if (ch == 'L')
679     {
680       do { ch = *ptr++; } while (ch != ';');
681     }
682
683   return ptr;
684 }
685
686 static ffi_type*
687 get_ffi_type_from_signature (unsigned char* ptr)
688 {
689   switch (*ptr) 
690     {
691     case 'L':
692     case '[':
693       return &ffi_type_pointer;
694       break;
695
696     case 'Z':
697       // On some platforms a bool is a byte, on others an int.
698       if (sizeof (jboolean) == sizeof (jbyte))
699         return &ffi_type_sint8;
700       else
701         {
702           JvAssert (sizeof (jbyte) == sizeof (jint));
703           return &ffi_type_sint32;
704         }
705       break;
706
707     case 'B':
708       return &ffi_type_sint8;
709       break;
710       
711     case 'C':
712       return &ffi_type_uint16;
713       break;
714           
715     case 'S': 
716       return &ffi_type_sint16;
717       break;
718           
719     case 'I':
720       return &ffi_type_sint32;
721       break;
722           
723     case 'J':
724       return &ffi_type_sint64;
725       break;
726           
727     case 'F':
728       return &ffi_type_float;
729       break;
730           
731     case 'D':
732       return &ffi_type_double;
733       break;
734
735     case 'V':
736       return &ffi_type_void;
737       break;
738     }
739
740   throw_internal_error ("unknown type in signature");
741 }
742
743 /* this function yields the number of actual arguments, that is, if the
744  * function is non-static, then one is added to the number of elements
745  * found in the signature */
746
747 int 
748 _Jv_count_arguments (_Jv_Utf8Const *signature,
749                      jboolean staticp)
750 {
751   unsigned char *ptr = (unsigned char*) signature->data;
752   int arg_count = staticp ? 0 : 1;
753
754   /* first, count number of arguments */
755
756   // skip '('
757   ptr++;
758
759   // count args
760   while (*ptr != ')')
761     {
762       ptr = skip_one_type (ptr);
763       arg_count += 1;
764     }
765
766   return arg_count;
767 }
768
769 /* This beast will build a cif, given the signature.  Memory for
770  * the cif itself and for the argument types must be allocated by the
771  * caller.
772  */
773
774 static int 
775 init_cif (_Jv_Utf8Const* signature,
776           int arg_count,
777           jboolean staticp,
778           ffi_cif *cif,
779           ffi_type **arg_types,
780           ffi_type **rtype_p)
781 {
782   unsigned char *ptr = (unsigned char*) signature->data;
783
784   int arg_index = 0;            // arg number
785   int item_count = 0;           // stack-item count
786
787   // setup receiver
788   if (!staticp)
789     {
790       arg_types[arg_index++] = &ffi_type_pointer;
791       item_count += 1;
792     }
793
794   // skip '('
795   ptr++;
796
797   // assign arg types
798   while (*ptr != ')')
799     {
800       arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
801
802       if (*ptr == 'J' || *ptr == 'D')
803         item_count += 2;
804       else
805         item_count += 1;
806
807       ptr = skip_one_type (ptr);
808     }
809
810   // skip ')'
811   ptr++;
812   ffi_type *rtype = get_ffi_type_from_signature (ptr);
813
814   ptr = skip_one_type (ptr);
815   if (ptr != (unsigned char*)signature->data + signature->length)
816     throw_internal_error ("did not find end of signature");
817
818   if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
819                     arg_count, rtype, arg_types) != FFI_OK)
820     throw_internal_error ("ffi_prep_cif failed");
821
822   if (rtype_p != NULL)
823     *rtype_p = rtype;
824
825   return item_count;
826 }
827
828 #if FFI_NATIVE_RAW_API
829 #   define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure
830 #   define FFI_RAW_SIZE ffi_raw_size
831 #else
832 #   define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure
833 #   define FFI_RAW_SIZE ffi_java_raw_size
834 #endif
835
836 /* we put this one here, and not in interpret.cc because it
837  * calls the utility routines _Jv_count_arguments 
838  * which are static to this module.  The following struct defines the
839  * layout we use for the stubs, it's only used in the ncode method. */
840
841 typedef struct {
842   ffi_raw_closure  closure;
843   ffi_cif   cif;
844   ffi_type *arg_types[0];
845 } ncode_closure;
846
847 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
848
849 void *
850 _Jv_InterpMethod::ncode ()
851 {
852   using namespace java::lang::reflect;
853
854   if (self->ncode != 0)
855     return self->ncode;
856
857   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
858   int arg_count = _Jv_count_arguments (self->signature, staticp);
859
860   ncode_closure *closure =
861     (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
862                                         + arg_count * sizeof (ffi_type*));
863
864   init_cif (self->signature,
865             arg_count,
866             staticp,
867             &closure->cif,
868             &closure->arg_types[0],
869             NULL);
870
871   ffi_closure_fun fun;
872
873   args_raw_size = FFI_RAW_SIZE (&closure->cif);
874
875   JvAssert ((self->accflags & Modifier::NATIVE) == 0);
876
877   if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
878     {
879       if (staticp)
880         fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
881       else
882         fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object; 
883     }
884   else
885     {
886       fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
887     }
888
889   FFI_PREP_RAW_CLOSURE (&closure->closure,
890                         &closure->cif, 
891                         fun,
892                         (void*)this);
893
894   self->ncode = (void*)closure;
895   return self->ncode;
896 }
897
898
899 void *
900 _Jv_JNIMethod::ncode ()
901 {
902   using namespace java::lang::reflect;
903
904   if (self->ncode != 0)
905     return self->ncode;
906
907   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
908   int arg_count = _Jv_count_arguments (self->signature, staticp);
909
910   ncode_closure *closure =
911     (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
912                                     + arg_count * sizeof (ffi_type*));
913
914   ffi_type *rtype;
915   init_cif (self->signature,
916             arg_count,
917             staticp,
918             &closure->cif,
919             &closure->arg_types[0],
920             &rtype);
921
922   ffi_closure_fun fun;
923
924   args_raw_size = FFI_RAW_SIZE (&closure->cif);
925
926   // Initialize the argument types and CIF that represent the actual
927   // underlying JNI function.
928   int extra_args = 1;
929   if ((self->accflags & Modifier::STATIC))
930     ++extra_args;
931   jni_arg_types = (ffi_type **) _Jv_Malloc ((extra_args + arg_count)
932                                             * sizeof (ffi_type *));
933   int offset = 0;
934   jni_arg_types[offset++] = &ffi_type_pointer;
935   if ((self->accflags & Modifier::STATIC))
936     jni_arg_types[offset++] = &ffi_type_pointer;
937   memcpy (&jni_arg_types[offset], &closure->arg_types[0],
938           arg_count * sizeof (ffi_type *));
939
940   if (ffi_prep_cif (&jni_cif, FFI_DEFAULT_ABI,
941                     extra_args + arg_count, rtype,
942                     jni_arg_types) != FFI_OK)
943     throw_internal_error ("ffi_prep_cif failed for JNI function");
944
945   JvAssert ((self->accflags & Modifier::NATIVE) != 0);
946
947   // FIXME: for now we assume that all native methods for
948   // interpreted code use JNI.
949   fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
950
951   FFI_PREP_RAW_CLOSURE (&closure->closure,
952                         &closure->cif, 
953                         fun,
954                         (void*) this);
955
956   self->ncode = (void *) closure;
957   return self->ncode;
958 }
959
960
961 /* A _Jv_ResolvedMethod is what is put in the constant pool for a
962  * MethodRef or InterfacemethodRef.  */
963 static _Jv_ResolvedMethod*
964 _Jv_BuildResolvedMethod (_Jv_Method* method,
965                          jclass      klass,
966                          jboolean staticp,
967                          jint vtable_index)
968 {
969   int arg_count = _Jv_count_arguments (method->signature, staticp);
970
971   _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
972     _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
973                     + arg_count*sizeof (ffi_type*));
974
975   result->stack_item_count
976     = init_cif (method->signature,
977                 arg_count,
978                 staticp,
979                 &result->cif,
980                 &result->arg_types[0],
981                 NULL);
982
983   result->vtable_index        = vtable_index;
984   result->method              = method;
985   result->klass               = klass;
986
987   return result;
988 }
989
990
991 static void
992 throw_class_format_error (jstring msg)
993 {
994   throw (msg
995          ? new java::lang::ClassFormatError (msg)
996          : new java::lang::ClassFormatError);
997 }
998
999 static void
1000 throw_class_format_error (char *msg)
1001 {
1002   throw_class_format_error (JvNewStringLatin1 (msg));
1003 }
1004
1005 static void
1006 throw_internal_error (char *msg)
1007 {
1008   throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1009 }
1010
1011
1012 #endif /* INTERPRETER */