OSDN Git Service

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