OSDN Git Service

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