* ptree.c (cxx_print_identifier): Print a leading space if the
[official-gcc.git] / libjava / link.cc
blobe97b31bb78ec4d11419baa63c742218e3ce5be65
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 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
49 template<typename T>
50 struct aligner
52 char c;
53 T field;
56 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
58 // This returns the alignment of a type as it would appear in a
59 // structure. This can be different from the alignment of the type
60 // itself. For instance on x86 double is 8-aligned but struct{double}
61 // is 4-aligned.
62 int
63 _Jv_Linker::get_alignment_from_class (jclass klass)
65 if (klass == JvPrimClass (byte))
66 return ALIGNOF (jbyte);
67 else if (klass == JvPrimClass (short))
68 return ALIGNOF (jshort);
69 else if (klass == JvPrimClass (int))
70 return ALIGNOF (jint);
71 else if (klass == JvPrimClass (long))
72 return ALIGNOF (jlong);
73 else if (klass == JvPrimClass (boolean))
74 return ALIGNOF (jboolean);
75 else if (klass == JvPrimClass (char))
76 return ALIGNOF (jchar);
77 else if (klass == JvPrimClass (float))
78 return ALIGNOF (jfloat);
79 else if (klass == JvPrimClass (double))
80 return ALIGNOF (jdouble);
81 else
82 return ALIGNOF (jobject);
85 void
86 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
88 if (! field->isResolved ())
90 _Jv_Utf8Const *sig = (_Jv_Utf8Const *) field->type;
91 jclass type = _Jv_FindClassFromSignature (sig->chars(), loader);
92 if (type == NULL)
93 throw new java::lang::NoClassDefFoundError(field->name->toString());
94 field->type = type;
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 _Jv_Utf8Const *type_name,
104 jclass *declarer)
106 while (search)
108 // From 5.4.3.2. First search class itself.
109 for (int i = 0; i < search->field_count; ++i)
111 _Jv_Field *field = &search->fields[i];
112 if (! _Jv_equalUtf8Consts (field->name, name))
113 continue;
115 if (! field->isResolved ())
116 resolve_field (field, search->loader);
118 // Note that we compare type names and not types. This is
119 // bizarre, but we do it because we want to find a field
120 // (and terminate the search) if it has the correct
121 // descriptor -- but then later reject it if the class
122 // loader check results in different classes. We can't just
123 // pass in the descriptor and check that way, because when
124 // the field is already resolved there is no easy way to
125 // find its descriptor again.
126 if (_Jv_equalUtf8Consts (type_name, field->type->name))
128 *declarer = search;
129 return field;
133 // Next search direct interfaces.
134 for (int i = 0; i < search->interface_count; ++i)
136 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
137 type_name, declarer);
138 if (result)
139 return result;
142 // Now search superclass.
143 search = search->superclass;
146 return NULL;
149 bool
150 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
152 for (int i = 0; i < search->field_count; ++i)
154 _Jv_Field *field = &search->fields[i];
155 if (_Jv_equalUtf8Consts (field->name, field_name))
156 return true;
158 return false;
161 // Find a field.
162 // KLASS is the class that is requesting the field.
163 // OWNER is the class in which the field should be found.
164 // FIELD_TYPE_NAME is the type descriptor for the field.
165 // Fill FOUND_CLASS with the address of the class in which the field
166 // is actually declared.
167 // This function does the class loader type checks, and
168 // also access checks. Returns the field, or throws an
169 // exception on error.
170 _Jv_Field *
171 _Jv_Linker::find_field (jclass klass, jclass owner,
172 jclass *found_class,
173 _Jv_Utf8Const *field_name,
174 _Jv_Utf8Const *field_type_name)
176 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
177 // it cheaper.
178 jclass field_type = _Jv_FindClassFromSignature (field_type_name->chars(),
179 klass->loader);
180 if (field_type == NULL)
181 throw new java::lang::NoClassDefFoundError(field_name->toString());
183 _Jv_Field *the_field = find_field_helper (owner, field_name,
184 field_type->name, found_class);
186 if (the_field == 0)
188 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
189 sb->append(JvNewStringLatin1("field "));
190 sb->append(owner->getName());
191 sb->append(JvNewStringLatin1("."));
192 sb->append(_Jv_NewStringUTF(field_name->chars()));
193 sb->append(JvNewStringLatin1(" was not found."));
194 throw new java::lang::NoSuchFieldError (sb->toString());
197 if (_Jv_CheckAccess (klass, *found_class, the_field->flags))
199 // Note that the field returned by find_field_helper is always
200 // resolved. There's no point checking class loaders here,
201 // since we already did the work to look up all the types.
202 // FIXME: being lazy here would be nice.
203 if (the_field->type != field_type)
204 throw new java::lang::LinkageError
205 (JvNewStringLatin1
206 ("field type mismatch with different loaders"));
208 else
210 java::lang::StringBuffer *sb
211 = new java::lang::StringBuffer ();
212 sb->append(klass->getName());
213 sb->append(JvNewStringLatin1(": "));
214 sb->append((*found_class)->getName());
215 sb->append(JvNewStringLatin1("."));
216 sb->append(_Jv_NewStringUtf8Const (field_name));
217 throw new java::lang::IllegalAccessError(sb->toString());
220 return the_field;
223 _Jv_word
224 _Jv_Linker::resolve_pool_entry (jclass klass, int index)
226 using namespace java::lang::reflect;
228 _Jv_Constants *pool = &klass->constants;
230 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
231 return pool->data[index];
233 switch (pool->tags[index])
235 case JV_CONSTANT_Class:
237 _Jv_Utf8Const *name = pool->data[index].utf8;
239 jclass found;
240 if (name->first() == '[')
241 found = _Jv_FindClassFromSignature (name->chars(),
242 klass->loader);
243 else
244 found = _Jv_FindClass (name, klass->loader);
246 if (! found)
247 throw new java::lang::NoClassDefFoundError (name->toString());
249 // Check accessibility, but first strip array types as
250 // _Jv_ClassNameSamePackage can't handle arrays.
251 jclass check;
252 for (check = found;
253 check && check->isArray();
254 check = check->getComponentType())
256 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
257 || (_Jv_ClassNameSamePackage (check->name,
258 klass->name)))
260 pool->data[index].clazz = found;
261 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
263 else
265 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
266 sb->append(klass->getName());
267 sb->append(JvNewStringLatin1(" can't access class "));
268 sb->append(found->getName());
269 throw new java::lang::IllegalAccessError(sb->toString());
272 break;
274 case JV_CONSTANT_String:
276 jstring str;
277 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
278 pool->data[index].o = str;
279 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
281 break;
283 case JV_CONSTANT_Fieldref:
285 _Jv_ushort class_index, name_and_type_index;
286 _Jv_loadIndexes (&pool->data[index],
287 class_index,
288 name_and_type_index);
289 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
291 if (owner != klass)
292 _Jv_InitClass (owner);
294 _Jv_ushort name_index, type_index;
295 _Jv_loadIndexes (&pool->data[name_and_type_index],
296 name_index,
297 type_index);
299 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
300 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
302 jclass found_class = 0;
303 _Jv_Field *the_field = find_field (klass, owner,
304 &found_class,
305 field_name,
306 field_type_name);
307 if (owner != found_class)
308 _Jv_InitClass (found_class);
309 pool->data[index].field = the_field;
310 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
312 break;
314 case JV_CONSTANT_Methodref:
315 case JV_CONSTANT_InterfaceMethodref:
317 _Jv_ushort class_index, name_and_type_index;
318 _Jv_loadIndexes (&pool->data[index],
319 class_index,
320 name_and_type_index);
321 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
323 if (owner != klass)
324 _Jv_InitClass (owner);
326 _Jv_ushort name_index, type_index;
327 _Jv_loadIndexes (&pool->data[name_and_type_index],
328 name_index,
329 type_index);
331 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
332 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
334 _Jv_Method *the_method = 0;
335 jclass found_class = 0;
337 // We're going to cache a pointer to the _Jv_Method object
338 // when we find it. So, to ensure this doesn't get moved from
339 // beneath us, we first put all the needed Miranda methods
340 // into the target class.
341 wait_for_state (klass, JV_STATE_LOADED);
343 // First search the class itself.
344 the_method = search_method_in_class (owner, klass,
345 method_name, method_signature);
347 if (the_method != 0)
349 found_class = owner;
350 goto end_of_method_search;
353 // If we are resolving an interface method, search the
354 // interface's superinterfaces (A superinterface is not an
355 // interface's superclass - a superinterface is implemented by
356 // the interface).
357 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
359 _Jv_ifaces ifaces;
360 ifaces.count = 0;
361 ifaces.len = 4;
362 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
363 * sizeof (jclass *));
365 get_interfaces (owner, &ifaces);
367 for (int i = 0; i < ifaces.count; i++)
369 jclass cls = ifaces.list[i];
370 the_method = search_method_in_class (cls, klass, method_name,
371 method_signature);
372 if (the_method != 0)
374 found_class = cls;
375 break;
379 _Jv_Free (ifaces.list);
381 if (the_method != 0)
382 goto end_of_method_search;
385 // Finally, search superclasses.
386 for (jclass cls = owner->getSuperclass (); cls != 0;
387 cls = cls->getSuperclass ())
389 the_method = search_method_in_class (cls, klass, method_name,
390 method_signature);
391 if (the_method != 0)
393 found_class = cls;
394 break;
398 end_of_method_search:
400 // FIXME: if (cls->loader != klass->loader), then we
401 // must actually check that the types of arguments
402 // correspond. That is, for each argument type, and
403 // the return type, doing _Jv_FindClassFromSignature
404 // with either loader should produce the same result,
405 // i.e., exactly the same jclass object. JVMS 5.4.3.3
407 if (the_method == 0)
409 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
410 sb->append(JvNewStringLatin1("method "));
411 sb->append(owner->getName());
412 sb->append(JvNewStringLatin1("."));
413 sb->append(_Jv_NewStringUTF(method_name->chars()));
414 sb->append(JvNewStringLatin1(" with signature "));
415 sb->append(_Jv_NewStringUTF(method_signature->chars()));
416 sb->append(JvNewStringLatin1(" was not found."));
417 throw new java::lang::NoSuchMethodError (sb->toString());
420 int vtable_index = -1;
421 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
422 vtable_index = (jshort)the_method->index;
424 pool->data[index].rmethod
425 = klass->engine->resolve_method(the_method,
426 found_class,
427 ((the_method->accflags
428 & Modifier::STATIC) != 0),
429 vtable_index);
430 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
432 break;
434 return pool->data[index];
437 // This function is used to lazily locate superclasses and
438 // superinterfaces. This must be called with the class lock held.
439 void
440 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
442 jclass ret = *classref;
444 // If superclass looks like a constant pool entry, resolve it now.
445 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
447 if (klass->state < JV_STATE_LINKED)
449 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
450 ret = _Jv_FindClass (name, klass->loader);
451 if (! ret)
453 throw new java::lang::NoClassDefFoundError (name->toString());
456 else
457 ret = klass->constants.data[(uaddr) classref].clazz;
458 *classref = ret;
462 // Find a method declared in the cls that is referenced from klass and
463 // perform access checks.
464 _Jv_Method *
465 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
466 _Jv_Utf8Const *method_name,
467 _Jv_Utf8Const *method_signature)
469 using namespace java::lang::reflect;
471 for (int i = 0; i < cls->method_count; i++)
473 _Jv_Method *method = &cls->methods[i];
474 if ( (!_Jv_equalUtf8Consts (method->name,
475 method_name))
476 || (!_Jv_equalUtf8Consts (method->signature,
477 method_signature)))
478 continue;
480 if (_Jv_CheckAccess (klass, cls, method->accflags))
481 return method;
482 else
484 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
485 sb->append(klass->getName());
486 sb->append(JvNewStringLatin1(": "));
487 sb->append(cls->getName());
488 sb->append(JvNewStringLatin1("."));
489 sb->append(_Jv_NewStringUTF(method_name->chars()));
490 sb->append(_Jv_NewStringUTF(method_signature->chars()));
491 throw new java::lang::IllegalAccessError (sb->toString());
494 return 0;
498 #define INITIAL_IOFFSETS_LEN 4
499 #define INITIAL_IFACES_LEN 4
501 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
503 // Generate tables for constant-time assignment testing and interface
504 // method lookup. This implements the technique described by Per Bothner
505 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
506 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
507 void
508 _Jv_Linker::prepare_constant_time_tables (jclass klass)
510 if (klass->isPrimitive () || klass->isInterface ())
511 return;
513 // Short-circuit in case we've been called already.
514 if ((klass->idt != NULL) || klass->depth != 0)
515 return;
517 // Calculate the class depth and ancestor table. The depth of a class
518 // is how many "extends" it is removed from Object. Thus the depth of
519 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
520 // is 2. Depth is defined for all regular and array classes, but not
521 // interfaces or primitive types.
523 jclass klass0 = klass;
524 jboolean has_interfaces = 0;
525 while (klass0 != &java::lang::Object::class$)
527 has_interfaces += klass0->interface_count;
528 klass0 = klass0->superclass;
529 klass->depth++;
532 // We do class member testing in constant time by using a small table
533 // of all the ancestor classes within each class. The first element is
534 // a pointer to the current class, and the rest are pointers to the
535 // classes ancestors, ordered from the current class down by decreasing
536 // depth. We do not include java.lang.Object in the table of ancestors,
537 // since it is redundant.
539 // FIXME: _Jv_AllocBytes
540 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth
541 * sizeof (jclass));
542 klass0 = klass;
543 for (int index = 0; index < klass->depth; index++)
545 klass->ancestors[index] = klass0;
546 klass0 = klass0->superclass;
549 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
550 return;
552 // Optimization: If class implements no interfaces, use a common
553 // predefined interface table.
554 if (!has_interfaces)
556 klass->idt = &null_idt;
557 return;
560 // FIXME: _Jv_AllocBytes
561 klass->idt =
562 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
564 _Jv_ifaces ifaces;
565 ifaces.count = 0;
566 ifaces.len = INITIAL_IFACES_LEN;
567 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
569 int itable_size = get_interfaces (klass, &ifaces);
571 if (ifaces.count > 0)
573 klass->idt->cls.itable =
574 // FIXME: _Jv_AllocBytes
575 (void **) _Jv_Malloc (itable_size * sizeof (void *));
576 klass->idt->cls.itable_length = itable_size;
578 jshort *itable_offsets =
579 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
581 generate_itable (klass, &ifaces, itable_offsets);
583 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
584 ifaces.count);
586 for (int i = 0; i < ifaces.count; i++)
588 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
589 itable_offsets[i];
592 klass->idt->cls.iindex = cls_iindex;
594 _Jv_Free (ifaces.list);
595 _Jv_Free (itable_offsets);
597 else
599 klass->idt->cls.iindex = SHRT_MAX;
603 // Return index of item in list, or -1 if item is not present.
604 inline jshort
605 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
607 for (int i=0; i < list_len; i++)
609 if (list[i] == item)
610 return i;
612 return -1;
615 // Find all unique interfaces directly or indirectly implemented by klass.
616 // Returns the size of the interface dispatch table (itable) for klass, which
617 // is the number of unique interfaces plus the total number of methods that
618 // those interfaces declare. May extend ifaces if required.
619 jshort
620 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
622 jshort result = 0;
624 for (int i = 0; i < klass->interface_count; i++)
626 jclass iface = klass->interfaces[i];
628 /* Make sure interface is linked. */
629 wait_for_state(iface, JV_STATE_LINKED);
631 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
633 if (ifaces->count + 1 >= ifaces->len)
635 /* Resize ifaces list */
636 ifaces->len = ifaces->len * 2;
637 ifaces->list
638 = (jclass *) _Jv_Realloc (ifaces->list,
639 ifaces->len * sizeof(jclass));
641 ifaces->list[ifaces->count] = iface;
642 ifaces->count++;
644 result += get_interfaces (klass->interfaces[i], ifaces);
648 if (klass->isInterface())
649 result += klass->method_count + 1;
650 else if (klass->superclass)
651 result += get_interfaces (klass->superclass, ifaces);
652 return result;
655 // Fill out itable in klass, resolving method declarations in each ifaces.
656 // itable_offsets is filled out with the position of each iface in itable,
657 // such that itable[itable_offsets[n]] == ifaces.list[n].
658 void
659 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
660 jshort *itable_offsets)
662 void **itable = klass->idt->cls.itable;
663 jshort itable_pos = 0;
665 for (int i = 0; i < ifaces->count; i++)
667 jclass iface = ifaces->list[i];
668 itable_offsets[i] = itable_pos;
669 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
671 /* Create interface dispatch table for iface */
672 if (iface->idt == NULL)
674 // FIXME: _Jv_AllocBytes
675 iface->idt
676 = (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
678 // The first element of ioffsets is its length (itself included).
679 // FIXME: _Jv_AllocBytes
680 jshort *ioffsets = (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN
681 * sizeof (jshort));
682 ioffsets[0] = INITIAL_IOFFSETS_LEN;
683 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
684 ioffsets[i] = -1;
686 iface->idt->iface.ioffsets = ioffsets;
691 // Format method name for use in error messages.
692 jstring
693 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
694 jclass derived)
696 using namespace java::lang;
697 StringBuffer *buf = new StringBuffer (klass->name->toString());
698 buf->append (jchar ('.'));
699 buf->append (meth->name->toString());
700 buf->append ((jchar) ' ');
701 buf->append (meth->signature->toString());
702 if (derived)
704 buf->append(JvNewStringLatin1(" in "));
705 buf->append(derived->name->toString());
707 return buf->toString();
710 void
711 _Jv_ThrowNoSuchMethodError ()
713 throw new java::lang::NoSuchMethodError;
716 // This is put in empty vtable slots.
717 void
718 _Jv_ThrowAbstractMethodError ()
720 throw new java::lang::AbstractMethodError();
723 // Each superinterface of a class (i.e. each interface that the class
724 // directly or indirectly implements) has a corresponding "Partial
725 // Interface Dispatch Table" whose size is (number of methods + 1) words.
726 // The first word is a pointer to the interface (i.e. the java.lang.Class
727 // instance for that interface). The remaining words are pointers to the
728 // actual methods that implement the methods declared in the interface,
729 // in order of declaration.
731 // Append partial interface dispatch table for "iface" to "itable", at
732 // position itable_pos.
733 // Returns the offset at which the next partial ITable should be appended.
734 jshort
735 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
736 void **itable, jshort pos)
738 using namespace java::lang::reflect;
740 itable[pos++] = (void *) iface;
741 _Jv_Method *meth;
743 for (int j=0; j < iface->method_count; j++)
745 meth = NULL;
746 for (jclass cl = klass; cl; cl = cl->getSuperclass())
748 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
749 iface->methods[j].signature);
751 if (meth)
752 break;
755 if (meth && (meth->name->first() == '<'))
757 // leave a placeholder in the itable for hidden init methods.
758 itable[pos] = NULL;
760 else if (meth)
762 if ((meth->accflags & Modifier::STATIC) != 0)
763 throw new java::lang::IncompatibleClassChangeError
764 (_Jv_GetMethodString (klass, meth));
765 if ((meth->accflags & Modifier::PUBLIC) == 0)
766 throw new java::lang::IllegalAccessError
767 (_Jv_GetMethodString (klass, meth));
769 if ((meth->accflags & Modifier::ABSTRACT) != 0)
770 itable[pos] = (void *) &_Jv_ThrowAbstractMethodError;
771 else
772 itable[pos] = meth->ncode;
774 else
776 // The method doesn't exist in klass. Binary compatibility rules
777 // permit this, so we delay the error until runtime using a pointer
778 // to a method which throws an exception.
779 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
781 pos++;
784 return pos;
787 static _Jv_Mutex_t iindex_mutex;
788 static bool iindex_mutex_initialized = false;
790 // We need to find the correct offset in the Class Interface Dispatch
791 // Table for a given interface. Once we have that, invoking an interface
792 // method just requires combining the Method's index in the interface
793 // (known at compile time) to get the correct method. Doing a type test
794 // (cast or instanceof) is the same problem: Once we have a possible Partial
795 // Interface Dispatch Table, we just compare the first element to see if it
796 // matches the desired interface. So how can we find the correct offset?
797 // Our solution is to keep a vector of candiate offsets in each interface
798 // (idt->iface.ioffsets), and in each class we have an index
799 // (idt->cls.iindex) used to select the correct offset from ioffsets.
801 // Calculate and return iindex for a new class.
802 // ifaces is a vector of num interfaces that the class implements.
803 // offsets[j] is the offset in the interface dispatch table for the
804 // interface corresponding to ifaces[j].
805 // May extend the interface ioffsets if required.
806 jshort
807 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
809 int i;
810 int j;
812 // Acquire a global lock to prevent itable corruption in case of multiple
813 // classes that implement an intersecting set of interfaces being linked
814 // simultaneously. We can assume that the mutex will be initialized
815 // single-threaded.
816 if (! iindex_mutex_initialized)
818 _Jv_MutexInit (&iindex_mutex);
819 iindex_mutex_initialized = true;
822 _Jv_MutexLock (&iindex_mutex);
824 for (i=1;; i++) /* each potential position in ioffsets */
826 for (j=0;; j++) /* each iface */
828 if (j >= num)
829 goto found;
830 if (i >= ifaces[j]->idt->iface.ioffsets[0])
831 continue;
832 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
833 /* We can potentially share this position with another class. */
834 if (ioffset >= 0 && ioffset != offsets[j])
835 break; /* Nope. Try next i. */
838 found:
839 for (j = 0; j < num; j++)
841 int len = ifaces[j]->idt->iface.ioffsets[0];
842 if (i >= len)
844 // Resize ioffsets.
845 int newlen = 2 * len;
846 if (i >= newlen)
847 newlen = i + 3;
848 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
849 // FIXME: _Jv_AllocBytes
850 jshort *new_ioffsets = (jshort *) _Jv_Malloc (newlen
851 * sizeof(jshort));
852 memcpy (&new_ioffsets[1], &old_ioffsets[1],
853 (len - 1) * sizeof (jshort));
854 new_ioffsets[0] = newlen;
856 while (len < newlen)
857 new_ioffsets[len++] = -1;
859 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
861 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
864 _Jv_MutexUnlock (&iindex_mutex);
866 return i;
870 // Functions for indirect dispatch (symbolic virtual binding) support.
872 // There are three tables, atable otable and itable. atable is an
873 // array of addresses, and otable is an array of offsets, and these
874 // are used for static and virtual members respectively. itable is an
875 // array of pairs {address, index} where each address is a pointer to
876 // an interface.
878 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
879 // symbol is a tuple of {classname, member name, signature}.
881 // Set this to true to enable debugging of indirect dispatch tables/linking.
882 static bool debug_link = false;
884 // link_symbol_table() scans these two arrays and fills in the
885 // corresponding atable and otable with the addresses of static
886 // members and the offsets of virtual members.
888 // The offset (in bytes) for each resolved method or field is placed
889 // at the corresponding position in the virtual method offset table
890 // (klass->otable).
892 // The same otable and atable may be shared by many classes.
894 // This must be called while holding the class lock.
896 void
897 _Jv_Linker::link_symbol_table (jclass klass)
899 int index = 0;
900 _Jv_MethodSymbol sym;
901 if (klass->otable == NULL
902 || klass->otable->state != 0)
903 goto atable;
905 klass->otable->state = 1;
907 if (debug_link)
908 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
909 for (index = 0;
910 (sym = klass->otable_syms[index]).class_name != NULL;
911 ++index)
913 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
914 _Jv_Method *meth = NULL;
916 _Jv_Utf8Const *signature = sym.signature;
919 static char *bounce = (char *)_Jv_ThrowNoSuchMethodError;
920 ptrdiff_t offset = (char *)(klass->vtable) - bounce;
921 klass->otable->offsets[index] = offset;
924 if (target_class == NULL)
925 throw new java::lang::NoClassDefFoundError
926 (_Jv_NewStringUTF (sym.class_name->chars()));
928 // We're looking for a field or a method, and we can tell
929 // which is needed by looking at the signature.
930 if (signature->first() == '(' && signature->len() >= 2)
932 // Looks like someone is trying to invoke an interface method
933 if (target_class->isInterface())
935 using namespace java::lang;
936 StringBuffer *sb = new StringBuffer();
937 sb->append(JvNewStringLatin1("found interface "));
938 sb->append(target_class->getName());
939 sb->append(JvNewStringLatin1(" when searching for a class"));
940 throw new VerifyError(sb->toString());
943 // If the target class does not have a vtable_method_count yet,
944 // then we can't tell the offsets for its methods, so we must lay
945 // it out now.
946 wait_for_state(target_class, JV_STATE_PREPARED);
948 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
949 sym.signature);
951 if (meth != NULL)
953 int offset = _Jv_VTable::idx_to_offset (meth->index);
954 if (offset == -1)
955 JvFail ("Bad method index");
956 JvAssert (meth->index < target_class->vtable_method_count);
957 klass->otable->offsets[index] = offset;
959 if (debug_link)
960 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
961 (int)index,
962 (int)klass->otable->offsets[index],
963 (const char*)target_class->name->chars(),
964 target_class,
965 (const char*)sym.name->chars(),
966 (const char*)signature->chars());
967 continue;
970 // Try fields.
972 wait_for_state(target_class, JV_STATE_PREPARED);
973 jclass found_class;
974 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
975 sym.name, sym.signature);
976 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
977 throw new java::lang::IncompatibleClassChangeError;
978 else
979 klass->otable->offsets[index] = the_field->u.boffset;
983 atable:
984 if (klass->atable == NULL || klass->atable->state != 0)
985 goto itable;
987 klass->atable->state = 1;
989 for (index = 0;
990 (sym = klass->atable_syms[index]).class_name != NULL;
991 ++index)
993 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
994 _Jv_Method *meth = NULL;
995 _Jv_Utf8Const *signature = sym.signature;
997 // ??? Setting this pointer to null will at least get us a
998 // NullPointerException
999 klass->atable->addresses[index] = NULL;
1001 if (target_class == NULL)
1002 throw new java::lang::NoClassDefFoundError
1003 (_Jv_NewStringUTF (sym.class_name->chars()));
1005 // We're looking for a static field or a static method, and we
1006 // can tell which is needed by looking at the signature.
1007 if (signature->first() == '(' && signature->len() >= 2)
1009 // If the target class does not have a vtable_method_count yet,
1010 // then we can't tell the offsets for its methods, so we must lay
1011 // it out now.
1012 wait_for_state (target_class, JV_STATE_PREPARED);
1014 // Interface methods cannot have bodies.
1015 if (target_class->isInterface())
1017 using namespace java::lang;
1018 StringBuffer *sb = new StringBuffer();
1019 sb->append(JvNewStringLatin1("class "));
1020 sb->append(target_class->getName());
1021 sb->append(JvNewStringLatin1(" is an interface: "
1022 "class expected"));
1023 throw new VerifyError(sb->toString());
1026 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1027 sym.signature);
1029 if (meth != NULL)
1031 if (meth->ncode) // Maybe abstract?
1033 klass->atable->addresses[index] = meth->ncode;
1034 if (debug_link)
1035 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1036 index,
1037 &klass->atable->addresses[index],
1038 (const char*)target_class->name->chars(),
1039 klass,
1040 (const char*)sym.name->chars(),
1041 (const char*)signature->chars());
1044 else
1045 klass->atable->addresses[index]
1046 = (void *)_Jv_ThrowNoSuchMethodError;
1048 continue;
1051 // Try fields.
1053 wait_for_state(target_class, JV_STATE_PREPARED);
1054 jclass found_class;
1055 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
1056 sym.name, sym.signature);
1057 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1058 klass->atable->addresses[index] = the_field->u.addr;
1059 else
1060 throw new java::lang::IncompatibleClassChangeError;
1064 itable:
1065 if (klass->itable == NULL
1066 || klass->itable->state != 0)
1067 return;
1069 klass->itable->state = 1;
1071 for (index = 0;
1072 (sym = klass->itable_syms[index]).class_name != NULL;
1073 ++index)
1075 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1076 _Jv_Utf8Const *signature = sym.signature;
1078 jclass cls;
1079 int i;
1081 wait_for_state(target_class, JV_STATE_LOADED);
1082 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1083 sym.name, sym.signature);
1085 if (found)
1087 klass->itable->addresses[index * 2] = cls;
1088 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1089 if (debug_link)
1091 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1092 index,
1093 klass->itable->addresses[index * 2],
1094 (const char*)cls->name->chars(),
1095 cls,
1096 (const char*)sym.name->chars(),
1097 (const char*)signature->chars());
1098 fprintf (stderr, " [%d] = offset %d\n",
1099 index + 1,
1100 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1104 else
1105 throw new java::lang::IncompatibleClassChangeError;
1110 // For each catch_record in the list of caught classes, fill in the
1111 // address field.
1112 void
1113 _Jv_Linker::link_exception_table (jclass self)
1115 struct _Jv_CatchClass *catch_record = self->catch_classes;
1116 if (!catch_record || catch_record->classname)
1117 return;
1118 catch_record++;
1119 while (catch_record->classname)
1123 jclass target_class
1124 = _Jv_FindClass (catch_record->classname,
1125 self->getClassLoaderInternal ());
1126 *catch_record->address = target_class;
1128 catch (::java::lang::Throwable *t)
1130 // FIXME: We need to do something better here.
1131 *catch_record->address = 0;
1133 catch_record++;
1135 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1138 // Set itable method indexes for members of interface IFACE.
1139 void
1140 _Jv_Linker::layout_interface_methods (jclass iface)
1142 if (! iface->isInterface())
1143 return;
1145 // itable indexes start at 1.
1146 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1147 // itable so they are also assigned an index here.
1148 for (int i = 0; i < iface->method_count; i++)
1149 iface->methods[i].index = i + 1;
1152 // Prepare virtual method declarations in KLASS, and any superclasses
1153 // as required, by determining their vtable index, setting
1154 // method->index, and finally setting the class's vtable_method_count.
1155 // Must be called with the lock for KLASS held.
1156 void
1157 _Jv_Linker::layout_vtable_methods (jclass klass)
1159 if (klass->vtable != NULL || klass->isInterface()
1160 || klass->vtable_method_count != -1)
1161 return;
1163 jclass superclass = klass->getSuperclass();
1165 if (superclass != NULL && superclass->vtable_method_count == -1)
1167 JvSynchronize sync (superclass);
1168 layout_vtable_methods (superclass);
1171 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1173 for (int i = 0; i < klass->method_count; ++i)
1175 _Jv_Method *meth = &klass->methods[i];
1176 _Jv_Method *super_meth = NULL;
1178 if (! _Jv_isVirtualMethod (meth))
1179 continue;
1181 if (superclass != NULL)
1183 jclass declarer;
1184 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1185 meth->signature, &declarer);
1186 // See if this method actually overrides the other method
1187 // we've found.
1188 if (super_meth)
1190 if (! _Jv_isVirtualMethod (super_meth)
1191 || ! _Jv_CheckAccess (klass, declarer,
1192 super_meth->accflags))
1193 super_meth = NULL;
1194 else if ((super_meth->accflags
1195 & java::lang::reflect::Modifier::FINAL) != 0)
1197 using namespace java::lang;
1198 StringBuffer *sb = new StringBuffer();
1199 sb->append(JvNewStringLatin1("method "));
1200 sb->append(_Jv_GetMethodString(klass, meth));
1201 sb->append(JvNewStringLatin1(" overrides final method "));
1202 sb->append(_Jv_GetMethodString(declarer, super_meth));
1203 throw new VerifyError(sb->toString());
1208 if (super_meth)
1209 meth->index = super_meth->index;
1210 else
1211 meth->index = index++;
1214 klass->vtable_method_count = index;
1217 // Set entries in VTABLE for virtual methods declared in KLASS.
1218 void
1219 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1221 for (int i = klass->method_count - 1; i >= 0; i--)
1223 using namespace java::lang::reflect;
1225 _Jv_Method *meth = &klass->methods[i];
1226 if (meth->index == (_Jv_ushort) -1)
1227 continue;
1228 if ((meth->accflags & Modifier::ABSTRACT))
1229 // FIXME: it might be nice to have a libffi trampoline here,
1230 // so we could pass in the method name and other information.
1231 vtable->set_method(meth->index,
1232 (void *) &_Jv_ThrowAbstractMethodError);
1233 else
1234 vtable->set_method(meth->index, meth->ncode);
1238 // Allocate and lay out the virtual method table for KLASS. This will
1239 // also cause vtables to be generated for any non-abstract
1240 // superclasses, and virtual method layout to occur for any abstract
1241 // superclasses. Must be called with monitor lock for KLASS held.
1242 void
1243 _Jv_Linker::make_vtable (jclass klass)
1245 using namespace java::lang::reflect;
1247 // If the vtable exists, or for interface classes, do nothing. All
1248 // other classes, including abstract classes, need a vtable.
1249 if (klass->vtable != NULL || klass->isInterface())
1250 return;
1252 // Ensure all the `ncode' entries are set.
1253 klass->engine->create_ncode(klass);
1255 // Class must be laid out before we can create a vtable.
1256 if (klass->vtable_method_count == -1)
1257 layout_vtable_methods (klass);
1259 // Allocate the new vtable.
1260 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1261 klass->vtable = vtable;
1263 // Copy the vtable of the closest superclass.
1264 jclass superclass = klass->superclass;
1266 JvSynchronize sync (superclass);
1267 make_vtable (superclass);
1269 for (int i = 0; i < superclass->vtable_method_count; ++i)
1270 vtable->set_method (i, superclass->vtable->get_method (i));
1272 // Set the class pointer and GC descriptor.
1273 vtable->clas = klass;
1274 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1276 // For each virtual declared in klass, set new vtable entry or
1277 // override an old one.
1278 set_vtable_entries (klass, vtable);
1280 // Note that we don't check for abstract methods here. We used to,
1281 // but there is a JVMS clarification that indicates that a check
1282 // here would be too eager. And, a simple test case confirms this.
1285 // Lay out the class, allocating space for static fields and computing
1286 // offsets of instance fields. The class lock must be held by the
1287 // caller.
1288 void
1289 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1291 if (klass->size_in_bytes != -1)
1292 return;
1294 // Compute the alignment for this type by searching through the
1295 // superclasses and finding the maximum required alignment. We
1296 // could consider caching this in the Class.
1297 int max_align = __alignof__ (java::lang::Object);
1298 jclass super = klass->getSuperclass();
1299 while (super != NULL)
1301 // Ensure that our super has its super installed before
1302 // recursing.
1303 wait_for_state(super, JV_STATE_LOADING);
1304 ensure_fields_laid_out(super);
1305 int num = JvNumInstanceFields (super);
1306 _Jv_Field *field = JvGetFirstInstanceField (super);
1307 while (num > 0)
1309 int field_align = get_alignment_from_class (field->type);
1310 if (field_align > max_align)
1311 max_align = field_align;
1312 ++field;
1313 --num;
1315 super = super->getSuperclass();
1318 int instance_size;
1319 int static_size = 0;
1321 // Although java.lang.Object is never interpreted, an interface can
1322 // have a null superclass. Note that we have to lay out an
1323 // interface because it might have static fields.
1324 if (klass->superclass)
1325 instance_size = klass->superclass->size();
1326 else
1327 instance_size = java::lang::Object::class$.size();
1329 for (int i = 0; i < klass->field_count; i++)
1331 int field_size;
1332 int field_align;
1334 _Jv_Field *field = &klass->fields[i];
1336 if (! field->isRef ())
1338 // It is safe to resolve the field here, since it's a
1339 // primitive class, which does not cause loading to happen.
1340 resolve_field (field, klass->loader);
1342 field_size = field->type->size ();
1343 field_align = get_alignment_from_class (field->type);
1345 else
1347 field_size = sizeof (jobject);
1348 field_align = __alignof__ (jobject);
1351 field->bsize = field_size;
1353 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1355 if (field->u.addr == NULL)
1357 // This computes an offset into a region we'll allocate
1358 // shortly, and then add this offset to the start
1359 // address.
1360 static_size = ROUND (static_size, field_align);
1361 field->u.boffset = static_size;
1362 static_size += field_size;
1365 else
1367 instance_size = ROUND (instance_size, field_align);
1368 field->u.boffset = instance_size;
1369 instance_size += field_size;
1370 if (field_align > max_align)
1371 max_align = field_align;
1375 if (static_size != 0)
1376 klass->engine->allocate_static_fields (klass, static_size);
1378 // Set the instance size for the class. Note that first we round it
1379 // to the alignment required for this object; this keeps us in sync
1380 // with our current ABI.
1381 instance_size = ROUND (instance_size, max_align);
1382 klass->size_in_bytes = instance_size;
1385 // This takes the class to state JV_STATE_LINKED. The class lock must
1386 // be held when calling this.
1387 void
1388 _Jv_Linker::ensure_class_linked (jclass klass)
1390 if (klass->state >= JV_STATE_LINKED)
1391 return;
1393 int state = klass->state;
1396 // Short-circuit, so that mutually dependent classes are ok.
1397 klass->state = JV_STATE_LINKED;
1399 _Jv_Constants *pool = &klass->constants;
1401 // Compiled classes require that their class constants be
1402 // resolved here. However, interpreted classes need their
1403 // constants to be resolved lazily. If we resolve an
1404 // interpreted class' constants eagerly, we can end up with
1405 // spurious IllegalAccessErrors when the constant pool contains
1406 // a reference to a class we can't access. This can validly
1407 // occur in an obscure case involving the InnerClasses
1408 // attribute.
1409 if (! _Jv_IsInterpretedClass (klass))
1411 // Resolve class constants first, since other constant pool
1412 // entries may rely on these.
1413 for (int index = 1; index < pool->size; ++index)
1415 if (pool->tags[index] == JV_CONSTANT_Class)
1416 resolve_pool_entry (klass, index);
1420 #if 0 // Should be redundant now
1421 // If superclass looks like a constant pool entry,
1422 // resolve it now.
1423 if ((uaddr) klass->superclass < (uaddr) pool->size)
1424 klass->superclass = pool->data[(uaddr) klass->superclass].clazz;
1426 // Likewise for interfaces.
1427 for (int i = 0; i < klass->interface_count; i++)
1429 if ((uaddr) klass->interfaces[i] < (uaddr) pool->size)
1430 klass->interfaces[i]
1431 = pool->data[(uaddr) klass->interfaces[i]].clazz;
1433 #endif
1435 // Resolve the remaining constant pool entries.
1436 for (int index = 1; index < pool->size; ++index)
1438 if (pool->tags[index] == JV_CONSTANT_String)
1440 jstring str;
1442 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1443 pool->data[index].o = str;
1444 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1448 if (klass->engine->need_resolve_string_fields())
1450 jfieldID f = JvGetFirstStaticField (klass);
1451 for (int n = JvNumStaticFields (klass); n > 0; --n)
1453 int mod = f->getModifiers ();
1454 // If we have a static String field with a non-null initial
1455 // value, we know it points to a Utf8Const.
1456 resolve_field(f, klass->loader);
1457 if (f->getClass () == &java::lang::String::class$
1458 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1460 jstring *strp = (jstring *) f->u.addr;
1461 if (*strp)
1462 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1464 f = f->getNextField ();
1468 klass->notifyAll ();
1470 _Jv_PushClass (klass);
1472 catch (java::lang::Throwable *t)
1474 klass->state = state;
1475 throw t;
1479 // This ensures that symbolic superclass and superinterface references
1480 // are resolved for the indicated class. This must be called with the
1481 // class lock held.
1482 void
1483 _Jv_Linker::ensure_supers_installed (jclass klass)
1485 resolve_class_ref (klass, &klass->superclass);
1486 // An interface won't have a superclass.
1487 if (klass->superclass)
1488 wait_for_state (klass->superclass, JV_STATE_LOADING);
1490 for (int i = 0; i < klass->interface_count; ++i)
1492 resolve_class_ref (klass, &klass->interfaces[i]);
1493 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1497 // This adds missing `Miranda methods' to a class.
1498 void
1499 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1501 // Note that at this point, all our supers, and the supers of all
1502 // our superclasses and superinterfaces, will have been installed.
1504 for (int i = 0; i < iface_class->interface_count; ++i)
1506 jclass interface = iface_class->interfaces[i];
1508 for (int j = 0; j < interface->method_count; ++j)
1510 _Jv_Method *meth = &interface->methods[j];
1511 // Don't bother with <clinit>.
1512 if (meth->name->first() == '<')
1513 continue;
1514 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1515 meth->signature);
1516 if (! new_meth)
1518 // We assume that such methods are very unlikely, so we
1519 // just reallocate the method array each time one is
1520 // found. This greatly simplifies the searching --
1521 // otherwise we have to make sure that each such method
1522 // found is really unique among all superinterfaces.
1523 int new_count = base->method_count + 1;
1524 _Jv_Method *new_m
1525 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
1526 * new_count);
1527 memcpy (new_m, base->methods,
1528 sizeof (_Jv_Method) * base->method_count);
1530 // Add new method.
1531 new_m[base->method_count] = *meth;
1532 new_m[base->method_count].index = (_Jv_ushort) -1;
1533 new_m[base->method_count].accflags
1534 |= java::lang::reflect::Modifier::INVISIBLE;
1536 base->methods = new_m;
1537 base->method_count = new_count;
1541 wait_for_state (interface, JV_STATE_LOADED);
1542 add_miranda_methods (base, interface);
1546 // This ensures that the class' method table is "complete". This must
1547 // be called with the class lock held.
1548 void
1549 _Jv_Linker::ensure_method_table_complete (jclass klass)
1551 if (klass->vtable != NULL || klass->isInterface())
1552 return;
1554 // We need our superclass to have its own Miranda methods installed.
1555 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1557 // A class might have so-called "Miranda methods". This is a method
1558 // that is declared in an interface and not re-declared in an
1559 // abstract class. Some compilers don't emit declarations for such
1560 // methods in the class; this will give us problems since we expect
1561 // a declaration for any method requiring a vtable entry. We handle
1562 // this here by searching for such methods and constructing new
1563 // internal declarations for them. Note that we do this
1564 // unconditionally, and not just for abstract classes, to correctly
1565 // account for cases where a class is modified to be concrete and
1566 // still incorrectly inherits an abstract method.
1567 int pre_count = klass->method_count;
1568 add_miranda_methods (klass, klass);
1570 // Let the execution engine know that we've added methods.
1571 if (klass->method_count != pre_count)
1572 klass->engine->post_miranda_hook(klass);
1575 // Verify a class. Must be called with class lock held.
1576 void
1577 _Jv_Linker::verify_class (jclass klass)
1579 klass->engine->verify(klass);
1582 // Check the assertions contained in the type assertion table for KLASS.
1583 // This is the equivilent of bytecode verification for native, BC-ABI code.
1584 void
1585 _Jv_Linker::verify_type_assertions (jclass klass)
1587 if (debug_link)
1588 fprintf (stderr, "Evaluating type assertions for %s:\n",
1589 klass->name->chars());
1591 if (klass->assertion_table == NULL)
1592 return;
1594 for (int i = 0;; i++)
1596 int assertion_code = klass->assertion_table[i].assertion_code;
1597 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1598 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1600 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1601 return;
1602 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1604 if (debug_link)
1606 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1607 assertion_code, op1->chars(), op2->chars());
1610 // The operands are class signatures. op1 is the source,
1611 // op2 is the target.
1612 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1613 klass->getClassLoaderInternal());
1614 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1615 klass->getClassLoaderInternal());
1617 // If the class doesn't exist, ignore the assertion. An exception
1618 // will be thrown later if an attempt is made to actually
1619 // instantiate the class.
1620 if (cl1 == NULL || cl2 == NULL)
1621 continue;
1623 if (! _Jv_IsAssignableFromSlow (cl2, cl1))
1625 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1626 s = s->concat (klass->getName());
1627 s = s->concat (JvNewStringUTF (": "));
1628 s = s->concat (cl1->getName());
1629 s = s->concat (JvNewStringUTF (" is not assignable to "));
1630 s = s->concat (cl2->getName());
1631 throw new java::lang::VerifyError (s);
1634 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1636 // TODO: Implement this.
1638 // Unknown assertion codes are ignored, for forwards-compatibility.
1642 void
1643 _Jv_Linker::print_class_loaded (jclass klass)
1645 char *codesource = NULL;
1646 if (klass->protectionDomain != NULL)
1648 java::security::CodeSource *cs
1649 = klass->protectionDomain->getCodeSource();
1650 if (cs != NULL)
1652 jstring css = cs->toString();
1653 int len = JvGetStringUTFLength(css);
1654 codesource = (char *) _Jv_AllocBytes(len + 1);
1655 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1656 codesource[len] = '\0';
1659 if (codesource == NULL)
1660 codesource = "<no code source>";
1662 // We use a somewhat bogus test for the ABI here.
1663 char *abi;
1664 if (_Jv_IsInterpretedClass (klass))
1665 abi = "bytecode";
1666 else if (klass->state == JV_STATE_PRELOADING)
1667 abi = "BC-compiled";
1668 else
1669 abi = "pre-compiled";
1671 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1672 codesource);
1675 // FIXME: mention invariants and stuff.
1676 void
1677 _Jv_Linker::wait_for_state (jclass klass, int state)
1679 if (klass->state >= state)
1680 return;
1682 JvSynchronize sync (klass);
1684 // This is similar to the strategy for class initialization. If we
1685 // already hold the lock, just leave.
1686 java::lang::Thread *self = java::lang::Thread::currentThread();
1687 while (klass->state <= state
1688 && klass->thread
1689 && klass->thread != self)
1690 klass->wait ();
1692 java::lang::Thread *save = klass->thread;
1693 klass->thread = self;
1695 // Print some debugging info if requested. Interpreted classes are
1696 // handled in defineclass, so we only need to handle the two
1697 // pre-compiled cases here.
1698 if (gcj::verbose_class_flag
1699 && (klass->state == JV_STATE_COMPILED
1700 || klass->state == JV_STATE_PRELOADING)
1701 && ! _Jv_IsInterpretedClass (klass))
1702 print_class_loaded (klass);
1706 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
1708 ensure_supers_installed (klass);
1709 klass->set_state(JV_STATE_LOADING);
1712 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
1714 ensure_method_table_complete (klass);
1715 klass->set_state(JV_STATE_LOADED);
1718 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
1720 ensure_fields_laid_out (klass);
1721 make_vtable (klass);
1722 layout_interface_methods (klass);
1723 prepare_constant_time_tables (klass);
1724 klass->set_state(JV_STATE_PREPARED);
1727 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
1729 if (gcj::verifyClasses)
1730 verify_class (klass);
1732 ensure_class_linked (klass);
1733 link_exception_table (klass);
1734 link_symbol_table (klass);
1735 klass->set_state(JV_STATE_LINKED);
1738 catch (java::lang::Throwable *exc)
1740 klass->thread = save;
1741 klass->set_state(JV_STATE_ERROR);
1742 throw exc;
1745 klass->thread = save;
1747 if (klass->state == JV_STATE_ERROR)
1748 throw new java::lang::LinkageError;