OSDN Git Service

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