OSDN Git Service

* configure: Rebuilt.
[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  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 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 /** FIXME: this is a terribly inefficient algorithm!  It would improve
323     things if compiled classes to know vtable offset, and _Jv_Method had
324     a field for this.
325
326     Returns 0  if this class does not declare the given method.
327     Returns -1 if the given method does not appear in the vtable.
328                i.e., it is static, private, final or a constructor.
329     Otherwise, returns the vtable index.  */
330 int 
331 _Jv_DetermineVTableIndex (jclass klass,
332                           _Jv_Utf8Const *name,
333                           _Jv_Utf8Const *signature)
334 {
335   using namespace java::lang::reflect;
336
337   jclass super_class = klass->getSuperclass ();
338
339   if (super_class != NULL)
340     {
341       int prev = _Jv_DetermineVTableIndex (super_class,
342                                            name,
343                                            signature);
344       if (prev != 0)
345         return prev;
346     }
347
348   /* at this point, we know that the super-class does not declare
349    * the method.  Otherwise, the above call would have found it, and
350    * determined the result of this function (-1 or some positive
351    * number).
352    */
353
354   _Jv_Method *meth = _Jv_GetMethodLocal (klass, name, signature);
355
356   /* now, if we do not declare this method, return zero */
357   if (meth == NULL)
358     return 0;
359
360   /* so now, we know not only that the super class does not declare the
361    * method, but we do!  So, this is a first declaration of the method. */
362
363   /* now, the checks for things that are declared in this class, but do
364    * not go into the vtable.  There are three cases.  
365    * 1) the method is static, private or final
366    * 2) the class itself is final, or
367    * 3) it is the method <init>
368    */
369
370   if ((meth->accflags & (Modifier::STATIC
371                          | Modifier::PRIVATE
372                          | Modifier::FINAL)) != 0
373       || (klass->accflags & Modifier::FINAL) != 0
374       || _Jv_equalUtf8Consts (name, init_name))
375     return -1;
376
377   /* reaching this point, we know for sure, that the method in question
378    * will be in the vtable.  The question is where. */
379
380   /* the base offset, is where we will start assigning vtable
381    * indexes for this class.  It is 1 for base classes
382    * (vtable->method[0] is unused), and for non-base classes it is the
383    * number of entries in the super class' vtable plus 1. */
384
385   int base_offset;
386   if (super_class == 0)
387     base_offset = 1;
388   else
389     base_offset = super_class->vtable_method_count+1;
390
391   /* we will consider methods 0..this_method_index-1.  And for each one,
392    * determine if it is new (i.e., if it appears in the super class),
393    * and if it should go in the vtable.  If so, increment base_offset */
394
395   int this_method_index = meth - (&klass->methods[0]);
396
397   for (int i = 0; i < this_method_index; i++)
398     {
399       _Jv_Method *m = &klass->methods[i];
400
401       /* fist some checks for things that surely do not go in the
402        * vtable */
403
404       if ((m->accflags & (Modifier::STATIC | Modifier::PRIVATE)) != 0)
405         continue;
406       if (_Jv_equalUtf8Consts (m->name, init_name))
407         continue;
408       
409       /* Then, we need to know if this method appears in the
410          superclass. (This is where this function gets expensive) */
411       _Jv_Method *sm = _Jv_LookupDeclaredMethod (super_class,
412                                                  m->name,
413                                                  m->signature);
414       
415       /* if it was somehow declared in the superclass, skip this */
416       if (sm != NULL)
417         continue;
418
419       /* but if it is final, and not declared in the super class,
420        * then we also skip it */
421       if ((m->accflags & Modifier::FINAL) != 0)
422         continue;
423
424       /* finally, we can assign the index of this method */
425       /* m->vtable_index = base_offset */
426       base_offset += 1;
427     }
428
429   return base_offset;
430 }
431
432 /* this is installed in place of abstract methods */
433 static void
434 _Jv_abstractMethodError ()
435 {
436   JvThrow (new java::lang::AbstractMethodError);
437 }
438
439 void 
440 _Jv_PrepareClass(jclass klass)
441 {
442   using namespace java::lang::reflect;
443
444  /*
445   * The job of this function is to: 1) assign storage to fields, and 2)
446   * build the vtable.  static fields are assigned real memory, instance
447   * fields are assigned offsets.
448   *
449   * NOTE: we have a contract with the garbage collector here.  Static
450   * reference fields must not be resolved, until after they have storage
451   * assigned which is the check used by the collector to see if it
452   * should indirect the static field reference and mark the object
453   * pointed to. 
454   *
455   * Most fields are resolved lazily (i.e. have their class-type
456   * assigned) when they are accessed the first time by calling as part
457   * of _Jv_ResolveField, which is allways called after _Jv_PrepareClass.
458   * Static fields with initializers are resolved as part of this
459   * function, as are fields with primitive types.
460   */
461
462   if (! _Jv_IsInterpretedClass (klass))
463     return;
464
465   if (klass->state >= JV_STATE_PREPARED)
466     return;
467
468   // make sure super-class is linked.  This involves taking a lock on
469   // the super class, so we use the Java method resolveClass, which will
470   // unlock it properly, should an exception happen.
471
472   java::lang::ClassLoader::resolveClass0 (klass->superclass);
473
474   _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
475
476   /************ PART ONE: OBJECT LAYOUT ***************/
477
478   int instance_size;
479   int static_size;
480
481   // java.lang.Object is never interpreted!
482   instance_size = clz->superclass->size ();
483   static_size   = 0;
484
485   for (int i = 0; i < clz->field_count; i++)
486     {
487       int field_size;
488       int field_align;
489
490       _Jv_Field *field = &clz->fields[i];
491
492       if (! field->isRef ())
493         {
494           // it's safe to resolve the field here, since it's 
495           // a primitive class, which does not cause loading to happen.
496           _Jv_ResolveField (field, clz->loader);
497
498           field_size = field->type->size ();
499           field_align = get_alignment_from_class (field->type);
500         }
501       else 
502         {
503           field_size = sizeof (jobject);
504           field_align = __alignof__ (jobject);
505         }
506
507 #ifndef COMPACT_FIELDS
508       field->bsize = field_size;
509 #endif
510
511       if (field->flags & Modifier::STATIC)
512         {
513           /* this computes an offset into a region we'll allocate 
514              shortly, and then add this offset to the start address */
515
516           static_size        = ROUND (static_size, field_align);
517           field->u.boffset   = static_size;
518           static_size       += field_size;
519         }
520       else
521         {
522           instance_size      = ROUND (instance_size, field_align);
523           field->u.boffset   = instance_size;
524           instance_size     += field_size;
525         }
526     }
527
528   // set the instance size for the class
529   clz->size_in_bytes = instance_size;
530     
531   // allocate static memory
532   if (static_size != 0)
533     {
534       char *static_data = (char*)_Jv_AllocBytesChecked (static_size);
535
536       memset (static_data, 0, static_size);
537
538       for (int i = 0; i < clz->field_count; i++)
539         {
540           _Jv_Field *field = &clz->fields[i];
541
542           if ((field->flags & Modifier::STATIC) != 0)
543             {
544               field->u.addr  = static_data + field->u.boffset;
545                             
546               if (clz->field_initializers[i] != 0)
547                 {
548                   _Jv_ResolveField (field, clz->loader);
549                   _Jv_InitField (0, clz, i);
550                 }
551             }
552         }
553
554       // now we don't need the field_initializers anymore, so let the
555       // collector get rid of it!
556
557       clz->field_initializers = 0;
558     }
559
560   /************ PART TWO: VTABLE LAYOUT ***************/
561
562   /* preparation: build the vtable stubs (even interfaces can)
563      have code -- for static constructors. */
564   for (int i = 0; i < clz->method_count; i++)
565     {
566       _Jv_MethodBase *imeth = clz->interpreted_methods[i];
567
568       if ((clz->methods[i].accflags & Modifier::NATIVE) != 0)
569         {
570           // You might think we could use a virtual `ncode' method in
571           // the _Jv_MethodBase and unify the native and non-native
572           // cases.  Well, we can't, because we don't allocate these
573           // objects using `new', and thus they don't get a vtable.
574           _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
575           clz->methods[i].ncode = jnim->ncode ();
576         }
577       else if (imeth != 0)              // it could be abstract
578         {
579           _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
580           clz->methods[i].ncode = im->ncode ();
581         }
582     }
583
584   if (clz->accflags & Modifier::INTERFACE)
585     {
586       clz->state = JV_STATE_PREPARED;
587       clz->notifyAll ();
588       return;
589     }
590
591   /* Now onto the actual job: vtable layout.  First, count how many new
592      methods we have */
593   int new_method_count = 0;
594
595   jclass super_class = clz->getSuperclass ();
596
597   if (super_class == 0)
598     throw_internal_error ("cannot handle interpreted base classes");
599
600   for (int i = 0; i < clz->method_count; i++)
601     {
602       _Jv_Method *this_meth = &clz->methods[i];
603
604       if ((this_meth->accflags & (Modifier::STATIC | Modifier::PRIVATE)) != 0
605           || _Jv_equalUtf8Consts (this_meth->name, init_name))
606         {
607           /* skip this, it doesn't go in the vtable */
608           continue;
609         }
610           
611       _Jv_Method *orig_meth = _Jv_LookupDeclaredMethod (super_class,
612                                                         this_meth->name,
613                                                         this_meth->signature);
614
615       if (orig_meth == 0)
616         {
617           // new methods that are final, also don't go in the vtable
618           if ((this_meth->accflags & Modifier::FINAL) != 0)
619             continue;
620
621           new_method_count += 1;
622           continue;
623         }
624
625       if ((orig_meth->accflags & (Modifier::STATIC
626                                   | Modifier::PRIVATE
627                                   | Modifier::FINAL)) != 0
628           || ((orig_meth->accflags & Modifier::ABSTRACT) == 0
629               && (this_meth->accflags & Modifier::ABSTRACT) != 0
630               && (klass->accflags & Modifier::ABSTRACT) == 0))
631         {
632           clz->state = JV_STATE_ERROR;
633           clz->notifyAll ();
634           JvThrow (new java::lang::IncompatibleClassChangeError 
635                            (clz->getName ()));
636         }
637
638       /* FIXME: At this point, if (loader != super_class->loader), we
639        * need to "impose class loader constraints" for the types
640        * involved in the signature of this method */
641     }
642   
643   /* determine size */
644   int vtable_count = (super_class->vtable_method_count) + new_method_count;
645   clz->vtable_method_count = vtable_count;
646
647   /* allocate vtable structure */
648   _Jv_VTable *vtable = (_Jv_VTable*) 
649     _Jv_AllocBytesChecked (sizeof (_Jv_VTable) 
650                            + (sizeof (void*) * (vtable_count)));
651   vtable->clas = clz;
652
653   {
654     jclass effective_superclass = super_class;
655
656     /* If super_class is abstract or an interface it has no vtable.
657        We need to find a real one... */
658     while (effective_superclass && effective_superclass->vtable == NULL)
659       effective_superclass = effective_superclass->superclass;
660
661     /* copy super class' vtable entries (index 0 goes unused). */
662     if (effective_superclass && effective_superclass->vtable)
663       memcpy ((void*)&vtable->method[1],
664               (void*)&effective_superclass->vtable->method[1],
665               sizeof (void*) * effective_superclass->vtable_method_count);
666   }
667
668   /* now, install our own vtable entries, reprise... */
669   for (int i = 0; i < clz->method_count; i++)
670     {
671       _Jv_Method *this_meth = &clz->methods[i];
672
673       int index = _Jv_DetermineVTableIndex (clz, 
674                                             this_meth->name,
675                                             this_meth->signature);
676
677       if (index == 0)
678         throw_internal_error ("method now found in own class");
679
680       if (index != -1)
681         {
682           if (index > clz->vtable_method_count+1)
683             throw_internal_error ("vtable problem...");
684
685           if (clz->interpreted_methods[i] == 0)
686             vtable->method[index] = (void*)&_Jv_abstractMethodError;
687           else
688             vtable->method[index] = this_meth->ncode;
689         }
690     }
691
692   /* finally, assign the vtable! */
693   clz->vtable = vtable;
694
695   /* wooha! we're done. */
696   clz->state = JV_STATE_PREPARED;
697   clz->notifyAll ();
698 }
699
700 /** Do static initialization for fields with a constant initializer */
701 void
702 _Jv_InitField (jobject obj, jclass klass, int index)
703 {
704   using namespace java::lang::reflect;
705
706   if (obj != 0 && klass == 0)
707     klass = obj->getClass ();
708
709   if (!_Jv_IsInterpretedClass (klass))
710     return;
711
712   _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
713
714   _Jv_Field * field = (&clz->fields[0]) + index;
715
716   if (index > clz->field_count)
717     throw_internal_error ("field out of range");
718
719   int init = clz->field_initializers[index];
720   if (init == 0)
721     return;
722
723   _Jv_Constants *pool = &clz->constants;
724   int tag = pool->tags[init];
725
726   if (! field->isResolved ())
727     throw_internal_error ("initializing unresolved field");
728
729   if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
730     throw_internal_error ("initializing non-static field with no object");
731
732   void *addr = 0;
733
734   if ((field->flags & Modifier::STATIC) != 0)
735     addr = (void*) field->u.addr;
736   else
737     addr = (void*) (((char*)obj) + field->u.boffset);
738
739   switch (tag)
740     {
741     case JV_CONSTANT_String:
742       {
743         _Jv_MonitorEnter (clz);
744         jstring str;
745         str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
746         pool->data[init].string = str;
747         pool->tags[init] = JV_CONSTANT_ResolvedString;
748         _Jv_MonitorExit (clz);
749       }
750       /* fall through */
751
752     case JV_CONSTANT_ResolvedString:
753       if (! (field->type == &StringClass || field->type == &ObjectClass))
754         throw_class_format_error ("string initialiser to non-string field");
755
756       *(jstring*)addr = pool->data[init].string;
757       break;
758
759     case JV_CONSTANT_Integer:
760       {
761         int value = pool->data[init].i;
762
763         if (field->type == JvPrimClass (boolean))
764           *(jboolean*)addr = (jboolean)value;
765         
766         else if (field->type == JvPrimClass (byte))
767           *(jbyte*)addr = (jbyte)value;
768         
769         else if (field->type == JvPrimClass (char))
770           *(jchar*)addr = (jchar)value;
771
772         else if (field->type == JvPrimClass (short))
773           *(jshort*)addr = (jshort)value;
774         
775         else if (field->type == JvPrimClass (int))
776           *(jint*)addr = (jint)value;
777
778         else
779           throw_class_format_error ("erroneous field initializer");
780       }  
781       break;
782
783     case JV_CONSTANT_Long:
784       if (field->type != JvPrimClass (long))
785         throw_class_format_error ("erroneous field initializer");
786
787       *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
788       break;
789
790     case JV_CONSTANT_Float:
791       if (field->type != JvPrimClass (float))
792         throw_class_format_error ("erroneous field initializer");
793
794       *(jfloat*)addr = pool->data[init].f;
795       break;
796
797     case JV_CONSTANT_Double:
798       if (field->type != JvPrimClass (double))
799         throw_class_format_error ("erroneous field initializer");
800
801       *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
802       break;
803
804     default:
805       throw_class_format_error ("erroneous field initializer");
806     }
807 }
808
809 static int
810 get_alignment_from_class (jclass klass)
811 {
812   if (klass == JvPrimClass (byte))
813     return  __alignof__ (jbyte);
814   else if (klass == JvPrimClass (short))
815     return  __alignof__ (jshort);
816   else if (klass == JvPrimClass (int)) 
817     return  __alignof__ (jint);
818   else if (klass == JvPrimClass (long))
819     return  __alignof__ (jlong);
820   else if (klass == JvPrimClass (boolean))
821     return  __alignof__ (jboolean);
822   else if (klass == JvPrimClass (char))
823     return  __alignof__ (jchar);
824   else if (klass == JvPrimClass (float))
825     return  __alignof__ (jfloat);
826   else if (klass == JvPrimClass (double))
827     return  __alignof__ (jdouble);
828   else
829     return __alignof__ (jobject);
830 }
831
832
833 inline static unsigned char*
834 skip_one_type (unsigned char* ptr)
835 {
836   int ch = *ptr++;
837
838   while (ch == '[')
839     { 
840       ch = *ptr++;
841     }
842   
843   if (ch == 'L')
844     {
845       do { ch = *ptr++; } while (ch != ';');
846     }
847
848   return ptr;
849 }
850
851 static ffi_type*
852 get_ffi_type_from_signature (unsigned char* ptr)
853 {
854   switch (*ptr) 
855     {
856     case 'L':
857     case '[':
858       return &ffi_type_pointer;
859       break;
860
861     case 'Z':
862       // On some platforms a bool is a byte, on others an int.
863       if (sizeof (jboolean) == sizeof (jbyte))
864         return &ffi_type_sint8;
865       else
866         {
867           JvAssert (sizeof (jbyte) == sizeof (jint));
868           return &ffi_type_sint32;
869         }
870       break;
871
872     case 'B':
873       return &ffi_type_sint8;
874       break;
875       
876     case 'C':
877       return &ffi_type_uint16;
878       break;
879           
880     case 'S': 
881       return &ffi_type_sint16;
882       break;
883           
884     case 'I':
885       return &ffi_type_sint32;
886       break;
887           
888     case 'J':
889       return &ffi_type_sint64;
890       break;
891           
892     case 'F':
893       return &ffi_type_float;
894       break;
895           
896     case 'D':
897       return &ffi_type_double;
898       break;
899
900     case 'V':
901       return &ffi_type_void;
902       break;
903     }
904
905   throw_internal_error ("unknown type in signature");
906 }
907
908 /* this function yields the number of actual arguments, that is, if the
909  * function is non-static, then one is added to the number of elements
910  * found in the signature */
911
912 static int 
913 count_arguments (_Jv_Utf8Const *signature,
914                  jboolean staticp)
915 {
916   unsigned char *ptr = (unsigned char*) signature->data;
917   int arg_count = staticp ? 0 : 1;
918
919   /* first, count number of arguments */
920
921   // skip '('
922   ptr++;
923
924   // count args
925   while (*ptr != ')')
926     {
927       ptr = skip_one_type (ptr);
928       arg_count += 1;
929     }
930
931   return arg_count;
932 }
933
934 /* This beast will build a cif, given the signature.  Memory for
935  * the cif itself and for the argument types must be allocated by the
936  * caller.
937  */
938
939 static int 
940 init_cif (_Jv_Utf8Const* signature,
941           int arg_count,
942           jboolean staticp,
943           ffi_cif *cif,
944           ffi_type **arg_types,
945           ffi_type **rtype_p)
946 {
947   unsigned char *ptr = (unsigned char*) signature->data;
948
949   int arg_index = 0;            // arg number
950   int item_count = 0;           // stack-item count
951
952   // setup receiver
953   if (!staticp)
954     {
955       arg_types[arg_index++] = &ffi_type_pointer;
956       item_count += 1;
957     }
958
959   // skip '('
960   ptr++;
961
962   // assign arg types
963   while (*ptr != ')')
964     {
965       arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
966
967       if (*ptr == 'J' || *ptr == 'D')
968         item_count += 2;
969       else
970         item_count += 1;
971
972       ptr = skip_one_type (ptr);
973     }
974
975   // skip ')'
976   ptr++;
977   ffi_type *rtype = get_ffi_type_from_signature (ptr);
978
979   ptr = skip_one_type (ptr);
980   if (ptr != (unsigned char*)signature->data + signature->length)
981     throw_internal_error ("did not find end of signature");
982
983   if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
984                     arg_count, rtype, arg_types) != FFI_OK)
985     throw_internal_error ("ffi_prep_cif failed");
986
987   if (rtype_p != NULL)
988     *rtype_p = rtype;
989
990   return item_count;
991 }
992
993
994 /* we put this one here, and not in interpret.cc because it
995  * calls the utility routines count_arguments 
996  * which are static to this module.  The following struct defines the
997  * layout we use for the stubs, it's only used in the ncode method. */
998
999 typedef struct {
1000   ffi_raw_closure  closure;
1001   ffi_cif   cif;
1002   ffi_type *arg_types[0];
1003 } ncode_closure;
1004
1005 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
1006
1007 void *
1008 _Jv_InterpMethod::ncode ()
1009 {
1010   using namespace java::lang::reflect;
1011
1012   if (self->ncode != 0)
1013     return self->ncode;
1014
1015   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1016   int arg_count = count_arguments (self->signature, staticp);
1017
1018   ncode_closure *closure =
1019     (ncode_closure*)_Jv_AllocBytesChecked (sizeof (ncode_closure)
1020                                         + arg_count * sizeof (ffi_type*));
1021
1022   init_cif (self->signature,
1023             arg_count,
1024             staticp,
1025             &closure->cif,
1026             &closure->arg_types[0],
1027             NULL);
1028
1029   ffi_closure_fun fun;
1030
1031   args_raw_size = ffi_raw_size (&closure->cif);
1032
1033   JvAssert ((self->accflags & Modifier::NATIVE) == 0);
1034
1035   if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
1036     {
1037       if (staticp)
1038         fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
1039       else
1040         fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object; 
1041     }
1042   else
1043     {
1044       fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
1045     }
1046
1047   ffi_prep_raw_closure (&closure->closure,
1048                         &closure->cif, 
1049                         fun,
1050                         (void*) this);
1051
1052   self->ncode = (void*)closure;
1053   return self->ncode;
1054 }
1055
1056
1057 void *
1058 _Jv_JNIMethod::ncode ()
1059 {
1060   using namespace java::lang::reflect;
1061
1062   if (self->ncode != 0)
1063     return self->ncode;
1064
1065   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1066   int arg_count = count_arguments (self->signature, staticp);
1067
1068   ncode_closure *closure =
1069     (ncode_closure*)_Jv_AllocBytesChecked (sizeof (ncode_closure)
1070                                         + arg_count * sizeof (ffi_type*));
1071
1072   ffi_type *rtype;
1073   init_cif (self->signature,
1074             arg_count,
1075             staticp,
1076             &closure->cif,
1077             &closure->arg_types[0],
1078             &rtype);
1079
1080   ffi_closure_fun fun;
1081
1082   args_raw_size = ffi_raw_size (&closure->cif);
1083
1084   // Initialize the argument types and CIF that represent the actual
1085   // underlying JNI function.
1086   int extra_args = 1;
1087   if ((self->accflags & Modifier::STATIC))
1088     ++extra_args;
1089   jni_arg_types = (ffi_type **) _Jv_Malloc ((extra_args + arg_count)
1090                                             * sizeof (ffi_type *));
1091   int offset = 0;
1092   jni_arg_types[offset++] = &ffi_type_pointer;
1093   if ((self->accflags & Modifier::STATIC))
1094     jni_arg_types[offset++] = &ffi_type_pointer;
1095   memcpy (&jni_arg_types[offset], &closure->arg_types[0],
1096           arg_count * sizeof (ffi_type *));
1097
1098   if (ffi_prep_cif (&jni_cif, FFI_DEFAULT_ABI,
1099                     extra_args + arg_count, rtype,
1100                     jni_arg_types) != FFI_OK)
1101     throw_internal_error ("ffi_prep_cif failed for JNI function");
1102
1103   JvAssert ((self->accflags & Modifier::NATIVE) != 0);
1104
1105   // FIXME: for now we assume that all native methods for
1106   // interpreted code use JNI.
1107   fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
1108
1109   ffi_prep_raw_closure (&closure->closure,
1110                         &closure->cif, 
1111                         fun,
1112                         (void*) this);
1113
1114   self->ncode = (void *) closure;
1115   return self->ncode;
1116 }
1117
1118
1119 /* A _Jv_ResolvedMethod is what is put in the constant pool for a
1120  * MethodRef or InterfacemethodRef.  */
1121 static _Jv_ResolvedMethod*
1122 _Jv_BuildResolvedMethod (_Jv_Method* method,
1123                          jclass      klass,
1124                          jboolean staticp,
1125                          jint vtable_index)
1126 {
1127   int arg_count = count_arguments (method->signature, staticp);
1128
1129   _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
1130     _Jv_AllocBytesChecked (sizeof (_Jv_ResolvedMethod)
1131                            + arg_count*sizeof (ffi_type*));
1132
1133   result->stack_item_count
1134     = init_cif (method->signature,
1135                 arg_count,
1136                 staticp,
1137                 &result->cif,
1138                 &result->arg_types[0],
1139                 NULL);
1140
1141   result->vtable_index        = vtable_index;
1142   result->method              = method;
1143   result->klass               = klass;
1144
1145   return result;
1146 }
1147
1148
1149 static void
1150 throw_class_format_error (jstring msg)
1151 {
1152   if (msg == 0)
1153     JvThrow (new java::lang::ClassFormatError);
1154   else
1155     JvThrow (new java::lang::ClassFormatError (msg));
1156 }
1157
1158 static void
1159 throw_class_format_error (char *msg)
1160 {
1161   throw_class_format_error (JvNewStringLatin1 (msg));
1162 }
1163
1164 static void
1165 throw_internal_error (char *msg)
1166 {
1167   JvThrow 
1168     (new java::lang::InternalError (JvNewStringLatin1 (msg)));
1169 }
1170
1171
1172 #endif /* INTERPRETER */