OSDN Git Service

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