* gcc.dg/20050121-1.c: New test.
[official-gcc.git] / libjava / link.cc
blobb0559c4fc00dd162367d181d8b01fb2a173dfb15
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 <java-interp.h>
18 #include <jvm.h>
19 #include <gcj/cni.h>
20 #include <string.h>
21 #include <limits.h>
22 #include <java-cpool.h>
23 #include <execution.h>
24 #include <java/lang/Class.h>
25 #include <java/lang/String.h>
26 #include <java/lang/StringBuffer.h>
27 #include <java/lang/Thread.h>
28 #include <java/lang/InternalError.h>
29 #include <java/lang/VirtualMachineError.h>
30 #include <java/lang/VerifyError.h>
31 #include <java/lang/NoSuchFieldError.h>
32 #include <java/lang/NoSuchMethodError.h>
33 #include <java/lang/ClassFormatError.h>
34 #include <java/lang/IllegalAccessError.h>
35 #include <java/lang/AbstractMethodError.h>
36 #include <java/lang/NoClassDefFoundError.h>
37 #include <java/lang/IncompatibleClassChangeError.h>
38 #include <java/lang/VerifyError.h>
39 #include <java/lang/VMClassLoader.h>
40 #include <java/lang/reflect/Modifier.h>
41 #include <java/security/CodeSource.h>
43 using namespace gcj;
45 // When true, print debugging information about class loading.
46 bool gcj::verbose_class_flag;
48 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
50 template<typename T>
51 struct aligner
53 char c;
54 T field;
57 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
59 // This returns the alignment of a type as it would appear in a
60 // structure. This can be different from the alignment of the type
61 // itself. For instance on x86 double is 8-aligned but struct{double}
62 // is 4-aligned.
63 int
64 _Jv_Linker::get_alignment_from_class (jclass klass)
66 if (klass == JvPrimClass (byte))
67 return ALIGNOF (jbyte);
68 else if (klass == JvPrimClass (short))
69 return ALIGNOF (jshort);
70 else if (klass == JvPrimClass (int))
71 return ALIGNOF (jint);
72 else if (klass == JvPrimClass (long))
73 return ALIGNOF (jlong);
74 else if (klass == JvPrimClass (boolean))
75 return ALIGNOF (jboolean);
76 else if (klass == JvPrimClass (char))
77 return ALIGNOF (jchar);
78 else if (klass == JvPrimClass (float))
79 return ALIGNOF (jfloat);
80 else if (klass == JvPrimClass (double))
81 return ALIGNOF (jdouble);
82 else
83 return ALIGNOF (jobject);
86 void
87 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
89 if (! field->isResolved ())
91 _Jv_Utf8Const *sig = (_Jv_Utf8Const*)field->type;
92 field->type = _Jv_FindClassFromSignature (sig->chars(), loader);
93 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
97 // A helper for find_field that knows how to recursively search
98 // superclasses and interfaces.
99 _Jv_Field *
100 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
101 jclass *declarer)
103 while (search)
105 // From 5.4.3.2. First search class itself.
106 for (int i = 0; i < search->field_count; ++i)
108 _Jv_Field *field = &search->fields[i];
109 if (_Jv_equalUtf8Consts (field->name, name))
111 *declarer = search;
112 return field;
116 // Next search direct interfaces.
117 for (int i = 0; i < search->interface_count; ++i)
119 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
120 declarer);
121 if (result)
122 return result;
125 // Now search superclass.
126 search = search->superclass;
129 return NULL;
132 // Find a field.
133 // KLASS is the class that is requesting the field.
134 // OWNER is the class in which the field should be found.
135 // FIELD_TYPE_NAME is the type descriptor for the field.
136 // This function does the class loader type checks, and
137 // also access checks. Returns the field, or throws an
138 // exception on error.
139 _Jv_Field *
140 _Jv_Linker::find_field (jclass klass, jclass owner,
141 _Jv_Utf8Const *field_name,
142 _Jv_Utf8Const *field_type_name)
144 jclass field_type = 0;
146 if (owner->loader != klass->loader)
148 // FIXME: The implementation of this function
149 // (_Jv_FindClassFromSignature) will generate an instance of
150 // _Jv_Utf8Const for each call if the field type is a class name
151 // (Lxx.yy.Z;). This may be too expensive to do for each and
152 // every fieldref being resolved. For now, we fix the problem
153 // by only doing it when we have a loader different from the
154 // class declaring the field.
155 field_type = _Jv_FindClassFromSignature (field_type_name->chars(),
156 klass->loader);
159 jclass found_class = 0;
160 _Jv_Field *the_field = find_field_helper (owner, field_name, &found_class);
162 if (the_field == 0)
164 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
165 sb->append(JvNewStringLatin1("field "));
166 sb->append(owner->getName());
167 sb->append(JvNewStringLatin1("."));
168 sb->append(_Jv_NewStringUTF(field_name->chars()));
169 sb->append(JvNewStringLatin1(" was not found."));
170 throw new java::lang::NoSuchFieldError (sb->toString());
173 if (_Jv_CheckAccess (klass, found_class, the_field->flags))
175 // Resolve the field using the class' own loader if necessary.
177 if (!the_field->isResolved ())
178 resolve_field (the_field, found_class->loader);
180 if (field_type != 0 && the_field->type != field_type)
181 throw new java::lang::LinkageError
182 (JvNewStringLatin1
183 ("field type mismatch with different loaders"));
185 else
187 java::lang::StringBuffer *sb
188 = new java::lang::StringBuffer ();
189 sb->append(klass->getName());
190 sb->append(JvNewStringLatin1(": "));
191 sb->append(found_class->getName());
192 sb->append(JvNewStringLatin1("."));
193 sb->append(_Jv_NewStringUtf8Const (field_name));
194 throw new java::lang::IllegalAccessError(sb->toString());
197 return the_field;
200 _Jv_word
201 _Jv_Linker::resolve_pool_entry (jclass klass, int index)
203 using namespace java::lang::reflect;
205 _Jv_Constants *pool = &klass->constants;
207 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
208 return pool->data[index];
210 switch (pool->tags[index])
212 case JV_CONSTANT_Class:
214 _Jv_Utf8Const *name = pool->data[index].utf8;
216 jclass found;
217 if (name->first() == '[')
218 found = _Jv_FindClassFromSignature (name->chars(),
219 klass->loader);
220 else
221 found = _Jv_FindClass (name, klass->loader);
223 if (! found)
224 throw new java::lang::NoClassDefFoundError (name->toString());
226 // Check accessibility, but first strip array types as
227 // _Jv_ClassNameSamePackage can't handle arrays.
228 jclass check;
229 for (check = found;
230 check && check->isArray();
231 check = check->getComponentType())
233 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
234 || (_Jv_ClassNameSamePackage (check->name,
235 klass->name)))
237 pool->data[index].clazz = found;
238 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
240 else
242 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
243 sb->append(klass->getName());
244 sb->append(JvNewStringLatin1(" can't access class "));
245 sb->append(found->getName());
246 throw new java::lang::IllegalAccessError(sb->toString());
249 break;
251 case JV_CONSTANT_String:
253 jstring str;
254 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
255 pool->data[index].o = str;
256 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
258 break;
260 case JV_CONSTANT_Fieldref:
262 _Jv_ushort class_index, name_and_type_index;
263 _Jv_loadIndexes (&pool->data[index],
264 class_index,
265 name_and_type_index);
266 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
268 if (owner != klass)
269 _Jv_InitClass (owner);
271 _Jv_ushort name_index, type_index;
272 _Jv_loadIndexes (&pool->data[name_and_type_index],
273 name_index,
274 type_index);
276 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
277 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
279 _Jv_Field *the_field = find_field (klass, owner, field_name,
280 field_type_name);
282 pool->data[index].field = the_field;
283 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
285 break;
287 case JV_CONSTANT_Methodref:
288 case JV_CONSTANT_InterfaceMethodref:
290 _Jv_ushort class_index, name_and_type_index;
291 _Jv_loadIndexes (&pool->data[index],
292 class_index,
293 name_and_type_index);
294 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
296 if (owner != klass)
297 _Jv_InitClass (owner);
299 _Jv_ushort name_index, type_index;
300 _Jv_loadIndexes (&pool->data[name_and_type_index],
301 name_index,
302 type_index);
304 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
305 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
307 _Jv_Method *the_method = 0;
308 jclass found_class = 0;
310 // We're going to cache a pointer to the _Jv_Method object
311 // when we find it. So, to ensure this doesn't get moved from
312 // beneath us, we first put all the needed Miranda methods
313 // into the target class.
314 wait_for_state (klass, JV_STATE_LOADED);
316 // First search the class itself.
317 the_method = search_method_in_class (owner, klass,
318 method_name, method_signature);
320 if (the_method != 0)
322 found_class = owner;
323 goto end_of_method_search;
326 // If we are resolving an interface method, search the
327 // interface's superinterfaces (A superinterface is not an
328 // interface's superclass - a superinterface is implemented by
329 // the interface).
330 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
332 _Jv_ifaces ifaces;
333 ifaces.count = 0;
334 ifaces.len = 4;
335 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
336 * sizeof (jclass *));
338 get_interfaces (owner, &ifaces);
340 for (int i = 0; i < ifaces.count; i++)
342 jclass cls = ifaces.list[i];
343 the_method = search_method_in_class (cls, klass, method_name,
344 method_signature);
345 if (the_method != 0)
347 found_class = cls;
348 break;
352 _Jv_Free (ifaces.list);
354 if (the_method != 0)
355 goto end_of_method_search;
358 // Finally, search superclasses.
359 for (jclass cls = owner->getSuperclass (); cls != 0;
360 cls = cls->getSuperclass ())
362 the_method = search_method_in_class (cls, klass, method_name,
363 method_signature);
364 if (the_method != 0)
366 found_class = cls;
367 break;
371 end_of_method_search:
373 // FIXME: if (cls->loader != klass->loader), then we
374 // must actually check that the types of arguments
375 // correspond. That is, for each argument type, and
376 // the return type, doing _Jv_FindClassFromSignature
377 // with either loader should produce the same result,
378 // i.e., exactly the same jclass object. JVMS 5.4.3.3
380 if (the_method == 0)
382 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
383 sb->append(JvNewStringLatin1("method "));
384 sb->append(owner->getName());
385 sb->append(JvNewStringLatin1("."));
386 sb->append(_Jv_NewStringUTF(method_name->chars()));
387 sb->append(JvNewStringLatin1(" with signature "));
388 sb->append(_Jv_NewStringUTF(method_signature->chars()));
389 sb->append(JvNewStringLatin1(" was not found."));
390 throw new java::lang::NoSuchMethodError (sb->toString());
393 int vtable_index = -1;
394 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
395 vtable_index = (jshort)the_method->index;
397 pool->data[index].rmethod
398 = klass->engine->resolve_method(the_method,
399 found_class,
400 ((the_method->accflags
401 & Modifier::STATIC) != 0),
402 vtable_index);
403 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
405 break;
407 return pool->data[index];
410 // This function is used to lazily locate superclasses and
411 // superinterfaces. This must be called with the class lock held.
412 void
413 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
415 jclass ret = *classref;
417 // If superclass looks like a constant pool entry, resolve it now.
418 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
420 if (klass->state < JV_STATE_LINKED)
422 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
423 ret = _Jv_FindClass (name, klass->loader);
424 if (! ret)
426 throw new java::lang::NoClassDefFoundError (name->toString());
429 else
430 ret = klass->constants.data[(uaddr) classref].clazz;
431 *classref = ret;
435 // Find a method declared in the cls that is referenced from klass and
436 // perform access checks.
437 _Jv_Method *
438 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
439 _Jv_Utf8Const *method_name,
440 _Jv_Utf8Const *method_signature)
442 using namespace java::lang::reflect;
444 for (int i = 0; i < cls->method_count; i++)
446 _Jv_Method *method = &cls->methods[i];
447 if ( (!_Jv_equalUtf8Consts (method->name,
448 method_name))
449 || (!_Jv_equalUtf8Consts (method->signature,
450 method_signature)))
451 continue;
453 if (_Jv_CheckAccess (klass, cls, method->accflags))
454 return method;
455 else
457 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
458 sb->append(klass->getName());
459 sb->append(JvNewStringLatin1(": "));
460 sb->append(cls->getName());
461 sb->append(JvNewStringLatin1("."));
462 sb->append(_Jv_NewStringUTF(method_name->chars()));
463 sb->append(_Jv_NewStringUTF(method_signature->chars()));
464 throw new java::lang::IllegalAccessError (sb->toString());
467 return 0;
471 #define INITIAL_IOFFSETS_LEN 4
472 #define INITIAL_IFACES_LEN 4
474 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
476 // Generate tables for constant-time assignment testing and interface
477 // method lookup. This implements the technique described by Per Bothner
478 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
479 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
480 void
481 _Jv_Linker::prepare_constant_time_tables (jclass klass)
483 if (klass->isPrimitive () || klass->isInterface ())
484 return;
486 // Short-circuit in case we've been called already.
487 if ((klass->idt != NULL) || klass->depth != 0)
488 return;
490 // Calculate the class depth and ancestor table. The depth of a class
491 // is how many "extends" it is removed from Object. Thus the depth of
492 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
493 // is 2. Depth is defined for all regular and array classes, but not
494 // interfaces or primitive types.
496 jclass klass0 = klass;
497 jboolean has_interfaces = 0;
498 while (klass0 != &java::lang::Object::class$)
500 has_interfaces += klass0->interface_count;
501 klass0 = klass0->superclass;
502 klass->depth++;
505 // We do class member testing in constant time by using a small table
506 // of all the ancestor classes within each class. The first element is
507 // a pointer to the current class, and the rest are pointers to the
508 // classes ancestors, ordered from the current class down by decreasing
509 // depth. We do not include java.lang.Object in the table of ancestors,
510 // since it is redundant.
512 // FIXME: _Jv_AllocBytes
513 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth
514 * sizeof (jclass));
515 klass0 = klass;
516 for (int index = 0; index < klass->depth; index++)
518 klass->ancestors[index] = klass0;
519 klass0 = klass0->superclass;
522 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
523 return;
525 // Optimization: If class implements no interfaces, use a common
526 // predefined interface table.
527 if (!has_interfaces)
529 klass->idt = &null_idt;
530 return;
533 // FIXME: _Jv_AllocBytes
534 klass->idt =
535 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
537 _Jv_ifaces ifaces;
538 ifaces.count = 0;
539 ifaces.len = INITIAL_IFACES_LEN;
540 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
542 int itable_size = get_interfaces (klass, &ifaces);
544 if (ifaces.count > 0)
546 klass->idt->cls.itable =
547 // FIXME: _Jv_AllocBytes
548 (void **) _Jv_Malloc (itable_size * sizeof (void *));
549 klass->idt->cls.itable_length = itable_size;
551 jshort *itable_offsets =
552 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
554 generate_itable (klass, &ifaces, itable_offsets);
556 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
557 ifaces.count);
559 for (int i = 0; i < ifaces.count; i++)
561 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
562 itable_offsets[i];
565 klass->idt->cls.iindex = cls_iindex;
567 _Jv_Free (ifaces.list);
568 _Jv_Free (itable_offsets);
570 else
572 klass->idt->cls.iindex = SHRT_MAX;
576 // Return index of item in list, or -1 if item is not present.
577 inline jshort
578 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
580 for (int i=0; i < list_len; i++)
582 if (list[i] == item)
583 return i;
585 return -1;
588 // Find all unique interfaces directly or indirectly implemented by klass.
589 // Returns the size of the interface dispatch table (itable) for klass, which
590 // is the number of unique interfaces plus the total number of methods that
591 // those interfaces declare. May extend ifaces if required.
592 jshort
593 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
595 jshort result = 0;
597 for (int i = 0; i < klass->interface_count; i++)
599 jclass iface = klass->interfaces[i];
601 /* Make sure interface is linked. */
602 wait_for_state(iface, JV_STATE_LINKED);
604 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
606 if (ifaces->count + 1 >= ifaces->len)
608 /* Resize ifaces list */
609 ifaces->len = ifaces->len * 2;
610 ifaces->list
611 = (jclass *) _Jv_Realloc (ifaces->list,
612 ifaces->len * sizeof(jclass));
614 ifaces->list[ifaces->count] = iface;
615 ifaces->count++;
617 result += get_interfaces (klass->interfaces[i], ifaces);
621 if (klass->isInterface())
622 result += klass->method_count + 1;
623 else if (klass->superclass)
624 result += get_interfaces (klass->superclass, ifaces);
625 return result;
628 // Fill out itable in klass, resolving method declarations in each ifaces.
629 // itable_offsets is filled out with the position of each iface in itable,
630 // such that itable[itable_offsets[n]] == ifaces.list[n].
631 void
632 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
633 jshort *itable_offsets)
635 void **itable = klass->idt->cls.itable;
636 jshort itable_pos = 0;
638 for (int i = 0; i < ifaces->count; i++)
640 jclass iface = ifaces->list[i];
641 itable_offsets[i] = itable_pos;
642 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
644 /* Create interface dispatch table for iface */
645 if (iface->idt == NULL)
647 // FIXME: _Jv_AllocBytes
648 iface->idt
649 = (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
651 // The first element of ioffsets is its length (itself included).
652 // FIXME: _Jv_AllocBytes
653 jshort *ioffsets = (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN
654 * sizeof (jshort));
655 ioffsets[0] = INITIAL_IOFFSETS_LEN;
656 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
657 ioffsets[i] = -1;
659 iface->idt->iface.ioffsets = ioffsets;
664 // Format method name for use in error messages.
665 jstring
666 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
668 jstring r = klass->name->toString();
669 r = r->concat (JvNewStringUTF ("."));
670 r = r->concat (name->toString());
671 return r;
674 void
675 _Jv_ThrowNoSuchMethodError ()
677 throw new java::lang::NoSuchMethodError;
680 // Each superinterface of a class (i.e. each interface that the class
681 // directly or indirectly implements) has a corresponding "Partial
682 // Interface Dispatch Table" whose size is (number of methods + 1) words.
683 // The first word is a pointer to the interface (i.e. the java.lang.Class
684 // instance for that interface). The remaining words are pointers to the
685 // actual methods that implement the methods declared in the interface,
686 // in order of declaration.
688 // Append partial interface dispatch table for "iface" to "itable", at
689 // position itable_pos.
690 // Returns the offset at which the next partial ITable should be appended.
691 jshort
692 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
693 void **itable, jshort pos)
695 using namespace java::lang::reflect;
697 itable[pos++] = (void *) iface;
698 _Jv_Method *meth;
700 for (int j=0; j < iface->method_count; j++)
702 meth = NULL;
703 for (jclass cl = klass; cl; cl = cl->getSuperclass())
705 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
706 iface->methods[j].signature);
708 if (meth)
709 break;
712 if (meth && (meth->name->first() == '<'))
714 // leave a placeholder in the itable for hidden init methods.
715 itable[pos] = NULL;
717 else if (meth)
719 if ((meth->accflags & Modifier::STATIC) != 0)
720 throw new java::lang::IncompatibleClassChangeError
721 (_Jv_GetMethodString (klass, meth->name));
722 if ((meth->accflags & Modifier::ABSTRACT) != 0)
723 throw new java::lang::AbstractMethodError
724 (_Jv_GetMethodString (klass, meth->name));
725 if ((meth->accflags & Modifier::PUBLIC) == 0)
726 throw new java::lang::IllegalAccessError
727 (_Jv_GetMethodString (klass, meth->name));
729 itable[pos] = meth->ncode;
731 else
733 // The method doesn't exist in klass. Binary compatibility rules
734 // permit this, so we delay the error until runtime using a pointer
735 // to a method which throws an exception.
736 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
738 pos++;
741 return pos;
744 static _Jv_Mutex_t iindex_mutex;
745 static bool iindex_mutex_initialized = false;
747 // We need to find the correct offset in the Class Interface Dispatch
748 // Table for a given interface. Once we have that, invoking an interface
749 // method just requires combining the Method's index in the interface
750 // (known at compile time) to get the correct method. Doing a type test
751 // (cast or instanceof) is the same problem: Once we have a possible Partial
752 // Interface Dispatch Table, we just compare the first element to see if it
753 // matches the desired interface. So how can we find the correct offset?
754 // Our solution is to keep a vector of candiate offsets in each interface
755 // (idt->iface.ioffsets), and in each class we have an index
756 // (idt->cls.iindex) used to select the correct offset from ioffsets.
758 // Calculate and return iindex for a new class.
759 // ifaces is a vector of num interfaces that the class implements.
760 // offsets[j] is the offset in the interface dispatch table for the
761 // interface corresponding to ifaces[j].
762 // May extend the interface ioffsets if required.
763 jshort
764 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
766 int i;
767 int j;
769 // Acquire a global lock to prevent itable corruption in case of multiple
770 // classes that implement an intersecting set of interfaces being linked
771 // simultaneously. We can assume that the mutex will be initialized
772 // single-threaded.
773 if (! iindex_mutex_initialized)
775 _Jv_MutexInit (&iindex_mutex);
776 iindex_mutex_initialized = true;
779 _Jv_MutexLock (&iindex_mutex);
781 for (i=1;; i++) /* each potential position in ioffsets */
783 for (j=0;; j++) /* each iface */
785 if (j >= num)
786 goto found;
787 if (i >= ifaces[j]->idt->iface.ioffsets[0])
788 continue;
789 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
790 /* We can potentially share this position with another class. */
791 if (ioffset >= 0 && ioffset != offsets[j])
792 break; /* Nope. Try next i. */
795 found:
796 for (j = 0; j < num; j++)
798 int len = ifaces[j]->idt->iface.ioffsets[0];
799 if (i >= len)
801 // Resize ioffsets.
802 int newlen = 2 * len;
803 if (i >= newlen)
804 newlen = i + 3;
805 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
806 // FIXME: _Jv_AllocBytes
807 jshort *new_ioffsets = (jshort *) _Jv_Malloc (newlen
808 * sizeof(jshort));
809 memcpy (&new_ioffsets[1], &old_ioffsets[1],
810 (len - 1) * sizeof (jshort));
811 new_ioffsets[0] = newlen;
813 while (len < newlen)
814 new_ioffsets[len++] = -1;
816 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
818 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
821 _Jv_MutexUnlock (&iindex_mutex);
823 return i;
827 // Functions for indirect dispatch (symbolic virtual binding) support.
829 // There are three tables, atable otable and itable. atable is an
830 // array of addresses, and otable is an array of offsets, and these
831 // are used for static and virtual members respectively. itable is an
832 // array of pairs {address, index} where each address is a pointer to
833 // an interface.
835 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
836 // symbol is a tuple of {classname, member name, signature}.
838 // Set this to true to enable debugging of indirect dispatch tables/linking.
839 static bool debug_link = false;
841 // link_symbol_table() scans these two arrays and fills in the
842 // corresponding atable and otable with the addresses of static
843 // members and the offsets of virtual members.
845 // The offset (in bytes) for each resolved method or field is placed
846 // at the corresponding position in the virtual method offset table
847 // (klass->otable).
849 // The same otable and atable may be shared by many classes.
851 // This must be called while holding the class lock.
853 void
854 _Jv_Linker::link_symbol_table (jclass klass)
856 int index = 0;
857 _Jv_MethodSymbol sym;
858 if (klass->otable == NULL
859 || klass->otable->state != 0)
860 goto atable;
862 klass->otable->state = 1;
864 if (debug_link)
865 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
866 for (index = 0;
867 (sym = klass->otable_syms[index]).class_name != NULL;
868 ++index)
870 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
871 _Jv_Method *meth = NULL;
873 _Jv_Utf8Const *signature = sym.signature;
876 static char *bounce = (char *)_Jv_ThrowNoSuchMethodError;
877 ptrdiff_t offset = (char *)(klass->vtable) - bounce;
878 klass->otable->offsets[index] = offset;
881 if (target_class == NULL)
882 throw new java::lang::NoClassDefFoundError
883 (_Jv_NewStringUTF (sym.class_name->chars()));
885 // We're looking for a field or a method, and we can tell
886 // which is needed by looking at the signature.
887 if (signature->first() == '(' && signature->len() >= 2)
889 // Looks like someone is trying to invoke an interface method
890 if (target_class->isInterface())
892 using namespace java::lang;
893 StringBuffer *sb = new StringBuffer();
894 sb->append(JvNewStringLatin1("found interface "));
895 sb->append(target_class->getName());
896 sb->append(JvNewStringLatin1(" when searching for a class"));
897 throw new VerifyError(sb->toString());
900 // If the target class does not have a vtable_method_count yet,
901 // then we can't tell the offsets for its methods, so we must lay
902 // it out now.
903 wait_for_state(target_class, JV_STATE_PREPARED);
905 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
906 sym.signature);
908 if (meth != NULL)
910 int offset = _Jv_VTable::idx_to_offset (meth->index);
911 if (offset == -1)
912 JvFail ("Bad method index");
913 JvAssert (meth->index < target_class->vtable_method_count);
914 klass->otable->offsets[index] = offset;
916 if (debug_link)
917 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
918 (int)index,
919 (int)klass->otable->offsets[index],
920 (const char*)target_class->name->chars(),
921 target_class,
922 (const char*)sym.name->chars(),
923 (const char*)signature->chars());
924 continue;
927 // Try fields.
929 wait_for_state(target_class, JV_STATE_PREPARED);
930 _Jv_Field *the_field = find_field (klass, target_class,
931 sym.name, sym.signature);
932 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
933 throw new java::lang::IncompatibleClassChangeError;
934 else
935 klass->otable->offsets[index] = the_field->u.boffset;
939 atable:
940 if (klass->atable == NULL || klass->atable->state != 0)
941 goto itable;
943 klass->atable->state = 1;
945 for (index = 0;
946 (sym = klass->atable_syms[index]).class_name != NULL;
947 ++index)
949 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
950 _Jv_Method *meth = NULL;
951 _Jv_Utf8Const *signature = sym.signature;
953 // ??? Setting this pointer to null will at least get us a
954 // NullPointerException
955 klass->atable->addresses[index] = NULL;
957 if (target_class == NULL)
958 throw new java::lang::NoClassDefFoundError
959 (_Jv_NewStringUTF (sym.class_name->chars()));
961 // We're looking for a static field or a static method, and we
962 // can tell which is needed by looking at the signature.
963 if (signature->first() == '(' && signature->len() >= 2)
965 // If the target class does not have a vtable_method_count yet,
966 // then we can't tell the offsets for its methods, so we must lay
967 // it out now.
968 wait_for_state (target_class, JV_STATE_PREPARED);
970 // Interface methods cannot have bodies.
971 if (target_class->isInterface())
973 using namespace java::lang;
974 StringBuffer *sb = new StringBuffer();
975 sb->append(JvNewStringLatin1("class "));
976 sb->append(target_class->getName());
977 sb->append(JvNewStringLatin1(" is an interface: "
978 "class expected"));
979 throw new VerifyError(sb->toString());
982 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
983 sym.signature);
985 if (meth != NULL)
987 if (meth->ncode) // Maybe abstract?
989 klass->atable->addresses[index] = meth->ncode;
990 if (debug_link)
991 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
992 index,
993 &klass->atable->addresses[index],
994 (const char*)target_class->name->chars(),
995 klass,
996 (const char*)sym.name->chars(),
997 (const char*)signature->chars());
1000 else
1001 klass->atable->addresses[index]
1002 = (void *)_Jv_ThrowNoSuchMethodError;
1004 continue;
1007 // Try fields.
1009 wait_for_state(target_class, JV_STATE_PREPARED);
1010 _Jv_Field *the_field = find_field (klass, target_class,
1011 sym.name, sym.signature);
1012 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1013 klass->atable->addresses[index] = the_field->u.addr;
1014 else
1015 throw new java::lang::IncompatibleClassChangeError;
1019 itable:
1020 if (klass->itable == NULL
1021 || klass->itable->state != 0)
1022 return;
1024 klass->itable->state = 1;
1026 for (index = 0;
1027 (sym = klass->itable_syms[index]).class_name != NULL;
1028 ++index)
1030 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1031 _Jv_Utf8Const *signature = sym.signature;
1033 jclass cls;
1034 int i;
1036 wait_for_state(target_class, JV_STATE_LOADED);
1037 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1038 sym.name, sym.signature);
1040 if (found)
1042 klass->itable->addresses[index * 2] = cls;
1043 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1044 if (debug_link)
1046 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1047 index,
1048 klass->itable->addresses[index * 2],
1049 (const char*)cls->name->chars(),
1050 cls,
1051 (const char*)sym.name->chars(),
1052 (const char*)signature->chars());
1053 fprintf (stderr, " [%d] = offset %d\n",
1054 index + 1,
1055 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1059 else
1060 throw new java::lang::IncompatibleClassChangeError;
1065 // For each catch_record in the list of caught classes, fill in the
1066 // address field.
1067 void
1068 _Jv_Linker::link_exception_table (jclass self)
1070 struct _Jv_CatchClass *catch_record = self->catch_classes;
1071 if (!catch_record || catch_record->classname)
1072 return;
1073 catch_record++;
1074 while (catch_record->classname)
1078 jclass target_class
1079 = _Jv_FindClass (catch_record->classname,
1080 self->getClassLoaderInternal ());
1081 *catch_record->address = target_class;
1083 catch (::java::lang::Throwable *t)
1085 // FIXME: We need to do something better here.
1086 *catch_record->address = 0;
1088 catch_record++;
1090 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1093 // This is put in empty vtable slots.
1094 static void
1095 _Jv_abstractMethodError (void)
1097 throw new java::lang::AbstractMethodError();
1100 // Set itable method indexes for members of interface IFACE.
1101 void
1102 _Jv_Linker::layout_interface_methods (jclass iface)
1104 if (! iface->isInterface())
1105 return;
1107 // itable indexes start at 1.
1108 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1109 // itable so they are also assigned an index here.
1110 for (int i = 0; i < iface->method_count; i++)
1111 iface->methods[i].index = i + 1;
1114 // Prepare virtual method declarations in KLASS, and any superclasses
1115 // as required, by determining their vtable index, setting
1116 // method->index, and finally setting the class's vtable_method_count.
1117 // Must be called with the lock for KLASS held.
1118 void
1119 _Jv_Linker::layout_vtable_methods (jclass klass)
1121 if (klass->vtable != NULL || klass->isInterface()
1122 || klass->vtable_method_count != -1)
1123 return;
1125 jclass superclass = klass->getSuperclass();
1127 if (superclass != NULL && superclass->vtable_method_count == -1)
1129 JvSynchronize sync (superclass);
1130 layout_vtable_methods (superclass);
1133 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1135 for (int i = 0; i < klass->method_count; ++i)
1137 _Jv_Method *meth = &klass->methods[i];
1138 _Jv_Method *super_meth = NULL;
1140 if (! _Jv_isVirtualMethod (meth))
1141 continue;
1143 if (superclass != NULL)
1145 jclass declarer;
1146 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1147 meth->signature, &declarer);
1148 // See if this method actually overrides the other method
1149 // we've found.
1150 if (super_meth)
1152 if (! _Jv_isVirtualMethod (super_meth)
1153 || ! _Jv_CheckAccess (klass, declarer,
1154 super_meth->accflags))
1155 super_meth = NULL;
1156 else if ((super_meth->accflags
1157 & java::lang::reflect::Modifier::FINAL) != 0)
1159 using namespace java::lang;
1160 StringBuffer *sb = new StringBuffer();
1161 sb->append(JvNewStringLatin1("method "));
1162 sb->append(_Jv_GetMethodString(klass, meth->name));
1163 sb->append(JvNewStringLatin1(" overrides final method "));
1164 sb->append(_Jv_GetMethodString(declarer, super_meth->name));
1165 throw new VerifyError(sb->toString());
1170 if (super_meth)
1171 meth->index = super_meth->index;
1172 else
1173 meth->index = index++;
1176 klass->vtable_method_count = index;
1179 // Set entries in VTABLE for virtual methods declared in KLASS.
1180 void
1181 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1183 for (int i = klass->method_count - 1; i >= 0; i--)
1185 using namespace java::lang::reflect;
1187 _Jv_Method *meth = &klass->methods[i];
1188 if (meth->index == (_Jv_ushort) -1)
1189 continue;
1190 if ((meth->accflags & Modifier::ABSTRACT))
1191 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1192 else
1193 vtable->set_method(meth->index, meth->ncode);
1197 // Allocate and lay out the virtual method table for KLASS. This will
1198 // also cause vtables to be generated for any non-abstract
1199 // superclasses, and virtual method layout to occur for any abstract
1200 // superclasses. Must be called with monitor lock for KLASS held.
1201 void
1202 _Jv_Linker::make_vtable (jclass klass)
1204 using namespace java::lang::reflect;
1206 // If the vtable exists, or for interface classes, do nothing. All
1207 // other classes, including abstract classes, need a vtable.
1208 if (klass->vtable != NULL || klass->isInterface())
1209 return;
1211 // Ensure all the `ncode' entries are set.
1212 klass->engine->create_ncode(klass);
1214 // Class must be laid out before we can create a vtable.
1215 if (klass->vtable_method_count == -1)
1216 layout_vtable_methods (klass);
1218 // Allocate the new vtable.
1219 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1220 klass->vtable = vtable;
1222 // Copy the vtable of the closest superclass.
1223 jclass superclass = klass->superclass;
1225 JvSynchronize sync (superclass);
1226 make_vtable (superclass);
1228 for (int i = 0; i < superclass->vtable_method_count; ++i)
1229 vtable->set_method (i, superclass->vtable->get_method (i));
1231 // Set the class pointer and GC descriptor.
1232 vtable->clas = klass;
1233 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1235 // For each virtual declared in klass, set new vtable entry or
1236 // override an old one.
1237 set_vtable_entries (klass, vtable);
1239 // It is an error to have an abstract method in a concrete class.
1240 if (! (klass->accflags & Modifier::ABSTRACT))
1242 for (int i = 0; i < klass->vtable_method_count; ++i)
1243 if (vtable->get_method(i) == (void *) &_Jv_abstractMethodError)
1245 using namespace java::lang;
1246 while (klass != NULL)
1248 for (int j = 0; j < klass->method_count; ++j)
1250 if (klass->methods[j].index == i)
1252 StringBuffer *buf = new StringBuffer ();
1253 buf->append (_Jv_NewStringUtf8Const (klass->methods[j].name));
1254 buf->append ((jchar) ' ');
1255 buf->append (_Jv_NewStringUtf8Const (klass->methods[j].signature));
1256 throw new AbstractMethodError (buf->toString ());
1259 klass = klass->getSuperclass ();
1261 // Couldn't find the name, which is weird.
1262 // But we still must throw the error.
1263 throw new AbstractMethodError ();
1268 // Lay out the class, allocating space for static fields and computing
1269 // offsets of instance fields. The class lock must be held by the
1270 // caller.
1271 void
1272 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1274 if (klass->size_in_bytes != -1)
1275 return;
1277 // Compute the alignment for this type by searching through the
1278 // superclasses and finding the maximum required alignment. We
1279 // could consider caching this in the Class.
1280 int max_align = __alignof__ (java::lang::Object);
1281 jclass super = klass->getSuperclass();
1282 while (super != NULL)
1284 // Ensure that our super has its super installed before
1285 // recursing.
1286 wait_for_state(super, JV_STATE_LOADING);
1287 ensure_fields_laid_out(super);
1288 int num = JvNumInstanceFields (super);
1289 _Jv_Field *field = JvGetFirstInstanceField (super);
1290 while (num > 0)
1292 int field_align = get_alignment_from_class (field->type);
1293 if (field_align > max_align)
1294 max_align = field_align;
1295 ++field;
1296 --num;
1298 super = super->getSuperclass();
1301 int instance_size;
1302 int static_size = 0;
1304 // Although java.lang.Object is never interpreted, an interface can
1305 // have a null superclass. Note that we have to lay out an
1306 // interface because it might have static fields.
1307 if (klass->superclass)
1308 instance_size = klass->superclass->size();
1309 else
1310 instance_size = java::lang::Object::class$.size();
1312 for (int i = 0; i < klass->field_count; i++)
1314 int field_size;
1315 int field_align;
1317 _Jv_Field *field = &klass->fields[i];
1319 if (! field->isRef ())
1321 // It is safe to resolve the field here, since it's a
1322 // primitive class, which does not cause loading to happen.
1323 resolve_field (field, klass->loader);
1325 field_size = field->type->size ();
1326 field_align = get_alignment_from_class (field->type);
1328 else
1330 field_size = sizeof (jobject);
1331 field_align = __alignof__ (jobject);
1334 field->bsize = field_size;
1336 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1338 if (field->u.addr == NULL)
1340 // This computes an offset into a region we'll allocate
1341 // shortly, and then add this offset to the start
1342 // address.
1343 static_size = ROUND (static_size, field_align);
1344 field->u.boffset = static_size;
1345 static_size += field_size;
1348 else
1350 instance_size = ROUND (instance_size, field_align);
1351 field->u.boffset = instance_size;
1352 instance_size += field_size;
1353 if (field_align > max_align)
1354 max_align = field_align;
1358 if (static_size != 0)
1359 klass->engine->allocate_static_fields (klass, static_size);
1361 // Set the instance size for the class. Note that first we round it
1362 // to the alignment required for this object; this keeps us in sync
1363 // with our current ABI.
1364 instance_size = ROUND (instance_size, max_align);
1365 klass->size_in_bytes = instance_size;
1368 // This takes the class to state JV_STATE_LINKED. The class lock must
1369 // be held when calling this.
1370 void
1371 _Jv_Linker::ensure_class_linked (jclass klass)
1373 if (klass->state >= JV_STATE_LINKED)
1374 return;
1376 int state = klass->state;
1379 // Short-circuit, so that mutually dependent classes are ok.
1380 klass->state = JV_STATE_LINKED;
1382 _Jv_Constants *pool = &klass->constants;
1384 // Compiled classes require that their class constants be
1385 // resolved here. However, interpreted classes need their
1386 // constants to be resolved lazily. If we resolve an
1387 // interpreted class' constants eagerly, we can end up with
1388 // spurious IllegalAccessErrors when the constant pool contains
1389 // a reference to a class we can't access. This can validly
1390 // occur in an obscure case involving the InnerClasses
1391 // attribute.
1392 #ifdef INTERPRETER
1393 if (! _Jv_IsInterpretedClass (klass))
1394 #endif
1396 // Resolve class constants first, since other constant pool
1397 // entries may rely on these.
1398 for (int index = 1; index < pool->size; ++index)
1400 if (pool->tags[index] == JV_CONSTANT_Class)
1401 resolve_pool_entry (klass, index);
1405 #if 0 // Should be redundant now
1406 // If superclass looks like a constant pool entry,
1407 // resolve it now.
1408 if ((uaddr) klass->superclass < (uaddr) pool->size)
1409 klass->superclass = pool->data[(uaddr) klass->superclass].clazz;
1411 // Likewise for interfaces.
1412 for (int i = 0; i < klass->interface_count; i++)
1414 if ((uaddr) klass->interfaces[i] < (uaddr) pool->size)
1415 klass->interfaces[i]
1416 = pool->data[(uaddr) klass->interfaces[i]].clazz;
1418 #endif
1420 // Resolve the remaining constant pool entries.
1421 for (int index = 1; index < pool->size; ++index)
1423 if (pool->tags[index] == JV_CONSTANT_String)
1425 jstring str;
1427 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1428 pool->data[index].o = str;
1429 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1433 if (klass->engine->need_resolve_string_fields())
1435 jfieldID f = JvGetFirstStaticField (klass);
1436 for (int n = JvNumStaticFields (klass); n > 0; --n)
1438 int mod = f->getModifiers ();
1439 // If we have a static String field with a non-null initial
1440 // value, we know it points to a Utf8Const.
1441 resolve_field(f, klass->loader);
1442 if (f->getClass () == &java::lang::String::class$
1443 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1445 jstring *strp = (jstring *) f->u.addr;
1446 if (*strp)
1447 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1449 f = f->getNextField ();
1453 klass->notifyAll ();
1455 _Jv_PushClass (klass);
1457 catch (java::lang::Throwable *t)
1459 klass->state = state;
1460 throw t;
1464 // This ensures that symbolic superclass and superinterface references
1465 // are resolved for the indicated class. This must be called with the
1466 // class lock held.
1467 void
1468 _Jv_Linker::ensure_supers_installed (jclass klass)
1470 resolve_class_ref (klass, &klass->superclass);
1471 // An interface won't have a superclass.
1472 if (klass->superclass)
1473 wait_for_state (klass->superclass, JV_STATE_LOADING);
1475 for (int i = 0; i < klass->interface_count; ++i)
1477 resolve_class_ref (klass, &klass->interfaces[i]);
1478 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1482 // This adds missing `Miranda methods' to a class.
1483 void
1484 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1486 // Note that at this point, all our supers, and the supers of all
1487 // our superclasses and superinterfaces, will have been installed.
1489 for (int i = 0; i < iface_class->interface_count; ++i)
1491 jclass interface = iface_class->interfaces[i];
1493 for (int j = 0; j < interface->method_count; ++j)
1495 _Jv_Method *meth = &interface->methods[j];
1496 // Don't bother with <clinit>.
1497 if (meth->name->first() == '<')
1498 continue;
1499 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1500 meth->signature);
1501 if (! new_meth)
1503 // We assume that such methods are very unlikely, so we
1504 // just reallocate the method array each time one is
1505 // found. This greatly simplifies the searching --
1506 // otherwise we have to make sure that each such method
1507 // found is really unique among all superinterfaces.
1508 int new_count = base->method_count + 1;
1509 _Jv_Method *new_m
1510 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
1511 * new_count);
1512 memcpy (new_m, base->methods,
1513 sizeof (_Jv_Method) * base->method_count);
1515 // Add new method.
1516 new_m[base->method_count] = *meth;
1517 new_m[base->method_count].index = (_Jv_ushort) -1;
1518 new_m[base->method_count].accflags
1519 |= java::lang::reflect::Modifier::INVISIBLE;
1521 base->methods = new_m;
1522 base->method_count = new_count;
1526 wait_for_state (interface, JV_STATE_LOADED);
1527 add_miranda_methods (base, interface);
1531 // This ensures that the class' method table is "complete". This must
1532 // be called with the class lock held.
1533 void
1534 _Jv_Linker::ensure_method_table_complete (jclass klass)
1536 if (klass->vtable != NULL || klass->isInterface())
1537 return;
1539 // We need our superclass to have its own Miranda methods installed.
1540 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1542 // A class might have so-called "Miranda methods". This is a method
1543 // that is declared in an interface and not re-declared in an
1544 // abstract class. Some compilers don't emit declarations for such
1545 // methods in the class; this will give us problems since we expect
1546 // a declaration for any method requiring a vtable entry. We handle
1547 // this here by searching for such methods and constructing new
1548 // internal declarations for them. Note that we do this
1549 // unconditionally, and not just for abstract classes, to correctly
1550 // account for cases where a class is modified to be concrete and
1551 // still incorrectly inherits an abstract method.
1552 int pre_count = klass->method_count;
1553 add_miranda_methods (klass, klass);
1555 // Let the execution engine know that we've added methods.
1556 if (klass->method_count != pre_count)
1557 klass->engine->post_miranda_hook(klass);
1560 // Verify a class. Must be called with class lock held.
1561 void
1562 _Jv_Linker::verify_class (jclass klass)
1564 klass->engine->verify(klass);
1567 // Check the assertions contained in the type assertion table for KLASS.
1568 // This is the equivilent of bytecode verification for native, BC-ABI code.
1569 void
1570 _Jv_Linker::verify_type_assertions (jclass klass)
1572 if (debug_link)
1573 fprintf (stderr, "Evaluating type assertions for %s:\n",
1574 klass->name->chars());
1576 if (klass->assertion_table == NULL)
1577 return;
1579 for (int i = 0;; i++)
1581 int assertion_code = klass->assertion_table[i].assertion_code;
1582 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1583 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1585 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1586 return;
1587 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1589 if (debug_link)
1591 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1592 assertion_code, op1->chars(), op2->chars());
1595 // The operands are class signatures. op1 is the source,
1596 // op2 is the target.
1597 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1598 klass->getClassLoaderInternal());
1599 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1600 klass->getClassLoaderInternal());
1602 // If the class doesn't exist, ignore the assertion. An exception
1603 // will be thrown later if an attempt is made to actually
1604 // instantiate the class.
1605 if (cl1 == NULL || cl2 == NULL)
1606 continue;
1608 if (! _Jv_IsAssignableFromSlow (cl2, cl1))
1610 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1611 s = s->concat (klass->getName());
1612 s = s->concat (JvNewStringUTF (": "));
1613 s = s->concat (cl1->getName());
1614 s = s->concat (JvNewStringUTF (" is not assignable to "));
1615 s = s->concat (cl2->getName());
1616 throw new java::lang::VerifyError (s);
1619 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1621 // TODO: Implement this.
1623 // Unknown assertion codes are ignored, for forwards-compatibility.
1627 void
1628 _Jv_Linker::print_class_loaded (jclass klass)
1630 char *codesource = NULL;
1631 if (klass->protectionDomain != NULL)
1633 java::security::CodeSource *cs
1634 = klass->protectionDomain->getCodeSource();
1635 if (cs != NULL)
1637 jstring css = cs->toString();
1638 int len = JvGetStringUTFLength(css);
1639 codesource = (char *) _Jv_AllocBytes(len + 1);
1640 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1641 codesource[len] = '\0';
1644 if (codesource == NULL)
1645 codesource = "<no code source>";
1647 // We use a somewhat bogus test for the ABI here.
1648 char *abi;
1649 #ifdef INTERPRETER
1650 if (_Jv_IsInterpretedClass (klass))
1651 #else
1652 if (false)
1653 #endif
1654 abi = "bytecode";
1655 else if (klass->state == JV_STATE_PRELOADING)
1656 abi = "BC-compiled";
1657 else
1658 abi = "pre-compiled";
1660 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1661 codesource);
1664 // FIXME: mention invariants and stuff.
1665 void
1666 _Jv_Linker::wait_for_state (jclass klass, int state)
1668 if (klass->state >= state)
1669 return;
1671 JvSynchronize sync (klass);
1673 // This is similar to the strategy for class initialization. If we
1674 // already hold the lock, just leave.
1675 java::lang::Thread *self = java::lang::Thread::currentThread();
1676 while (klass->state <= state
1677 && klass->thread
1678 && klass->thread != self)
1679 klass->wait ();
1681 java::lang::Thread *save = klass->thread;
1682 klass->thread = self;
1684 // Print some debugging info if requested. Interpreted classes are
1685 // handled in defineclass, so we only need to handle the two
1686 // pre-compiled cases here.
1687 if (gcj::verbose_class_flag
1688 && (klass->state == JV_STATE_COMPILED
1689 || klass->state == JV_STATE_PRELOADING)
1690 #ifdef INTERPRETER
1691 && ! _Jv_IsInterpretedClass (klass)
1692 #endif
1694 print_class_loaded (klass);
1698 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
1700 ensure_supers_installed (klass);
1701 klass->set_state(JV_STATE_LOADING);
1704 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
1706 ensure_method_table_complete (klass);
1707 klass->set_state(JV_STATE_LOADED);
1710 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
1712 ensure_fields_laid_out (klass);
1713 make_vtable (klass);
1714 layout_interface_methods (klass);
1715 prepare_constant_time_tables (klass);
1716 klass->set_state(JV_STATE_PREPARED);
1719 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
1721 verify_class (klass);
1723 ensure_class_linked (klass);
1724 link_exception_table (klass);
1725 link_symbol_table (klass);
1726 klass->set_state(JV_STATE_LINKED);
1729 catch (java::lang::Throwable *exc)
1731 klass->thread = save;
1732 klass->set_state(JV_STATE_ERROR);
1733 throw exc;
1736 klass->thread = save;
1738 if (klass->state == JV_STATE_ERROR)
1739 throw new java::lang::LinkageError;