OSDN Git Service

gcc/java
[pf3gnuchains/gcc-fork.git] / libjava / link.cc
1 // link.cc - Code for linking and resolving classes and pool entries.
2
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 /* Author: Kresten Krab Thorup <krab@gnu.org>  */
12
13 #include <config.h>
14 #include <platform.h>
15
16 #include <stdio.h>
17
18 #ifdef USE_LIBFFI
19 #include <ffi.h>
20 #endif
21
22 #include <java-interp.h>
23
24 #include <jvm.h>
25 #include <gcj/cni.h>
26 #include <string.h>
27 #include <limits.h>
28 #include <java-cpool.h>
29 #include <execution.h>
30 #include <java/lang/Class.h>
31 #include <java/lang/String.h>
32 #include <java/lang/StringBuffer.h>
33 #include <java/lang/Thread.h>
34 #include <java/lang/InternalError.h>
35 #include <java/lang/VirtualMachineError.h>
36 #include <java/lang/VerifyError.h>
37 #include <java/lang/NoSuchFieldError.h>
38 #include <java/lang/NoSuchMethodError.h>
39 #include <java/lang/ClassFormatError.h>
40 #include <java/lang/IllegalAccessError.h>
41 #include <java/lang/InternalError.h>
42 #include <java/lang/AbstractMethodError.h>
43 #include <java/lang/NoClassDefFoundError.h>
44 #include <java/lang/IncompatibleClassChangeError.h>
45 #include <java/lang/VerifyError.h>
46 #include <java/lang/VMClassLoader.h>
47 #include <java/lang/reflect/Modifier.h>
48 #include <java/security/CodeSource.h>
49
50 using namespace gcj;
51
52 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
53
54 template<typename T>
55 struct aligner
56 {
57   char c;
58   T field;
59 };
60
61 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
62
63 // This returns the alignment of a type as it would appear in a
64 // structure.  This can be different from the alignment of the type
65 // itself.  For instance on x86 double is 8-aligned but struct{double}
66 // is 4-aligned.
67 int
68 _Jv_Linker::get_alignment_from_class (jclass klass)
69 {
70   if (klass == JvPrimClass (byte))
71     return ALIGNOF (jbyte);
72   else if (klass == JvPrimClass (short))
73     return ALIGNOF (jshort);
74   else if (klass == JvPrimClass (int)) 
75     return ALIGNOF (jint);
76   else if (klass == JvPrimClass (long))
77     return ALIGNOF (jlong);
78   else if (klass == JvPrimClass (boolean))
79     return ALIGNOF (jboolean);
80   else if (klass == JvPrimClass (char))
81     return ALIGNOF (jchar);
82   else if (klass == JvPrimClass (float))
83     return ALIGNOF (jfloat);
84   else if (klass == JvPrimClass (double))
85     return ALIGNOF (jdouble);
86   else
87     return ALIGNOF (jobject);
88 }
89
90 void
91 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
92 {
93   if (! field->isResolved ())
94     {
95       _Jv_Utf8Const *sig = (_Jv_Utf8Const *) field->type;
96       jclass type = _Jv_FindClassFromSignature (sig->chars(), loader);
97       if (type == NULL)
98         throw new java::lang::NoClassDefFoundError(field->name->toString());
99       field->type = type;
100       field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
101     }
102 }
103
104 // A helper for find_field that knows how to recursively search
105 // superclasses and interfaces.
106 _Jv_Field *
107 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
108                                _Jv_Utf8Const *type_name, jclass type,
109                                jclass *declarer)
110 {
111   while (search)
112     {
113       // From 5.4.3.2.  First search class itself.
114       for (int i = 0; i < search->field_count; ++i)
115         {
116           _Jv_Field *field = &search->fields[i];
117           if (! _Jv_equalUtf8Consts (field->name, name))
118             continue;
119
120           // Checks for the odd situation where we were able to retrieve the
121           // field's class from signature but the resolution of the field itself
122           // failed which means a different class was resolved.
123           if (type != NULL)
124             {
125               try
126                 {
127                   resolve_field (field, search->loader);
128                 }
129               catch (java::lang::Throwable *exc)
130                 {
131                   java::lang::LinkageError *le = new java::lang::LinkageError
132                     (JvNewStringLatin1 
133                       ("field type mismatch with different loaders"));
134
135                   le->initCause(exc);
136
137                   throw le;
138                 }
139             }
140
141           // Note that we compare type names and not types.  This is
142           // bizarre, but we do it because we want to find a field
143           // (and terminate the search) if it has the correct
144           // descriptor -- but then later reject it if the class
145           // loader check results in different classes.  We can't just
146           // pass in the descriptor and check that way, because when
147           // the field is already resolved there is no easy way to
148           // find its descriptor again.
149           if ((field->isResolved ()
150                ? _Jv_equalUtf8Classnames (type_name, field->type->name)
151                : _Jv_equalUtf8Classnames (type_name,
152                                           (_Jv_Utf8Const *) field->type)))
153             {
154               *declarer = search;
155               return field;
156             }
157         }
158
159       // Next search direct interfaces.
160       for (int i = 0; i < search->interface_count; ++i)
161         {
162           _Jv_Field *result = find_field_helper (search->interfaces[i], name,
163                                                  type_name, type, declarer);
164           if (result)
165             return result;
166         }
167
168       // Now search superclass.
169       search = search->superclass;
170     }
171
172   return NULL;
173 }
174
175 bool
176 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
177 {
178   for (int i = 0; i < search->field_count; ++i)
179     {
180       _Jv_Field *field = &search->fields[i];
181       if (_Jv_equalUtf8Consts (field->name, field_name))
182         return true;
183     }
184   return false;
185 }
186
187 // Find a field.
188 // KLASS is the class that is requesting the field.
189 // OWNER is the class in which the field should be found.
190 // FIELD_TYPE_NAME is the type descriptor for the field.
191 // Fill FOUND_CLASS with the address of the class in which the field
192 // is actually declared.
193 // This function does the class loader type checks, and
194 // also access checks.  Returns the field, or throws an
195 // exception on error.
196 _Jv_Field *
197 _Jv_Linker::find_field (jclass klass, jclass owner,
198                         jclass *found_class,
199                         _Jv_Utf8Const *field_name,
200                         _Jv_Utf8Const *field_type_name)
201 {
202   // FIXME: this allocates a _Jv_Utf8Const each time.  We should make
203   // it cheaper.
204   // Note: This call will resolve the primitive type names ("Z", "B", ...) to
205   // their Java counterparts ("boolean", "byte", ...) if accessed via
206   // field_type->name later.  Using these variants of the type name is in turn
207   // important for the find_field_helper function.  However if the class
208   // resolution failed then we can only use the already given type name.
209   jclass field_type 
210     = _Jv_FindClassFromSignatureNoException (field_type_name->chars(),
211                                              klass->loader);
212
213   _Jv_Field *the_field
214     = find_field_helper (owner, field_name,
215                          (field_type
216                            ? field_type->name :
217                              field_type_name ),
218                            field_type, found_class);
219
220   if (the_field == 0)
221     {
222       java::lang::StringBuffer *sb = new java::lang::StringBuffer();
223       sb->append(JvNewStringLatin1("field "));
224       sb->append(owner->getName());
225       sb->append(JvNewStringLatin1("."));
226       sb->append(_Jv_NewStringUTF(field_name->chars()));
227       sb->append(JvNewStringLatin1(" was not found."));
228       throw new java::lang::NoSuchFieldError (sb->toString());
229     }
230
231   // Accept it when the field's class could not be resolved.
232   if (field_type == NULL)
233     // Silently ignore that we were not able to retrieve the type to make it
234     // possible to run code which does not access this field.
235     return the_field;
236
237   if (_Jv_CheckAccess (klass, *found_class, the_field->flags))
238     {
239       // Note that the field returned by find_field_helper is always
240       // resolved.  There's no point checking class loaders here,
241       // since we already did the work to look up all the types.
242       // FIXME: being lazy here would be nice.
243       if (the_field->type != field_type)
244         throw new java::lang::LinkageError
245           (JvNewStringLatin1 
246            ("field type mismatch with different loaders"));
247     }
248   else
249     {
250       java::lang::StringBuffer *sb
251         = new java::lang::StringBuffer ();
252       sb->append(klass->getName());
253       sb->append(JvNewStringLatin1(": "));
254       sb->append((*found_class)->getName());
255       sb->append(JvNewStringLatin1("."));
256       sb->append(_Jv_NewStringUtf8Const (field_name));
257       throw new java::lang::IllegalAccessError(sb->toString());
258     }
259
260   return the_field;
261 }
262
263 _Jv_word
264 _Jv_Linker::resolve_pool_entry (jclass klass, int index, bool lazy)
265 {
266   using namespace java::lang::reflect;
267
268   _Jv_Constants *pool = &klass->constants;
269
270   if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
271     return pool->data[index];
272
273   switch (pool->tags[index])
274     {
275     case JV_CONSTANT_Class:
276       {
277         _Jv_Utf8Const *name = pool->data[index].utf8;
278
279         jclass found;
280         if (name->first() == '[')
281           found = _Jv_FindClassFromSignatureNoException (name->chars(),
282                                                          klass->loader);
283         else
284           found = _Jv_FindClassNoException (name, klass->loader);
285
286         // If the class could not be loaded a phantom class is created. Any
287         // function that deals with such a class but cannot do something useful
288         // with it should just throw a NoClassDefFoundError with the class'
289         // name.
290         if (! found)
291           if (lazy)
292             {
293               found = _Jv_NewClass(name, NULL, NULL);
294               found->state = JV_STATE_PHANTOM;
295               pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
296               pool->data[index].clazz = found;
297               break;
298             }
299           else
300             throw new java::lang::NoClassDefFoundError (name->toString());
301
302         // Check accessibility, but first strip array types as
303         // _Jv_ClassNameSamePackage can't handle arrays.
304         jclass check;
305         for (check = found;
306              check && check->isArray();
307              check = check->getComponentType())
308           ;
309         if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
310             || (_Jv_ClassNameSamePackage (check->name,
311                                           klass->name)))
312           {
313             pool->data[index].clazz = found;
314             pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
315           }
316         else
317           {
318             java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
319             sb->append(klass->getName());
320             sb->append(JvNewStringLatin1(" can't access class "));
321             sb->append(found->getName());
322             throw new java::lang::IllegalAccessError(sb->toString());
323           }
324       }
325       break;
326
327     case JV_CONSTANT_String:
328       {
329         jstring str;
330         str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
331         pool->data[index].o = str;
332         pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
333       }
334       break;
335
336     case JV_CONSTANT_Fieldref:
337       {
338         _Jv_ushort class_index, name_and_type_index;
339         _Jv_loadIndexes (&pool->data[index],
340                          class_index,
341                          name_and_type_index);
342         jclass owner = (resolve_pool_entry (klass, class_index, true)).clazz;
343
344         // If a phantom class was resolved our field reference is
345         // unusable because of the missing class.
346         if (owner->state == JV_STATE_PHANTOM)
347           throw new java::lang::NoClassDefFoundError(owner->getName());
348
349         if (owner != klass)
350           _Jv_InitClass (owner);
351
352         _Jv_ushort name_index, type_index;
353         _Jv_loadIndexes (&pool->data[name_and_type_index],
354                          name_index,
355                          type_index);
356
357         _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
358         _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
359
360         jclass found_class = 0;
361         _Jv_Field *the_field = find_field (klass, owner, 
362                                            &found_class,
363                                            field_name,
364                                            field_type_name);
365         if (owner != found_class)
366           _Jv_InitClass (found_class);
367         pool->data[index].field = the_field;
368         pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
369       }
370       break;
371
372     case JV_CONSTANT_Methodref:
373     case JV_CONSTANT_InterfaceMethodref:
374       {
375         _Jv_ushort class_index, name_and_type_index;
376         _Jv_loadIndexes (&pool->data[index],
377                          class_index,
378                          name_and_type_index);
379         jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
380
381         if (owner != klass)
382           _Jv_InitClass (owner);
383
384         _Jv_ushort name_index, type_index;
385         _Jv_loadIndexes (&pool->data[name_and_type_index],
386                          name_index,
387                          type_index);
388
389         _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
390         _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
391
392         _Jv_Method *the_method = 0;
393         jclass found_class = 0;
394
395         // We're going to cache a pointer to the _Jv_Method object
396         // when we find it.  So, to ensure this doesn't get moved from
397         // beneath us, we first put all the needed Miranda methods
398         // into the target class.
399         wait_for_state (klass, JV_STATE_LOADED);
400
401         // First search the class itself.
402         the_method = search_method_in_class (owner, klass,
403                                              method_name, method_signature);
404
405         if (the_method != 0)
406           {
407             found_class = owner;
408             goto end_of_method_search;
409           }
410
411         // If we are resolving an interface method, search the
412         // interface's superinterfaces (A superinterface is not an
413         // interface's superclass - a superinterface is implemented by
414         // the interface).
415         if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
416           {
417             _Jv_ifaces ifaces;
418             ifaces.count = 0;
419             ifaces.len = 4;
420             ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
421                                                  * sizeof (jclass *));
422
423             get_interfaces (owner, &ifaces);
424
425             for (int i = 0; i < ifaces.count; i++)
426               {
427                 jclass cls = ifaces.list[i];
428                 the_method = search_method_in_class (cls, klass, method_name, 
429                                                      method_signature);
430                 if (the_method != 0)
431                   {
432                     found_class = cls;
433                     break;
434                   }
435               }
436
437             _Jv_Free (ifaces.list);
438
439             if (the_method != 0)
440               goto end_of_method_search;
441           }
442
443         // Finally, search superclasses. 
444         for (jclass cls = owner->getSuperclass (); cls != 0; 
445              cls = cls->getSuperclass ())
446           {
447             the_method = search_method_in_class (cls, klass, method_name,
448                                                  method_signature);
449             if (the_method != 0)
450               {
451                 found_class = cls;
452                 break;
453               }
454           }
455
456       end_of_method_search:
457     
458         // FIXME: if (cls->loader != klass->loader), then we
459         // must actually check that the types of arguments
460         // correspond.  That is, for each argument type, and
461         // the return type, doing _Jv_FindClassFromSignature
462         // with either loader should produce the same result,
463         // i.e., exactly the same jclass object. JVMS 5.4.3.3    
464     
465         if (the_method == 0)
466           {
467             java::lang::StringBuffer *sb = new java::lang::StringBuffer();
468             sb->append(JvNewStringLatin1("method "));
469             sb->append(owner->getName());
470             sb->append(JvNewStringLatin1("."));
471             sb->append(_Jv_NewStringUTF(method_name->chars()));
472             sb->append(JvNewStringLatin1(" with signature "));
473             sb->append(_Jv_NewStringUTF(method_signature->chars()));
474             sb->append(JvNewStringLatin1(" was not found."));
475             throw new java::lang::NoSuchMethodError (sb->toString());
476           }
477       
478         int vtable_index = -1;
479         if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
480           vtable_index = (jshort)the_method->index;
481
482         pool->data[index].rmethod
483           = klass->engine->resolve_method(the_method,
484                                           found_class,
485                                           ((the_method->accflags
486                                             & Modifier::STATIC) != 0),
487                                           vtable_index);
488         pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
489       }
490       break;
491     }
492   return pool->data[index];
493 }
494
495 // This function is used to lazily locate superclasses and
496 // superinterfaces.  This must be called with the class lock held.
497 void
498 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
499 {
500   jclass ret = *classref;
501
502   // If superclass looks like a constant pool entry, resolve it now.
503   if (ret && (uaddr) ret < (uaddr) klass->constants.size)
504     {
505       if (klass->state < JV_STATE_LINKED)
506         {
507           _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
508           ret = _Jv_FindClass (name, klass->loader);
509           if (! ret)
510             {
511               throw new java::lang::NoClassDefFoundError (name->toString());
512             }
513         }
514       else
515         ret = klass->constants.data[(uaddr) classref].clazz;
516       *classref = ret;
517     }
518 }
519
520 // Find a method declared in the cls that is referenced from klass and
521 // perform access checks.
522 _Jv_Method *
523 _Jv_Linker::search_method_in_class (jclass cls, jclass klass, 
524                                     _Jv_Utf8Const *method_name, 
525                                     _Jv_Utf8Const *method_signature)
526 {
527   using namespace java::lang::reflect;
528
529   for (int i = 0;  i < cls->method_count;  i++)
530     {
531       _Jv_Method *method = &cls->methods[i];
532       if (   (!_Jv_equalUtf8Consts (method->name,
533                                     method_name))
534           || (!_Jv_equalUtf8Consts (method->signature,
535                                     method_signature)))
536         continue;
537
538       if (_Jv_CheckAccess (klass, cls, method->accflags))
539         return method;
540       else
541         {
542           java::lang::StringBuffer *sb = new java::lang::StringBuffer();
543           sb->append(klass->getName());
544           sb->append(JvNewStringLatin1(": "));
545           sb->append(cls->getName());
546           sb->append(JvNewStringLatin1("."));
547           sb->append(_Jv_NewStringUTF(method_name->chars()));
548           sb->append(_Jv_NewStringUTF(method_signature->chars()));
549           throw new java::lang::IllegalAccessError (sb->toString());
550         }
551     }
552   return 0;
553 }
554
555
556 #define INITIAL_IOFFSETS_LEN 4
557 #define INITIAL_IFACES_LEN 4
558
559 static _Jv_IDispatchTable null_idt = {SHRT_MAX, 0, {}};
560
561 // Generate tables for constant-time assignment testing and interface
562 // method lookup. This implements the technique described by Per Bothner
563 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
564 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
565 void
566 _Jv_Linker::prepare_constant_time_tables (jclass klass)
567 {  
568   if (klass->isPrimitive () || klass->isInterface ())
569     return;
570
571   // Short-circuit in case we've been called already.
572   if ((klass->idt != NULL) || klass->depth != 0)
573     return;
574
575   // Calculate the class depth and ancestor table. The depth of a class 
576   // is how many "extends" it is removed from Object. Thus the depth of 
577   // java.lang.Object is 0, but the depth of java.io.FilterOutputStream 
578   // is 2. Depth is defined for all regular and array classes, but not 
579   // interfaces or primitive types.
580    
581   jclass klass0 = klass;
582   jboolean has_interfaces = 0;
583   while (klass0 != &java::lang::Object::class$)
584     {
585       has_interfaces += klass0->interface_count;
586       klass0 = klass0->superclass;
587       klass->depth++;
588     }
589
590   // We do class member testing in constant time by using a small table 
591   // of all the ancestor classes within each class. The first element is 
592   // a pointer to the current class, and the rest are pointers to the 
593   // classes ancestors, ordered from the current class down by decreasing 
594   // depth. We do not include java.lang.Object in the table of ancestors, 
595   // since it is redundant.  Note that the classes pointed to by
596   // 'ancestors' will always be reachable by other paths.
597
598   klass->ancestors = (jclass *) _Jv_AllocBytes (klass->depth
599                                                 * sizeof (jclass));
600   klass0 = klass;
601   for (int index = 0; index < klass->depth; index++)
602     {
603       klass->ancestors[index] = klass0;
604       klass0 = klass0->superclass;
605     }
606
607   if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
608     return;
609
610   // Optimization: If class implements no interfaces, use a common
611   // predefined interface table.
612   if (!has_interfaces)
613     {
614       klass->idt = &null_idt;
615       return;
616     }
617
618   _Jv_ifaces ifaces;
619   ifaces.count = 0;
620   ifaces.len = INITIAL_IFACES_LEN;
621   ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
622
623   int itable_size = get_interfaces (klass, &ifaces);
624
625   if (ifaces.count > 0)
626     {
627       // The classes pointed to by the itable will always be reachable
628       // via other paths.
629       int idt_bytes = sizeof (_Jv_IDispatchTable) + (itable_size 
630                                                      * sizeof (void *));
631       klass->idt = (_Jv_IDispatchTable *) _Jv_AllocBytes (idt_bytes);
632       klass->idt->itable_length = itable_size;
633
634       jshort *itable_offsets = 
635         (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
636
637       generate_itable (klass, &ifaces, itable_offsets);
638
639       jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
640                                        ifaces.count);
641
642       for (int i = 0; i < ifaces.count; i++)
643         {
644           ifaces.list[i]->ioffsets[cls_iindex] = itable_offsets[i];
645         }
646
647       klass->idt->iindex = cls_iindex;      
648
649       _Jv_Free (ifaces.list);
650       _Jv_Free (itable_offsets);
651     }
652   else 
653     {
654       klass->idt->iindex = SHRT_MAX;
655     }
656 }
657
658 // Return index of item in list, or -1 if item is not present.
659 inline jshort
660 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
661 {
662   for (int i=0; i < list_len; i++)
663     {
664       if (list[i] == item)
665         return i;
666     }
667   return -1;
668 }
669
670 // Find all unique interfaces directly or indirectly implemented by klass.
671 // Returns the size of the interface dispatch table (itable) for klass, which 
672 // is the number of unique interfaces plus the total number of methods that 
673 // those interfaces declare. May extend ifaces if required.
674 jshort
675 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
676 {
677   jshort result = 0;
678   
679   for (int i = 0; i < klass->interface_count; i++)
680     {
681       jclass iface = klass->interfaces[i];
682
683       /* Make sure interface is linked.  */
684       wait_for_state(iface, JV_STATE_LINKED);
685
686       if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
687         {
688           if (ifaces->count + 1 >= ifaces->len)
689             {
690               /* Resize ifaces list */
691               ifaces->len = ifaces->len * 2;
692               ifaces->list
693                 = (jclass *) _Jv_Realloc (ifaces->list,
694                                           ifaces->len * sizeof(jclass));
695             }
696           ifaces->list[ifaces->count] = iface;
697           ifaces->count++;
698
699           result += get_interfaces (klass->interfaces[i], ifaces);
700         }
701     }
702
703   if (klass->isInterface())
704     {
705       // We want to add 1 plus the number of interface methods here.
706       // But, we take special care to skip <clinit>.
707       ++result;
708       for (int i = 0; i < klass->method_count; ++i)
709         {
710           if (klass->methods[i].name->first() != '<')
711             ++result;
712         }
713     }
714   else if (klass->superclass)
715     result += get_interfaces (klass->superclass, ifaces);
716   return result;
717 }
718
719 // Fill out itable in klass, resolving method declarations in each ifaces.
720 // itable_offsets is filled out with the position of each iface in itable,
721 // such that itable[itable_offsets[n]] == ifaces.list[n].
722 void
723 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
724                                jshort *itable_offsets)
725 {
726   void **itable = klass->idt->itable;
727   jshort itable_pos = 0;
728
729   for (int i = 0; i < ifaces->count; i++)
730     { 
731       jclass iface = ifaces->list[i];
732       itable_offsets[i] = itable_pos;
733       itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
734
735       /* Create ioffsets table for iface */
736       if (iface->ioffsets == NULL)
737         {
738           // The first element of ioffsets is its length (itself included).
739           jshort *ioffsets = (jshort *) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
740                                                         * sizeof (jshort));
741           ioffsets[0] = INITIAL_IOFFSETS_LEN;
742           for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
743             ioffsets[i] = -1;
744
745           iface->ioffsets = ioffsets;
746         }
747     }
748 }
749
750 // Format method name for use in error messages.
751 jstring
752 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
753                      jclass derived)
754 {
755   using namespace java::lang;
756   StringBuffer *buf = new StringBuffer (klass->name->toString());
757   buf->append (jchar ('.'));
758   buf->append (meth->name->toString());
759   buf->append ((jchar) ' ');
760   buf->append (meth->signature->toString());
761   if (derived)
762     {
763       buf->append(JvNewStringLatin1(" in "));
764       buf->append(derived->name->toString());
765     }
766   return buf->toString();
767 }
768
769 void
770 _Jv_ThrowNoSuchMethodError ()
771 {
772   throw new java::lang::NoSuchMethodError;
773 }
774
775 #ifdef USE_LIBFFI
776 // A function whose invocation is prepared using libffi. It gets called
777 // whenever a static method of a missing class is invoked. The data argument
778 // holds a reference to a String denoting the missing class.
779 // The prepared function call is stored in a class' atable.
780 void
781 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif *,
782                                         void *,
783                                         void **,
784                                         void *data)
785 {
786   throw new java::lang::NoClassDefFoundError(
787     _Jv_NewStringUtf8Const((_Jv_Utf8Const *) data));
788 }
789 #else
790 // A variant of the NoClassDefFoundError throwing method that can
791 // be used without libffi.
792 void
793 _Jv_ThrowNoClassDefFoundError()
794 {
795   throw new java::lang::NoClassDefFoundError();
796 }
797 #endif
798
799 // Throw a NoSuchFieldError.  Called by compiler-generated code when
800 // an otable entry is zero.  OTABLE_INDEX is the index in the caller's
801 // otable that refers to the missing field.  This index may be used to
802 // print diagnostic information about the field.
803 void
804 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
805 {
806   throw new java::lang::NoSuchFieldError;
807 }
808
809 // This is put in empty vtable slots.
810 void
811 _Jv_ThrowAbstractMethodError ()
812 {
813   throw new java::lang::AbstractMethodError();
814 }
815
816 // Each superinterface of a class (i.e. each interface that the class
817 // directly or indirectly implements) has a corresponding "Partial
818 // Interface Dispatch Table" whose size is (number of methods + 1) words.
819 // The first word is a pointer to the interface (i.e. the java.lang.Class
820 // instance for that interface).  The remaining words are pointers to the
821 // actual methods that implement the methods declared in the interface,
822 // in order of declaration.
823 //
824 // Append partial interface dispatch table for "iface" to "itable", at
825 // position itable_pos.
826 // Returns the offset at which the next partial ITable should be appended.
827 jshort
828 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
829                                    void **itable, jshort pos)
830 {
831   using namespace java::lang::reflect;
832
833   itable[pos++] = (void *) iface;
834   _Jv_Method *meth;
835   
836   for (int j=0; j < iface->method_count; j++)
837     {
838       // Skip '<clinit>' here.
839       if (iface->methods[j].name->first() == '<')
840         continue;
841
842       meth = NULL;
843       for (jclass cl = klass; cl; cl = cl->getSuperclass())
844         {
845           meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
846                                      iface->methods[j].signature);
847                  
848           if (meth)
849             break;
850         }
851
852       if (meth)
853         {
854           if ((meth->accflags & Modifier::STATIC) != 0)
855             throw new java::lang::IncompatibleClassChangeError
856               (_Jv_GetMethodString (klass, meth));
857           if ((meth->accflags & Modifier::PUBLIC) == 0)
858             throw new java::lang::IllegalAccessError
859               (_Jv_GetMethodString (klass, meth));
860
861           if ((meth->accflags & Modifier::ABSTRACT) != 0)
862             itable[pos] = (void *) &_Jv_ThrowAbstractMethodError;
863           else
864             itable[pos] = meth->ncode;
865         }
866       else
867         {
868           // The method doesn't exist in klass. Binary compatibility rules
869           // permit this, so we delay the error until runtime using a pointer
870           // to a method which throws an exception.
871           itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
872         }
873       pos++;
874     }
875     
876   return pos;
877 }
878
879 static _Jv_Mutex_t iindex_mutex;
880 static bool iindex_mutex_initialized = false;
881
882 // We need to find the correct offset in the Class Interface Dispatch 
883 // Table for a given interface. Once we have that, invoking an interface 
884 // method just requires combining the Method's index in the interface 
885 // (known at compile time) to get the correct method.  Doing a type test 
886 // (cast or instanceof) is the same problem: Once we have a possible Partial 
887 // Interface Dispatch Table, we just compare the first element to see if it 
888 // matches the desired interface. So how can we find the correct offset?  
889 // Our solution is to keep a vector of candiate offsets in each interface 
890 // (ioffsets), and in each class we have an index (idt->iindex) used to
891 // select the correct offset from ioffsets.
892 //
893 // Calculate and return iindex for a new class. 
894 // ifaces is a vector of num interfaces that the class implements.
895 // offsets[j] is the offset in the interface dispatch table for the
896 // interface corresponding to ifaces[j].
897 // May extend the interface ioffsets if required.
898 jshort
899 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
900 {
901   int i;
902   int j;
903   
904   // Acquire a global lock to prevent itable corruption in case of multiple 
905   // classes that implement an intersecting set of interfaces being linked
906   // simultaneously. We can assume that the mutex will be initialized
907   // single-threaded.
908   if (! iindex_mutex_initialized)
909     {
910       _Jv_MutexInit (&iindex_mutex);
911       iindex_mutex_initialized = true;
912     }
913   
914   _Jv_MutexLock (&iindex_mutex);
915   
916   for (i=1;; i++)  /* each potential position in ioffsets */
917     {
918       for (j=0;; j++)  /* each iface */
919         {
920           if (j >= num)
921             goto found;
922           if (i >= ifaces[j]->ioffsets[0])
923             continue;
924           int ioffset = ifaces[j]->ioffsets[i];
925           /* We can potentially share this position with another class. */
926           if (ioffset >= 0 && ioffset != offsets[j])
927             break; /* Nope. Try next i. */        
928         }
929     }
930   found:
931   for (j = 0; j < num; j++)
932     {
933       int len = ifaces[j]->ioffsets[0];
934       if (i >= len) 
935         {
936           // Resize ioffsets.
937           int newlen = 2 * len;
938           if (i >= newlen)
939             newlen = i + 3;
940
941           jshort *old_ioffsets = ifaces[j]->ioffsets;
942           jshort *new_ioffsets = (jshort *) _Jv_AllocBytes (newlen
943                                                             * sizeof(jshort));
944           memcpy (&new_ioffsets[1], &old_ioffsets[1],
945                   (len - 1) * sizeof (jshort));
946           new_ioffsets[0] = newlen;
947
948           while (len < newlen)
949             new_ioffsets[len++] = -1;
950           
951           ifaces[j]->ioffsets = new_ioffsets;
952         }
953       ifaces[j]->ioffsets[i] = offsets[j];
954     }
955
956   _Jv_MutexUnlock (&iindex_mutex);
957
958   return i;
959 }
960
961 #ifdef USE_LIBFFI
962 // We use a structure of this type to store the closure that
963 // represents a missing method.
964 struct method_closure
965 {
966   // This field must come first, since the address of this field will
967   // be the same as the address of the overall structure.  This is due
968   // to disabling interior pointers in the GC.
969   ffi_closure closure;
970   ffi_cif cif;
971   ffi_type *arg_types[1];
972 };
973
974 void *
975 _Jv_Linker::create_error_method (_Jv_Utf8Const *class_name)
976 {
977   method_closure *closure
978     = (method_closure *) _Jv_AllocBytes(sizeof (method_closure));
979
980   closure->arg_types[0] = &ffi_type_void;
981
982   // Initializes the cif and the closure.  If that worked the closure
983   // is returned and can be used as a function pointer in a class'
984   // atable.
985   if (   ffi_prep_cif (&closure->cif,
986                        FFI_DEFAULT_ABI,
987                        1,
988                        &ffi_type_void,
989                        closure->arg_types) == FFI_OK
990       && ffi_prep_closure (&closure->closure,
991                            &closure->cif,
992                            _Jv_ThrowNoClassDefFoundErrorTrampoline,
993                            class_name) == FFI_OK)
994     return &closure->closure;
995   else
996     {
997       java::lang::StringBuffer *buffer = new java::lang::StringBuffer();
998       buffer->append(JvNewStringLatin1("Error setting up FFI closure"
999                                        " for static method of"
1000                                        " missing class: "));
1001       buffer->append (_Jv_NewStringUtf8Const(class_name));
1002       throw new java::lang::InternalError(buffer->toString());
1003     }
1004 }
1005 #else
1006 void *
1007 _Jv_Linker::create_error_method (_Jv_Utf8Const *)
1008 {
1009   // Codepath for platforms which do not support (or want) libffi.
1010   // You have to accept that it is impossible to provide the name
1011   // of the missing class then.
1012   return (void *) _Jv_ThrowNoClassDefFoundError;
1013 }
1014 #endif // USE_LIBFFI
1015
1016 // Functions for indirect dispatch (symbolic virtual binding) support.
1017
1018 // There are three tables, atable otable and itable.  atable is an
1019 // array of addresses, and otable is an array of offsets, and these
1020 // are used for static and virtual members respectively.  itable is an
1021 // array of pairs {address, index} where each address is a pointer to
1022 // an interface.
1023
1024 // {a,o,i}table_syms is an array of _Jv_MethodSymbols.  Each such
1025 // symbol is a tuple of {classname, member name, signature}.
1026
1027 // Set this to true to enable debugging of indirect dispatch tables/linking.
1028 static bool debug_link = false;
1029
1030 // link_symbol_table() scans these two arrays and fills in the
1031 // corresponding atable and otable with the addresses of static
1032 // members and the offsets of virtual members.
1033
1034 // The offset (in bytes) for each resolved method or field is placed
1035 // at the corresponding position in the virtual method offset table
1036 // (klass->otable). 
1037
1038 // The same otable and atable may be shared by many classes.
1039
1040 // This must be called while holding the class lock.
1041
1042 void
1043 _Jv_Linker::link_symbol_table (jclass klass)
1044 {
1045   int index = 0;
1046   _Jv_MethodSymbol sym;
1047   if (klass->otable == NULL
1048       || klass->otable->state != 0)
1049     goto atable;
1050    
1051   klass->otable->state = 1;
1052
1053   if (debug_link)
1054     fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
1055   for (index = 0;
1056        (sym = klass->otable_syms[index]).class_name != NULL;
1057        ++index)
1058     {
1059       jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1060       _Jv_Method *meth = NULL;            
1061
1062       _Jv_Utf8Const *signature = sym.signature;
1063
1064       if (target_class == NULL)
1065         throw new java::lang::NoClassDefFoundError 
1066           (_Jv_NewStringUTF (sym.class_name->chars()));
1067
1068       // We're looking for a field or a method, and we can tell
1069       // which is needed by looking at the signature.
1070       if (signature->first() == '(' && signature->len() >= 2)
1071         {
1072           // Looks like someone is trying to invoke an interface method
1073           if (target_class->isInterface())
1074             {
1075               using namespace java::lang;
1076               StringBuffer *sb = new StringBuffer();
1077               sb->append(JvNewStringLatin1("found interface "));
1078               sb->append(target_class->getName());
1079               sb->append(JvNewStringLatin1(" when searching for a class"));
1080               throw new VerifyError(sb->toString());
1081             }
1082
1083           // If the target class does not have a vtable_method_count yet, 
1084           // then we can't tell the offsets for its methods, so we must lay 
1085           // it out now.
1086           wait_for_state(target_class, JV_STATE_PREPARED);
1087
1088           meth = _Jv_LookupDeclaredMethod(target_class, sym.name, 
1089                                           sym.signature);
1090
1091           // Every class has a throwNoSuchMethodErrorIndex method that
1092           // it inherits from java.lang.Object.  Find its vtable
1093           // offset.
1094           static int throwNoSuchMethodErrorIndex;
1095           if (throwNoSuchMethodErrorIndex == 0)
1096             {
1097               Utf8Const* name 
1098                 = _Jv_makeUtf8Const ("throwNoSuchMethodError", 
1099                                      strlen ("throwNoSuchMethodError"));
1100               _Jv_Method* meth
1101                 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$, 
1102                                             name, gcj::void_signature);
1103               throwNoSuchMethodErrorIndex 
1104                 = _Jv_VTable::idx_to_offset (meth->index);
1105             }
1106           
1107           // If we don't find a nonstatic method, insert the
1108           // vtable index of Object.throwNoSuchMethodError().
1109           // This defers the missing method error until an attempt
1110           // is made to execute it.       
1111           {
1112             int offset;
1113             
1114             if (meth != NULL)
1115               offset = _Jv_VTable::idx_to_offset (meth->index);
1116             else
1117               offset = throwNoSuchMethodErrorIndex;                 
1118             
1119             if (offset == -1)
1120               JvFail ("Bad method index");
1121             JvAssert (meth->index < target_class->vtable_method_count);
1122             
1123             klass->otable->offsets[index] = offset;
1124           }
1125
1126           if (debug_link)
1127             fprintf (stderr, "  offsets[%d] = %d (class %s@%p : %s(%s))\n",
1128                      (int)index,
1129                      (int)klass->otable->offsets[index],
1130                      (const char*)target_class->name->chars(),
1131                      target_class,
1132                      (const char*)sym.name->chars(),
1133                      (const char*)signature->chars());
1134           continue;
1135         }
1136
1137       // Try fields.
1138       {
1139         wait_for_state(target_class, JV_STATE_PREPARED);
1140         jclass found_class;
1141         _Jv_Field *the_field = NULL;
1142         try
1143           {
1144             the_field = find_field (klass, target_class, &found_class,
1145                                     sym.name, sym.signature);
1146             if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1147               throw new java::lang::IncompatibleClassChangeError;
1148             else
1149               klass->otable->offsets[index] = the_field->u.boffset;
1150           }
1151         catch (java::lang::NoSuchFieldError *err)
1152           {
1153             klass->otable->offsets[index] = 0;
1154           }
1155       }
1156     }
1157
1158  atable:
1159   if (klass->atable == NULL || klass->atable->state != 0)
1160     goto itable;
1161
1162   klass->atable->state = 1;
1163
1164   for (index = 0;
1165        (sym = klass->atable_syms[index]).class_name != NULL;
1166        ++index)
1167     {
1168       jclass target_class =
1169         _Jv_FindClassNoException (sym.class_name, klass->loader);
1170
1171       _Jv_Method *meth = NULL;            
1172       _Jv_Utf8Const *signature = sym.signature;
1173
1174       // ??? Setting this pointer to null will at least get us a
1175       // NullPointerException
1176       klass->atable->addresses[index] = NULL;
1177
1178       // If the target class is missing we prepare a function call
1179       // that throws a NoClassDefFoundError and store the address of
1180       // that newly prepare method in the atable. The user can run
1181       // code in classes where the missing class is part of the
1182       // execution environment as long as it is never referenced.
1183       if (target_class == NULL)
1184         klass->atable->addresses[index] = create_error_method(sym.class_name);
1185       // We're looking for a static field or a static method, and we
1186       // can tell which is needed by looking at the signature.
1187       else if (signature->first() == '(' && signature->len() >= 2)
1188         {
1189           // If the target class does not have a vtable_method_count yet, 
1190           // then we can't tell the offsets for its methods, so we must lay 
1191           // it out now.
1192           wait_for_state (target_class, JV_STATE_PREPARED);
1193
1194           // Interface methods cannot have bodies.
1195           if (target_class->isInterface())
1196             {
1197               using namespace java::lang;
1198               StringBuffer *sb = new StringBuffer();
1199               sb->append(JvNewStringLatin1("class "));
1200               sb->append(target_class->getName());
1201               sb->append(JvNewStringLatin1(" is an interface: "
1202                                            "class expected"));
1203               throw new VerifyError(sb->toString());
1204             }
1205
1206           meth = _Jv_LookupDeclaredMethod(target_class, sym.name, 
1207                                           sym.signature);
1208
1209           if (meth != NULL)
1210             {
1211               if (meth->ncode) // Maybe abstract?
1212                 {
1213                   klass->atable->addresses[index] = meth->ncode;
1214                   if (debug_link)
1215                     fprintf (stderr, "  addresses[%d] = %p (class %s@%p : %s(%s))\n",
1216                              index,
1217                              &klass->atable->addresses[index],
1218                              (const char*)target_class->name->chars(),
1219                              klass,
1220                              (const char*)sym.name->chars(),
1221                              (const char*)signature->chars());
1222                 }
1223             }
1224           else
1225             klass->atable->addresses[index]
1226               = create_error_method(sym.class_name);
1227
1228           continue;
1229         }
1230
1231       // Try fields only if the target class exists.
1232       if (target_class != NULL)
1233       {
1234         wait_for_state(target_class, JV_STATE_PREPARED);
1235         jclass found_class;
1236         _Jv_Field *the_field = find_field (klass, target_class, &found_class,
1237                                            sym.name, sym.signature);
1238         if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1239           klass->atable->addresses[index] = the_field->u.addr;
1240         else
1241           throw new java::lang::IncompatibleClassChangeError;
1242       }
1243     }
1244
1245  itable:
1246   if (klass->itable == NULL
1247       || klass->itable->state != 0)
1248     return;
1249
1250   klass->itable->state = 1;
1251
1252   for (index = 0;
1253        (sym = klass->itable_syms[index]).class_name != NULL; 
1254        ++index)
1255     {
1256       jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1257       _Jv_Utf8Const *signature = sym.signature;
1258
1259       jclass cls;
1260       int i;
1261
1262       wait_for_state(target_class, JV_STATE_LOADED);
1263       bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1264                                            sym.name, sym.signature);
1265
1266       if (found)
1267         {
1268           klass->itable->addresses[index * 2] = cls;
1269           klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1270           if (debug_link)
1271             {
1272               fprintf (stderr, "  interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1273                        index,
1274                        klass->itable->addresses[index * 2],
1275                        (const char*)cls->name->chars(),
1276                        cls,
1277                        (const char*)sym.name->chars(),
1278                        (const char*)signature->chars());
1279               fprintf (stderr, "            [%d] = offset %d\n",
1280                        index + 1,
1281                        (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1282             }
1283
1284         }
1285       else
1286         throw new java::lang::IncompatibleClassChangeError;
1287     }
1288
1289 }
1290
1291 // For each catch_record in the list of caught classes, fill in the
1292 // address field.
1293 void 
1294 _Jv_Linker::link_exception_table (jclass self)
1295 {
1296   struct _Jv_CatchClass *catch_record = self->catch_classes;
1297   if (!catch_record || catch_record->classname)
1298     return;  
1299   catch_record++;
1300   while (catch_record->classname)
1301     {
1302       try
1303         {
1304           jclass target_class
1305             = _Jv_FindClass (catch_record->classname,  
1306                              self->getClassLoaderInternal ());
1307           *catch_record->address = target_class;
1308         }
1309       catch (::java::lang::Throwable *t)
1310         {
1311           // FIXME: We need to do something better here.
1312           *catch_record->address = 0;
1313         }
1314       catch_record++;
1315     }
1316   self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1317 }
1318   
1319 // Set itable method indexes for members of interface IFACE.
1320 void
1321 _Jv_Linker::layout_interface_methods (jclass iface)
1322 {
1323   if (! iface->isInterface())
1324     return;
1325
1326   // itable indexes start at 1. 
1327   // FIXME: Static initalizers currently get a NULL placeholder entry in the
1328   // itable so they are also assigned an index here.
1329   for (int i = 0; i < iface->method_count; i++)
1330     iface->methods[i].index = i + 1;
1331 }
1332
1333 // Prepare virtual method declarations in KLASS, and any superclasses
1334 // as required, by determining their vtable index, setting
1335 // method->index, and finally setting the class's vtable_method_count.
1336 // Must be called with the lock for KLASS held.
1337 void
1338 _Jv_Linker::layout_vtable_methods (jclass klass)
1339 {
1340   if (klass->vtable != NULL || klass->isInterface() 
1341       || klass->vtable_method_count != -1)
1342     return;
1343
1344   jclass superclass = klass->getSuperclass();
1345
1346   if (superclass != NULL && superclass->vtable_method_count == -1)
1347     {
1348       JvSynchronize sync (superclass);
1349       layout_vtable_methods (superclass);
1350     }
1351
1352   int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1353
1354   for (int i = 0; i < klass->method_count; ++i)
1355     {
1356       _Jv_Method *meth = &klass->methods[i];
1357       _Jv_Method *super_meth = NULL;
1358
1359       if (! _Jv_isVirtualMethod (meth))
1360         continue;
1361
1362       if (superclass != NULL)
1363         {
1364           jclass declarer;
1365           super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1366                                                  meth->signature, &declarer);
1367           // See if this method actually overrides the other method
1368           // we've found.
1369           if (super_meth)
1370             {
1371               if (! _Jv_isVirtualMethod (super_meth)
1372                   || ! _Jv_CheckAccess (klass, declarer,
1373                                         super_meth->accflags))
1374                 super_meth = NULL;
1375               else if ((super_meth->accflags
1376                         & java::lang::reflect::Modifier::FINAL) != 0)
1377                 {
1378                   using namespace java::lang;
1379                   StringBuffer *sb = new StringBuffer();
1380                   sb->append(JvNewStringLatin1("method "));
1381                   sb->append(_Jv_GetMethodString(klass, meth));
1382                   sb->append(JvNewStringLatin1(" overrides final method "));
1383                   sb->append(_Jv_GetMethodString(declarer, super_meth));
1384                   throw new VerifyError(sb->toString());
1385                 }
1386             }
1387         }
1388
1389       if (super_meth)
1390         meth->index = super_meth->index;
1391       else
1392         meth->index = index++;
1393     }
1394
1395   klass->vtable_method_count = index;
1396 }
1397
1398 // Set entries in VTABLE for virtual methods declared in KLASS.
1399 void
1400 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1401 {
1402   for (int i = klass->method_count - 1; i >= 0; i--)
1403     {
1404       using namespace java::lang::reflect;
1405
1406       _Jv_Method *meth = &klass->methods[i];
1407       if (meth->index == (_Jv_ushort) -1)
1408         continue;
1409       if ((meth->accflags & Modifier::ABSTRACT))
1410         // FIXME: it might be nice to have a libffi trampoline here,
1411         // so we could pass in the method name and other information.
1412         vtable->set_method(meth->index,
1413                            (void *) &_Jv_ThrowAbstractMethodError);
1414       else
1415         vtable->set_method(meth->index, meth->ncode);
1416     }
1417 }
1418
1419 // Allocate and lay out the virtual method table for KLASS.  This will
1420 // also cause vtables to be generated for any non-abstract
1421 // superclasses, and virtual method layout to occur for any abstract
1422 // superclasses.  Must be called with monitor lock for KLASS held.
1423 void
1424 _Jv_Linker::make_vtable (jclass klass)
1425 {
1426   using namespace java::lang::reflect;  
1427
1428   // If the vtable exists, or for interface classes, do nothing.  All
1429   // other classes, including abstract classes, need a vtable.
1430   if (klass->vtable != NULL || klass->isInterface())
1431     return;
1432
1433   // Ensure all the `ncode' entries are set.
1434   klass->engine->create_ncode(klass);
1435
1436   // Class must be laid out before we can create a vtable. 
1437   if (klass->vtable_method_count == -1)
1438     layout_vtable_methods (klass);
1439
1440   // Allocate the new vtable.
1441   _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1442   klass->vtable = vtable;
1443
1444   // Copy the vtable of the closest superclass.
1445   jclass superclass = klass->superclass;
1446   {
1447     JvSynchronize sync (superclass);
1448     make_vtable (superclass);
1449   }
1450   for (int i = 0; i < superclass->vtable_method_count; ++i)
1451     vtable->set_method (i, superclass->vtable->get_method (i));
1452
1453   // Set the class pointer and GC descriptor.
1454   vtable->clas = klass;
1455   vtable->gc_descr = _Jv_BuildGCDescr (klass);
1456
1457   // For each virtual declared in klass, set new vtable entry or
1458   // override an old one.
1459   set_vtable_entries (klass, vtable);
1460
1461   // Note that we don't check for abstract methods here.  We used to,
1462   // but there is a JVMS clarification that indicates that a check
1463   // here would be too eager.  And, a simple test case confirms this.
1464 }
1465
1466 // Lay out the class, allocating space for static fields and computing
1467 // offsets of instance fields.  The class lock must be held by the
1468 // caller.
1469 void
1470 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1471 {  
1472   if (klass->size_in_bytes != -1)
1473     return;
1474
1475   // Compute the alignment for this type by searching through the
1476   // superclasses and finding the maximum required alignment.  We
1477   // could consider caching this in the Class.
1478   int max_align = __alignof__ (java::lang::Object);
1479   jclass super = klass->getSuperclass();
1480   while (super != NULL)
1481     {
1482       // Ensure that our super has its super installed before
1483       // recursing.
1484       wait_for_state(super, JV_STATE_LOADING);
1485       ensure_fields_laid_out(super);
1486       int num = JvNumInstanceFields (super);
1487       _Jv_Field *field = JvGetFirstInstanceField (super);
1488       while (num > 0)
1489         {
1490           int field_align = get_alignment_from_class (field->type);
1491           if (field_align > max_align)
1492             max_align = field_align;
1493           ++field;
1494           --num;
1495         }
1496       super = super->getSuperclass();
1497     }
1498
1499   int instance_size;
1500   // This is the size of the 'static' non-reference fields.
1501   int non_reference_size = 0;
1502   // This is the size of the 'static' reference fields.  We count
1503   // these separately to make it simpler for the GC to scan them.
1504   int reference_size = 0;
1505
1506   // Although java.lang.Object is never interpreted, an interface can
1507   // have a null superclass.  Note that we have to lay out an
1508   // interface because it might have static fields.
1509   if (klass->superclass)
1510     instance_size = klass->superclass->size();
1511   else
1512     instance_size = java::lang::Object::class$.size();
1513
1514   for (int i = 0; i < klass->field_count; i++)
1515     {
1516       int field_size;
1517       int field_align;
1518
1519       _Jv_Field *field = &klass->fields[i];
1520
1521       if (! field->isRef ())
1522         {
1523           // It is safe to resolve the field here, since it's a
1524           // primitive class, which does not cause loading to happen.
1525           resolve_field (field, klass->loader);
1526
1527           field_size = field->type->size ();
1528           field_align = get_alignment_from_class (field->type);
1529         }
1530       else 
1531         {
1532           field_size = sizeof (jobject);
1533           field_align = __alignof__ (jobject);
1534         }
1535
1536       field->bsize = field_size;
1537
1538       if ((field->flags & java::lang::reflect::Modifier::STATIC))
1539         {
1540           if (field->u.addr == NULL)
1541             {
1542               // This computes an offset into a region we'll allocate
1543               // shortly, and then adds this offset to the start
1544               // address.
1545               if (field->isRef())
1546                 {
1547                   reference_size = ROUND (reference_size, field_align);
1548                   field->u.boffset = reference_size;
1549                   reference_size += field_size;
1550                 }
1551               else
1552                 {
1553                   non_reference_size = ROUND (non_reference_size, field_align);
1554                   field->u.boffset = non_reference_size;
1555                   non_reference_size += field_size;
1556                 }
1557             }
1558         }
1559       else
1560         {
1561           instance_size      = ROUND (instance_size, field_align);
1562           field->u.boffset   = instance_size;
1563           instance_size     += field_size;
1564           if (field_align > max_align)
1565             max_align = field_align;
1566         }
1567     }
1568
1569   if (reference_size != 0 || non_reference_size != 0)
1570     klass->engine->allocate_static_fields (klass, reference_size,
1571                                            non_reference_size);
1572
1573   // Set the instance size for the class.  Note that first we round it
1574   // to the alignment required for this object; this keeps us in sync
1575   // with our current ABI.
1576   instance_size = ROUND (instance_size, max_align);
1577   klass->size_in_bytes = instance_size;
1578 }
1579
1580 // This takes the class to state JV_STATE_LINKED.  The class lock must
1581 // be held when calling this.
1582 void
1583 _Jv_Linker::ensure_class_linked (jclass klass)
1584 {
1585   if (klass->state >= JV_STATE_LINKED)
1586     return;
1587
1588   int state = klass->state;
1589   try
1590     {
1591       // Short-circuit, so that mutually dependent classes are ok.
1592       klass->state = JV_STATE_LINKED;
1593
1594       _Jv_Constants *pool = &klass->constants;
1595
1596       // Compiled classes require that their class constants be
1597       // resolved here.  However, interpreted classes need their
1598       // constants to be resolved lazily.  If we resolve an
1599       // interpreted class' constants eagerly, we can end up with
1600       // spurious IllegalAccessErrors when the constant pool contains
1601       // a reference to a class we can't access.  This can validly
1602       // occur in an obscure case involving the InnerClasses
1603       // attribute.
1604       if (! _Jv_IsInterpretedClass (klass))
1605         {
1606           // Resolve class constants first, since other constant pool
1607           // entries may rely on these.
1608           for (int index = 1; index < pool->size; ++index)
1609             {
1610               if (pool->tags[index] == JV_CONSTANT_Class)
1611                 // Lazily resolve the entries.
1612                 resolve_pool_entry (klass, index, true);
1613             }
1614         }
1615
1616 #if 0  // Should be redundant now
1617       // If superclass looks like a constant pool entry,
1618       // resolve it now.
1619       if ((uaddr) klass->superclass < (uaddr) pool->size)
1620         klass->superclass = pool->data[(uaddr) klass->superclass].clazz;
1621
1622       // Likewise for interfaces.
1623       for (int i = 0; i < klass->interface_count; i++)
1624         {
1625           if ((uaddr) klass->interfaces[i] < (uaddr) pool->size)
1626             klass->interfaces[i]
1627               = pool->data[(uaddr) klass->interfaces[i]].clazz;
1628         }
1629 #endif
1630
1631       // Resolve the remaining constant pool entries.
1632       for (int index = 1; index < pool->size; ++index)
1633         {
1634           if (pool->tags[index] == JV_CONSTANT_String)
1635             {
1636               jstring str;
1637
1638               str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1639               pool->data[index].o = str;
1640               pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1641             }
1642         }
1643
1644       if (klass->engine->need_resolve_string_fields())
1645         {
1646           jfieldID f = JvGetFirstStaticField (klass);
1647           for (int n = JvNumStaticFields (klass); n > 0; --n)
1648             {
1649               int mod = f->getModifiers ();
1650               // If we have a static String field with a non-null initial
1651               // value, we know it points to a Utf8Const.
1652
1653               // Finds out whether we have to initialize a String without the
1654               // need to resolve the field.
1655               if ((f->isResolved()
1656                    ? (f->type == &java::lang::String::class$)
1657                    : _Jv_equalUtf8Classnames((_Jv_Utf8Const *) f->type,
1658                                              java::lang::String::class$.name))
1659                   && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1660                 {
1661                   jstring *strp = (jstring *) f->u.addr;
1662                   if (*strp)
1663                     *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1664                 }
1665               f = f->getNextField ();
1666             }
1667         }
1668
1669       klass->notifyAll ();
1670
1671       _Jv_PushClass (klass);
1672     }
1673   catch (java::lang::Throwable *t)
1674     {
1675       klass->state = state;
1676       throw t;
1677     }
1678 }
1679
1680 // This ensures that symbolic superclass and superinterface references
1681 // are resolved for the indicated class.  This must be called with the
1682 // class lock held.
1683 void
1684 _Jv_Linker::ensure_supers_installed (jclass klass)
1685 {
1686   resolve_class_ref (klass, &klass->superclass);
1687   // An interface won't have a superclass.
1688   if (klass->superclass)
1689     wait_for_state (klass->superclass, JV_STATE_LOADING);
1690
1691   for (int i = 0; i < klass->interface_count; ++i)
1692     {
1693       resolve_class_ref (klass, &klass->interfaces[i]);
1694       wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1695     }
1696 }
1697
1698 // This adds missing `Miranda methods' to a class.
1699 void
1700 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1701 {
1702   // Note that at this point, all our supers, and the supers of all
1703   // our superclasses and superinterfaces, will have been installed.
1704
1705   for (int i = 0; i < iface_class->interface_count; ++i)
1706     {
1707       jclass interface = iface_class->interfaces[i];
1708
1709       for (int j = 0; j < interface->method_count; ++j)
1710         {
1711           _Jv_Method *meth = &interface->methods[j];
1712           // Don't bother with <clinit>.
1713           if (meth->name->first() == '<')
1714             continue;
1715           _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1716                                                            meth->signature);
1717           if (! new_meth)
1718             {
1719               // We assume that such methods are very unlikely, so we
1720               // just reallocate the method array each time one is
1721               // found.  This greatly simplifies the searching --
1722               // otherwise we have to make sure that each such method
1723               // found is really unique among all superinterfaces.
1724               int new_count = base->method_count + 1;
1725               _Jv_Method *new_m
1726                 = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method)
1727                                                   * new_count);
1728               memcpy (new_m, base->methods,
1729                       sizeof (_Jv_Method) * base->method_count);
1730
1731               // Add new method.
1732               new_m[base->method_count] = *meth;
1733               new_m[base->method_count].index = (_Jv_ushort) -1;
1734               new_m[base->method_count].accflags
1735                 |= java::lang::reflect::Modifier::INVISIBLE;
1736
1737               base->methods = new_m;
1738               base->method_count = new_count;
1739             }
1740         }
1741
1742       wait_for_state (interface, JV_STATE_LOADED);
1743       add_miranda_methods (base, interface);
1744     }
1745 }
1746
1747 // This ensures that the class' method table is "complete".  This must
1748 // be called with the class lock held.
1749 void
1750 _Jv_Linker::ensure_method_table_complete (jclass klass)
1751 {
1752   if (klass->vtable != NULL)
1753     return;
1754
1755   // We need our superclass to have its own Miranda methods installed.
1756   if (! klass->isInterface())
1757     wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1758
1759   // A class might have so-called "Miranda methods".  This is a method
1760   // that is declared in an interface and not re-declared in an
1761   // abstract class.  Some compilers don't emit declarations for such
1762   // methods in the class; this will give us problems since we expect
1763   // a declaration for any method requiring a vtable entry.  We handle
1764   // this here by searching for such methods and constructing new
1765   // internal declarations for them.  Note that we do this
1766   // unconditionally, and not just for abstract classes, to correctly
1767   // account for cases where a class is modified to be concrete and
1768   // still incorrectly inherits an abstract method.
1769   int pre_count = klass->method_count;
1770   add_miranda_methods (klass, klass);
1771
1772   // Let the execution engine know that we've added methods.
1773   if (klass->method_count != pre_count)
1774     klass->engine->post_miranda_hook(klass);
1775 }
1776
1777 // Verify a class.  Must be called with class lock held.
1778 void
1779 _Jv_Linker::verify_class (jclass klass)
1780 {
1781   klass->engine->verify(klass);
1782 }
1783
1784 // Check the assertions contained in the type assertion table for KLASS.
1785 // This is the equivilent of bytecode verification for native, BC-ABI code.
1786 void
1787 _Jv_Linker::verify_type_assertions (jclass klass)
1788 {
1789   if (debug_link)
1790     fprintf (stderr, "Evaluating type assertions for %s:\n",
1791              klass->name->chars());
1792
1793   if (klass->assertion_table == NULL)
1794     return;
1795
1796   for (int i = 0;; i++)
1797     {
1798       int assertion_code = klass->assertion_table[i].assertion_code;
1799       _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1800       _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1801       
1802       if (assertion_code == JV_ASSERT_END_OF_TABLE)
1803         return;
1804       else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1805         {
1806           if (debug_link)
1807             {
1808               fprintf (stderr, "  code=%i, operand A=%s B=%s\n",
1809                        assertion_code, op1->chars(), op2->chars());
1810             }
1811         
1812           // The operands are class signatures. op1 is the source, 
1813           // op2 is the target.
1814           jclass cl1 = _Jv_FindClassFromSignature (op1->chars(), 
1815             klass->getClassLoaderInternal());
1816           jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1817             klass->getClassLoaderInternal());
1818             
1819           // If the class doesn't exist, ignore the assertion. An exception
1820           // will be thrown later if an attempt is made to actually 
1821           // instantiate the class.
1822           if (cl1 == NULL || cl2 == NULL)
1823             continue;
1824
1825           if (! _Jv_IsAssignableFromSlow (cl1, cl2))
1826             {
1827               jstring s = JvNewStringUTF ("Incompatible types: In class ");
1828               s = s->concat (klass->getName());
1829               s = s->concat (JvNewStringUTF (": "));
1830               s = s->concat (cl1->getName());
1831               s = s->concat (JvNewStringUTF (" is not assignable to "));
1832               s = s->concat (cl2->getName());
1833               throw new java::lang::VerifyError (s);
1834             }
1835         }
1836       else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1837         {
1838           // TODO: Implement this.
1839         }
1840       // Unknown assertion codes are ignored, for forwards-compatibility.
1841     }
1842 }
1843    
1844 void
1845 _Jv_Linker::print_class_loaded (jclass klass)
1846 {
1847   char *codesource = NULL;
1848   if (klass->protectionDomain != NULL)
1849     {
1850       java::security::CodeSource *cs
1851         = klass->protectionDomain->getCodeSource();
1852       if (cs != NULL)
1853         {
1854           jstring css = cs->toString();
1855           int len = JvGetStringUTFLength(css);
1856           codesource = (char *) _Jv_AllocBytes(len + 1);
1857           JvGetStringUTFRegion(css, 0, css->length(), codesource);
1858           codesource[len] = '\0';
1859         }
1860     }
1861   if (codesource == NULL)
1862     codesource = (char *) "<no code source>";
1863
1864   const char *abi;
1865   if (_Jv_IsInterpretedClass (klass))
1866     abi = "bytecode";
1867   else if (_Jv_IsBinaryCompatibilityABI (klass))
1868     abi = "BC-compiled";
1869   else
1870     abi = "pre-compiled";
1871
1872   fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1873            codesource);
1874 }
1875
1876 // FIXME: mention invariants and stuff.
1877 void
1878 _Jv_Linker::wait_for_state (jclass klass, int state)
1879 {
1880   if (klass->state >= state)
1881     return;
1882
1883   JvSynchronize sync (klass);
1884
1885   // This is similar to the strategy for class initialization.  If we
1886   // already hold the lock, just leave.
1887   java::lang::Thread *self = java::lang::Thread::currentThread();
1888   while (klass->state <= state
1889          && klass->thread 
1890          && klass->thread != self)
1891     klass->wait ();
1892
1893   java::lang::Thread *save = klass->thread;
1894   klass->thread = self;
1895
1896   // Print some debugging info if requested.  Interpreted classes are
1897   // handled in defineclass, so we only need to handle the two
1898   // pre-compiled cases here.
1899   if (gcj::verbose_class_flag
1900       && (klass->state == JV_STATE_COMPILED
1901           || klass->state == JV_STATE_PRELOADING)
1902       && ! _Jv_IsInterpretedClass (klass))
1903     print_class_loaded (klass);
1904
1905   try
1906     {
1907       if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
1908         {
1909           ensure_supers_installed (klass);
1910           klass->set_state(JV_STATE_LOADING);
1911         }
1912
1913       if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
1914         {
1915           ensure_method_table_complete (klass);
1916           klass->set_state(JV_STATE_LOADED);
1917         }
1918
1919       if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
1920         {
1921           ensure_fields_laid_out (klass);
1922           make_vtable (klass);
1923           layout_interface_methods (klass);
1924           prepare_constant_time_tables (klass);
1925           klass->set_state(JV_STATE_PREPARED);
1926         }
1927
1928       if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
1929         {
1930           if (gcj::verifyClasses)
1931             verify_class (klass);
1932
1933           ensure_class_linked (klass);
1934           link_exception_table (klass);
1935           link_symbol_table (klass);
1936           klass->set_state(JV_STATE_LINKED);
1937         }
1938     }
1939   catch (java::lang::Throwable *exc)
1940     {
1941       klass->thread = save;
1942       klass->set_state(JV_STATE_ERROR);
1943       throw exc;
1944     }
1945
1946   klass->thread = save;
1947
1948   if (klass->state == JV_STATE_ERROR)
1949     throw new java::lang::LinkageError;
1950 }