OSDN Git Service

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