Merge from the pain train
[official-gcc.git] / libjava / link.cc
bloba1fa9188930c1497e53273b6fe3f7b163c6f32a7
1 // link.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 /* Author: Kresten Krab Thorup <krab@gnu.org> */
13 #include <config.h>
14 #include <platform.h>
16 #include <stdio.h>
18 #include <java-interp.h>
20 #include <jvm.h>
21 #include <gcj/cni.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <java-cpool.h>
25 #include <execution.h>
26 #include <java/lang/Class.h>
27 #include <java/lang/String.h>
28 #include <java/lang/StringBuffer.h>
29 #include <java/lang/Thread.h>
30 #include <java/lang/InternalError.h>
31 #include <java/lang/VirtualMachineError.h>
32 #include <java/lang/VerifyError.h>
33 #include <java/lang/NoSuchFieldError.h>
34 #include <java/lang/NoSuchMethodError.h>
35 #include <java/lang/ClassFormatError.h>
36 #include <java/lang/IllegalAccessError.h>
37 #include <java/lang/AbstractMethodError.h>
38 #include <java/lang/NoClassDefFoundError.h>
39 #include <java/lang/IncompatibleClassChangeError.h>
40 #include <java/lang/VerifyError.h>
41 #include <java/lang/VMClassLoader.h>
42 #include <java/lang/reflect/Modifier.h>
43 #include <java/security/CodeSource.h>
45 using namespace gcj;
47 // When true, print debugging information about class loading.
48 bool gcj::verbose_class_flag;
50 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
52 template<typename T>
53 struct aligner
55 char c;
56 T field;
59 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
61 // This returns the alignment of a type as it would appear in a
62 // structure. This can be different from the alignment of the type
63 // itself. For instance on x86 double is 8-aligned but struct{double}
64 // is 4-aligned.
65 int
66 _Jv_Linker::get_alignment_from_class (jclass klass)
68 if (klass == JvPrimClass (byte))
69 return ALIGNOF (jbyte);
70 else if (klass == JvPrimClass (short))
71 return ALIGNOF (jshort);
72 else if (klass == JvPrimClass (int))
73 return ALIGNOF (jint);
74 else if (klass == JvPrimClass (long))
75 return ALIGNOF (jlong);
76 else if (klass == JvPrimClass (boolean))
77 return ALIGNOF (jboolean);
78 else if (klass == JvPrimClass (char))
79 return ALIGNOF (jchar);
80 else if (klass == JvPrimClass (float))
81 return ALIGNOF (jfloat);
82 else if (klass == JvPrimClass (double))
83 return ALIGNOF (jdouble);
84 else
85 return ALIGNOF (jobject);
88 void
89 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
91 if (! field->isResolved ())
93 _Jv_Utf8Const *sig = (_Jv_Utf8Const*)field->type;
94 field->type = _Jv_FindClassFromSignature (sig->chars(), loader);
95 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
99 // A helper for find_field that knows how to recursively search
100 // superclasses and interfaces.
101 _Jv_Field *
102 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
103 jclass *declarer)
105 while (search)
107 // From 5.4.3.2. First search class itself.
108 for (int i = 0; i < search->field_count; ++i)
110 _Jv_Field *field = &search->fields[i];
111 if (_Jv_equalUtf8Consts (field->name, name))
113 *declarer = search;
114 return field;
118 // Next search direct interfaces.
119 for (int i = 0; i < search->interface_count; ++i)
121 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
122 declarer);
123 if (result)
124 return result;
127 // Now search superclass.
128 search = search->superclass;
131 return NULL;
134 bool
135 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
137 for (int i = 0; i < search->field_count; ++i)
139 _Jv_Field *field = &search->fields[i];
140 if (_Jv_equalUtf8Consts (field->name, field_name))
141 return true;
143 return false;
146 // Find a field.
147 // KLASS is the class that is requesting the field.
148 // OWNER is the class in which the field should be found.
149 // FIELD_TYPE_NAME is the type descriptor for the field.
150 // This function does the class loader type checks, and
151 // also access checks. Returns the field, or throws an
152 // exception on error.
153 _Jv_Field *
154 _Jv_Linker::find_field (jclass klass, jclass owner,
155 _Jv_Utf8Const *field_name,
156 _Jv_Utf8Const *field_type_name)
158 jclass field_type = 0;
160 if (owner->loader != klass->loader)
162 // FIXME: The implementation of this function
163 // (_Jv_FindClassFromSignature) will generate an instance of
164 // _Jv_Utf8Const for each call if the field type is a class name
165 // (Lxx.yy.Z;). This may be too expensive to do for each and
166 // every fieldref being resolved. For now, we fix the problem
167 // by only doing it when we have a loader different from the
168 // class declaring the field.
169 field_type = _Jv_FindClassFromSignature (field_type_name->chars(),
170 klass->loader);
173 jclass found_class = 0;
174 _Jv_Field *the_field = find_field_helper (owner, field_name, &found_class);
176 if (the_field == 0)
178 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
179 sb->append(JvNewStringLatin1("field "));
180 sb->append(owner->getName());
181 sb->append(JvNewStringLatin1("."));
182 sb->append(_Jv_NewStringUTF(field_name->chars()));
183 sb->append(JvNewStringLatin1(" was not found."));
184 throw new java::lang::NoSuchFieldError (sb->toString());
187 if (_Jv_CheckAccess (klass, found_class, the_field->flags))
189 // Resolve the field using the class' own loader if necessary.
191 if (!the_field->isResolved ())
192 resolve_field (the_field, found_class->loader);
194 if (field_type != 0 && the_field->type != field_type)
195 throw new java::lang::LinkageError
196 (JvNewStringLatin1
197 ("field type mismatch with different loaders"));
199 else
201 java::lang::StringBuffer *sb
202 = new java::lang::StringBuffer ();
203 sb->append(klass->getName());
204 sb->append(JvNewStringLatin1(": "));
205 sb->append(found_class->getName());
206 sb->append(JvNewStringLatin1("."));
207 sb->append(_Jv_NewStringUtf8Const (field_name));
208 throw new java::lang::IllegalAccessError(sb->toString());
211 return the_field;
214 _Jv_word
215 _Jv_Linker::resolve_pool_entry (jclass klass, int index)
217 using namespace java::lang::reflect;
219 _Jv_Constants *pool = &klass->constants;
221 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
222 return pool->data[index];
224 switch (pool->tags[index])
226 case JV_CONSTANT_Class:
228 _Jv_Utf8Const *name = pool->data[index].utf8;
230 jclass found;
231 if (name->first() == '[')
232 found = _Jv_FindClassFromSignature (name->chars(),
233 klass->loader);
234 else
235 found = _Jv_FindClass (name, klass->loader);
237 if (! found)
238 throw new java::lang::NoClassDefFoundError (name->toString());
240 // Check accessibility, but first strip array types as
241 // _Jv_ClassNameSamePackage can't handle arrays.
242 jclass check;
243 for (check = found;
244 check && check->isArray();
245 check = check->getComponentType())
247 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
248 || (_Jv_ClassNameSamePackage (check->name,
249 klass->name)))
251 pool->data[index].clazz = found;
252 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
254 else
256 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
257 sb->append(klass->getName());
258 sb->append(JvNewStringLatin1(" can't access class "));
259 sb->append(found->getName());
260 throw new java::lang::IllegalAccessError(sb->toString());
263 break;
265 case JV_CONSTANT_String:
267 jstring str;
268 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
269 pool->data[index].o = str;
270 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
272 break;
274 case JV_CONSTANT_Fieldref:
276 _Jv_ushort class_index, name_and_type_index;
277 _Jv_loadIndexes (&pool->data[index],
278 class_index,
279 name_and_type_index);
280 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
282 if (owner != klass)
283 _Jv_InitClass (owner);
285 _Jv_ushort name_index, type_index;
286 _Jv_loadIndexes (&pool->data[name_and_type_index],
287 name_index,
288 type_index);
290 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
291 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
293 _Jv_Field *the_field = find_field (klass, owner, field_name,
294 field_type_name);
296 pool->data[index].field = the_field;
297 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
299 break;
301 case JV_CONSTANT_Methodref:
302 case JV_CONSTANT_InterfaceMethodref:
304 _Jv_ushort class_index, name_and_type_index;
305 _Jv_loadIndexes (&pool->data[index],
306 class_index,
307 name_and_type_index);
308 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
310 if (owner != klass)
311 _Jv_InitClass (owner);
313 _Jv_ushort name_index, type_index;
314 _Jv_loadIndexes (&pool->data[name_and_type_index],
315 name_index,
316 type_index);
318 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
319 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
321 _Jv_Method *the_method = 0;
322 jclass found_class = 0;
324 // We're going to cache a pointer to the _Jv_Method object
325 // when we find it. So, to ensure this doesn't get moved from
326 // beneath us, we first put all the needed Miranda methods
327 // into the target class.
328 wait_for_state (klass, JV_STATE_LOADED);
330 // First search the class itself.
331 the_method = search_method_in_class (owner, klass,
332 method_name, method_signature);
334 if (the_method != 0)
336 found_class = owner;
337 goto end_of_method_search;
340 // If we are resolving an interface method, search the
341 // interface's superinterfaces (A superinterface is not an
342 // interface's superclass - a superinterface is implemented by
343 // the interface).
344 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
346 _Jv_ifaces ifaces;
347 ifaces.count = 0;
348 ifaces.len = 4;
349 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
350 * sizeof (jclass *));
352 get_interfaces (owner, &ifaces);
354 for (int i = 0; i < ifaces.count; i++)
356 jclass cls = ifaces.list[i];
357 the_method = search_method_in_class (cls, klass, method_name,
358 method_signature);
359 if (the_method != 0)
361 found_class = cls;
362 break;
366 _Jv_Free (ifaces.list);
368 if (the_method != 0)
369 goto end_of_method_search;
372 // Finally, search superclasses.
373 for (jclass cls = owner->getSuperclass (); cls != 0;
374 cls = cls->getSuperclass ())
376 the_method = search_method_in_class (cls, klass, method_name,
377 method_signature);
378 if (the_method != 0)
380 found_class = cls;
381 break;
385 end_of_method_search:
387 // FIXME: if (cls->loader != klass->loader), then we
388 // must actually check that the types of arguments
389 // correspond. That is, for each argument type, and
390 // the return type, doing _Jv_FindClassFromSignature
391 // with either loader should produce the same result,
392 // i.e., exactly the same jclass object. JVMS 5.4.3.3
394 if (the_method == 0)
396 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
397 sb->append(JvNewStringLatin1("method "));
398 sb->append(owner->getName());
399 sb->append(JvNewStringLatin1("."));
400 sb->append(_Jv_NewStringUTF(method_name->chars()));
401 sb->append(JvNewStringLatin1(" with signature "));
402 sb->append(_Jv_NewStringUTF(method_signature->chars()));
403 sb->append(JvNewStringLatin1(" was not found."));
404 throw new java::lang::NoSuchMethodError (sb->toString());
407 int vtable_index = -1;
408 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
409 vtable_index = (jshort)the_method->index;
411 pool->data[index].rmethod
412 = klass->engine->resolve_method(the_method,
413 found_class,
414 ((the_method->accflags
415 & Modifier::STATIC) != 0),
416 vtable_index);
417 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
419 break;
421 return pool->data[index];
424 // This function is used to lazily locate superclasses and
425 // superinterfaces. This must be called with the class lock held.
426 void
427 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
429 jclass ret = *classref;
431 // If superclass looks like a constant pool entry, resolve it now.
432 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
434 if (klass->state < JV_STATE_LINKED)
436 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
437 ret = _Jv_FindClass (name, klass->loader);
438 if (! ret)
440 throw new java::lang::NoClassDefFoundError (name->toString());
443 else
444 ret = klass->constants.data[(uaddr) classref].clazz;
445 *classref = ret;
449 // Find a method declared in the cls that is referenced from klass and
450 // perform access checks.
451 _Jv_Method *
452 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
453 _Jv_Utf8Const *method_name,
454 _Jv_Utf8Const *method_signature)
456 using namespace java::lang::reflect;
458 for (int i = 0; i < cls->method_count; i++)
460 _Jv_Method *method = &cls->methods[i];
461 if ( (!_Jv_equalUtf8Consts (method->name,
462 method_name))
463 || (!_Jv_equalUtf8Consts (method->signature,
464 method_signature)))
465 continue;
467 if (_Jv_CheckAccess (klass, cls, method->accflags))
468 return method;
469 else
471 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
472 sb->append(klass->getName());
473 sb->append(JvNewStringLatin1(": "));
474 sb->append(cls->getName());
475 sb->append(JvNewStringLatin1("."));
476 sb->append(_Jv_NewStringUTF(method_name->chars()));
477 sb->append(_Jv_NewStringUTF(method_signature->chars()));
478 throw new java::lang::IllegalAccessError (sb->toString());
481 return 0;
485 #define INITIAL_IOFFSETS_LEN 4
486 #define INITIAL_IFACES_LEN 4
488 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
490 // Generate tables for constant-time assignment testing and interface
491 // method lookup. This implements the technique described by Per Bothner
492 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
493 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
494 void
495 _Jv_Linker::prepare_constant_time_tables (jclass klass)
497 if (klass->isPrimitive () || klass->isInterface ())
498 return;
500 // Short-circuit in case we've been called already.
501 if ((klass->idt != NULL) || klass->depth != 0)
502 return;
504 // Calculate the class depth and ancestor table. The depth of a class
505 // is how many "extends" it is removed from Object. Thus the depth of
506 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
507 // is 2. Depth is defined for all regular and array classes, but not
508 // interfaces or primitive types.
510 jclass klass0 = klass;
511 jboolean has_interfaces = 0;
512 while (klass0 != &java::lang::Object::class$)
514 has_interfaces += klass0->interface_count;
515 klass0 = klass0->superclass;
516 klass->depth++;
519 // We do class member testing in constant time by using a small table
520 // of all the ancestor classes within each class. The first element is
521 // a pointer to the current class, and the rest are pointers to the
522 // classes ancestors, ordered from the current class down by decreasing
523 // depth. We do not include java.lang.Object in the table of ancestors,
524 // since it is redundant.
526 // FIXME: _Jv_AllocBytes
527 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth
528 * sizeof (jclass));
529 klass0 = klass;
530 for (int index = 0; index < klass->depth; index++)
532 klass->ancestors[index] = klass0;
533 klass0 = klass0->superclass;
536 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
537 return;
539 // Optimization: If class implements no interfaces, use a common
540 // predefined interface table.
541 if (!has_interfaces)
543 klass->idt = &null_idt;
544 return;
547 // FIXME: _Jv_AllocBytes
548 klass->idt =
549 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
551 _Jv_ifaces ifaces;
552 ifaces.count = 0;
553 ifaces.len = INITIAL_IFACES_LEN;
554 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
556 int itable_size = get_interfaces (klass, &ifaces);
558 if (ifaces.count > 0)
560 klass->idt->cls.itable =
561 // FIXME: _Jv_AllocBytes
562 (void **) _Jv_Malloc (itable_size * sizeof (void *));
563 klass->idt->cls.itable_length = itable_size;
565 jshort *itable_offsets =
566 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
568 generate_itable (klass, &ifaces, itable_offsets);
570 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
571 ifaces.count);
573 for (int i = 0; i < ifaces.count; i++)
575 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
576 itable_offsets[i];
579 klass->idt->cls.iindex = cls_iindex;
581 _Jv_Free (ifaces.list);
582 _Jv_Free (itable_offsets);
584 else
586 klass->idt->cls.iindex = SHRT_MAX;
590 // Return index of item in list, or -1 if item is not present.
591 inline jshort
592 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
594 for (int i=0; i < list_len; i++)
596 if (list[i] == item)
597 return i;
599 return -1;
602 // Find all unique interfaces directly or indirectly implemented by klass.
603 // Returns the size of the interface dispatch table (itable) for klass, which
604 // is the number of unique interfaces plus the total number of methods that
605 // those interfaces declare. May extend ifaces if required.
606 jshort
607 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
609 jshort result = 0;
611 for (int i = 0; i < klass->interface_count; i++)
613 jclass iface = klass->interfaces[i];
615 /* Make sure interface is linked. */
616 wait_for_state(iface, JV_STATE_LINKED);
618 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
620 if (ifaces->count + 1 >= ifaces->len)
622 /* Resize ifaces list */
623 ifaces->len = ifaces->len * 2;
624 ifaces->list
625 = (jclass *) _Jv_Realloc (ifaces->list,
626 ifaces->len * sizeof(jclass));
628 ifaces->list[ifaces->count] = iface;
629 ifaces->count++;
631 result += get_interfaces (klass->interfaces[i], ifaces);
635 if (klass->isInterface())
636 result += klass->method_count + 1;
637 else if (klass->superclass)
638 result += get_interfaces (klass->superclass, ifaces);
639 return result;
642 // Fill out itable in klass, resolving method declarations in each ifaces.
643 // itable_offsets is filled out with the position of each iface in itable,
644 // such that itable[itable_offsets[n]] == ifaces.list[n].
645 void
646 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
647 jshort *itable_offsets)
649 void **itable = klass->idt->cls.itable;
650 jshort itable_pos = 0;
652 for (int i = 0; i < ifaces->count; i++)
654 jclass iface = ifaces->list[i];
655 itable_offsets[i] = itable_pos;
656 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
658 /* Create interface dispatch table for iface */
659 if (iface->idt == NULL)
661 // FIXME: _Jv_AllocBytes
662 iface->idt
663 = (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
665 // The first element of ioffsets is its length (itself included).
666 // FIXME: _Jv_AllocBytes
667 jshort *ioffsets = (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN
668 * sizeof (jshort));
669 ioffsets[0] = INITIAL_IOFFSETS_LEN;
670 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
671 ioffsets[i] = -1;
673 iface->idt->iface.ioffsets = ioffsets;
678 // Format method name for use in error messages.
679 jstring
680 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
681 jclass derived)
683 using namespace java::lang;
684 StringBuffer *buf = new StringBuffer (klass->name->toString());
685 buf->append (jchar ('.'));
686 buf->append (meth->name->toString());
687 buf->append ((jchar) ' ');
688 buf->append (meth->signature->toString());
689 if (derived)
691 buf->append(JvNewStringLatin1(" in "));
692 buf->append(derived->name->toString());
694 return buf->toString();
697 void
698 _Jv_ThrowNoSuchMethodError ()
700 throw new java::lang::NoSuchMethodError;
703 // This is put in empty vtable slots.
704 static void
705 _Jv_abstractMethodError (void)
707 throw new java::lang::AbstractMethodError();
710 // Each superinterface of a class (i.e. each interface that the class
711 // directly or indirectly implements) has a corresponding "Partial
712 // Interface Dispatch Table" whose size is (number of methods + 1) words.
713 // The first word is a pointer to the interface (i.e. the java.lang.Class
714 // instance for that interface). The remaining words are pointers to the
715 // actual methods that implement the methods declared in the interface,
716 // in order of declaration.
718 // Append partial interface dispatch table for "iface" to "itable", at
719 // position itable_pos.
720 // Returns the offset at which the next partial ITable should be appended.
721 jshort
722 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
723 void **itable, jshort pos)
725 using namespace java::lang::reflect;
727 itable[pos++] = (void *) iface;
728 _Jv_Method *meth;
730 for (int j=0; j < iface->method_count; j++)
732 meth = NULL;
733 for (jclass cl = klass; cl; cl = cl->getSuperclass())
735 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
736 iface->methods[j].signature);
738 if (meth)
739 break;
742 if (meth && (meth->name->first() == '<'))
744 // leave a placeholder in the itable for hidden init methods.
745 itable[pos] = NULL;
747 else if (meth)
749 if ((meth->accflags & Modifier::STATIC) != 0)
750 throw new java::lang::IncompatibleClassChangeError
751 (_Jv_GetMethodString (klass, meth));
752 if ((meth->accflags & Modifier::PUBLIC) == 0)
753 throw new java::lang::IllegalAccessError
754 (_Jv_GetMethodString (klass, meth));
756 if ((meth->accflags & Modifier::ABSTRACT) != 0)
757 itable[pos] = (void *) &_Jv_abstractMethodError;
758 else
759 itable[pos] = meth->ncode;
761 else
763 // The method doesn't exist in klass. Binary compatibility rules
764 // permit this, so we delay the error until runtime using a pointer
765 // to a method which throws an exception.
766 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
768 pos++;
771 return pos;
774 static _Jv_Mutex_t iindex_mutex;
775 static bool iindex_mutex_initialized = false;
777 // We need to find the correct offset in the Class Interface Dispatch
778 // Table for a given interface. Once we have that, invoking an interface
779 // method just requires combining the Method's index in the interface
780 // (known at compile time) to get the correct method. Doing a type test
781 // (cast or instanceof) is the same problem: Once we have a possible Partial
782 // Interface Dispatch Table, we just compare the first element to see if it
783 // matches the desired interface. So how can we find the correct offset?
784 // Our solution is to keep a vector of candiate offsets in each interface
785 // (idt->iface.ioffsets), and in each class we have an index
786 // (idt->cls.iindex) used to select the correct offset from ioffsets.
788 // Calculate and return iindex for a new class.
789 // ifaces is a vector of num interfaces that the class implements.
790 // offsets[j] is the offset in the interface dispatch table for the
791 // interface corresponding to ifaces[j].
792 // May extend the interface ioffsets if required.
793 jshort
794 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
796 int i;
797 int j;
799 // Acquire a global lock to prevent itable corruption in case of multiple
800 // classes that implement an intersecting set of interfaces being linked
801 // simultaneously. We can assume that the mutex will be initialized
802 // single-threaded.
803 if (! iindex_mutex_initialized)
805 _Jv_MutexInit (&iindex_mutex);
806 iindex_mutex_initialized = true;
809 _Jv_MutexLock (&iindex_mutex);
811 for (i=1;; i++) /* each potential position in ioffsets */
813 for (j=0;; j++) /* each iface */
815 if (j >= num)
816 goto found;
817 if (i >= ifaces[j]->idt->iface.ioffsets[0])
818 continue;
819 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
820 /* We can potentially share this position with another class. */
821 if (ioffset >= 0 && ioffset != offsets[j])
822 break; /* Nope. Try next i. */
825 found:
826 for (j = 0; j < num; j++)
828 int len = ifaces[j]->idt->iface.ioffsets[0];
829 if (i >= len)
831 // Resize ioffsets.
832 int newlen = 2 * len;
833 if (i >= newlen)
834 newlen = i + 3;
835 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
836 // FIXME: _Jv_AllocBytes
837 jshort *new_ioffsets = (jshort *) _Jv_Malloc (newlen
838 * sizeof(jshort));
839 memcpy (&new_ioffsets[1], &old_ioffsets[1],
840 (len - 1) * sizeof (jshort));
841 new_ioffsets[0] = newlen;
843 while (len < newlen)
844 new_ioffsets[len++] = -1;
846 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
848 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
851 _Jv_MutexUnlock (&iindex_mutex);
853 return i;
857 // Functions for indirect dispatch (symbolic virtual binding) support.
859 // There are three tables, atable otable and itable. atable is an
860 // array of addresses, and otable is an array of offsets, and these
861 // are used for static and virtual members respectively. itable is an
862 // array of pairs {address, index} where each address is a pointer to
863 // an interface.
865 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
866 // symbol is a tuple of {classname, member name, signature}.
868 // Set this to true to enable debugging of indirect dispatch tables/linking.
869 static bool debug_link = false;
871 // link_symbol_table() scans these two arrays and fills in the
872 // corresponding atable and otable with the addresses of static
873 // members and the offsets of virtual members.
875 // The offset (in bytes) for each resolved method or field is placed
876 // at the corresponding position in the virtual method offset table
877 // (klass->otable).
879 // The same otable and atable may be shared by many classes.
881 // This must be called while holding the class lock.
883 void
884 _Jv_Linker::link_symbol_table (jclass klass)
886 int index = 0;
887 _Jv_MethodSymbol sym;
888 if (klass->otable == NULL
889 || klass->otable->state != 0)
890 goto atable;
892 klass->otable->state = 1;
894 if (debug_link)
895 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
896 for (index = 0;
897 (sym = klass->otable_syms[index]).class_name != NULL;
898 ++index)
900 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
901 _Jv_Method *meth = NULL;
903 _Jv_Utf8Const *signature = sym.signature;
906 static char *bounce = (char *)_Jv_ThrowNoSuchMethodError;
907 ptrdiff_t offset = (char *)(klass->vtable) - bounce;
908 klass->otable->offsets[index] = offset;
911 if (target_class == NULL)
912 throw new java::lang::NoClassDefFoundError
913 (_Jv_NewStringUTF (sym.class_name->chars()));
915 // We're looking for a field or a method, and we can tell
916 // which is needed by looking at the signature.
917 if (signature->first() == '(' && signature->len() >= 2)
919 // Looks like someone is trying to invoke an interface method
920 if (target_class->isInterface())
922 using namespace java::lang;
923 StringBuffer *sb = new StringBuffer();
924 sb->append(JvNewStringLatin1("found interface "));
925 sb->append(target_class->getName());
926 sb->append(JvNewStringLatin1(" when searching for a class"));
927 throw new VerifyError(sb->toString());
930 // If the target class does not have a vtable_method_count yet,
931 // then we can't tell the offsets for its methods, so we must lay
932 // it out now.
933 wait_for_state(target_class, JV_STATE_PREPARED);
935 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
936 sym.signature);
938 if (meth != NULL)
940 int offset = _Jv_VTable::idx_to_offset (meth->index);
941 if (offset == -1)
942 JvFail ("Bad method index");
943 JvAssert (meth->index < target_class->vtable_method_count);
944 klass->otable->offsets[index] = offset;
946 if (debug_link)
947 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
948 (int)index,
949 (int)klass->otable->offsets[index],
950 (const char*)target_class->name->chars(),
951 target_class,
952 (const char*)sym.name->chars(),
953 (const char*)signature->chars());
954 continue;
957 // Try fields.
959 wait_for_state(target_class, JV_STATE_PREPARED);
960 _Jv_Field *the_field = find_field (klass, target_class,
961 sym.name, sym.signature);
962 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
963 throw new java::lang::IncompatibleClassChangeError;
964 else
965 klass->otable->offsets[index] = the_field->u.boffset;
969 atable:
970 if (klass->atable == NULL || klass->atable->state != 0)
971 goto itable;
973 klass->atable->state = 1;
975 for (index = 0;
976 (sym = klass->atable_syms[index]).class_name != NULL;
977 ++index)
979 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
980 _Jv_Method *meth = NULL;
981 _Jv_Utf8Const *signature = sym.signature;
983 // ??? Setting this pointer to null will at least get us a
984 // NullPointerException
985 klass->atable->addresses[index] = NULL;
987 if (target_class == NULL)
988 throw new java::lang::NoClassDefFoundError
989 (_Jv_NewStringUTF (sym.class_name->chars()));
991 // We're looking for a static field or a static method, and we
992 // can tell which is needed by looking at the signature.
993 if (signature->first() == '(' && signature->len() >= 2)
995 // If the target class does not have a vtable_method_count yet,
996 // then we can't tell the offsets for its methods, so we must lay
997 // it out now.
998 wait_for_state (target_class, JV_STATE_PREPARED);
1000 // Interface methods cannot have bodies.
1001 if (target_class->isInterface())
1003 using namespace java::lang;
1004 StringBuffer *sb = new StringBuffer();
1005 sb->append(JvNewStringLatin1("class "));
1006 sb->append(target_class->getName());
1007 sb->append(JvNewStringLatin1(" is an interface: "
1008 "class expected"));
1009 throw new VerifyError(sb->toString());
1012 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1013 sym.signature);
1015 if (meth != NULL)
1017 if (meth->ncode) // Maybe abstract?
1019 klass->atable->addresses[index] = meth->ncode;
1020 if (debug_link)
1021 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1022 index,
1023 &klass->atable->addresses[index],
1024 (const char*)target_class->name->chars(),
1025 klass,
1026 (const char*)sym.name->chars(),
1027 (const char*)signature->chars());
1030 else
1031 klass->atable->addresses[index]
1032 = (void *)_Jv_ThrowNoSuchMethodError;
1034 continue;
1037 // Try fields.
1039 wait_for_state(target_class, JV_STATE_PREPARED);
1040 _Jv_Field *the_field = find_field (klass, target_class,
1041 sym.name, sym.signature);
1042 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1043 klass->atable->addresses[index] = the_field->u.addr;
1044 else
1045 throw new java::lang::IncompatibleClassChangeError;
1049 itable:
1050 if (klass->itable == NULL
1051 || klass->itable->state != 0)
1052 return;
1054 klass->itable->state = 1;
1056 for (index = 0;
1057 (sym = klass->itable_syms[index]).class_name != NULL;
1058 ++index)
1060 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1061 _Jv_Utf8Const *signature = sym.signature;
1063 jclass cls;
1064 int i;
1066 wait_for_state(target_class, JV_STATE_LOADED);
1067 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1068 sym.name, sym.signature);
1070 if (found)
1072 klass->itable->addresses[index * 2] = cls;
1073 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1074 if (debug_link)
1076 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1077 index,
1078 klass->itable->addresses[index * 2],
1079 (const char*)cls->name->chars(),
1080 cls,
1081 (const char*)sym.name->chars(),
1082 (const char*)signature->chars());
1083 fprintf (stderr, " [%d] = offset %d\n",
1084 index + 1,
1085 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1089 else
1090 throw new java::lang::IncompatibleClassChangeError;
1095 // For each catch_record in the list of caught classes, fill in the
1096 // address field.
1097 void
1098 _Jv_Linker::link_exception_table (jclass self)
1100 struct _Jv_CatchClass *catch_record = self->catch_classes;
1101 if (!catch_record || catch_record->classname)
1102 return;
1103 catch_record++;
1104 while (catch_record->classname)
1108 jclass target_class
1109 = _Jv_FindClass (catch_record->classname,
1110 self->getClassLoaderInternal ());
1111 *catch_record->address = target_class;
1113 catch (::java::lang::Throwable *t)
1115 // FIXME: We need to do something better here.
1116 *catch_record->address = 0;
1118 catch_record++;
1120 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1123 // Set itable method indexes for members of interface IFACE.
1124 void
1125 _Jv_Linker::layout_interface_methods (jclass iface)
1127 if (! iface->isInterface())
1128 return;
1130 // itable indexes start at 1.
1131 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1132 // itable so they are also assigned an index here.
1133 for (int i = 0; i < iface->method_count; i++)
1134 iface->methods[i].index = i + 1;
1137 // Prepare virtual method declarations in KLASS, and any superclasses
1138 // as required, by determining their vtable index, setting
1139 // method->index, and finally setting the class's vtable_method_count.
1140 // Must be called with the lock for KLASS held.
1141 void
1142 _Jv_Linker::layout_vtable_methods (jclass klass)
1144 if (klass->vtable != NULL || klass->isInterface()
1145 || klass->vtable_method_count != -1)
1146 return;
1148 jclass superclass = klass->getSuperclass();
1150 if (superclass != NULL && superclass->vtable_method_count == -1)
1152 JvSynchronize sync (superclass);
1153 layout_vtable_methods (superclass);
1156 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1158 for (int i = 0; i < klass->method_count; ++i)
1160 _Jv_Method *meth = &klass->methods[i];
1161 _Jv_Method *super_meth = NULL;
1163 if (! _Jv_isVirtualMethod (meth))
1164 continue;
1166 if (superclass != NULL)
1168 jclass declarer;
1169 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1170 meth->signature, &declarer);
1171 // See if this method actually overrides the other method
1172 // we've found.
1173 if (super_meth)
1175 if (! _Jv_isVirtualMethod (super_meth)
1176 || ! _Jv_CheckAccess (klass, declarer,
1177 super_meth->accflags))
1178 super_meth = NULL;
1179 else if ((super_meth->accflags
1180 & java::lang::reflect::Modifier::FINAL) != 0)
1182 using namespace java::lang;
1183 StringBuffer *sb = new StringBuffer();
1184 sb->append(JvNewStringLatin1("method "));
1185 sb->append(_Jv_GetMethodString(klass, meth));
1186 sb->append(JvNewStringLatin1(" overrides final method "));
1187 sb->append(_Jv_GetMethodString(declarer, super_meth));
1188 throw new VerifyError(sb->toString());
1193 if (super_meth)
1194 meth->index = super_meth->index;
1195 else
1196 meth->index = index++;
1199 klass->vtable_method_count = index;
1202 // Set entries in VTABLE for virtual methods declared in KLASS.
1203 void
1204 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1206 for (int i = klass->method_count - 1; i >= 0; i--)
1208 using namespace java::lang::reflect;
1210 _Jv_Method *meth = &klass->methods[i];
1211 if (meth->index == (_Jv_ushort) -1)
1212 continue;
1213 if ((meth->accflags & Modifier::ABSTRACT))
1214 // FIXME: it might be nice to have a libffi trampoline here,
1215 // so we could pass in the method name and other information.
1216 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1217 else
1218 vtable->set_method(meth->index, meth->ncode);
1222 // Allocate and lay out the virtual method table for KLASS. This will
1223 // also cause vtables to be generated for any non-abstract
1224 // superclasses, and virtual method layout to occur for any abstract
1225 // superclasses. Must be called with monitor lock for KLASS held.
1226 void
1227 _Jv_Linker::make_vtable (jclass klass)
1229 using namespace java::lang::reflect;
1231 // If the vtable exists, or for interface classes, do nothing. All
1232 // other classes, including abstract classes, need a vtable.
1233 if (klass->vtable != NULL || klass->isInterface())
1234 return;
1236 // Ensure all the `ncode' entries are set.
1237 klass->engine->create_ncode(klass);
1239 // Class must be laid out before we can create a vtable.
1240 if (klass->vtable_method_count == -1)
1241 layout_vtable_methods (klass);
1243 // Allocate the new vtable.
1244 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1245 klass->vtable = vtable;
1247 // Copy the vtable of the closest superclass.
1248 jclass superclass = klass->superclass;
1250 JvSynchronize sync (superclass);
1251 make_vtable (superclass);
1253 for (int i = 0; i < superclass->vtable_method_count; ++i)
1254 vtable->set_method (i, superclass->vtable->get_method (i));
1256 // Set the class pointer and GC descriptor.
1257 vtable->clas = klass;
1258 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1260 // For each virtual declared in klass, set new vtable entry or
1261 // override an old one.
1262 set_vtable_entries (klass, vtable);
1264 // Note that we don't check for abstract methods here. We used to,
1265 // but there is a JVMS clarification that indicates that a check
1266 // here would be too eager. And, a simple test case confirms this.
1269 // Lay out the class, allocating space for static fields and computing
1270 // offsets of instance fields. The class lock must be held by the
1271 // caller.
1272 void
1273 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1275 if (klass->size_in_bytes != -1)
1276 return;
1278 // Compute the alignment for this type by searching through the
1279 // superclasses and finding the maximum required alignment. We
1280 // could consider caching this in the Class.
1281 int max_align = __alignof__ (java::lang::Object);
1282 jclass super = klass->getSuperclass();
1283 while (super != NULL)
1285 // Ensure that our super has its super installed before
1286 // recursing.
1287 wait_for_state(super, JV_STATE_LOADING);
1288 ensure_fields_laid_out(super);
1289 int num = JvNumInstanceFields (super);
1290 _Jv_Field *field = JvGetFirstInstanceField (super);
1291 while (num > 0)
1293 int field_align = get_alignment_from_class (field->type);
1294 if (field_align > max_align)
1295 max_align = field_align;
1296 ++field;
1297 --num;
1299 super = super->getSuperclass();
1302 int instance_size;
1303 int static_size = 0;
1305 // Although java.lang.Object is never interpreted, an interface can
1306 // have a null superclass. Note that we have to lay out an
1307 // interface because it might have static fields.
1308 if (klass->superclass)
1309 instance_size = klass->superclass->size();
1310 else
1311 instance_size = java::lang::Object::class$.size();
1313 for (int i = 0; i < klass->field_count; i++)
1315 int field_size;
1316 int field_align;
1318 _Jv_Field *field = &klass->fields[i];
1320 if (! field->isRef ())
1322 // It is safe to resolve the field here, since it's a
1323 // primitive class, which does not cause loading to happen.
1324 resolve_field (field, klass->loader);
1326 field_size = field->type->size ();
1327 field_align = get_alignment_from_class (field->type);
1329 else
1331 field_size = sizeof (jobject);
1332 field_align = __alignof__ (jobject);
1335 field->bsize = field_size;
1337 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1339 if (field->u.addr == NULL)
1341 // This computes an offset into a region we'll allocate
1342 // shortly, and then add this offset to the start
1343 // address.
1344 static_size = ROUND (static_size, field_align);
1345 field->u.boffset = static_size;
1346 static_size += field_size;
1349 else
1351 instance_size = ROUND (instance_size, field_align);
1352 field->u.boffset = instance_size;
1353 instance_size += field_size;
1354 if (field_align > max_align)
1355 max_align = field_align;
1359 if (static_size != 0)
1360 klass->engine->allocate_static_fields (klass, static_size);
1362 // Set the instance size for the class. Note that first we round it
1363 // to the alignment required for this object; this keeps us in sync
1364 // with our current ABI.
1365 instance_size = ROUND (instance_size, max_align);
1366 klass->size_in_bytes = instance_size;
1369 // This takes the class to state JV_STATE_LINKED. The class lock must
1370 // be held when calling this.
1371 void
1372 _Jv_Linker::ensure_class_linked (jclass klass)
1374 if (klass->state >= JV_STATE_LINKED)
1375 return;
1377 int state = klass->state;
1380 // Short-circuit, so that mutually dependent classes are ok.
1381 klass->state = JV_STATE_LINKED;
1383 _Jv_Constants *pool = &klass->constants;
1385 // Compiled classes require that their class constants be
1386 // resolved here. However, interpreted classes need their
1387 // constants to be resolved lazily. If we resolve an
1388 // interpreted class' constants eagerly, we can end up with
1389 // spurious IllegalAccessErrors when the constant pool contains
1390 // a reference to a class we can't access. This can validly
1391 // occur in an obscure case involving the InnerClasses
1392 // attribute.
1393 #ifdef INTERPRETER
1394 if (! _Jv_IsInterpretedClass (klass))
1395 #endif
1397 // Resolve class constants first, since other constant pool
1398 // entries may rely on these.
1399 for (int index = 1; index < pool->size; ++index)
1401 if (pool->tags[index] == JV_CONSTANT_Class)
1402 resolve_pool_entry (klass, index);
1406 #if 0 // Should be redundant now
1407 // If superclass looks like a constant pool entry,
1408 // resolve it now.
1409 if ((uaddr) klass->superclass < (uaddr) pool->size)
1410 klass->superclass = pool->data[(uaddr) klass->superclass].clazz;
1412 // Likewise for interfaces.
1413 for (int i = 0; i < klass->interface_count; i++)
1415 if ((uaddr) klass->interfaces[i] < (uaddr) pool->size)
1416 klass->interfaces[i]
1417 = pool->data[(uaddr) klass->interfaces[i]].clazz;
1419 #endif
1421 // Resolve the remaining constant pool entries.
1422 for (int index = 1; index < pool->size; ++index)
1424 if (pool->tags[index] == JV_CONSTANT_String)
1426 jstring str;
1428 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1429 pool->data[index].o = str;
1430 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1434 if (klass->engine->need_resolve_string_fields())
1436 jfieldID f = JvGetFirstStaticField (klass);
1437 for (int n = JvNumStaticFields (klass); n > 0; --n)
1439 int mod = f->getModifiers ();
1440 // If we have a static String field with a non-null initial
1441 // value, we know it points to a Utf8Const.
1442 resolve_field(f, klass->loader);
1443 if (f->getClass () == &java::lang::String::class$
1444 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1446 jstring *strp = (jstring *) f->u.addr;
1447 if (*strp)
1448 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1450 f = f->getNextField ();
1454 klass->notifyAll ();
1456 _Jv_PushClass (klass);
1458 catch (java::lang::Throwable *t)
1460 klass->state = state;
1461 throw t;
1465 // This ensures that symbolic superclass and superinterface references
1466 // are resolved for the indicated class. This must be called with the
1467 // class lock held.
1468 void
1469 _Jv_Linker::ensure_supers_installed (jclass klass)
1471 resolve_class_ref (klass, &klass->superclass);
1472 // An interface won't have a superclass.
1473 if (klass->superclass)
1474 wait_for_state (klass->superclass, JV_STATE_LOADING);
1476 for (int i = 0; i < klass->interface_count; ++i)
1478 resolve_class_ref (klass, &klass->interfaces[i]);
1479 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1483 // This adds missing `Miranda methods' to a class.
1484 void
1485 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1487 // Note that at this point, all our supers, and the supers of all
1488 // our superclasses and superinterfaces, will have been installed.
1490 for (int i = 0; i < iface_class->interface_count; ++i)
1492 jclass interface = iface_class->interfaces[i];
1494 for (int j = 0; j < interface->method_count; ++j)
1496 _Jv_Method *meth = &interface->methods[j];
1497 // Don't bother with <clinit>.
1498 if (meth->name->first() == '<')
1499 continue;
1500 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1501 meth->signature);
1502 if (! new_meth)
1504 // We assume that such methods are very unlikely, so we
1505 // just reallocate the method array each time one is
1506 // found. This greatly simplifies the searching --
1507 // otherwise we have to make sure that each such method
1508 // found is really unique among all superinterfaces.
1509 int new_count = base->method_count + 1;
1510 _Jv_Method *new_m
1511 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
1512 * new_count);
1513 memcpy (new_m, base->methods,
1514 sizeof (_Jv_Method) * base->method_count);
1516 // Add new method.
1517 new_m[base->method_count] = *meth;
1518 new_m[base->method_count].index = (_Jv_ushort) -1;
1519 new_m[base->method_count].accflags
1520 |= java::lang::reflect::Modifier::INVISIBLE;
1522 base->methods = new_m;
1523 base->method_count = new_count;
1527 wait_for_state (interface, JV_STATE_LOADED);
1528 add_miranda_methods (base, interface);
1532 // This ensures that the class' method table is "complete". This must
1533 // be called with the class lock held.
1534 void
1535 _Jv_Linker::ensure_method_table_complete (jclass klass)
1537 if (klass->vtable != NULL || klass->isInterface())
1538 return;
1540 // We need our superclass to have its own Miranda methods installed.
1541 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1543 // A class might have so-called "Miranda methods". This is a method
1544 // that is declared in an interface and not re-declared in an
1545 // abstract class. Some compilers don't emit declarations for such
1546 // methods in the class; this will give us problems since we expect
1547 // a declaration for any method requiring a vtable entry. We handle
1548 // this here by searching for such methods and constructing new
1549 // internal declarations for them. Note that we do this
1550 // unconditionally, and not just for abstract classes, to correctly
1551 // account for cases where a class is modified to be concrete and
1552 // still incorrectly inherits an abstract method.
1553 int pre_count = klass->method_count;
1554 add_miranda_methods (klass, klass);
1556 // Let the execution engine know that we've added methods.
1557 if (klass->method_count != pre_count)
1558 klass->engine->post_miranda_hook(klass);
1561 // Verify a class. Must be called with class lock held.
1562 void
1563 _Jv_Linker::verify_class (jclass klass)
1565 klass->engine->verify(klass);
1568 // Check the assertions contained in the type assertion table for KLASS.
1569 // This is the equivilent of bytecode verification for native, BC-ABI code.
1570 void
1571 _Jv_Linker::verify_type_assertions (jclass klass)
1573 if (debug_link)
1574 fprintf (stderr, "Evaluating type assertions for %s:\n",
1575 klass->name->chars());
1577 if (klass->assertion_table == NULL)
1578 return;
1580 for (int i = 0;; i++)
1582 int assertion_code = klass->assertion_table[i].assertion_code;
1583 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1584 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1586 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1587 return;
1588 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1590 if (debug_link)
1592 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1593 assertion_code, op1->chars(), op2->chars());
1596 // The operands are class signatures. op1 is the source,
1597 // op2 is the target.
1598 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1599 klass->getClassLoaderInternal());
1600 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1601 klass->getClassLoaderInternal());
1603 // If the class doesn't exist, ignore the assertion. An exception
1604 // will be thrown later if an attempt is made to actually
1605 // instantiate the class.
1606 if (cl1 == NULL || cl2 == NULL)
1607 continue;
1609 if (! _Jv_IsAssignableFromSlow (cl2, cl1))
1611 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1612 s = s->concat (klass->getName());
1613 s = s->concat (JvNewStringUTF (": "));
1614 s = s->concat (cl1->getName());
1615 s = s->concat (JvNewStringUTF (" is not assignable to "));
1616 s = s->concat (cl2->getName());
1617 throw new java::lang::VerifyError (s);
1620 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1622 // TODO: Implement this.
1624 // Unknown assertion codes are ignored, for forwards-compatibility.
1628 void
1629 _Jv_Linker::print_class_loaded (jclass klass)
1631 char *codesource = NULL;
1632 if (klass->protectionDomain != NULL)
1634 java::security::CodeSource *cs
1635 = klass->protectionDomain->getCodeSource();
1636 if (cs != NULL)
1638 jstring css = cs->toString();
1639 int len = JvGetStringUTFLength(css);
1640 codesource = (char *) _Jv_AllocBytes(len + 1);
1641 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1642 codesource[len] = '\0';
1645 if (codesource == NULL)
1646 codesource = "<no code source>";
1648 // We use a somewhat bogus test for the ABI here.
1649 char *abi;
1650 #ifdef INTERPRETER
1651 if (_Jv_IsInterpretedClass (klass))
1652 #else
1653 if (false)
1654 #endif
1655 abi = "bytecode";
1656 else if (klass->state == JV_STATE_PRELOADING)
1657 abi = "BC-compiled";
1658 else
1659 abi = "pre-compiled";
1661 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1662 codesource);
1665 // FIXME: mention invariants and stuff.
1666 void
1667 _Jv_Linker::wait_for_state (jclass klass, int state)
1669 if (klass->state >= state)
1670 return;
1672 JvSynchronize sync (klass);
1674 // This is similar to the strategy for class initialization. If we
1675 // already hold the lock, just leave.
1676 java::lang::Thread *self = java::lang::Thread::currentThread();
1677 while (klass->state <= state
1678 && klass->thread
1679 && klass->thread != self)
1680 klass->wait ();
1682 java::lang::Thread *save = klass->thread;
1683 klass->thread = self;
1685 // Print some debugging info if requested. Interpreted classes are
1686 // handled in defineclass, so we only need to handle the two
1687 // pre-compiled cases here.
1688 if (gcj::verbose_class_flag
1689 && (klass->state == JV_STATE_COMPILED
1690 || klass->state == JV_STATE_PRELOADING)
1691 #ifdef INTERPRETER
1692 && ! _Jv_IsInterpretedClass (klass)
1693 #endif
1695 print_class_loaded (klass);
1699 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
1701 ensure_supers_installed (klass);
1702 klass->set_state(JV_STATE_LOADING);
1705 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
1707 ensure_method_table_complete (klass);
1708 klass->set_state(JV_STATE_LOADED);
1711 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
1713 ensure_fields_laid_out (klass);
1714 make_vtable (klass);
1715 layout_interface_methods (klass);
1716 prepare_constant_time_tables (klass);
1717 klass->set_state(JV_STATE_PREPARED);
1720 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
1722 verify_class (klass);
1724 ensure_class_linked (klass);
1725 link_exception_table (klass);
1726 link_symbol_table (klass);
1727 klass->set_state(JV_STATE_LINKED);
1730 catch (java::lang::Throwable *exc)
1732 klass->thread = save;
1733 klass->set_state(JV_STATE_ERROR);
1734 throw exc;
1737 klass->thread = save;
1739 if (klass->state == JV_STATE_ERROR)
1740 throw new java::lang::LinkageError;