OSDN Git Service

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