OSDN Git Service

2002-09-25 Jesse Rosenstock <jmr@ugcs.caltech.edu>
[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 // Exceptional return values for _Jv_DetermineVTableIndex
59 #define METHOD_NOT_THERE (-2)
60 #define METHOD_INACCESSIBLE (-1)
61
62 static int get_alignment_from_class (jclass);
63
64 static _Jv_ResolvedMethod* 
65 _Jv_BuildResolvedMethod (_Jv_Method*,
66                          jclass,
67                          jboolean,
68                          jint);
69
70
71 static void throw_incompatible_class_change_error (jstring msg)
72 {
73   throw new java::lang::IncompatibleClassChangeError (msg);
74 }
75
76 _Jv_word
77 _Jv_ResolvePoolEntry (jclass klass, int index)
78 {
79   using namespace java::lang::reflect;
80
81   _Jv_Constants *pool = &klass->constants;
82
83   if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
84     return pool->data[index];
85
86   switch (pool->tags[index]) {
87   case JV_CONSTANT_Class:
88     {
89       _Jv_Utf8Const *name = pool->data[index].utf8;
90
91       jclass found;
92       if (name->data[0] == '[')
93         found = _Jv_FindClassFromSignature (&name->data[0],
94                                             klass->loader);
95       else
96         found = _Jv_FindClass (name, klass->loader);
97
98       if (! found)
99         {
100           jstring str = _Jv_NewStringUTF (name->data);
101           // This exception is specified in JLS 2nd Ed, section 5.1.
102           throw new java::lang::NoClassDefFoundError (str);
103         }
104
105       if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
106           || (_Jv_ClassNameSamePackage (found->name,
107                                         klass->name)))
108         {
109           pool->data[index].clazz = found;
110           pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
111         }
112       else
113         {
114           throw new java::lang::IllegalAccessError (found->getName());
115         }
116     }
117     break;
118
119   case JV_CONSTANT_String:
120     {
121       jstring str;
122       str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
123       pool->data[index].o = str;
124       pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
125     }
126     break;
127
128
129   case JV_CONSTANT_Fieldref:
130     {
131       _Jv_ushort class_index, name_and_type_index;
132       _Jv_loadIndexes (&pool->data[index],
133                        class_index,
134                        name_and_type_index);
135       jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
136
137       if (owner != klass)
138         _Jv_InitClass (owner);
139
140       _Jv_ushort name_index, type_index;
141       _Jv_loadIndexes (&pool->data[name_and_type_index],
142                        name_index,
143                        type_index);
144
145       _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
146       _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
147
148       // FIXME: The implementation of this function
149       // (_Jv_FindClassFromSignature) will generate an instance of
150       // _Jv_Utf8Const for each call if the field type is a class name
151       // (Lxx.yy.Z;).  This may be too expensive to do for each and
152       // every fieldref being resolved.  For now, we fix the problem by
153       // only doing it when we have a loader different from the class
154       // declaring the field.
155
156       jclass field_type = 0;
157
158       if (owner->loader != klass->loader)
159         field_type = _Jv_FindClassFromSignature (field_type_name->data,
160                                                  klass->loader);
161       
162       _Jv_Field* the_field = 0;
163
164       for (jclass cls = owner; cls != 0; cls = cls->getSuperclass ())
165         {
166           for (int i = 0;  i < cls->field_count;  i++)
167             {
168               _Jv_Field *field = &cls->fields[i];
169               if (! _Jv_equalUtf8Consts (field->name, field_name))
170                 continue;
171
172               // now, check field access. 
173
174               if (   (cls == klass)
175                   || ((field->flags & Modifier::PUBLIC) != 0)
176                   || (((field->flags & Modifier::PROTECTED) != 0)
177                       && cls->isAssignableFrom (klass))
178                   || (((field->flags & Modifier::PRIVATE) == 0)
179                       && _Jv_ClassNameSamePackage (cls->name,
180                                                    klass->name)))
181                 {
182                   /* resove the field using the class' own loader
183                      if necessary */
184
185                   if (!field->isResolved ())
186                     _Jv_ResolveField (field, cls->loader);
187
188                   if (field_type != 0 && field->type != field_type)
189                     throw new java::lang::LinkageError
190                       (JvNewStringLatin1 
191                        ("field type mismatch with different loaders"));
192
193                   the_field = field;
194                   goto end_of_field_search;
195                 }
196               else
197                 {
198                   throw new java::lang::IllegalAccessError;
199                 }
200             }
201         }
202
203     end_of_field_search:
204       if (the_field == 0)
205         {
206           java::lang::StringBuffer *sb = new java::lang::StringBuffer();
207           sb->append(JvNewStringLatin1("field "));
208           sb->append(owner->getName());
209           sb->append(JvNewStringLatin1("."));
210           sb->append(_Jv_NewStringUTF(field_name->data));
211           sb->append(JvNewStringLatin1(" was not found."));
212           throw_incompatible_class_change_error(sb->toString());
213         }
214
215       pool->data[index].field = the_field;
216       pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
217     }
218     break;
219
220   case JV_CONSTANT_Methodref:
221   case JV_CONSTANT_InterfaceMethodref:
222     {
223       _Jv_ushort class_index, name_and_type_index;
224       _Jv_loadIndexes (&pool->data[index],
225                        class_index,
226                        name_and_type_index);
227       jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
228
229       if (owner != klass)
230         _Jv_InitClass (owner);
231
232       _Jv_ushort name_index, type_index;
233       _Jv_loadIndexes (&pool->data[name_and_type_index],
234                        name_index,
235                        type_index);
236
237       _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
238       _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
239
240       int vtable_index = -1;
241       _Jv_Method *the_method = 0;
242       jclass found_class = 0;
243
244       // First search the class itself.
245       the_method = _Jv_SearchMethodInClass (owner, klass, 
246                    method_name, method_signature);
247
248       if (the_method != 0)
249         {
250           found_class = owner;
251           goto end_of_method_search;
252         }
253
254       // If we are resolving an interface method, search the interface's 
255       // superinterfaces (A superinterface is not an interface's superclass - 
256       // a superinterface is implemented by the interface).
257       if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
258         {
259           _Jv_ifaces ifaces;
260           ifaces.count = 0;
261           ifaces.len = 4;
262           ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
263
264           _Jv_GetInterfaces (owner, &ifaces);     
265           
266           for (int i=0; i < ifaces.count; i++)
267             {
268               jclass cls = ifaces.list[i];
269               the_method = _Jv_SearchMethodInClass (cls, klass, method_name, 
270                                                     method_signature);
271               if (the_method != 0)
272                 {
273                   found_class = cls;
274                   break;
275                 }
276             }
277           
278           _Jv_Free (ifaces.list);
279           
280           if (the_method != 0)
281             goto end_of_method_search;
282         }
283
284       // Finally, search superclasses. 
285       for (jclass cls = owner->getSuperclass (); cls != 0; 
286            cls = cls->getSuperclass ())
287         {
288           the_method = _Jv_SearchMethodInClass (cls, klass, 
289                        method_name, method_signature);
290           if (the_method != 0)
291             {
292               found_class = cls;
293               break;
294             }
295         }
296
297     end_of_method_search:
298     
299       // FIXME: if (cls->loader != klass->loader), then we
300       // must actually check that the types of arguments
301       // correspond.  That is, for each argument type, and
302       // the return type, doing _Jv_FindClassFromSignature
303       // with either loader should produce the same result,
304       // i.e., exactly the same jclass object. JVMS 5.4.3.3    
305     
306       if (the_method == 0)
307         {
308           java::lang::StringBuffer *sb = new java::lang::StringBuffer();
309           sb->append(JvNewStringLatin1("method "));
310           sb->append(owner->getName());
311           sb->append(JvNewStringLatin1("."));
312           sb->append(_Jv_NewStringUTF(method_name->data));
313           sb->append(JvNewStringLatin1(" was not found."));
314           throw new java::lang::NoSuchMethodError (sb->toString());
315         }
316       
317       if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
318         vtable_index = -1;
319       else
320         vtable_index = _Jv_DetermineVTableIndex (found_class, method_name,
321                                                  method_signature);
322
323       if (vtable_index == METHOD_NOT_THERE)
324         throw_incompatible_class_change_error
325           (JvNewStringLatin1 ("method not found"));
326
327       pool->data[index].rmethod = 
328         _Jv_BuildResolvedMethod(the_method,
329                                 found_class,
330                                 (the_method->accflags & Modifier::STATIC) != 0,
331                                 vtable_index);
332       pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
333     }
334     break;
335
336   }
337
338   return pool->data[index];
339 }
340
341 // Find a method declared in the cls that is referenced from klass and
342 // perform access checks.
343 _Jv_Method *
344 _Jv_SearchMethodInClass (jclass cls, jclass klass, 
345                          _Jv_Utf8Const *method_name, 
346                          _Jv_Utf8Const *method_signature)
347 {
348   using namespace java::lang::reflect;
349
350   for (int i = 0;  i < cls->method_count;  i++)
351     {
352       _Jv_Method *method = &cls->methods[i];
353       if (   (!_Jv_equalUtf8Consts (method->name,
354                                     method_name))
355           || (!_Jv_equalUtf8Consts (method->signature,
356                                     method_signature)))
357         continue;
358
359       if (cls == klass 
360           || ((method->accflags & Modifier::PUBLIC) != 0)
361           || (((method->accflags & Modifier::PROTECTED) != 0)
362               && cls->isAssignableFrom (klass))
363           || (((method->accflags & Modifier::PRIVATE) == 0)
364               && _Jv_ClassNameSamePackage (cls->name,
365                                            klass->name)))
366         {
367           return method;
368         }
369       else
370         {
371           throw new java::lang::IllegalAccessError;
372         }
373     }
374   return 0;
375 }
376
377 /** FIXME: this is a terribly inefficient algorithm!  It would improve
378     things if compiled classes to know vtable offset, and _Jv_Method had
379     a field for this.
380
381     Returns METHOD_NOT_THERE if this class does not declare the given method.
382     Returns METHOD_INACCESSIBLE if the given method does not appear in the
383                 vtable, i.e., it is static, private, final or a constructor.
384     Otherwise, returns the vtable index.  */
385 int 
386 _Jv_DetermineVTableIndex (jclass klass,
387                           _Jv_Utf8Const *name,
388                           _Jv_Utf8Const *signature)
389 {
390   using namespace java::lang::reflect;
391
392   jclass super_class = klass->getSuperclass ();
393
394   if (super_class != NULL)
395     {
396       int prev = _Jv_DetermineVTableIndex (super_class,
397                                            name,
398                                            signature);
399       if (prev != METHOD_NOT_THERE)
400         return prev;
401     }
402
403   /* at this point, we know that the super-class does not declare
404    * the method.  Otherwise, the above call would have found it, and
405    * determined the result of this function (-1 or some positive
406    * number).
407    */
408
409   _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
410
411   /* now, if we do not declare this method, return zero */
412   if (meth == NULL)
413     return METHOD_NOT_THERE;
414
415   /* so now, we know not only that the super class does not declare the
416    * method, but we do!  So, this is a first declaration of the method. */
417
418   /* now, the checks for things that are declared in this class, but do
419    * not go into the vtable.  There are three cases.  
420    * 1) the method is static, private or final
421    * 2) the class itself is final, or
422    * 3) it is the method <init>
423    */
424
425   if ((meth->accflags & (Modifier::STATIC
426                          | Modifier::PRIVATE
427                          | Modifier::FINAL)) != 0
428       || (klass->accflags & Modifier::FINAL) != 0
429       || _Jv_equalUtf8Consts (name, init_name))
430     return METHOD_INACCESSIBLE;
431
432   /* reaching this point, we know for sure, that the method in question
433    * will be in the vtable.  The question is where. */
434
435   /* the base offset, is where we will start assigning vtable
436    * indexes for this class.  It is 0 for base classes
437    * and for non-base classes it is the
438    * number of entries in the super class' vtable. */
439
440   int base_offset;
441   if (super_class == 0)
442     base_offset = 0;
443   else
444     base_offset = super_class->vtable_method_count;
445
446   /* we will consider methods 0..this_method_index-1.  And for each one,
447    * determine if it is new (i.e., if it appears in the super class),
448    * and if it should go in the vtable.  If so, increment base_offset */
449
450   int this_method_index = meth - (&klass->methods[0]);
451
452   for (int i = 0; i < this_method_index; i++)
453     {
454       _Jv_Method *m = &klass->methods[i];
455
456       /* fist some checks for things that surely do not go in the
457        * vtable */
458
459       if ((m->accflags & (Modifier::STATIC | Modifier::PRIVATE)) != 0)
460         continue;
461       if (_Jv_equalUtf8Consts (m->name, init_name))
462         continue;
463       
464       /* Then, we need to know if this method appears in the
465          superclass. (This is where this function gets expensive) */
466       _Jv_Method *sm = _Jv_LookupDeclaredMethod (super_class,
467                                                  m->name,
468                                                  m->signature);
469       
470       /* if it was somehow declared in the superclass, skip this */
471       if (sm != NULL)
472         continue;
473
474       /* but if it is final, and not declared in the super class,
475        * then we also skip it */
476       if ((m->accflags & Modifier::FINAL) != 0)
477         continue;
478
479       /* finally, we can assign the index of this method */
480       /* m->vtable_index = base_offset */
481       base_offset += 1;
482     }
483
484   return base_offset;
485 }
486
487 /* this is installed in place of abstract methods */
488 static void
489 _Jv_abstractMethodError ()
490 {
491   throw new java::lang::AbstractMethodError;
492 }
493
494 void 
495 _Jv_PrepareClass(jclass klass)
496 {
497   using namespace java::lang::reflect;
498
499  /*
500   * The job of this function is to: 1) assign storage to fields, and 2)
501   * build the vtable.  static fields are assigned real memory, instance
502   * fields are assigned offsets.
503   *
504   * NOTE: we have a contract with the garbage collector here.  Static
505   * reference fields must not be resolved, until after they have storage
506   * assigned which is the check used by the collector to see if it
507   * should indirect the static field reference and mark the object
508   * pointed to. 
509   *
510   * Most fields are resolved lazily (i.e. have their class-type
511   * assigned) when they are accessed the first time by calling as part
512   * of _Jv_ResolveField, which is allways called after _Jv_PrepareClass.
513   * Static fields with initializers are resolved as part of this
514   * function, as are fields with primitive types.
515   */
516
517   if (! _Jv_IsInterpretedClass (klass))
518     return;
519
520   if (klass->state >= JV_STATE_PREPARED)
521     return;
522
523   // Make sure super-class is linked.  This involves taking a lock on
524   // the super class, so we use the Java method resolveClass, which
525   // will unlock it properly, should an exception happen.  If there's
526   // no superclass, do nothing -- Object will already have been
527   // resolved.
528
529   if (klass->superclass)
530     java::lang::ClassLoader::resolveClass0 (klass->superclass);
531
532   _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
533
534   /************ PART ONE: OBJECT LAYOUT ***************/
535
536   int instance_size;
537   int static_size;
538
539   // Although java.lang.Object is never interpreted, an interface can
540   // have a null superclass.
541   if (clz->superclass)
542     instance_size = clz->superclass->size();
543   else
544     instance_size = java::lang::Object::class$.size();
545   static_size   = 0;
546
547   for (int i = 0; i < clz->field_count; i++)
548     {
549       int field_size;
550       int field_align;
551
552       _Jv_Field *field = &clz->fields[i];
553
554       if (! field->isRef ())
555         {
556           // it's safe to resolve the field here, since it's 
557           // a primitive class, which does not cause loading to happen.
558           _Jv_ResolveField (field, clz->loader);
559
560           field_size = field->type->size ();
561           field_align = get_alignment_from_class (field->type);
562         }
563       else 
564         {
565           field_size = sizeof (jobject);
566           field_align = __alignof__ (jobject);
567         }
568
569 #ifndef COMPACT_FIELDS
570       field->bsize = field_size;
571 #endif
572
573       if (field->flags & Modifier::STATIC)
574         {
575           /* this computes an offset into a region we'll allocate 
576              shortly, and then add this offset to the start address */
577
578           static_size        = ROUND (static_size, field_align);
579           field->u.boffset   = static_size;
580           static_size       += field_size;
581         }
582       else
583         {
584           instance_size      = ROUND (instance_size, field_align);
585           field->u.boffset   = instance_size;
586           instance_size     += field_size;
587         }
588     }
589
590   // set the instance size for the class
591   clz->size_in_bytes = instance_size;
592
593   // allocate static memory
594   if (static_size != 0)
595     {
596       char *static_data = (char*)_Jv_AllocBytes (static_size);
597
598       memset (static_data, 0, static_size);
599
600       for (int i = 0; i < clz->field_count; i++)
601         {
602           _Jv_Field *field = &clz->fields[i];
603
604           if ((field->flags & Modifier::STATIC) != 0)
605             {
606               field->u.addr  = static_data + field->u.boffset;
607                             
608               if (clz->field_initializers[i] != 0)
609                 {
610                   _Jv_ResolveField (field, clz->loader);
611                   _Jv_InitField (0, clz, i);
612                 }
613             }
614         }
615
616       // now we don't need the field_initializers anymore, so let the
617       // collector get rid of it!
618
619       clz->field_initializers = 0;
620     }
621
622   /************ PART TWO: VTABLE LAYOUT ***************/
623
624   /* preparation: build the vtable stubs (even interfaces can)
625      have code -- for static constructors. */
626   for (int i = 0; i < clz->method_count; i++)
627     {
628       _Jv_MethodBase *imeth = clz->interpreted_methods[i];
629
630       if ((clz->methods[i].accflags & Modifier::NATIVE) != 0)
631         {
632           // You might think we could use a virtual `ncode' method in
633           // the _Jv_MethodBase and unify the native and non-native
634           // cases.  Well, we can't, because we don't allocate these
635           // objects using `new', and thus they don't get a vtable.
636           _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
637           clz->methods[i].ncode = jnim->ncode ();
638         }
639       else if (imeth != 0)              // it could be abstract
640         {
641           _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
642           _Jv_VerifyMethod (im);
643           clz->methods[i].ncode = im->ncode ();
644         }
645     }
646
647   if (clz->accflags & Modifier::INTERFACE)
648     {
649       clz->state = JV_STATE_PREPARED;
650       clz->notifyAll ();
651       return;
652     }
653
654   /* Now onto the actual job: vtable layout.  First, count how many new
655      methods we have */
656   int new_method_count = 0;
657
658   jclass super_class = clz->getSuperclass ();
659
660   for (int i = 0; i < clz->method_count; i++)
661     {
662       _Jv_Method *this_meth = &clz->methods[i];
663
664       if ((this_meth->accflags & (Modifier::STATIC | Modifier::PRIVATE)) != 0
665           || _Jv_equalUtf8Consts (this_meth->name, init_name))
666         {
667           /* skip this, it doesn't go in the vtable */
668           continue;
669         }
670           
671       _Jv_Method *orig_meth = _Jv_LookupDeclaredMethod (super_class,
672                                                         this_meth->name,
673                                                         this_meth->signature);
674
675       if (orig_meth == 0)
676         {
677           // new methods that are final, also don't go in the vtable
678           if ((this_meth->accflags & Modifier::FINAL) != 0)
679             continue;
680
681           new_method_count += 1;
682           continue;
683         }
684
685       if ((orig_meth->accflags & (Modifier::STATIC
686                                   | Modifier::PRIVATE
687                                   | Modifier::FINAL)) != 0
688           || ((orig_meth->accflags & Modifier::ABSTRACT) == 0
689               && (this_meth->accflags & Modifier::ABSTRACT) != 0
690               && (klass->accflags & Modifier::ABSTRACT) == 0))
691         {
692           clz->state = JV_STATE_ERROR;
693           clz->notifyAll ();
694           throw new java::lang::IncompatibleClassChangeError (clz->getName ());
695         }
696
697       /* FIXME: At this point, if (loader != super_class->loader), we
698        * need to "impose class loader constraints" for the types
699        * involved in the signature of this method */
700     }
701   
702   /* determine size */
703   int vtable_count = (super_class->vtable_method_count) + new_method_count;
704   clz->vtable_method_count = vtable_count;
705
706   /* allocate vtable structure */
707   _Jv_VTable *vtable = _Jv_VTable::new_vtable (vtable_count);
708   vtable->clas = clz;
709   vtable->gc_descr = _Jv_BuildGCDescr(clz);
710
711   {
712     jclass effective_superclass = super_class;
713
714     /* If super_class is abstract or an interface it has no vtable.
715        We need to find a real one... */
716     while (effective_superclass && effective_superclass->vtable == NULL)
717       effective_superclass = effective_superclass->superclass;
718
719     /* If we ended up without a superclass, use Object.  */
720     if (! effective_superclass)
721       effective_superclass = &java::lang::Object::class$;
722
723     /* copy super class' vtable entries. */
724     if (effective_superclass && effective_superclass->vtable)
725       for (int i = 0; i < effective_superclass->vtable_method_count; ++i)
726         vtable->set_method (i, effective_superclass->vtable->get_method (i));
727   }
728
729   /* now, install our own vtable entries, reprise... */
730   for (int i = 0; i < clz->method_count; i++)
731     {
732       _Jv_Method *this_meth = &clz->methods[i];
733
734       int index = _Jv_DetermineVTableIndex (clz, 
735                                             this_meth->name,
736                                             this_meth->signature);
737
738       if (index == METHOD_NOT_THERE)
739         throw_internal_error ("method now found in own class");
740
741       if (index != METHOD_INACCESSIBLE)
742         {
743           if (index > clz->vtable_method_count)
744             throw_internal_error ("vtable problem...");
745
746           if (clz->interpreted_methods[i] == 0)
747             vtable->set_method(index, (void*)&_Jv_abstractMethodError);
748           else
749             vtable->set_method(index, this_meth->ncode);
750         }
751     }
752
753   /* finally, assign the vtable! */
754   clz->vtable = vtable;
755
756   /* wooha! we're done. */
757   clz->state = JV_STATE_PREPARED;
758   clz->notifyAll ();
759 }
760
761 /** Do static initialization for fields with a constant initializer */
762 void
763 _Jv_InitField (jobject obj, jclass klass, int index)
764 {
765   using namespace java::lang::reflect;
766
767   if (obj != 0 && klass == 0)
768     klass = obj->getClass ();
769
770   if (!_Jv_IsInterpretedClass (klass))
771     return;
772
773   _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
774
775   _Jv_Field * field = (&clz->fields[0]) + index;
776
777   if (index > clz->field_count)
778     throw_internal_error ("field out of range");
779
780   int init = clz->field_initializers[index];
781   if (init == 0)
782     return;
783
784   _Jv_Constants *pool = &clz->constants;
785   int tag = pool->tags[init];
786
787   if (! field->isResolved ())
788     throw_internal_error ("initializing unresolved field");
789
790   if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
791     throw_internal_error ("initializing non-static field with no object");
792
793   void *addr = 0;
794
795   if ((field->flags & Modifier::STATIC) != 0)
796     addr = (void*) field->u.addr;
797   else
798     addr = (void*) (((char*)obj) + field->u.boffset);
799
800   switch (tag)
801     {
802     case JV_CONSTANT_String:
803       {
804         _Jv_MonitorEnter (clz);
805         jstring str;
806         str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
807         pool->data[init].string = str;
808         pool->tags[init] = JV_CONSTANT_ResolvedString;
809         _Jv_MonitorExit (clz);
810       }
811       /* fall through */
812
813     case JV_CONSTANT_ResolvedString:
814       if (! (field->type == &StringClass
815              || field->type == &java::lang::Class::class$))
816         throw_class_format_error ("string initialiser to non-string field");
817
818       *(jstring*)addr = pool->data[init].string;
819       break;
820
821     case JV_CONSTANT_Integer:
822       {
823         int value = pool->data[init].i;
824
825         if (field->type == JvPrimClass (boolean))
826           *(jboolean*)addr = (jboolean)value;
827         
828         else if (field->type == JvPrimClass (byte))
829           *(jbyte*)addr = (jbyte)value;
830         
831         else if (field->type == JvPrimClass (char))
832           *(jchar*)addr = (jchar)value;
833
834         else if (field->type == JvPrimClass (short))
835           *(jshort*)addr = (jshort)value;
836         
837         else if (field->type == JvPrimClass (int))
838           *(jint*)addr = (jint)value;
839
840         else
841           throw_class_format_error ("erroneous field initializer");
842       }  
843       break;
844
845     case JV_CONSTANT_Long:
846       if (field->type != JvPrimClass (long))
847         throw_class_format_error ("erroneous field initializer");
848
849       *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
850       break;
851
852     case JV_CONSTANT_Float:
853       if (field->type != JvPrimClass (float))
854         throw_class_format_error ("erroneous field initializer");
855
856       *(jfloat*)addr = pool->data[init].f;
857       break;
858
859     case JV_CONSTANT_Double:
860       if (field->type != JvPrimClass (double))
861         throw_class_format_error ("erroneous field initializer");
862
863       *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
864       break;
865
866     default:
867       throw_class_format_error ("erroneous field initializer");
868     }
869 }
870
871 static int
872 get_alignment_from_class (jclass klass)
873 {
874   if (klass == JvPrimClass (byte))
875     return  __alignof__ (jbyte);
876   else if (klass == JvPrimClass (short))
877     return  __alignof__ (jshort);
878   else if (klass == JvPrimClass (int)) 
879     return  __alignof__ (jint);
880   else if (klass == JvPrimClass (long))
881     return  __alignof__ (jlong);
882   else if (klass == JvPrimClass (boolean))
883     return  __alignof__ (jboolean);
884   else if (klass == JvPrimClass (char))
885     return  __alignof__ (jchar);
886   else if (klass == JvPrimClass (float))
887     return  __alignof__ (jfloat);
888   else if (klass == JvPrimClass (double))
889     return  __alignof__ (jdouble);
890   else
891     return __alignof__ (jobject);
892 }
893
894
895 inline static unsigned char*
896 skip_one_type (unsigned char* ptr)
897 {
898   int ch = *ptr++;
899
900   while (ch == '[')
901     { 
902       ch = *ptr++;
903     }
904   
905   if (ch == 'L')
906     {
907       do { ch = *ptr++; } while (ch != ';');
908     }
909
910   return ptr;
911 }
912
913 static ffi_type*
914 get_ffi_type_from_signature (unsigned char* ptr)
915 {
916   switch (*ptr) 
917     {
918     case 'L':
919     case '[':
920       return &ffi_type_pointer;
921       break;
922
923     case 'Z':
924       // On some platforms a bool is a byte, on others an int.
925       if (sizeof (jboolean) == sizeof (jbyte))
926         return &ffi_type_sint8;
927       else
928         {
929           JvAssert (sizeof (jbyte) == sizeof (jint));
930           return &ffi_type_sint32;
931         }
932       break;
933
934     case 'B':
935       return &ffi_type_sint8;
936       break;
937       
938     case 'C':
939       return &ffi_type_uint16;
940       break;
941           
942     case 'S': 
943       return &ffi_type_sint16;
944       break;
945           
946     case 'I':
947       return &ffi_type_sint32;
948       break;
949           
950     case 'J':
951       return &ffi_type_sint64;
952       break;
953           
954     case 'F':
955       return &ffi_type_float;
956       break;
957           
958     case 'D':
959       return &ffi_type_double;
960       break;
961
962     case 'V':
963       return &ffi_type_void;
964       break;
965     }
966
967   throw_internal_error ("unknown type in signature");
968 }
969
970 /* this function yields the number of actual arguments, that is, if the
971  * function is non-static, then one is added to the number of elements
972  * found in the signature */
973
974 int 
975 _Jv_count_arguments (_Jv_Utf8Const *signature,
976                      jboolean staticp)
977 {
978   unsigned char *ptr = (unsigned char*) signature->data;
979   int arg_count = staticp ? 0 : 1;
980
981   /* first, count number of arguments */
982
983   // skip '('
984   ptr++;
985
986   // count args
987   while (*ptr != ')')
988     {
989       ptr = skip_one_type (ptr);
990       arg_count += 1;
991     }
992
993   return arg_count;
994 }
995
996 /* This beast will build a cif, given the signature.  Memory for
997  * the cif itself and for the argument types must be allocated by the
998  * caller.
999  */
1000
1001 static int 
1002 init_cif (_Jv_Utf8Const* signature,
1003           int arg_count,
1004           jboolean staticp,
1005           ffi_cif *cif,
1006           ffi_type **arg_types,
1007           ffi_type **rtype_p)
1008 {
1009   unsigned char *ptr = (unsigned char*) signature->data;
1010
1011   int arg_index = 0;            // arg number
1012   int item_count = 0;           // stack-item count
1013
1014   // setup receiver
1015   if (!staticp)
1016     {
1017       arg_types[arg_index++] = &ffi_type_pointer;
1018       item_count += 1;
1019     }
1020
1021   // skip '('
1022   ptr++;
1023
1024   // assign arg types
1025   while (*ptr != ')')
1026     {
1027       arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
1028
1029       if (*ptr == 'J' || *ptr == 'D')
1030         item_count += 2;
1031       else
1032         item_count += 1;
1033
1034       ptr = skip_one_type (ptr);
1035     }
1036
1037   // skip ')'
1038   ptr++;
1039   ffi_type *rtype = get_ffi_type_from_signature (ptr);
1040
1041   ptr = skip_one_type (ptr);
1042   if (ptr != (unsigned char*)signature->data + signature->length)
1043     throw_internal_error ("did not find end of signature");
1044
1045   if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
1046                     arg_count, rtype, arg_types) != FFI_OK)
1047     throw_internal_error ("ffi_prep_cif failed");
1048
1049   if (rtype_p != NULL)
1050     *rtype_p = rtype;
1051
1052   return item_count;
1053 }
1054
1055 #if FFI_NATIVE_RAW_API
1056 #   define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure
1057 #   define FFI_RAW_SIZE ffi_raw_size
1058 #else
1059 #   define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure
1060 #   define FFI_RAW_SIZE ffi_java_raw_size
1061 #endif
1062
1063 /* we put this one here, and not in interpret.cc because it
1064  * calls the utility routines _Jv_count_arguments 
1065  * which are static to this module.  The following struct defines the
1066  * layout we use for the stubs, it's only used in the ncode method. */
1067
1068 typedef struct {
1069   ffi_raw_closure  closure;
1070   ffi_cif   cif;
1071   ffi_type *arg_types[0];
1072 } ncode_closure;
1073
1074 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
1075
1076 void *
1077 _Jv_InterpMethod::ncode ()
1078 {
1079   using namespace java::lang::reflect;
1080
1081   if (self->ncode != 0)
1082     return self->ncode;
1083
1084   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1085   int arg_count = _Jv_count_arguments (self->signature, staticp);
1086
1087   ncode_closure *closure =
1088     (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
1089                                         + arg_count * sizeof (ffi_type*));
1090
1091   init_cif (self->signature,
1092             arg_count,
1093             staticp,
1094             &closure->cif,
1095             &closure->arg_types[0],
1096             NULL);
1097
1098   ffi_closure_fun fun;
1099
1100   args_raw_size = FFI_RAW_SIZE (&closure->cif);
1101
1102   JvAssert ((self->accflags & Modifier::NATIVE) == 0);
1103
1104   if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
1105     {
1106       if (staticp)
1107         fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
1108       else
1109         fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object; 
1110     }
1111   else
1112     {
1113       fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
1114     }
1115
1116   FFI_PREP_RAW_CLOSURE (&closure->closure,
1117                         &closure->cif, 
1118                         fun,
1119                         (void*)this);
1120
1121   self->ncode = (void*)closure;
1122   return self->ncode;
1123 }
1124
1125
1126 void *
1127 _Jv_JNIMethod::ncode ()
1128 {
1129   using namespace java::lang::reflect;
1130
1131   if (self->ncode != 0)
1132     return self->ncode;
1133
1134   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1135   int arg_count = _Jv_count_arguments (self->signature, staticp);
1136
1137   ncode_closure *closure =
1138     (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
1139                                     + arg_count * sizeof (ffi_type*));
1140
1141   ffi_type *rtype;
1142   init_cif (self->signature,
1143             arg_count,
1144             staticp,
1145             &closure->cif,
1146             &closure->arg_types[0],
1147             &rtype);
1148
1149   ffi_closure_fun fun;
1150
1151   args_raw_size = FFI_RAW_SIZE (&closure->cif);
1152
1153   // Initialize the argument types and CIF that represent the actual
1154   // underlying JNI function.
1155   int extra_args = 1;
1156   if ((self->accflags & Modifier::STATIC))
1157     ++extra_args;
1158   jni_arg_types = (ffi_type **) _Jv_Malloc ((extra_args + arg_count)
1159                                             * sizeof (ffi_type *));
1160   int offset = 0;
1161   jni_arg_types[offset++] = &ffi_type_pointer;
1162   if ((self->accflags & Modifier::STATIC))
1163     jni_arg_types[offset++] = &ffi_type_pointer;
1164   memcpy (&jni_arg_types[offset], &closure->arg_types[0],
1165           arg_count * sizeof (ffi_type *));
1166
1167   if (ffi_prep_cif (&jni_cif, FFI_DEFAULT_ABI,
1168                     extra_args + arg_count, rtype,
1169                     jni_arg_types) != FFI_OK)
1170     throw_internal_error ("ffi_prep_cif failed for JNI function");
1171
1172   JvAssert ((self->accflags & Modifier::NATIVE) != 0);
1173
1174   // FIXME: for now we assume that all native methods for
1175   // interpreted code use JNI.
1176   fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
1177
1178   FFI_PREP_RAW_CLOSURE (&closure->closure,
1179                         &closure->cif, 
1180                         fun,
1181                         (void*) this);
1182
1183   self->ncode = (void *) closure;
1184   return self->ncode;
1185 }
1186
1187
1188 /* A _Jv_ResolvedMethod is what is put in the constant pool for a
1189  * MethodRef or InterfacemethodRef.  */
1190 static _Jv_ResolvedMethod*
1191 _Jv_BuildResolvedMethod (_Jv_Method* method,
1192                          jclass      klass,
1193                          jboolean staticp,
1194                          jint vtable_index)
1195 {
1196   int arg_count = _Jv_count_arguments (method->signature, staticp);
1197
1198   _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
1199     _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
1200                     + arg_count*sizeof (ffi_type*));
1201
1202   result->stack_item_count
1203     = init_cif (method->signature,
1204                 arg_count,
1205                 staticp,
1206                 &result->cif,
1207                 &result->arg_types[0],
1208                 NULL);
1209
1210   result->vtable_index        = vtable_index;
1211   result->method              = method;
1212   result->klass               = klass;
1213
1214   return result;
1215 }
1216
1217
1218 static void
1219 throw_class_format_error (jstring msg)
1220 {
1221   throw (msg
1222          ? new java::lang::ClassFormatError (msg)
1223          : new java::lang::ClassFormatError);
1224 }
1225
1226 static void
1227 throw_class_format_error (char *msg)
1228 {
1229   throw_class_format_error (JvNewStringLatin1 (msg));
1230 }
1231
1232 static void
1233 throw_internal_error (char *msg)
1234 {
1235   throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1236 }
1237
1238
1239 #endif /* INTERPRETER */