OSDN Git Service

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