Mark ChangeLog
[official-gcc.git] / libjava / link.cc
blobaf67d9a01cbbc7d5452bf1e357ad2f056446ce29
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 field->type = _Jv_FindClassFromSignature (sig->chars(), loader);
92 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
96 // A helper for find_field that knows how to recursively search
97 // superclasses and interfaces.
98 _Jv_Field *
99 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
100 _Jv_Utf8Const *type_name,
101 jclass *declarer)
103 while (search)
105 // From 5.4.3.2. First search class itself.
106 for (int i = 0; i < search->field_count; ++i)
108 _Jv_Field *field = &search->fields[i];
109 if (! _Jv_equalUtf8Consts (field->name, name))
110 continue;
112 if (! field->isResolved ())
113 resolve_field (field, search->loader);
115 // Note that we compare type names and not types. This is
116 // bizarre, but we do it because we want to find a field
117 // (and terminate the search) if it has the correct
118 // descriptor -- but then later reject it if the class
119 // loader check results in different classes. We can't just
120 // pass in the descriptor and check that way, because when
121 // the field is already resolved there is no easy way to
122 // find its descriptor again.
123 if (_Jv_equalUtf8Consts (type_name, field->type->name))
125 *declarer = search;
126 return field;
130 // Next search direct interfaces.
131 for (int i = 0; i < search->interface_count; ++i)
133 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
134 type_name, declarer);
135 if (result)
136 return result;
139 // Now search superclass.
140 search = search->superclass;
143 return NULL;
146 bool
147 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
149 for (int i = 0; i < search->field_count; ++i)
151 _Jv_Field *field = &search->fields[i];
152 if (_Jv_equalUtf8Consts (field->name, field_name))
153 return true;
155 return false;
158 // Find a field.
159 // KLASS is the class that is requesting the field.
160 // OWNER is the class in which the field should be found.
161 // FIELD_TYPE_NAME is the type descriptor for the field.
162 // Fill FOUND_CLASS with the address of the class in which the field
163 // is actually declared.
164 // This function does the class loader type checks, and
165 // also access checks. Returns the field, or throws an
166 // exception on error.
167 _Jv_Field *
168 _Jv_Linker::find_field (jclass klass, jclass owner,
169 jclass *found_class,
170 _Jv_Utf8Const *field_name,
171 _Jv_Utf8Const *field_type_name)
173 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
174 // it cheaper.
175 jclass field_type = _Jv_FindClassFromSignature (field_type_name->chars(),
176 klass->loader);
178 _Jv_Field *the_field = find_field_helper (owner, field_name,
179 field_type->name, found_class);
181 if (the_field == 0)
183 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
184 sb->append(JvNewStringLatin1("field "));
185 sb->append(owner->getName());
186 sb->append(JvNewStringLatin1("."));
187 sb->append(_Jv_NewStringUTF(field_name->chars()));
188 sb->append(JvNewStringLatin1(" was not found."));
189 throw new java::lang::NoSuchFieldError (sb->toString());
192 if (_Jv_CheckAccess (klass, *found_class, the_field->flags))
194 // Note that the field returned by find_field_helper is always
195 // resolved. There's no point checking class loaders here,
196 // since we already did the work to look up all the types.
197 // FIXME: being lazy here would be nice.
198 if (the_field->type != field_type)
199 throw new java::lang::LinkageError
200 (JvNewStringLatin1
201 ("field type mismatch with different loaders"));
203 else
205 java::lang::StringBuffer *sb
206 = new java::lang::StringBuffer ();
207 sb->append(klass->getName());
208 sb->append(JvNewStringLatin1(": "));
209 sb->append((*found_class)->getName());
210 sb->append(JvNewStringLatin1("."));
211 sb->append(_Jv_NewStringUtf8Const (field_name));
212 throw new java::lang::IllegalAccessError(sb->toString());
215 return the_field;
218 _Jv_word
219 _Jv_Linker::resolve_pool_entry (jclass klass, int index)
221 using namespace java::lang::reflect;
223 _Jv_Constants *pool = &klass->constants;
225 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
226 return pool->data[index];
228 switch (pool->tags[index])
230 case JV_CONSTANT_Class:
232 _Jv_Utf8Const *name = pool->data[index].utf8;
234 jclass found;
235 if (name->first() == '[')
236 found = _Jv_FindClassFromSignature (name->chars(),
237 klass->loader);
238 else
239 found = _Jv_FindClass (name, klass->loader);
241 if (! found)
242 throw new java::lang::NoClassDefFoundError (name->toString());
244 // Check accessibility, but first strip array types as
245 // _Jv_ClassNameSamePackage can't handle arrays.
246 jclass check;
247 for (check = found;
248 check && check->isArray();
249 check = check->getComponentType())
251 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
252 || (_Jv_ClassNameSamePackage (check->name,
253 klass->name)))
255 pool->data[index].clazz = found;
256 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
258 else
260 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
261 sb->append(klass->getName());
262 sb->append(JvNewStringLatin1(" can't access class "));
263 sb->append(found->getName());
264 throw new java::lang::IllegalAccessError(sb->toString());
267 break;
269 case JV_CONSTANT_String:
271 jstring str;
272 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
273 pool->data[index].o = str;
274 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
276 break;
278 case JV_CONSTANT_Fieldref:
280 _Jv_ushort class_index, name_and_type_index;
281 _Jv_loadIndexes (&pool->data[index],
282 class_index,
283 name_and_type_index);
284 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
286 if (owner != klass)
287 _Jv_InitClass (owner);
289 _Jv_ushort name_index, type_index;
290 _Jv_loadIndexes (&pool->data[name_and_type_index],
291 name_index,
292 type_index);
294 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
295 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
297 jclass found_class = 0;
298 _Jv_Field *the_field = find_field (klass, owner,
299 &found_class,
300 field_name,
301 field_type_name);
302 if (owner != found_class)
303 _Jv_InitClass (found_class);
304 pool->data[index].field = the_field;
305 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
307 break;
309 case JV_CONSTANT_Methodref:
310 case JV_CONSTANT_InterfaceMethodref:
312 _Jv_ushort class_index, name_and_type_index;
313 _Jv_loadIndexes (&pool->data[index],
314 class_index,
315 name_and_type_index);
316 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
318 if (owner != klass)
319 _Jv_InitClass (owner);
321 _Jv_ushort name_index, type_index;
322 _Jv_loadIndexes (&pool->data[name_and_type_index],
323 name_index,
324 type_index);
326 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
327 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
329 _Jv_Method *the_method = 0;
330 jclass found_class = 0;
332 // We're going to cache a pointer to the _Jv_Method object
333 // when we find it. So, to ensure this doesn't get moved from
334 // beneath us, we first put all the needed Miranda methods
335 // into the target class.
336 wait_for_state (klass, JV_STATE_LOADED);
338 // First search the class itself.
339 the_method = search_method_in_class (owner, klass,
340 method_name, method_signature);
342 if (the_method != 0)
344 found_class = owner;
345 goto end_of_method_search;
348 // If we are resolving an interface method, search the
349 // interface's superinterfaces (A superinterface is not an
350 // interface's superclass - a superinterface is implemented by
351 // the interface).
352 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
354 _Jv_ifaces ifaces;
355 ifaces.count = 0;
356 ifaces.len = 4;
357 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
358 * sizeof (jclass *));
360 get_interfaces (owner, &ifaces);
362 for (int i = 0; i < ifaces.count; i++)
364 jclass cls = ifaces.list[i];
365 the_method = search_method_in_class (cls, klass, method_name,
366 method_signature);
367 if (the_method != 0)
369 found_class = cls;
370 break;
374 _Jv_Free (ifaces.list);
376 if (the_method != 0)
377 goto end_of_method_search;
380 // Finally, search superclasses.
381 for (jclass cls = owner->getSuperclass (); cls != 0;
382 cls = cls->getSuperclass ())
384 the_method = search_method_in_class (cls, klass, method_name,
385 method_signature);
386 if (the_method != 0)
388 found_class = cls;
389 break;
393 end_of_method_search:
395 // FIXME: if (cls->loader != klass->loader), then we
396 // must actually check that the types of arguments
397 // correspond. That is, for each argument type, and
398 // the return type, doing _Jv_FindClassFromSignature
399 // with either loader should produce the same result,
400 // i.e., exactly the same jclass object. JVMS 5.4.3.3
402 if (the_method == 0)
404 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
405 sb->append(JvNewStringLatin1("method "));
406 sb->append(owner->getName());
407 sb->append(JvNewStringLatin1("."));
408 sb->append(_Jv_NewStringUTF(method_name->chars()));
409 sb->append(JvNewStringLatin1(" with signature "));
410 sb->append(_Jv_NewStringUTF(method_signature->chars()));
411 sb->append(JvNewStringLatin1(" was not found."));
412 throw new java::lang::NoSuchMethodError (sb->toString());
415 int vtable_index = -1;
416 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
417 vtable_index = (jshort)the_method->index;
419 pool->data[index].rmethod
420 = klass->engine->resolve_method(the_method,
421 found_class,
422 ((the_method->accflags
423 & Modifier::STATIC) != 0),
424 vtable_index);
425 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
427 break;
429 return pool->data[index];
432 // This function is used to lazily locate superclasses and
433 // superinterfaces. This must be called with the class lock held.
434 void
435 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
437 jclass ret = *classref;
439 // If superclass looks like a constant pool entry, resolve it now.
440 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
442 if (klass->state < JV_STATE_LINKED)
444 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
445 ret = _Jv_FindClass (name, klass->loader);
446 if (! ret)
448 throw new java::lang::NoClassDefFoundError (name->toString());
451 else
452 ret = klass->constants.data[(uaddr) classref].clazz;
453 *classref = ret;
457 // Find a method declared in the cls that is referenced from klass and
458 // perform access checks.
459 _Jv_Method *
460 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
461 _Jv_Utf8Const *method_name,
462 _Jv_Utf8Const *method_signature)
464 using namespace java::lang::reflect;
466 for (int i = 0; i < cls->method_count; i++)
468 _Jv_Method *method = &cls->methods[i];
469 if ( (!_Jv_equalUtf8Consts (method->name,
470 method_name))
471 || (!_Jv_equalUtf8Consts (method->signature,
472 method_signature)))
473 continue;
475 if (_Jv_CheckAccess (klass, cls, method->accflags))
476 return method;
477 else
479 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
480 sb->append(klass->getName());
481 sb->append(JvNewStringLatin1(": "));
482 sb->append(cls->getName());
483 sb->append(JvNewStringLatin1("."));
484 sb->append(_Jv_NewStringUTF(method_name->chars()));
485 sb->append(_Jv_NewStringUTF(method_signature->chars()));
486 throw new java::lang::IllegalAccessError (sb->toString());
489 return 0;
493 #define INITIAL_IOFFSETS_LEN 4
494 #define INITIAL_IFACES_LEN 4
496 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
498 // Generate tables for constant-time assignment testing and interface
499 // method lookup. This implements the technique described by Per Bothner
500 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
501 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
502 void
503 _Jv_Linker::prepare_constant_time_tables (jclass klass)
505 if (klass->isPrimitive () || klass->isInterface ())
506 return;
508 // Short-circuit in case we've been called already.
509 if ((klass->idt != NULL) || klass->depth != 0)
510 return;
512 // Calculate the class depth and ancestor table. The depth of a class
513 // is how many "extends" it is removed from Object. Thus the depth of
514 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
515 // is 2. Depth is defined for all regular and array classes, but not
516 // interfaces or primitive types.
518 jclass klass0 = klass;
519 jboolean has_interfaces = 0;
520 while (klass0 != &java::lang::Object::class$)
522 has_interfaces += klass0->interface_count;
523 klass0 = klass0->superclass;
524 klass->depth++;
527 // We do class member testing in constant time by using a small table
528 // of all the ancestor classes within each class. The first element is
529 // a pointer to the current class, and the rest are pointers to the
530 // classes ancestors, ordered from the current class down by decreasing
531 // depth. We do not include java.lang.Object in the table of ancestors,
532 // since it is redundant.
534 // FIXME: _Jv_AllocBytes
535 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth
536 * sizeof (jclass));
537 klass0 = klass;
538 for (int index = 0; index < klass->depth; index++)
540 klass->ancestors[index] = klass0;
541 klass0 = klass0->superclass;
544 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
545 return;
547 // Optimization: If class implements no interfaces, use a common
548 // predefined interface table.
549 if (!has_interfaces)
551 klass->idt = &null_idt;
552 return;
555 // FIXME: _Jv_AllocBytes
556 klass->idt =
557 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
559 _Jv_ifaces ifaces;
560 ifaces.count = 0;
561 ifaces.len = INITIAL_IFACES_LEN;
562 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
564 int itable_size = get_interfaces (klass, &ifaces);
566 if (ifaces.count > 0)
568 klass->idt->cls.itable =
569 // FIXME: _Jv_AllocBytes
570 (void **) _Jv_Malloc (itable_size * sizeof (void *));
571 klass->idt->cls.itable_length = itable_size;
573 jshort *itable_offsets =
574 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
576 generate_itable (klass, &ifaces, itable_offsets);
578 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
579 ifaces.count);
581 for (int i = 0; i < ifaces.count; i++)
583 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
584 itable_offsets[i];
587 klass->idt->cls.iindex = cls_iindex;
589 _Jv_Free (ifaces.list);
590 _Jv_Free (itable_offsets);
592 else
594 klass->idt->cls.iindex = SHRT_MAX;
598 // Return index of item in list, or -1 if item is not present.
599 inline jshort
600 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
602 for (int i=0; i < list_len; i++)
604 if (list[i] == item)
605 return i;
607 return -1;
610 // Find all unique interfaces directly or indirectly implemented by klass.
611 // Returns the size of the interface dispatch table (itable) for klass, which
612 // is the number of unique interfaces plus the total number of methods that
613 // those interfaces declare. May extend ifaces if required.
614 jshort
615 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
617 jshort result = 0;
619 for (int i = 0; i < klass->interface_count; i++)
621 jclass iface = klass->interfaces[i];
623 /* Make sure interface is linked. */
624 wait_for_state(iface, JV_STATE_LINKED);
626 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
628 if (ifaces->count + 1 >= ifaces->len)
630 /* Resize ifaces list */
631 ifaces->len = ifaces->len * 2;
632 ifaces->list
633 = (jclass *) _Jv_Realloc (ifaces->list,
634 ifaces->len * sizeof(jclass));
636 ifaces->list[ifaces->count] = iface;
637 ifaces->count++;
639 result += get_interfaces (klass->interfaces[i], ifaces);
643 if (klass->isInterface())
644 result += klass->method_count + 1;
645 else if (klass->superclass)
646 result += get_interfaces (klass->superclass, ifaces);
647 return result;
650 // Fill out itable in klass, resolving method declarations in each ifaces.
651 // itable_offsets is filled out with the position of each iface in itable,
652 // such that itable[itable_offsets[n]] == ifaces.list[n].
653 void
654 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
655 jshort *itable_offsets)
657 void **itable = klass->idt->cls.itable;
658 jshort itable_pos = 0;
660 for (int i = 0; i < ifaces->count; i++)
662 jclass iface = ifaces->list[i];
663 itable_offsets[i] = itable_pos;
664 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
666 /* Create interface dispatch table for iface */
667 if (iface->idt == NULL)
669 // FIXME: _Jv_AllocBytes
670 iface->idt
671 = (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
673 // The first element of ioffsets is its length (itself included).
674 // FIXME: _Jv_AllocBytes
675 jshort *ioffsets = (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN
676 * sizeof (jshort));
677 ioffsets[0] = INITIAL_IOFFSETS_LEN;
678 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
679 ioffsets[i] = -1;
681 iface->idt->iface.ioffsets = ioffsets;
686 // Format method name for use in error messages.
687 jstring
688 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
689 jclass derived)
691 using namespace java::lang;
692 StringBuffer *buf = new StringBuffer (klass->name->toString());
693 buf->append (jchar ('.'));
694 buf->append (meth->name->toString());
695 buf->append ((jchar) ' ');
696 buf->append (meth->signature->toString());
697 if (derived)
699 buf->append(JvNewStringLatin1(" in "));
700 buf->append(derived->name->toString());
702 return buf->toString();
705 void
706 _Jv_ThrowNoSuchMethodError ()
708 throw new java::lang::NoSuchMethodError;
711 // This is put in empty vtable slots.
712 static void
713 _Jv_abstractMethodError (void)
715 throw new java::lang::AbstractMethodError();
718 // Each superinterface of a class (i.e. each interface that the class
719 // directly or indirectly implements) has a corresponding "Partial
720 // Interface Dispatch Table" whose size is (number of methods + 1) words.
721 // The first word is a pointer to the interface (i.e. the java.lang.Class
722 // instance for that interface). The remaining words are pointers to the
723 // actual methods that implement the methods declared in the interface,
724 // in order of declaration.
726 // Append partial interface dispatch table for "iface" to "itable", at
727 // position itable_pos.
728 // Returns the offset at which the next partial ITable should be appended.
729 jshort
730 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
731 void **itable, jshort pos)
733 using namespace java::lang::reflect;
735 itable[pos++] = (void *) iface;
736 _Jv_Method *meth;
738 for (int j=0; j < iface->method_count; j++)
740 meth = NULL;
741 for (jclass cl = klass; cl; cl = cl->getSuperclass())
743 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
744 iface->methods[j].signature);
746 if (meth)
747 break;
750 if (meth && (meth->name->first() == '<'))
752 // leave a placeholder in the itable for hidden init methods.
753 itable[pos] = NULL;
755 else if (meth)
757 if ((meth->accflags & Modifier::STATIC) != 0)
758 throw new java::lang::IncompatibleClassChangeError
759 (_Jv_GetMethodString (klass, meth));
760 if ((meth->accflags & Modifier::PUBLIC) == 0)
761 throw new java::lang::IllegalAccessError
762 (_Jv_GetMethodString (klass, meth));
764 if ((meth->accflags & Modifier::ABSTRACT) != 0)
765 itable[pos] = (void *) &_Jv_abstractMethodError;
766 else
767 itable[pos] = meth->ncode;
769 else
771 // The method doesn't exist in klass. Binary compatibility rules
772 // permit this, so we delay the error until runtime using a pointer
773 // to a method which throws an exception.
774 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
776 pos++;
779 return pos;
782 static _Jv_Mutex_t iindex_mutex;
783 static bool iindex_mutex_initialized = false;
785 // We need to find the correct offset in the Class Interface Dispatch
786 // Table for a given interface. Once we have that, invoking an interface
787 // method just requires combining the Method's index in the interface
788 // (known at compile time) to get the correct method. Doing a type test
789 // (cast or instanceof) is the same problem: Once we have a possible Partial
790 // Interface Dispatch Table, we just compare the first element to see if it
791 // matches the desired interface. So how can we find the correct offset?
792 // Our solution is to keep a vector of candiate offsets in each interface
793 // (idt->iface.ioffsets), and in each class we have an index
794 // (idt->cls.iindex) used to select the correct offset from ioffsets.
796 // Calculate and return iindex for a new class.
797 // ifaces is a vector of num interfaces that the class implements.
798 // offsets[j] is the offset in the interface dispatch table for the
799 // interface corresponding to ifaces[j].
800 // May extend the interface ioffsets if required.
801 jshort
802 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
804 int i;
805 int j;
807 // Acquire a global lock to prevent itable corruption in case of multiple
808 // classes that implement an intersecting set of interfaces being linked
809 // simultaneously. We can assume that the mutex will be initialized
810 // single-threaded.
811 if (! iindex_mutex_initialized)
813 _Jv_MutexInit (&iindex_mutex);
814 iindex_mutex_initialized = true;
817 _Jv_MutexLock (&iindex_mutex);
819 for (i=1;; i++) /* each potential position in ioffsets */
821 for (j=0;; j++) /* each iface */
823 if (j >= num)
824 goto found;
825 if (i >= ifaces[j]->idt->iface.ioffsets[0])
826 continue;
827 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
828 /* We can potentially share this position with another class. */
829 if (ioffset >= 0 && ioffset != offsets[j])
830 break; /* Nope. Try next i. */
833 found:
834 for (j = 0; j < num; j++)
836 int len = ifaces[j]->idt->iface.ioffsets[0];
837 if (i >= len)
839 // Resize ioffsets.
840 int newlen = 2 * len;
841 if (i >= newlen)
842 newlen = i + 3;
843 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
844 // FIXME: _Jv_AllocBytes
845 jshort *new_ioffsets = (jshort *) _Jv_Malloc (newlen
846 * sizeof(jshort));
847 memcpy (&new_ioffsets[1], &old_ioffsets[1],
848 (len - 1) * sizeof (jshort));
849 new_ioffsets[0] = newlen;
851 while (len < newlen)
852 new_ioffsets[len++] = -1;
854 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
856 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
859 _Jv_MutexUnlock (&iindex_mutex);
861 return i;
865 // Functions for indirect dispatch (symbolic virtual binding) support.
867 // There are three tables, atable otable and itable. atable is an
868 // array of addresses, and otable is an array of offsets, and these
869 // are used for static and virtual members respectively. itable is an
870 // array of pairs {address, index} where each address is a pointer to
871 // an interface.
873 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
874 // symbol is a tuple of {classname, member name, signature}.
876 // Set this to true to enable debugging of indirect dispatch tables/linking.
877 static bool debug_link = false;
879 // link_symbol_table() scans these two arrays and fills in the
880 // corresponding atable and otable with the addresses of static
881 // members and the offsets of virtual members.
883 // The offset (in bytes) for each resolved method or field is placed
884 // at the corresponding position in the virtual method offset table
885 // (klass->otable).
887 // The same otable and atable may be shared by many classes.
889 // This must be called while holding the class lock.
891 void
892 _Jv_Linker::link_symbol_table (jclass klass)
894 int index = 0;
895 _Jv_MethodSymbol sym;
896 if (klass->otable == NULL
897 || klass->otable->state != 0)
898 goto atable;
900 klass->otable->state = 1;
902 if (debug_link)
903 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
904 for (index = 0;
905 (sym = klass->otable_syms[index]).class_name != NULL;
906 ++index)
908 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
909 _Jv_Method *meth = NULL;
911 _Jv_Utf8Const *signature = sym.signature;
914 static char *bounce = (char *)_Jv_ThrowNoSuchMethodError;
915 ptrdiff_t offset = (char *)(klass->vtable) - bounce;
916 klass->otable->offsets[index] = offset;
919 if (target_class == NULL)
920 throw new java::lang::NoClassDefFoundError
921 (_Jv_NewStringUTF (sym.class_name->chars()));
923 // We're looking for a field or a method, and we can tell
924 // which is needed by looking at the signature.
925 if (signature->first() == '(' && signature->len() >= 2)
927 // Looks like someone is trying to invoke an interface method
928 if (target_class->isInterface())
930 using namespace java::lang;
931 StringBuffer *sb = new StringBuffer();
932 sb->append(JvNewStringLatin1("found interface "));
933 sb->append(target_class->getName());
934 sb->append(JvNewStringLatin1(" when searching for a class"));
935 throw new VerifyError(sb->toString());
938 // If the target class does not have a vtable_method_count yet,
939 // then we can't tell the offsets for its methods, so we must lay
940 // it out now.
941 wait_for_state(target_class, JV_STATE_PREPARED);
943 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
944 sym.signature);
946 if (meth != NULL)
948 int offset = _Jv_VTable::idx_to_offset (meth->index);
949 if (offset == -1)
950 JvFail ("Bad method index");
951 JvAssert (meth->index < target_class->vtable_method_count);
952 klass->otable->offsets[index] = offset;
954 if (debug_link)
955 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
956 (int)index,
957 (int)klass->otable->offsets[index],
958 (const char*)target_class->name->chars(),
959 target_class,
960 (const char*)sym.name->chars(),
961 (const char*)signature->chars());
962 continue;
965 // Try fields.
967 wait_for_state(target_class, JV_STATE_PREPARED);
968 jclass found_class;
969 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
970 sym.name, sym.signature);
971 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
972 throw new java::lang::IncompatibleClassChangeError;
973 else
974 klass->otable->offsets[index] = the_field->u.boffset;
978 atable:
979 if (klass->atable == NULL || klass->atable->state != 0)
980 goto itable;
982 klass->atable->state = 1;
984 for (index = 0;
985 (sym = klass->atable_syms[index]).class_name != NULL;
986 ++index)
988 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
989 _Jv_Method *meth = NULL;
990 _Jv_Utf8Const *signature = sym.signature;
992 // ??? Setting this pointer to null will at least get us a
993 // NullPointerException
994 klass->atable->addresses[index] = NULL;
996 if (target_class == NULL)
997 throw new java::lang::NoClassDefFoundError
998 (_Jv_NewStringUTF (sym.class_name->chars()));
1000 // We're looking for a static field or a static method, and we
1001 // can tell which is needed by looking at the signature.
1002 if (signature->first() == '(' && signature->len() >= 2)
1004 // If the target class does not have a vtable_method_count yet,
1005 // then we can't tell the offsets for its methods, so we must lay
1006 // it out now.
1007 wait_for_state (target_class, JV_STATE_PREPARED);
1009 // Interface methods cannot have bodies.
1010 if (target_class->isInterface())
1012 using namespace java::lang;
1013 StringBuffer *sb = new StringBuffer();
1014 sb->append(JvNewStringLatin1("class "));
1015 sb->append(target_class->getName());
1016 sb->append(JvNewStringLatin1(" is an interface: "
1017 "class expected"));
1018 throw new VerifyError(sb->toString());
1021 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1022 sym.signature);
1024 if (meth != NULL)
1026 if (meth->ncode) // Maybe abstract?
1028 klass->atable->addresses[index] = meth->ncode;
1029 if (debug_link)
1030 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1031 index,
1032 &klass->atable->addresses[index],
1033 (const char*)target_class->name->chars(),
1034 klass,
1035 (const char*)sym.name->chars(),
1036 (const char*)signature->chars());
1039 else
1040 klass->atable->addresses[index]
1041 = (void *)_Jv_ThrowNoSuchMethodError;
1043 continue;
1046 // Try fields.
1048 wait_for_state(target_class, JV_STATE_PREPARED);
1049 jclass found_class;
1050 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
1051 sym.name, sym.signature);
1052 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1053 klass->atable->addresses[index] = the_field->u.addr;
1054 else
1055 throw new java::lang::IncompatibleClassChangeError;
1059 itable:
1060 if (klass->itable == NULL
1061 || klass->itable->state != 0)
1062 return;
1064 klass->itable->state = 1;
1066 for (index = 0;
1067 (sym = klass->itable_syms[index]).class_name != NULL;
1068 ++index)
1070 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1071 _Jv_Utf8Const *signature = sym.signature;
1073 jclass cls;
1074 int i;
1076 wait_for_state(target_class, JV_STATE_LOADED);
1077 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1078 sym.name, sym.signature);
1080 if (found)
1082 klass->itable->addresses[index * 2] = cls;
1083 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1084 if (debug_link)
1086 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1087 index,
1088 klass->itable->addresses[index * 2],
1089 (const char*)cls->name->chars(),
1090 cls,
1091 (const char*)sym.name->chars(),
1092 (const char*)signature->chars());
1093 fprintf (stderr, " [%d] = offset %d\n",
1094 index + 1,
1095 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1099 else
1100 throw new java::lang::IncompatibleClassChangeError;
1105 // For each catch_record in the list of caught classes, fill in the
1106 // address field.
1107 void
1108 _Jv_Linker::link_exception_table (jclass self)
1110 struct _Jv_CatchClass *catch_record = self->catch_classes;
1111 if (!catch_record || catch_record->classname)
1112 return;
1113 catch_record++;
1114 while (catch_record->classname)
1118 jclass target_class
1119 = _Jv_FindClass (catch_record->classname,
1120 self->getClassLoaderInternal ());
1121 *catch_record->address = target_class;
1123 catch (::java::lang::Throwable *t)
1125 // FIXME: We need to do something better here.
1126 *catch_record->address = 0;
1128 catch_record++;
1130 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1133 // Set itable method indexes for members of interface IFACE.
1134 void
1135 _Jv_Linker::layout_interface_methods (jclass iface)
1137 if (! iface->isInterface())
1138 return;
1140 // itable indexes start at 1.
1141 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1142 // itable so they are also assigned an index here.
1143 for (int i = 0; i < iface->method_count; i++)
1144 iface->methods[i].index = i + 1;
1147 // Prepare virtual method declarations in KLASS, and any superclasses
1148 // as required, by determining their vtable index, setting
1149 // method->index, and finally setting the class's vtable_method_count.
1150 // Must be called with the lock for KLASS held.
1151 void
1152 _Jv_Linker::layout_vtable_methods (jclass klass)
1154 if (klass->vtable != NULL || klass->isInterface()
1155 || klass->vtable_method_count != -1)
1156 return;
1158 jclass superclass = klass->getSuperclass();
1160 if (superclass != NULL && superclass->vtable_method_count == -1)
1162 JvSynchronize sync (superclass);
1163 layout_vtable_methods (superclass);
1166 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1168 for (int i = 0; i < klass->method_count; ++i)
1170 _Jv_Method *meth = &klass->methods[i];
1171 _Jv_Method *super_meth = NULL;
1173 if (! _Jv_isVirtualMethod (meth))
1174 continue;
1176 if (superclass != NULL)
1178 jclass declarer;
1179 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1180 meth->signature, &declarer);
1181 // See if this method actually overrides the other method
1182 // we've found.
1183 if (super_meth)
1185 if (! _Jv_isVirtualMethod (super_meth)
1186 || ! _Jv_CheckAccess (klass, declarer,
1187 super_meth->accflags))
1188 super_meth = NULL;
1189 else if ((super_meth->accflags
1190 & java::lang::reflect::Modifier::FINAL) != 0)
1192 using namespace java::lang;
1193 StringBuffer *sb = new StringBuffer();
1194 sb->append(JvNewStringLatin1("method "));
1195 sb->append(_Jv_GetMethodString(klass, meth));
1196 sb->append(JvNewStringLatin1(" overrides final method "));
1197 sb->append(_Jv_GetMethodString(declarer, super_meth));
1198 throw new VerifyError(sb->toString());
1203 if (super_meth)
1204 meth->index = super_meth->index;
1205 else
1206 meth->index = index++;
1209 klass->vtable_method_count = index;
1212 // Set entries in VTABLE for virtual methods declared in KLASS.
1213 void
1214 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1216 for (int i = klass->method_count - 1; i >= 0; i--)
1218 using namespace java::lang::reflect;
1220 _Jv_Method *meth = &klass->methods[i];
1221 if (meth->index == (_Jv_ushort) -1)
1222 continue;
1223 if ((meth->accflags & Modifier::ABSTRACT))
1224 // FIXME: it might be nice to have a libffi trampoline here,
1225 // so we could pass in the method name and other information.
1226 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1227 else
1228 vtable->set_method(meth->index, meth->ncode);
1232 // Allocate and lay out the virtual method table for KLASS. This will
1233 // also cause vtables to be generated for any non-abstract
1234 // superclasses, and virtual method layout to occur for any abstract
1235 // superclasses. Must be called with monitor lock for KLASS held.
1236 void
1237 _Jv_Linker::make_vtable (jclass klass)
1239 using namespace java::lang::reflect;
1241 // If the vtable exists, or for interface classes, do nothing. All
1242 // other classes, including abstract classes, need a vtable.
1243 if (klass->vtable != NULL || klass->isInterface())
1244 return;
1246 // Ensure all the `ncode' entries are set.
1247 klass->engine->create_ncode(klass);
1249 // Class must be laid out before we can create a vtable.
1250 if (klass->vtable_method_count == -1)
1251 layout_vtable_methods (klass);
1253 // Allocate the new vtable.
1254 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1255 klass->vtable = vtable;
1257 // Copy the vtable of the closest superclass.
1258 jclass superclass = klass->superclass;
1260 JvSynchronize sync (superclass);
1261 make_vtable (superclass);
1263 for (int i = 0; i < superclass->vtable_method_count; ++i)
1264 vtable->set_method (i, superclass->vtable->get_method (i));
1266 // Set the class pointer and GC descriptor.
1267 vtable->clas = klass;
1268 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1270 // For each virtual declared in klass, set new vtable entry or
1271 // override an old one.
1272 set_vtable_entries (klass, vtable);
1274 // Note that we don't check for abstract methods here. We used to,
1275 // but there is a JVMS clarification that indicates that a check
1276 // here would be too eager. And, a simple test case confirms this.
1279 // Lay out the class, allocating space for static fields and computing
1280 // offsets of instance fields. The class lock must be held by the
1281 // caller.
1282 void
1283 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1285 if (klass->size_in_bytes != -1)
1286 return;
1288 // Compute the alignment for this type by searching through the
1289 // superclasses and finding the maximum required alignment. We
1290 // could consider caching this in the Class.
1291 int max_align = __alignof__ (java::lang::Object);
1292 jclass super = klass->getSuperclass();
1293 while (super != NULL)
1295 // Ensure that our super has its super installed before
1296 // recursing.
1297 wait_for_state(super, JV_STATE_LOADING);
1298 ensure_fields_laid_out(super);
1299 int num = JvNumInstanceFields (super);
1300 _Jv_Field *field = JvGetFirstInstanceField (super);
1301 while (num > 0)
1303 int field_align = get_alignment_from_class (field->type);
1304 if (field_align > max_align)
1305 max_align = field_align;
1306 ++field;
1307 --num;
1309 super = super->getSuperclass();
1312 int instance_size;
1313 int static_size = 0;
1315 // Although java.lang.Object is never interpreted, an interface can
1316 // have a null superclass. Note that we have to lay out an
1317 // interface because it might have static fields.
1318 if (klass->superclass)
1319 instance_size = klass->superclass->size();
1320 else
1321 instance_size = java::lang::Object::class$.size();
1323 for (int i = 0; i < klass->field_count; i++)
1325 int field_size;
1326 int field_align;
1328 _Jv_Field *field = &klass->fields[i];
1330 if (! field->isRef ())
1332 // It is safe to resolve the field here, since it's a
1333 // primitive class, which does not cause loading to happen.
1334 resolve_field (field, klass->loader);
1336 field_size = field->type->size ();
1337 field_align = get_alignment_from_class (field->type);
1339 else
1341 field_size = sizeof (jobject);
1342 field_align = __alignof__ (jobject);
1345 field->bsize = field_size;
1347 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1349 if (field->u.addr == NULL)
1351 // This computes an offset into a region we'll allocate
1352 // shortly, and then add this offset to the start
1353 // address.
1354 static_size = ROUND (static_size, field_align);
1355 field->u.boffset = static_size;
1356 static_size += field_size;
1359 else
1361 instance_size = ROUND (instance_size, field_align);
1362 field->u.boffset = instance_size;
1363 instance_size += field_size;
1364 if (field_align > max_align)
1365 max_align = field_align;
1369 if (static_size != 0)
1370 klass->engine->allocate_static_fields (klass, static_size);
1372 // Set the instance size for the class. Note that first we round it
1373 // to the alignment required for this object; this keeps us in sync
1374 // with our current ABI.
1375 instance_size = ROUND (instance_size, max_align);
1376 klass->size_in_bytes = instance_size;
1379 // This takes the class to state JV_STATE_LINKED. The class lock must
1380 // be held when calling this.
1381 void
1382 _Jv_Linker::ensure_class_linked (jclass klass)
1384 if (klass->state >= JV_STATE_LINKED)
1385 return;
1387 int state = klass->state;
1390 // Short-circuit, so that mutually dependent classes are ok.
1391 klass->state = JV_STATE_LINKED;
1393 _Jv_Constants *pool = &klass->constants;
1395 // Compiled classes require that their class constants be
1396 // resolved here. However, interpreted classes need their
1397 // constants to be resolved lazily. If we resolve an
1398 // interpreted class' constants eagerly, we can end up with
1399 // spurious IllegalAccessErrors when the constant pool contains
1400 // a reference to a class we can't access. This can validly
1401 // occur in an obscure case involving the InnerClasses
1402 // attribute.
1403 if (! _Jv_IsInterpretedClass (klass))
1405 // Resolve class constants first, since other constant pool
1406 // entries may rely on these.
1407 for (int index = 1; index < pool->size; ++index)
1409 if (pool->tags[index] == JV_CONSTANT_Class)
1410 resolve_pool_entry (klass, index);
1414 #if 0 // Should be redundant now
1415 // If superclass looks like a constant pool entry,
1416 // resolve it now.
1417 if ((uaddr) klass->superclass < (uaddr) pool->size)
1418 klass->superclass = pool->data[(uaddr) klass->superclass].clazz;
1420 // Likewise for interfaces.
1421 for (int i = 0; i < klass->interface_count; i++)
1423 if ((uaddr) klass->interfaces[i] < (uaddr) pool->size)
1424 klass->interfaces[i]
1425 = pool->data[(uaddr) klass->interfaces[i]].clazz;
1427 #endif
1429 // Resolve the remaining constant pool entries.
1430 for (int index = 1; index < pool->size; ++index)
1432 if (pool->tags[index] == JV_CONSTANT_String)
1434 jstring str;
1436 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1437 pool->data[index].o = str;
1438 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1442 if (klass->engine->need_resolve_string_fields())
1444 jfieldID f = JvGetFirstStaticField (klass);
1445 for (int n = JvNumStaticFields (klass); n > 0; --n)
1447 int mod = f->getModifiers ();
1448 // If we have a static String field with a non-null initial
1449 // value, we know it points to a Utf8Const.
1450 resolve_field(f, klass->loader);
1451 if (f->getClass () == &java::lang::String::class$
1452 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1454 jstring *strp = (jstring *) f->u.addr;
1455 if (*strp)
1456 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1458 f = f->getNextField ();
1462 klass->notifyAll ();
1464 _Jv_PushClass (klass);
1466 catch (java::lang::Throwable *t)
1468 klass->state = state;
1469 throw t;
1473 // This ensures that symbolic superclass and superinterface references
1474 // are resolved for the indicated class. This must be called with the
1475 // class lock held.
1476 void
1477 _Jv_Linker::ensure_supers_installed (jclass klass)
1479 resolve_class_ref (klass, &klass->superclass);
1480 // An interface won't have a superclass.
1481 if (klass->superclass)
1482 wait_for_state (klass->superclass, JV_STATE_LOADING);
1484 for (int i = 0; i < klass->interface_count; ++i)
1486 resolve_class_ref (klass, &klass->interfaces[i]);
1487 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1491 // This adds missing `Miranda methods' to a class.
1492 void
1493 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1495 // Note that at this point, all our supers, and the supers of all
1496 // our superclasses and superinterfaces, will have been installed.
1498 for (int i = 0; i < iface_class->interface_count; ++i)
1500 jclass interface = iface_class->interfaces[i];
1502 for (int j = 0; j < interface->method_count; ++j)
1504 _Jv_Method *meth = &interface->methods[j];
1505 // Don't bother with <clinit>.
1506 if (meth->name->first() == '<')
1507 continue;
1508 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1509 meth->signature);
1510 if (! new_meth)
1512 // We assume that such methods are very unlikely, so we
1513 // just reallocate the method array each time one is
1514 // found. This greatly simplifies the searching --
1515 // otherwise we have to make sure that each such method
1516 // found is really unique among all superinterfaces.
1517 int new_count = base->method_count + 1;
1518 _Jv_Method *new_m
1519 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
1520 * new_count);
1521 memcpy (new_m, base->methods,
1522 sizeof (_Jv_Method) * base->method_count);
1524 // Add new method.
1525 new_m[base->method_count] = *meth;
1526 new_m[base->method_count].index = (_Jv_ushort) -1;
1527 new_m[base->method_count].accflags
1528 |= java::lang::reflect::Modifier::INVISIBLE;
1530 base->methods = new_m;
1531 base->method_count = new_count;
1535 wait_for_state (interface, JV_STATE_LOADED);
1536 add_miranda_methods (base, interface);
1540 // This ensures that the class' method table is "complete". This must
1541 // be called with the class lock held.
1542 void
1543 _Jv_Linker::ensure_method_table_complete (jclass klass)
1545 if (klass->vtable != NULL)
1546 return;
1548 // We need our superclass to have its own Miranda methods installed.
1549 if (! klass->isInterface())
1550 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1552 // A class might have so-called "Miranda methods". This is a method
1553 // that is declared in an interface and not re-declared in an
1554 // abstract class. Some compilers don't emit declarations for such
1555 // methods in the class; this will give us problems since we expect
1556 // a declaration for any method requiring a vtable entry. We handle
1557 // this here by searching for such methods and constructing new
1558 // internal declarations for them. Note that we do this
1559 // unconditionally, and not just for abstract classes, to correctly
1560 // account for cases where a class is modified to be concrete and
1561 // still incorrectly inherits an abstract method.
1562 int pre_count = klass->method_count;
1563 add_miranda_methods (klass, klass);
1565 // Let the execution engine know that we've added methods.
1566 if (klass->method_count != pre_count)
1567 klass->engine->post_miranda_hook(klass);
1570 // Verify a class. Must be called with class lock held.
1571 void
1572 _Jv_Linker::verify_class (jclass klass)
1574 klass->engine->verify(klass);
1577 // Check the assertions contained in the type assertion table for KLASS.
1578 // This is the equivilent of bytecode verification for native, BC-ABI code.
1579 void
1580 _Jv_Linker::verify_type_assertions (jclass klass)
1582 if (debug_link)
1583 fprintf (stderr, "Evaluating type assertions for %s:\n",
1584 klass->name->chars());
1586 if (klass->assertion_table == NULL)
1587 return;
1589 for (int i = 0;; i++)
1591 int assertion_code = klass->assertion_table[i].assertion_code;
1592 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1593 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1595 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1596 return;
1597 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1599 if (debug_link)
1601 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1602 assertion_code, op1->chars(), op2->chars());
1605 // The operands are class signatures. op1 is the source,
1606 // op2 is the target.
1607 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1608 klass->getClassLoaderInternal());
1609 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1610 klass->getClassLoaderInternal());
1612 // If the class doesn't exist, ignore the assertion. An exception
1613 // will be thrown later if an attempt is made to actually
1614 // instantiate the class.
1615 if (cl1 == NULL || cl2 == NULL)
1616 continue;
1618 if (! _Jv_IsAssignableFromSlow (cl2, cl1))
1620 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1621 s = s->concat (klass->getName());
1622 s = s->concat (JvNewStringUTF (": "));
1623 s = s->concat (cl1->getName());
1624 s = s->concat (JvNewStringUTF (" is not assignable to "));
1625 s = s->concat (cl2->getName());
1626 throw new java::lang::VerifyError (s);
1629 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1631 // TODO: Implement this.
1633 // Unknown assertion codes are ignored, for forwards-compatibility.
1637 void
1638 _Jv_Linker::print_class_loaded (jclass klass)
1640 char *codesource = NULL;
1641 if (klass->protectionDomain != NULL)
1643 java::security::CodeSource *cs
1644 = klass->protectionDomain->getCodeSource();
1645 if (cs != NULL)
1647 jstring css = cs->toString();
1648 int len = JvGetStringUTFLength(css);
1649 codesource = (char *) _Jv_AllocBytes(len + 1);
1650 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1651 codesource[len] = '\0';
1654 if (codesource == NULL)
1655 codesource = "<no code source>";
1657 char *abi;
1658 if (_Jv_IsInterpretedClass (klass))
1659 abi = "bytecode";
1660 else if (_Jv_IsBinaryCompatibilityABI (klass))
1661 abi = "BC-compiled";
1662 else
1663 abi = "pre-compiled";
1665 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1666 codesource);
1669 // FIXME: mention invariants and stuff.
1670 void
1671 _Jv_Linker::wait_for_state (jclass klass, int state)
1673 if (klass->state >= state)
1674 return;
1676 JvSynchronize sync (klass);
1678 // This is similar to the strategy for class initialization. If we
1679 // already hold the lock, just leave.
1680 java::lang::Thread *self = java::lang::Thread::currentThread();
1681 while (klass->state <= state
1682 && klass->thread
1683 && klass->thread != self)
1684 klass->wait ();
1686 java::lang::Thread *save = klass->thread;
1687 klass->thread = self;
1689 // Print some debugging info if requested. Interpreted classes are
1690 // handled in defineclass, so we only need to handle the two
1691 // pre-compiled cases here.
1692 if (gcj::verbose_class_flag
1693 && (klass->state == JV_STATE_COMPILED
1694 || klass->state == JV_STATE_PRELOADING)
1695 && ! _Jv_IsInterpretedClass (klass))
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 if (gcj::verifyClasses)
1724 verify_class (klass);
1726 ensure_class_linked (klass);
1727 link_exception_table (klass);
1728 link_symbol_table (klass);
1729 klass->set_state(JV_STATE_LINKED);
1732 catch (java::lang::Throwable *exc)
1734 klass->thread = save;
1735 klass->set_state(JV_STATE_ERROR);
1736 throw exc;
1739 klass->thread = save;
1741 if (klass->state == JV_STATE_ERROR)
1742 throw new java::lang::LinkageError;