* ada/acats/tests/cxb/cxb30131.c: Include <stdlib.h> to properly
[official-gcc.git] / libjava / link.cc
blob3f45ac119a2f5a5128153c0c0e8b9d7b38f55c35
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 // Find a field.
135 // KLASS is the class that is requesting the field.
136 // OWNER is the class in which the field should be found.
137 // FIELD_TYPE_NAME is the type descriptor for the field.
138 // This function does the class loader type checks, and
139 // also access checks. Returns the field, or throws an
140 // exception on error.
141 _Jv_Field *
142 _Jv_Linker::find_field (jclass klass, jclass owner,
143 _Jv_Utf8Const *field_name,
144 _Jv_Utf8Const *field_type_name)
146 jclass field_type = 0;
148 if (owner->loader != klass->loader)
150 // FIXME: The implementation of this function
151 // (_Jv_FindClassFromSignature) will generate an instance of
152 // _Jv_Utf8Const for each call if the field type is a class name
153 // (Lxx.yy.Z;). This may be too expensive to do for each and
154 // every fieldref being resolved. For now, we fix the problem
155 // by only doing it when we have a loader different from the
156 // class declaring the field.
157 field_type = _Jv_FindClassFromSignature (field_type_name->chars(),
158 klass->loader);
161 jclass found_class = 0;
162 _Jv_Field *the_field = find_field_helper (owner, field_name, &found_class);
164 if (the_field == 0)
166 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
167 sb->append(JvNewStringLatin1("field "));
168 sb->append(owner->getName());
169 sb->append(JvNewStringLatin1("."));
170 sb->append(_Jv_NewStringUTF(field_name->chars()));
171 sb->append(JvNewStringLatin1(" was not found."));
172 throw new java::lang::NoSuchFieldError (sb->toString());
175 if (_Jv_CheckAccess (klass, found_class, the_field->flags))
177 // Resolve the field using the class' own loader if necessary.
179 if (!the_field->isResolved ())
180 resolve_field (the_field, found_class->loader);
182 if (field_type != 0 && the_field->type != field_type)
183 throw new java::lang::LinkageError
184 (JvNewStringLatin1
185 ("field type mismatch with different loaders"));
187 else
189 java::lang::StringBuffer *sb
190 = new java::lang::StringBuffer ();
191 sb->append(klass->getName());
192 sb->append(JvNewStringLatin1(": "));
193 sb->append(found_class->getName());
194 sb->append(JvNewStringLatin1("."));
195 sb->append(_Jv_NewStringUtf8Const (field_name));
196 throw new java::lang::IllegalAccessError(sb->toString());
199 return the_field;
202 _Jv_word
203 _Jv_Linker::resolve_pool_entry (jclass klass, int index)
205 using namespace java::lang::reflect;
207 _Jv_Constants *pool = &klass->constants;
209 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
210 return pool->data[index];
212 switch (pool->tags[index])
214 case JV_CONSTANT_Class:
216 _Jv_Utf8Const *name = pool->data[index].utf8;
218 jclass found;
219 if (name->first() == '[')
220 found = _Jv_FindClassFromSignature (name->chars(),
221 klass->loader);
222 else
223 found = _Jv_FindClass (name, klass->loader);
225 if (! found)
226 throw new java::lang::NoClassDefFoundError (name->toString());
228 // Check accessibility, but first strip array types as
229 // _Jv_ClassNameSamePackage can't handle arrays.
230 jclass check;
231 for (check = found;
232 check && check->isArray();
233 check = check->getComponentType())
235 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
236 || (_Jv_ClassNameSamePackage (check->name,
237 klass->name)))
239 pool->data[index].clazz = found;
240 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
242 else
244 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
245 sb->append(klass->getName());
246 sb->append(JvNewStringLatin1(" can't access class "));
247 sb->append(found->getName());
248 throw new java::lang::IllegalAccessError(sb->toString());
251 break;
253 case JV_CONSTANT_String:
255 jstring str;
256 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
257 pool->data[index].o = str;
258 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
260 break;
262 case JV_CONSTANT_Fieldref:
264 _Jv_ushort class_index, name_and_type_index;
265 _Jv_loadIndexes (&pool->data[index],
266 class_index,
267 name_and_type_index);
268 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
270 if (owner != klass)
271 _Jv_InitClass (owner);
273 _Jv_ushort name_index, type_index;
274 _Jv_loadIndexes (&pool->data[name_and_type_index],
275 name_index,
276 type_index);
278 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
279 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
281 _Jv_Field *the_field = find_field (klass, owner, field_name,
282 field_type_name);
284 pool->data[index].field = the_field;
285 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
287 break;
289 case JV_CONSTANT_Methodref:
290 case JV_CONSTANT_InterfaceMethodref:
292 _Jv_ushort class_index, name_and_type_index;
293 _Jv_loadIndexes (&pool->data[index],
294 class_index,
295 name_and_type_index);
296 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
298 if (owner != klass)
299 _Jv_InitClass (owner);
301 _Jv_ushort name_index, type_index;
302 _Jv_loadIndexes (&pool->data[name_and_type_index],
303 name_index,
304 type_index);
306 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
307 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
309 _Jv_Method *the_method = 0;
310 jclass found_class = 0;
312 // We're going to cache a pointer to the _Jv_Method object
313 // when we find it. So, to ensure this doesn't get moved from
314 // beneath us, we first put all the needed Miranda methods
315 // into the target class.
316 wait_for_state (klass, JV_STATE_LOADED);
318 // First search the class itself.
319 the_method = search_method_in_class (owner, klass,
320 method_name, method_signature);
322 if (the_method != 0)
324 found_class = owner;
325 goto end_of_method_search;
328 // If we are resolving an interface method, search the
329 // interface's superinterfaces (A superinterface is not an
330 // interface's superclass - a superinterface is implemented by
331 // the interface).
332 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
334 _Jv_ifaces ifaces;
335 ifaces.count = 0;
336 ifaces.len = 4;
337 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
338 * sizeof (jclass *));
340 get_interfaces (owner, &ifaces);
342 for (int i = 0; i < ifaces.count; i++)
344 jclass cls = ifaces.list[i];
345 the_method = search_method_in_class (cls, klass, method_name,
346 method_signature);
347 if (the_method != 0)
349 found_class = cls;
350 break;
354 _Jv_Free (ifaces.list);
356 if (the_method != 0)
357 goto end_of_method_search;
360 // Finally, search superclasses.
361 for (jclass cls = owner->getSuperclass (); cls != 0;
362 cls = cls->getSuperclass ())
364 the_method = search_method_in_class (cls, klass, method_name,
365 method_signature);
366 if (the_method != 0)
368 found_class = cls;
369 break;
373 end_of_method_search:
375 // FIXME: if (cls->loader != klass->loader), then we
376 // must actually check that the types of arguments
377 // correspond. That is, for each argument type, and
378 // the return type, doing _Jv_FindClassFromSignature
379 // with either loader should produce the same result,
380 // i.e., exactly the same jclass object. JVMS 5.4.3.3
382 if (the_method == 0)
384 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
385 sb->append(JvNewStringLatin1("method "));
386 sb->append(owner->getName());
387 sb->append(JvNewStringLatin1("."));
388 sb->append(_Jv_NewStringUTF(method_name->chars()));
389 sb->append(JvNewStringLatin1(" with signature "));
390 sb->append(_Jv_NewStringUTF(method_signature->chars()));
391 sb->append(JvNewStringLatin1(" was not found."));
392 throw new java::lang::NoSuchMethodError (sb->toString());
395 int vtable_index = -1;
396 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
397 vtable_index = (jshort)the_method->index;
399 pool->data[index].rmethod
400 = klass->engine->resolve_method(the_method,
401 found_class,
402 ((the_method->accflags
403 & Modifier::STATIC) != 0),
404 vtable_index);
405 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
407 break;
409 return pool->data[index];
412 // This function is used to lazily locate superclasses and
413 // superinterfaces. This must be called with the class lock held.
414 void
415 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
417 jclass ret = *classref;
419 // If superclass looks like a constant pool entry, resolve it now.
420 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
422 if (klass->state < JV_STATE_LINKED)
424 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
425 ret = _Jv_FindClass (name, klass->loader);
426 if (! ret)
428 throw new java::lang::NoClassDefFoundError (name->toString());
431 else
432 ret = klass->constants.data[(uaddr) classref].clazz;
433 *classref = ret;
437 // Find a method declared in the cls that is referenced from klass and
438 // perform access checks.
439 _Jv_Method *
440 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
441 _Jv_Utf8Const *method_name,
442 _Jv_Utf8Const *method_signature)
444 using namespace java::lang::reflect;
446 for (int i = 0; i < cls->method_count; i++)
448 _Jv_Method *method = &cls->methods[i];
449 if ( (!_Jv_equalUtf8Consts (method->name,
450 method_name))
451 || (!_Jv_equalUtf8Consts (method->signature,
452 method_signature)))
453 continue;
455 if (_Jv_CheckAccess (klass, cls, method->accflags))
456 return method;
457 else
459 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
460 sb->append(klass->getName());
461 sb->append(JvNewStringLatin1(": "));
462 sb->append(cls->getName());
463 sb->append(JvNewStringLatin1("."));
464 sb->append(_Jv_NewStringUTF(method_name->chars()));
465 sb->append(_Jv_NewStringUTF(method_signature->chars()));
466 throw new java::lang::IllegalAccessError (sb->toString());
469 return 0;
473 #define INITIAL_IOFFSETS_LEN 4
474 #define INITIAL_IFACES_LEN 4
476 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
478 // Generate tables for constant-time assignment testing and interface
479 // method lookup. This implements the technique described by Per Bothner
480 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
481 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
482 void
483 _Jv_Linker::prepare_constant_time_tables (jclass klass)
485 if (klass->isPrimitive () || klass->isInterface ())
486 return;
488 // Short-circuit in case we've been called already.
489 if ((klass->idt != NULL) || klass->depth != 0)
490 return;
492 // Calculate the class depth and ancestor table. The depth of a class
493 // is how many "extends" it is removed from Object. Thus the depth of
494 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
495 // is 2. Depth is defined for all regular and array classes, but not
496 // interfaces or primitive types.
498 jclass klass0 = klass;
499 jboolean has_interfaces = 0;
500 while (klass0 != &java::lang::Object::class$)
502 has_interfaces += klass0->interface_count;
503 klass0 = klass0->superclass;
504 klass->depth++;
507 // We do class member testing in constant time by using a small table
508 // of all the ancestor classes within each class. The first element is
509 // a pointer to the current class, and the rest are pointers to the
510 // classes ancestors, ordered from the current class down by decreasing
511 // depth. We do not include java.lang.Object in the table of ancestors,
512 // since it is redundant.
514 // FIXME: _Jv_AllocBytes
515 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth
516 * sizeof (jclass));
517 klass0 = klass;
518 for (int index = 0; index < klass->depth; index++)
520 klass->ancestors[index] = klass0;
521 klass0 = klass0->superclass;
524 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
525 return;
527 // Optimization: If class implements no interfaces, use a common
528 // predefined interface table.
529 if (!has_interfaces)
531 klass->idt = &null_idt;
532 return;
535 // FIXME: _Jv_AllocBytes
536 klass->idt =
537 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
539 _Jv_ifaces ifaces;
540 ifaces.count = 0;
541 ifaces.len = INITIAL_IFACES_LEN;
542 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
544 int itable_size = get_interfaces (klass, &ifaces);
546 if (ifaces.count > 0)
548 klass->idt->cls.itable =
549 // FIXME: _Jv_AllocBytes
550 (void **) _Jv_Malloc (itable_size * sizeof (void *));
551 klass->idt->cls.itable_length = itable_size;
553 jshort *itable_offsets =
554 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
556 generate_itable (klass, &ifaces, itable_offsets);
558 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
559 ifaces.count);
561 for (int i = 0; i < ifaces.count; i++)
563 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
564 itable_offsets[i];
567 klass->idt->cls.iindex = cls_iindex;
569 _Jv_Free (ifaces.list);
570 _Jv_Free (itable_offsets);
572 else
574 klass->idt->cls.iindex = SHRT_MAX;
578 // Return index of item in list, or -1 if item is not present.
579 inline jshort
580 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
582 for (int i=0; i < list_len; i++)
584 if (list[i] == item)
585 return i;
587 return -1;
590 // Find all unique interfaces directly or indirectly implemented by klass.
591 // Returns the size of the interface dispatch table (itable) for klass, which
592 // is the number of unique interfaces plus the total number of methods that
593 // those interfaces declare. May extend ifaces if required.
594 jshort
595 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
597 jshort result = 0;
599 for (int i = 0; i < klass->interface_count; i++)
601 jclass iface = klass->interfaces[i];
603 /* Make sure interface is linked. */
604 wait_for_state(iface, JV_STATE_LINKED);
606 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
608 if (ifaces->count + 1 >= ifaces->len)
610 /* Resize ifaces list */
611 ifaces->len = ifaces->len * 2;
612 ifaces->list
613 = (jclass *) _Jv_Realloc (ifaces->list,
614 ifaces->len * sizeof(jclass));
616 ifaces->list[ifaces->count] = iface;
617 ifaces->count++;
619 result += get_interfaces (klass->interfaces[i], ifaces);
623 if (klass->isInterface())
624 result += klass->method_count + 1;
625 else if (klass->superclass)
626 result += get_interfaces (klass->superclass, ifaces);
627 return result;
630 // Fill out itable in klass, resolving method declarations in each ifaces.
631 // itable_offsets is filled out with the position of each iface in itable,
632 // such that itable[itable_offsets[n]] == ifaces.list[n].
633 void
634 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
635 jshort *itable_offsets)
637 void **itable = klass->idt->cls.itable;
638 jshort itable_pos = 0;
640 for (int i = 0; i < ifaces->count; i++)
642 jclass iface = ifaces->list[i];
643 itable_offsets[i] = itable_pos;
644 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
646 /* Create interface dispatch table for iface */
647 if (iface->idt == NULL)
649 // FIXME: _Jv_AllocBytes
650 iface->idt
651 = (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
653 // The first element of ioffsets is its length (itself included).
654 // FIXME: _Jv_AllocBytes
655 jshort *ioffsets = (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN
656 * sizeof (jshort));
657 ioffsets[0] = INITIAL_IOFFSETS_LEN;
658 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
659 ioffsets[i] = -1;
661 iface->idt->iface.ioffsets = ioffsets;
666 // Format method name for use in error messages.
667 jstring
668 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
670 jstring r = klass->name->toString();
671 r = r->concat (JvNewStringUTF ("."));
672 r = r->concat (name->toString());
673 return r;
676 void
677 _Jv_ThrowNoSuchMethodError ()
679 throw new java::lang::NoSuchMethodError;
682 // Each superinterface of a class (i.e. each interface that the class
683 // directly or indirectly implements) has a corresponding "Partial
684 // Interface Dispatch Table" whose size is (number of methods + 1) words.
685 // The first word is a pointer to the interface (i.e. the java.lang.Class
686 // instance for that interface). The remaining words are pointers to the
687 // actual methods that implement the methods declared in the interface,
688 // in order of declaration.
690 // Append partial interface dispatch table for "iface" to "itable", at
691 // position itable_pos.
692 // Returns the offset at which the next partial ITable should be appended.
693 jshort
694 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
695 void **itable, jshort pos)
697 using namespace java::lang::reflect;
699 itable[pos++] = (void *) iface;
700 _Jv_Method *meth;
702 for (int j=0; j < iface->method_count; j++)
704 meth = NULL;
705 for (jclass cl = klass; cl; cl = cl->getSuperclass())
707 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
708 iface->methods[j].signature);
710 if (meth)
711 break;
714 if (meth && (meth->name->first() == '<'))
716 // leave a placeholder in the itable for hidden init methods.
717 itable[pos] = NULL;
719 else if (meth)
721 if ((meth->accflags & Modifier::STATIC) != 0)
722 throw new java::lang::IncompatibleClassChangeError
723 (_Jv_GetMethodString (klass, meth->name));
724 if ((meth->accflags & Modifier::ABSTRACT) != 0)
725 throw new java::lang::AbstractMethodError
726 (_Jv_GetMethodString (klass, meth->name));
727 if ((meth->accflags & Modifier::PUBLIC) == 0)
728 throw new java::lang::IllegalAccessError
729 (_Jv_GetMethodString (klass, meth->name));
731 itable[pos] = meth->ncode;
733 else
735 // The method doesn't exist in klass. Binary compatibility rules
736 // permit this, so we delay the error until runtime using a pointer
737 // to a method which throws an exception.
738 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
740 pos++;
743 return pos;
746 static _Jv_Mutex_t iindex_mutex;
747 static bool iindex_mutex_initialized = false;
749 // We need to find the correct offset in the Class Interface Dispatch
750 // Table for a given interface. Once we have that, invoking an interface
751 // method just requires combining the Method's index in the interface
752 // (known at compile time) to get the correct method. Doing a type test
753 // (cast or instanceof) is the same problem: Once we have a possible Partial
754 // Interface Dispatch Table, we just compare the first element to see if it
755 // matches the desired interface. So how can we find the correct offset?
756 // Our solution is to keep a vector of candiate offsets in each interface
757 // (idt->iface.ioffsets), and in each class we have an index
758 // (idt->cls.iindex) used to select the correct offset from ioffsets.
760 // Calculate and return iindex for a new class.
761 // ifaces is a vector of num interfaces that the class implements.
762 // offsets[j] is the offset in the interface dispatch table for the
763 // interface corresponding to ifaces[j].
764 // May extend the interface ioffsets if required.
765 jshort
766 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
768 int i;
769 int j;
771 // Acquire a global lock to prevent itable corruption in case of multiple
772 // classes that implement an intersecting set of interfaces being linked
773 // simultaneously. We can assume that the mutex will be initialized
774 // single-threaded.
775 if (! iindex_mutex_initialized)
777 _Jv_MutexInit (&iindex_mutex);
778 iindex_mutex_initialized = true;
781 _Jv_MutexLock (&iindex_mutex);
783 for (i=1;; i++) /* each potential position in ioffsets */
785 for (j=0;; j++) /* each iface */
787 if (j >= num)
788 goto found;
789 if (i >= ifaces[j]->idt->iface.ioffsets[0])
790 continue;
791 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
792 /* We can potentially share this position with another class. */
793 if (ioffset >= 0 && ioffset != offsets[j])
794 break; /* Nope. Try next i. */
797 found:
798 for (j = 0; j < num; j++)
800 int len = ifaces[j]->idt->iface.ioffsets[0];
801 if (i >= len)
803 // Resize ioffsets.
804 int newlen = 2 * len;
805 if (i >= newlen)
806 newlen = i + 3;
807 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
808 // FIXME: _Jv_AllocBytes
809 jshort *new_ioffsets = (jshort *) _Jv_Malloc (newlen
810 * sizeof(jshort));
811 memcpy (&new_ioffsets[1], &old_ioffsets[1],
812 (len - 1) * sizeof (jshort));
813 new_ioffsets[0] = newlen;
815 while (len < newlen)
816 new_ioffsets[len++] = -1;
818 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
820 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
823 _Jv_MutexUnlock (&iindex_mutex);
825 return i;
829 // Functions for indirect dispatch (symbolic virtual binding) support.
831 // There are three tables, atable otable and itable. atable is an
832 // array of addresses, and otable is an array of offsets, and these
833 // are used for static and virtual members respectively. itable is an
834 // array of pairs {address, index} where each address is a pointer to
835 // an interface.
837 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
838 // symbol is a tuple of {classname, member name, signature}.
840 // Set this to true to enable debugging of indirect dispatch tables/linking.
841 static bool debug_link = false;
843 // link_symbol_table() scans these two arrays and fills in the
844 // corresponding atable and otable with the addresses of static
845 // members and the offsets of virtual members.
847 // The offset (in bytes) for each resolved method or field is placed
848 // at the corresponding position in the virtual method offset table
849 // (klass->otable).
851 // The same otable and atable may be shared by many classes.
853 // This must be called while holding the class lock.
855 void
856 _Jv_Linker::link_symbol_table (jclass klass)
858 int index = 0;
859 _Jv_MethodSymbol sym;
860 if (klass->otable == NULL
861 || klass->otable->state != 0)
862 goto atable;
864 klass->otable->state = 1;
866 if (debug_link)
867 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
868 for (index = 0;
869 (sym = klass->otable_syms[index]).class_name != NULL;
870 ++index)
872 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
873 _Jv_Method *meth = NULL;
875 _Jv_Utf8Const *signature = sym.signature;
878 static char *bounce = (char *)_Jv_ThrowNoSuchMethodError;
879 ptrdiff_t offset = (char *)(klass->vtable) - bounce;
880 klass->otable->offsets[index] = offset;
883 if (target_class == NULL)
884 throw new java::lang::NoClassDefFoundError
885 (_Jv_NewStringUTF (sym.class_name->chars()));
887 // We're looking for a field or a method, and we can tell
888 // which is needed by looking at the signature.
889 if (signature->first() == '(' && signature->len() >= 2)
891 // Looks like someone is trying to invoke an interface method
892 if (target_class->isInterface())
894 using namespace java::lang;
895 StringBuffer *sb = new StringBuffer();
896 sb->append(JvNewStringLatin1("found interface "));
897 sb->append(target_class->getName());
898 sb->append(JvNewStringLatin1(" when searching for a class"));
899 throw new VerifyError(sb->toString());
902 // If the target class does not have a vtable_method_count yet,
903 // then we can't tell the offsets for its methods, so we must lay
904 // it out now.
905 wait_for_state(target_class, JV_STATE_PREPARED);
907 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
908 sym.signature);
910 if (meth != NULL)
912 int offset = _Jv_VTable::idx_to_offset (meth->index);
913 if (offset == -1)
914 JvFail ("Bad method index");
915 JvAssert (meth->index < target_class->vtable_method_count);
916 klass->otable->offsets[index] = offset;
918 if (debug_link)
919 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
920 (int)index,
921 (int)klass->otable->offsets[index],
922 (const char*)target_class->name->chars(),
923 target_class,
924 (const char*)sym.name->chars(),
925 (const char*)signature->chars());
926 continue;
929 // Try fields.
931 wait_for_state(target_class, JV_STATE_PREPARED);
932 _Jv_Field *the_field = find_field (klass, target_class,
933 sym.name, sym.signature);
934 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
935 throw new java::lang::IncompatibleClassChangeError;
936 else
937 klass->otable->offsets[index] = the_field->u.boffset;
941 atable:
942 if (klass->atable == NULL || klass->atable->state != 0)
943 goto itable;
945 klass->atable->state = 1;
947 for (index = 0;
948 (sym = klass->atable_syms[index]).class_name != NULL;
949 ++index)
951 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
952 _Jv_Method *meth = NULL;
953 _Jv_Utf8Const *signature = sym.signature;
955 // ??? Setting this pointer to null will at least get us a
956 // NullPointerException
957 klass->atable->addresses[index] = NULL;
959 if (target_class == NULL)
960 throw new java::lang::NoClassDefFoundError
961 (_Jv_NewStringUTF (sym.class_name->chars()));
963 // We're looking for a static field or a static method, and we
964 // can tell which is needed by looking at the signature.
965 if (signature->first() == '(' && signature->len() >= 2)
967 // If the target class does not have a vtable_method_count yet,
968 // then we can't tell the offsets for its methods, so we must lay
969 // it out now.
970 wait_for_state (target_class, JV_STATE_PREPARED);
972 // Interface methods cannot have bodies.
973 if (target_class->isInterface())
975 using namespace java::lang;
976 StringBuffer *sb = new StringBuffer();
977 sb->append(JvNewStringLatin1("class "));
978 sb->append(target_class->getName());
979 sb->append(JvNewStringLatin1(" is an interface: "
980 "class expected"));
981 throw new VerifyError(sb->toString());
984 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
985 sym.signature);
987 if (meth != NULL)
989 if (meth->ncode) // Maybe abstract?
991 klass->atable->addresses[index] = meth->ncode;
992 if (debug_link)
993 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
994 index,
995 &klass->atable->addresses[index],
996 (const char*)target_class->name->chars(),
997 klass,
998 (const char*)sym.name->chars(),
999 (const char*)signature->chars());
1002 else
1003 klass->atable->addresses[index]
1004 = (void *)_Jv_ThrowNoSuchMethodError;
1006 continue;
1009 // Try fields.
1011 wait_for_state(target_class, JV_STATE_PREPARED);
1012 _Jv_Field *the_field = find_field (klass, target_class,
1013 sym.name, sym.signature);
1014 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1015 klass->atable->addresses[index] = the_field->u.addr;
1016 else
1017 throw new java::lang::IncompatibleClassChangeError;
1021 itable:
1022 if (klass->itable == NULL
1023 || klass->itable->state != 0)
1024 return;
1026 klass->itable->state = 1;
1028 for (index = 0;
1029 (sym = klass->itable_syms[index]).class_name != NULL;
1030 ++index)
1032 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1033 _Jv_Utf8Const *signature = sym.signature;
1035 jclass cls;
1036 int i;
1038 wait_for_state(target_class, JV_STATE_LOADED);
1039 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1040 sym.name, sym.signature);
1042 if (found)
1044 klass->itable->addresses[index * 2] = cls;
1045 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1046 if (debug_link)
1048 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1049 index,
1050 klass->itable->addresses[index * 2],
1051 (const char*)cls->name->chars(),
1052 cls,
1053 (const char*)sym.name->chars(),
1054 (const char*)signature->chars());
1055 fprintf (stderr, " [%d] = offset %d\n",
1056 index + 1,
1057 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1061 else
1062 throw new java::lang::IncompatibleClassChangeError;
1067 // For each catch_record in the list of caught classes, fill in the
1068 // address field.
1069 void
1070 _Jv_Linker::link_exception_table (jclass self)
1072 struct _Jv_CatchClass *catch_record = self->catch_classes;
1073 if (!catch_record || catch_record->classname)
1074 return;
1075 catch_record++;
1076 while (catch_record->classname)
1080 jclass target_class
1081 = _Jv_FindClass (catch_record->classname,
1082 self->getClassLoaderInternal ());
1083 *catch_record->address = target_class;
1085 catch (::java::lang::Throwable *t)
1087 // FIXME: We need to do something better here.
1088 *catch_record->address = 0;
1090 catch_record++;
1092 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1095 // This is put in empty vtable slots.
1096 static void
1097 _Jv_abstractMethodError (void)
1099 throw new java::lang::AbstractMethodError();
1102 // Set itable method indexes for members of interface IFACE.
1103 void
1104 _Jv_Linker::layout_interface_methods (jclass iface)
1106 if (! iface->isInterface())
1107 return;
1109 // itable indexes start at 1.
1110 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1111 // itable so they are also assigned an index here.
1112 for (int i = 0; i < iface->method_count; i++)
1113 iface->methods[i].index = i + 1;
1116 // Prepare virtual method declarations in KLASS, and any superclasses
1117 // as required, by determining their vtable index, setting
1118 // method->index, and finally setting the class's vtable_method_count.
1119 // Must be called with the lock for KLASS held.
1120 void
1121 _Jv_Linker::layout_vtable_methods (jclass klass)
1123 if (klass->vtable != NULL || klass->isInterface()
1124 || klass->vtable_method_count != -1)
1125 return;
1127 jclass superclass = klass->getSuperclass();
1129 if (superclass != NULL && superclass->vtable_method_count == -1)
1131 JvSynchronize sync (superclass);
1132 layout_vtable_methods (superclass);
1135 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1137 for (int i = 0; i < klass->method_count; ++i)
1139 _Jv_Method *meth = &klass->methods[i];
1140 _Jv_Method *super_meth = NULL;
1142 if (! _Jv_isVirtualMethod (meth))
1143 continue;
1145 if (superclass != NULL)
1147 jclass declarer;
1148 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1149 meth->signature, &declarer);
1150 // See if this method actually overrides the other method
1151 // we've found.
1152 if (super_meth)
1154 if (! _Jv_isVirtualMethod (super_meth)
1155 || ! _Jv_CheckAccess (klass, declarer,
1156 super_meth->accflags))
1157 super_meth = NULL;
1158 else if ((super_meth->accflags
1159 & java::lang::reflect::Modifier::FINAL) != 0)
1161 using namespace java::lang;
1162 StringBuffer *sb = new StringBuffer();
1163 sb->append(JvNewStringLatin1("method "));
1164 sb->append(_Jv_GetMethodString(klass, meth->name));
1165 sb->append(JvNewStringLatin1(" overrides final method "));
1166 sb->append(_Jv_GetMethodString(declarer, super_meth->name));
1167 throw new VerifyError(sb->toString());
1172 if (super_meth)
1173 meth->index = super_meth->index;
1174 else
1175 meth->index = index++;
1178 klass->vtable_method_count = index;
1181 // Set entries in VTABLE for virtual methods declared in KLASS.
1182 void
1183 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1185 for (int i = klass->method_count - 1; i >= 0; i--)
1187 using namespace java::lang::reflect;
1189 _Jv_Method *meth = &klass->methods[i];
1190 if (meth->index == (_Jv_ushort) -1)
1191 continue;
1192 if ((meth->accflags & Modifier::ABSTRACT))
1193 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1194 else
1195 vtable->set_method(meth->index, meth->ncode);
1199 // Allocate and lay out the virtual method table for KLASS. This will
1200 // also cause vtables to be generated for any non-abstract
1201 // superclasses, and virtual method layout to occur for any abstract
1202 // superclasses. Must be called with monitor lock for KLASS held.
1203 void
1204 _Jv_Linker::make_vtable (jclass klass)
1206 using namespace java::lang::reflect;
1208 // If the vtable exists, or for interface classes, do nothing. All
1209 // other classes, including abstract classes, need a vtable.
1210 if (klass->vtable != NULL || klass->isInterface())
1211 return;
1213 // Ensure all the `ncode' entries are set.
1214 klass->engine->create_ncode(klass);
1216 // Class must be laid out before we can create a vtable.
1217 if (klass->vtable_method_count == -1)
1218 layout_vtable_methods (klass);
1220 // Allocate the new vtable.
1221 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1222 klass->vtable = vtable;
1224 // Copy the vtable of the closest superclass.
1225 jclass superclass = klass->superclass;
1227 JvSynchronize sync (superclass);
1228 make_vtable (superclass);
1230 for (int i = 0; i < superclass->vtable_method_count; ++i)
1231 vtable->set_method (i, superclass->vtable->get_method (i));
1233 // Set the class pointer and GC descriptor.
1234 vtable->clas = klass;
1235 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1237 // For each virtual declared in klass, set new vtable entry or
1238 // override an old one.
1239 set_vtable_entries (klass, vtable);
1241 // It is an error to have an abstract method in a concrete class.
1242 if (! (klass->accflags & Modifier::ABSTRACT))
1244 for (int i = 0; i < klass->vtable_method_count; ++i)
1245 if (vtable->get_method(i) == (void *) &_Jv_abstractMethodError)
1247 using namespace java::lang;
1248 while (klass != NULL)
1250 for (int j = 0; j < klass->method_count; ++j)
1252 if (klass->methods[j].index == i)
1254 StringBuffer *buf = new StringBuffer ();
1255 buf->append (_Jv_NewStringUtf8Const (klass->methods[j].name));
1256 buf->append ((jchar) ' ');
1257 buf->append (_Jv_NewStringUtf8Const (klass->methods[j].signature));
1258 throw new AbstractMethodError (buf->toString ());
1261 klass = klass->getSuperclass ();
1263 // Couldn't find the name, which is weird.
1264 // But we still must throw the error.
1265 throw new AbstractMethodError ();
1270 // Lay out the class, allocating space for static fields and computing
1271 // offsets of instance fields. The class lock must be held by the
1272 // caller.
1273 void
1274 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1276 if (klass->size_in_bytes != -1)
1277 return;
1279 // Compute the alignment for this type by searching through the
1280 // superclasses and finding the maximum required alignment. We
1281 // could consider caching this in the Class.
1282 int max_align = __alignof__ (java::lang::Object);
1283 jclass super = klass->getSuperclass();
1284 while (super != NULL)
1286 // Ensure that our super has its super installed before
1287 // recursing.
1288 wait_for_state(super, JV_STATE_LOADING);
1289 ensure_fields_laid_out(super);
1290 int num = JvNumInstanceFields (super);
1291 _Jv_Field *field = JvGetFirstInstanceField (super);
1292 while (num > 0)
1294 int field_align = get_alignment_from_class (field->type);
1295 if (field_align > max_align)
1296 max_align = field_align;
1297 ++field;
1298 --num;
1300 super = super->getSuperclass();
1303 int instance_size;
1304 int static_size = 0;
1306 // Although java.lang.Object is never interpreted, an interface can
1307 // have a null superclass. Note that we have to lay out an
1308 // interface because it might have static fields.
1309 if (klass->superclass)
1310 instance_size = klass->superclass->size();
1311 else
1312 instance_size = java::lang::Object::class$.size();
1314 for (int i = 0; i < klass->field_count; i++)
1316 int field_size;
1317 int field_align;
1319 _Jv_Field *field = &klass->fields[i];
1321 if (! field->isRef ())
1323 // It is safe to resolve the field here, since it's a
1324 // primitive class, which does not cause loading to happen.
1325 resolve_field (field, klass->loader);
1327 field_size = field->type->size ();
1328 field_align = get_alignment_from_class (field->type);
1330 else
1332 field_size = sizeof (jobject);
1333 field_align = __alignof__ (jobject);
1336 field->bsize = field_size;
1338 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1340 if (field->u.addr == NULL)
1342 // This computes an offset into a region we'll allocate
1343 // shortly, and then add this offset to the start
1344 // address.
1345 static_size = ROUND (static_size, field_align);
1346 field->u.boffset = static_size;
1347 static_size += field_size;
1350 else
1352 instance_size = ROUND (instance_size, field_align);
1353 field->u.boffset = instance_size;
1354 instance_size += field_size;
1355 if (field_align > max_align)
1356 max_align = field_align;
1360 if (static_size != 0)
1361 klass->engine->allocate_static_fields (klass, static_size);
1363 // Set the instance size for the class. Note that first we round it
1364 // to the alignment required for this object; this keeps us in sync
1365 // with our current ABI.
1366 instance_size = ROUND (instance_size, max_align);
1367 klass->size_in_bytes = instance_size;
1370 // This takes the class to state JV_STATE_LINKED. The class lock must
1371 // be held when calling this.
1372 void
1373 _Jv_Linker::ensure_class_linked (jclass klass)
1375 if (klass->state >= JV_STATE_LINKED)
1376 return;
1378 int state = klass->state;
1381 // Short-circuit, so that mutually dependent classes are ok.
1382 klass->state = JV_STATE_LINKED;
1384 _Jv_Constants *pool = &klass->constants;
1386 // Compiled classes require that their class constants be
1387 // resolved here. However, interpreted classes need their
1388 // constants to be resolved lazily. If we resolve an
1389 // interpreted class' constants eagerly, we can end up with
1390 // spurious IllegalAccessErrors when the constant pool contains
1391 // a reference to a class we can't access. This can validly
1392 // occur in an obscure case involving the InnerClasses
1393 // attribute.
1394 #ifdef INTERPRETER
1395 if (! _Jv_IsInterpretedClass (klass))
1396 #endif
1398 // Resolve class constants first, since other constant pool
1399 // entries may rely on these.
1400 for (int index = 1; index < pool->size; ++index)
1402 if (pool->tags[index] == JV_CONSTANT_Class)
1403 resolve_pool_entry (klass, index);
1407 #if 0 // Should be redundant now
1408 // If superclass looks like a constant pool entry,
1409 // resolve it now.
1410 if ((uaddr) klass->superclass < (uaddr) pool->size)
1411 klass->superclass = pool->data[(uaddr) klass->superclass].clazz;
1413 // Likewise for interfaces.
1414 for (int i = 0; i < klass->interface_count; i++)
1416 if ((uaddr) klass->interfaces[i] < (uaddr) pool->size)
1417 klass->interfaces[i]
1418 = pool->data[(uaddr) klass->interfaces[i]].clazz;
1420 #endif
1422 // Resolve the remaining constant pool entries.
1423 for (int index = 1; index < pool->size; ++index)
1425 if (pool->tags[index] == JV_CONSTANT_String)
1427 jstring str;
1429 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1430 pool->data[index].o = str;
1431 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1435 if (klass->engine->need_resolve_string_fields())
1437 jfieldID f = JvGetFirstStaticField (klass);
1438 for (int n = JvNumStaticFields (klass); n > 0; --n)
1440 int mod = f->getModifiers ();
1441 // If we have a static String field with a non-null initial
1442 // value, we know it points to a Utf8Const.
1443 resolve_field(f, klass->loader);
1444 if (f->getClass () == &java::lang::String::class$
1445 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1447 jstring *strp = (jstring *) f->u.addr;
1448 if (*strp)
1449 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1451 f = f->getNextField ();
1455 klass->notifyAll ();
1457 _Jv_PushClass (klass);
1459 catch (java::lang::Throwable *t)
1461 klass->state = state;
1462 throw t;
1466 // This ensures that symbolic superclass and superinterface references
1467 // are resolved for the indicated class. This must be called with the
1468 // class lock held.
1469 void
1470 _Jv_Linker::ensure_supers_installed (jclass klass)
1472 resolve_class_ref (klass, &klass->superclass);
1473 // An interface won't have a superclass.
1474 if (klass->superclass)
1475 wait_for_state (klass->superclass, JV_STATE_LOADING);
1477 for (int i = 0; i < klass->interface_count; ++i)
1479 resolve_class_ref (klass, &klass->interfaces[i]);
1480 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1484 // This adds missing `Miranda methods' to a class.
1485 void
1486 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1488 // Note that at this point, all our supers, and the supers of all
1489 // our superclasses and superinterfaces, will have been installed.
1491 for (int i = 0; i < iface_class->interface_count; ++i)
1493 jclass interface = iface_class->interfaces[i];
1495 for (int j = 0; j < interface->method_count; ++j)
1497 _Jv_Method *meth = &interface->methods[j];
1498 // Don't bother with <clinit>.
1499 if (meth->name->first() == '<')
1500 continue;
1501 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1502 meth->signature);
1503 if (! new_meth)
1505 // We assume that such methods are very unlikely, so we
1506 // just reallocate the method array each time one is
1507 // found. This greatly simplifies the searching --
1508 // otherwise we have to make sure that each such method
1509 // found is really unique among all superinterfaces.
1510 int new_count = base->method_count + 1;
1511 _Jv_Method *new_m
1512 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
1513 * new_count);
1514 memcpy (new_m, base->methods,
1515 sizeof (_Jv_Method) * base->method_count);
1517 // Add new method.
1518 new_m[base->method_count] = *meth;
1519 new_m[base->method_count].index = (_Jv_ushort) -1;
1520 new_m[base->method_count].accflags
1521 |= java::lang::reflect::Modifier::INVISIBLE;
1523 base->methods = new_m;
1524 base->method_count = new_count;
1528 wait_for_state (interface, JV_STATE_LOADED);
1529 add_miranda_methods (base, interface);
1533 // This ensures that the class' method table is "complete". This must
1534 // be called with the class lock held.
1535 void
1536 _Jv_Linker::ensure_method_table_complete (jclass klass)
1538 if (klass->vtable != NULL || klass->isInterface())
1539 return;
1541 // We need our superclass to have its own Miranda methods installed.
1542 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1544 // A class might have so-called "Miranda methods". This is a method
1545 // that is declared in an interface and not re-declared in an
1546 // abstract class. Some compilers don't emit declarations for such
1547 // methods in the class; this will give us problems since we expect
1548 // a declaration for any method requiring a vtable entry. We handle
1549 // this here by searching for such methods and constructing new
1550 // internal declarations for them. Note that we do this
1551 // unconditionally, and not just for abstract classes, to correctly
1552 // account for cases where a class is modified to be concrete and
1553 // still incorrectly inherits an abstract method.
1554 int pre_count = klass->method_count;
1555 add_miranda_methods (klass, klass);
1557 // Let the execution engine know that we've added methods.
1558 if (klass->method_count != pre_count)
1559 klass->engine->post_miranda_hook(klass);
1562 // Verify a class. Must be called with class lock held.
1563 void
1564 _Jv_Linker::verify_class (jclass klass)
1566 klass->engine->verify(klass);
1569 // Check the assertions contained in the type assertion table for KLASS.
1570 // This is the equivilent of bytecode verification for native, BC-ABI code.
1571 void
1572 _Jv_Linker::verify_type_assertions (jclass klass)
1574 if (debug_link)
1575 fprintf (stderr, "Evaluating type assertions for %s:\n",
1576 klass->name->chars());
1578 if (klass->assertion_table == NULL)
1579 return;
1581 for (int i = 0;; i++)
1583 int assertion_code = klass->assertion_table[i].assertion_code;
1584 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1585 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1587 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1588 return;
1589 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1591 if (debug_link)
1593 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1594 assertion_code, op1->chars(), op2->chars());
1597 // The operands are class signatures. op1 is the source,
1598 // op2 is the target.
1599 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1600 klass->getClassLoaderInternal());
1601 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1602 klass->getClassLoaderInternal());
1604 // If the class doesn't exist, ignore the assertion. An exception
1605 // will be thrown later if an attempt is made to actually
1606 // instantiate the class.
1607 if (cl1 == NULL || cl2 == NULL)
1608 continue;
1610 if (! _Jv_IsAssignableFromSlow (cl2, cl1))
1612 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1613 s = s->concat (klass->getName());
1614 s = s->concat (JvNewStringUTF (": "));
1615 s = s->concat (cl1->getName());
1616 s = s->concat (JvNewStringUTF (" is not assignable to "));
1617 s = s->concat (cl2->getName());
1618 throw new java::lang::VerifyError (s);
1621 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1623 // TODO: Implement this.
1625 // Unknown assertion codes are ignored, for forwards-compatibility.
1629 void
1630 _Jv_Linker::print_class_loaded (jclass klass)
1632 char *codesource = NULL;
1633 if (klass->protectionDomain != NULL)
1635 java::security::CodeSource *cs
1636 = klass->protectionDomain->getCodeSource();
1637 if (cs != NULL)
1639 jstring css = cs->toString();
1640 int len = JvGetStringUTFLength(css);
1641 codesource = (char *) _Jv_AllocBytes(len + 1);
1642 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1643 codesource[len] = '\0';
1646 if (codesource == NULL)
1647 codesource = "<no code source>";
1649 // We use a somewhat bogus test for the ABI here.
1650 char *abi;
1651 #ifdef INTERPRETER
1652 if (_Jv_IsInterpretedClass (klass))
1653 #else
1654 if (false)
1655 #endif
1656 abi = "bytecode";
1657 else if (klass->state == JV_STATE_PRELOADING)
1658 abi = "BC-compiled";
1659 else
1660 abi = "pre-compiled";
1662 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1663 codesource);
1666 // FIXME: mention invariants and stuff.
1667 void
1668 _Jv_Linker::wait_for_state (jclass klass, int state)
1670 if (klass->state >= state)
1671 return;
1673 JvSynchronize sync (klass);
1675 // This is similar to the strategy for class initialization. If we
1676 // already hold the lock, just leave.
1677 java::lang::Thread *self = java::lang::Thread::currentThread();
1678 while (klass->state <= state
1679 && klass->thread
1680 && klass->thread != self)
1681 klass->wait ();
1683 java::lang::Thread *save = klass->thread;
1684 klass->thread = self;
1686 // Print some debugging info if requested. Interpreted classes are
1687 // handled in defineclass, so we only need to handle the two
1688 // pre-compiled cases here.
1689 if (gcj::verbose_class_flag
1690 && (klass->state == JV_STATE_COMPILED
1691 || klass->state == JV_STATE_PRELOADING)
1692 #ifdef INTERPRETER
1693 && ! _Jv_IsInterpretedClass (klass)
1694 #endif
1696 print_class_loaded (klass);
1700 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
1702 ensure_supers_installed (klass);
1703 klass->set_state(JV_STATE_LOADING);
1706 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
1708 ensure_method_table_complete (klass);
1709 klass->set_state(JV_STATE_LOADED);
1712 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
1714 ensure_fields_laid_out (klass);
1715 make_vtable (klass);
1716 layout_interface_methods (klass);
1717 prepare_constant_time_tables (klass);
1718 klass->set_state(JV_STATE_PREPARED);
1721 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
1723 verify_class (klass);
1725 ensure_class_linked (klass);
1726 link_exception_table (klass);
1727 link_symbol_table (klass);
1728 klass->set_state(JV_STATE_LINKED);
1731 catch (java::lang::Throwable *exc)
1733 klass->thread = save;
1734 klass->set_state(JV_STATE_ERROR);
1735 throw exc;
1738 klass->thread = save;
1740 if (klass->state == JV_STATE_ERROR)
1741 throw new java::lang::LinkageError;