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