OSDN Git Service

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