OSDN Git Service

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