OSDN Git Service

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