* link.cc (link_symbol_table): Do not use intptr_t.
[official-gcc.git] / libjava / link.cc
blob2c5bd59fe82c57d67bbf3be81287ed54eeb571df
1 // link.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 /* Author: Kresten Krab Thorup <krab@gnu.org> */
13 #include <config.h>
14 #include <platform.h>
16 #include <java-interp.h>
18 #include <jvm.h>
19 #include <gcj/cni.h>
20 #include <string.h>
21 #include <java-cpool.h>
22 #include <execution.h>
23 #include <java/lang/Class.h>
24 #include <java/lang/String.h>
25 #include <java/lang/StringBuffer.h>
26 #include <java/lang/Thread.h>
27 #include <java/lang/InternalError.h>
28 #include <java/lang/VirtualMachineError.h>
29 #include <java/lang/VerifyError.h>
30 #include <java/lang/NoSuchFieldError.h>
31 #include <java/lang/NoSuchMethodError.h>
32 #include <java/lang/ClassFormatError.h>
33 #include <java/lang/IllegalAccessError.h>
34 #include <java/lang/AbstractMethodError.h>
35 #include <java/lang/NoClassDefFoundError.h>
36 #include <java/lang/IncompatibleClassChangeError.h>
37 #include <java/lang/VerifyError.h>
38 #include <java/lang/VMClassLoader.h>
39 #include <java/lang/reflect/Modifier.h>
40 #include <java/security/CodeSource.h>
42 using namespace gcj;
44 // When true, print debugging information about class loading.
45 bool gcj::verbose_class_flag;
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 _Jv_word
97 _Jv_Linker::resolve_pool_entry (jclass klass, int index)
99 using namespace java::lang::reflect;
101 _Jv_Constants *pool = &klass->constants;
103 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
104 return pool->data[index];
106 switch (pool->tags[index])
108 case JV_CONSTANT_Class:
110 _Jv_Utf8Const *name = pool->data[index].utf8;
112 jclass found;
113 if (name->first() == '[')
114 found = _Jv_FindClassFromSignature (name->chars(),
115 klass->loader);
116 else
117 found = _Jv_FindClass (name, klass->loader);
119 if (! found)
120 throw new java::lang::NoClassDefFoundError (name->toString());
122 // Check accessibility, but first strip array types as
123 // _Jv_ClassNameSamePackage can't handle arrays.
124 jclass check;
125 for (check = found;
126 check && check->isArray();
127 check = check->getComponentType())
129 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
130 || (_Jv_ClassNameSamePackage (check->name,
131 klass->name)))
133 pool->data[index].clazz = found;
134 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
136 else
138 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
139 sb->append(klass->getName());
140 sb->append(JvNewStringLatin1(" can't access class "));
141 sb->append(found->getName());
142 throw new java::lang::IllegalAccessError(sb->toString());
145 break;
147 case JV_CONSTANT_String:
149 jstring str;
150 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
151 pool->data[index].o = str;
152 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
154 break;
156 case JV_CONSTANT_Fieldref:
158 _Jv_ushort class_index, name_and_type_index;
159 _Jv_loadIndexes (&pool->data[index],
160 class_index,
161 name_and_type_index);
162 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
164 if (owner != klass)
165 _Jv_InitClass (owner);
167 _Jv_ushort name_index, type_index;
168 _Jv_loadIndexes (&pool->data[name_and_type_index],
169 name_index,
170 type_index);
172 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
173 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
175 // FIXME: The implementation of this function
176 // (_Jv_FindClassFromSignature) will generate an instance of
177 // _Jv_Utf8Const for each call if the field type is a class name
178 // (Lxx.yy.Z;). This may be too expensive to do for each and
179 // every fieldref being resolved. For now, we fix the problem by
180 // only doing it when we have a loader different from the class
181 // declaring the field.
183 jclass field_type = 0;
185 if (owner->loader != klass->loader)
186 field_type = _Jv_FindClassFromSignature (field_type_name->chars(),
187 klass->loader);
189 _Jv_Field* the_field = 0;
191 for (jclass cls = owner; cls != 0; cls = cls->getSuperclass ())
193 for (int i = 0; i < cls->field_count; i++)
195 _Jv_Field *field = &cls->fields[i];
196 if (! _Jv_equalUtf8Consts (field->name, field_name))
197 continue;
199 if (_Jv_CheckAccess (klass, cls, field->flags))
201 // Resolve the field using the class' own loader if
202 // necessary.
204 if (!field->isResolved ())
205 resolve_field (field, cls->loader);
207 if (field_type != 0 && field->type != field_type)
208 throw new java::lang::LinkageError
209 (JvNewStringLatin1
210 ("field type mismatch with different loaders"));
212 the_field = field;
213 goto end_of_field_search;
215 else
217 java::lang::StringBuffer *sb
218 = new java::lang::StringBuffer ();
219 sb->append(klass->getName());
220 sb->append(JvNewStringLatin1(": "));
221 sb->append(cls->getName());
222 sb->append(JvNewStringLatin1("."));
223 sb->append(_Jv_NewStringUtf8Const (field_name));
224 throw new java::lang::IllegalAccessError(sb->toString());
229 end_of_field_search:
230 if (the_field == 0)
232 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
233 sb->append(JvNewStringLatin1("field "));
234 sb->append(owner->getName());
235 sb->append(JvNewStringLatin1("."));
236 sb->append(_Jv_NewStringUTF(field_name->chars()));
237 sb->append(JvNewStringLatin1(" was not found."));
238 throw
239 new java::lang::IncompatibleClassChangeError (sb->toString());
242 pool->data[index].field = the_field;
243 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
245 break;
247 case JV_CONSTANT_Methodref:
248 case JV_CONSTANT_InterfaceMethodref:
250 _Jv_ushort class_index, name_and_type_index;
251 _Jv_loadIndexes (&pool->data[index],
252 class_index,
253 name_and_type_index);
254 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
256 if (owner != klass)
257 _Jv_InitClass (owner);
259 _Jv_ushort name_index, type_index;
260 _Jv_loadIndexes (&pool->data[name_and_type_index],
261 name_index,
262 type_index);
264 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
265 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
267 _Jv_Method *the_method = 0;
268 jclass found_class = 0;
270 // We're going to cache a pointer to the _Jv_Method object
271 // when we find it. So, to ensure this doesn't get moved from
272 // beneath us, we first put all the needed Miranda methods
273 // into the target class.
274 wait_for_state (klass, JV_STATE_LOADED);
276 // First search the class itself.
277 the_method = search_method_in_class (owner, klass,
278 method_name, method_signature);
280 if (the_method != 0)
282 found_class = owner;
283 goto end_of_method_search;
286 // If we are resolving an interface method, search the
287 // interface's superinterfaces (A superinterface is not an
288 // interface's superclass - a superinterface is implemented by
289 // the interface).
290 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
292 _Jv_ifaces ifaces;
293 ifaces.count = 0;
294 ifaces.len = 4;
295 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
296 * sizeof (jclass *));
298 get_interfaces (owner, &ifaces);
300 for (int i = 0; i < ifaces.count; i++)
302 jclass cls = ifaces.list[i];
303 the_method = search_method_in_class (cls, klass, method_name,
304 method_signature);
305 if (the_method != 0)
307 found_class = cls;
308 break;
312 _Jv_Free (ifaces.list);
314 if (the_method != 0)
315 goto end_of_method_search;
318 // Finally, search superclasses.
319 for (jclass cls = owner->getSuperclass (); cls != 0;
320 cls = cls->getSuperclass ())
322 the_method = search_method_in_class (cls, klass, method_name,
323 method_signature);
324 if (the_method != 0)
326 found_class = cls;
327 break;
331 end_of_method_search:
333 // FIXME: if (cls->loader != klass->loader), then we
334 // must actually check that the types of arguments
335 // correspond. That is, for each argument type, and
336 // the return type, doing _Jv_FindClassFromSignature
337 // with either loader should produce the same result,
338 // i.e., exactly the same jclass object. JVMS 5.4.3.3
340 if (the_method == 0)
342 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
343 sb->append(JvNewStringLatin1("method "));
344 sb->append(owner->getName());
345 sb->append(JvNewStringLatin1("."));
346 sb->append(_Jv_NewStringUTF(method_name->chars()));
347 sb->append(JvNewStringLatin1(" with signature "));
348 sb->append(_Jv_NewStringUTF(method_signature->chars()));
349 sb->append(JvNewStringLatin1(" was not found."));
350 throw new java::lang::NoSuchMethodError (sb->toString());
353 int vtable_index = -1;
354 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
355 vtable_index = (jshort)the_method->index;
357 pool->data[index].rmethod
358 = klass->engine->resolve_method(the_method,
359 found_class,
360 ((the_method->accflags
361 & Modifier::STATIC) != 0),
362 vtable_index);
363 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
365 break;
367 return pool->data[index];
370 // This function is used to lazily locate superclasses and
371 // superinterfaces. This must be called with the class lock held.
372 void
373 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
375 jclass ret = *classref;
377 // If superclass looks like a constant pool entry, resolve it now.
378 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
380 if (klass->state < JV_STATE_LINKED)
382 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
383 ret = _Jv_FindClass (name, klass->loader);
384 if (! ret)
386 throw new java::lang::NoClassDefFoundError (name->toString());
389 else
390 ret = klass->constants.data[(uaddr) classref].clazz;
391 *classref = ret;
395 // Find a method declared in the cls that is referenced from klass and
396 // perform access checks.
397 _Jv_Method *
398 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
399 _Jv_Utf8Const *method_name,
400 _Jv_Utf8Const *method_signature)
402 using namespace java::lang::reflect;
404 for (int i = 0; i < cls->method_count; i++)
406 _Jv_Method *method = &cls->methods[i];
407 if ( (!_Jv_equalUtf8Consts (method->name,
408 method_name))
409 || (!_Jv_equalUtf8Consts (method->signature,
410 method_signature)))
411 continue;
413 if (_Jv_CheckAccess (klass, cls, method->accflags))
414 return method;
415 else
417 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
418 sb->append(klass->getName());
419 sb->append(JvNewStringLatin1(": "));
420 sb->append(cls->getName());
421 sb->append(JvNewStringLatin1("."));
422 sb->append(_Jv_NewStringUTF(method_name->chars()));
423 sb->append(_Jv_NewStringUTF(method_signature->chars()));
424 throw new java::lang::IllegalAccessError (sb->toString());
427 return 0;
431 #define INITIAL_IOFFSETS_LEN 4
432 #define INITIAL_IFACES_LEN 4
434 static _Jv_IDispatchTable null_idt = { {SHRT_MAX, 0, NULL} };
436 // Generate tables for constant-time assignment testing and interface
437 // method lookup. This implements the technique described by Per Bothner
438 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
439 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
440 void
441 _Jv_Linker::prepare_constant_time_tables (jclass klass)
443 if (klass->isPrimitive () || klass->isInterface ())
444 return;
446 // Short-circuit in case we've been called already.
447 if ((klass->idt != NULL) || klass->depth != 0)
448 return;
450 // Calculate the class depth and ancestor table. The depth of a class
451 // is how many "extends" it is removed from Object. Thus the depth of
452 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
453 // is 2. Depth is defined for all regular and array classes, but not
454 // interfaces or primitive types.
456 jclass klass0 = klass;
457 jboolean has_interfaces = 0;
458 while (klass0 != &java::lang::Object::class$)
460 has_interfaces += klass0->interface_count;
461 klass0 = klass0->superclass;
462 klass->depth++;
465 // We do class member testing in constant time by using a small table
466 // of all the ancestor classes within each class. The first element is
467 // a pointer to the current class, and the rest are pointers to the
468 // classes ancestors, ordered from the current class down by decreasing
469 // depth. We do not include java.lang.Object in the table of ancestors,
470 // since it is redundant.
472 // FIXME: _Jv_AllocBytes
473 klass->ancestors = (jclass *) _Jv_Malloc (klass->depth
474 * sizeof (jclass));
475 klass0 = klass;
476 for (int index = 0; index < klass->depth; index++)
478 klass->ancestors[index] = klass0;
479 klass0 = klass0->superclass;
482 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
483 return;
485 // Optimization: If class implements no interfaces, use a common
486 // predefined interface table.
487 if (!has_interfaces)
489 klass->idt = &null_idt;
490 return;
493 // FIXME: _Jv_AllocBytes
494 klass->idt =
495 (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
497 _Jv_ifaces ifaces;
498 ifaces.count = 0;
499 ifaces.len = INITIAL_IFACES_LEN;
500 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
502 int itable_size = get_interfaces (klass, &ifaces);
504 if (ifaces.count > 0)
506 klass->idt->cls.itable =
507 // FIXME: _Jv_AllocBytes
508 (void **) _Jv_Malloc (itable_size * sizeof (void *));
509 klass->idt->cls.itable_length = itable_size;
511 jshort *itable_offsets =
512 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
514 generate_itable (klass, &ifaces, itable_offsets);
516 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
517 ifaces.count);
519 for (int i = 0; i < ifaces.count; i++)
521 ifaces.list[i]->idt->iface.ioffsets[cls_iindex] =
522 itable_offsets[i];
525 klass->idt->cls.iindex = cls_iindex;
527 _Jv_Free (ifaces.list);
528 _Jv_Free (itable_offsets);
530 else
532 klass->idt->cls.iindex = SHRT_MAX;
536 // Return index of item in list, or -1 if item is not present.
537 inline jshort
538 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
540 for (int i=0; i < list_len; i++)
542 if (list[i] == item)
543 return i;
545 return -1;
548 // Find all unique interfaces directly or indirectly implemented by klass.
549 // Returns the size of the interface dispatch table (itable) for klass, which
550 // is the number of unique interfaces plus the total number of methods that
551 // those interfaces declare. May extend ifaces if required.
552 jshort
553 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
555 jshort result = 0;
557 for (int i = 0; i < klass->interface_count; i++)
559 jclass iface = klass->interfaces[i];
561 /* Make sure interface is linked. */
562 wait_for_state(iface, JV_STATE_LINKED);
564 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
566 if (ifaces->count + 1 >= ifaces->len)
568 /* Resize ifaces list */
569 ifaces->len = ifaces->len * 2;
570 ifaces->list
571 = (jclass *) _Jv_Realloc (ifaces->list,
572 ifaces->len * sizeof(jclass));
574 ifaces->list[ifaces->count] = iface;
575 ifaces->count++;
577 result += get_interfaces (klass->interfaces[i], ifaces);
581 if (klass->isInterface())
582 result += klass->method_count + 1;
583 else if (klass->superclass)
584 result += get_interfaces (klass->superclass, ifaces);
585 return result;
588 // Fill out itable in klass, resolving method declarations in each ifaces.
589 // itable_offsets is filled out with the position of each iface in itable,
590 // such that itable[itable_offsets[n]] == ifaces.list[n].
591 void
592 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
593 jshort *itable_offsets)
595 void **itable = klass->idt->cls.itable;
596 jshort itable_pos = 0;
598 for (int i = 0; i < ifaces->count; i++)
600 jclass iface = ifaces->list[i];
601 itable_offsets[i] = itable_pos;
602 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
604 /* Create interface dispatch table for iface */
605 if (iface->idt == NULL)
607 // FIXME: _Jv_AllocBytes
608 iface->idt
609 = (_Jv_IDispatchTable *) _Jv_Malloc (sizeof (_Jv_IDispatchTable));
611 // The first element of ioffsets is its length (itself included).
612 // FIXME: _Jv_AllocBytes
613 jshort *ioffsets = (jshort *) _Jv_Malloc (INITIAL_IOFFSETS_LEN
614 * sizeof (jshort));
615 ioffsets[0] = INITIAL_IOFFSETS_LEN;
616 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
617 ioffsets[i] = -1;
619 iface->idt->iface.ioffsets = ioffsets;
624 // Format method name for use in error messages.
625 jstring
626 _Jv_GetMethodString (jclass klass, _Jv_Utf8Const *name)
628 jstring r = klass->name->toString();
629 r = r->concat (JvNewStringUTF ("."));
630 r = r->concat (name->toString());
631 return r;
634 void
635 _Jv_ThrowNoSuchMethodError ()
637 throw new java::lang::NoSuchMethodError;
640 // Each superinterface of a class (i.e. each interface that the class
641 // directly or indirectly implements) has a corresponding "Partial
642 // Interface Dispatch Table" whose size is (number of methods + 1) words.
643 // The first word is a pointer to the interface (i.e. the java.lang.Class
644 // instance for that interface). The remaining words are pointers to the
645 // actual methods that implement the methods declared in the interface,
646 // in order of declaration.
648 // Append partial interface dispatch table for "iface" to "itable", at
649 // position itable_pos.
650 // Returns the offset at which the next partial ITable should be appended.
651 jshort
652 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
653 void **itable, jshort pos)
655 using namespace java::lang::reflect;
657 itable[pos++] = (void *) iface;
658 _Jv_Method *meth;
660 for (int j=0; j < iface->method_count; j++)
662 meth = NULL;
663 for (jclass cl = klass; cl; cl = cl->getSuperclass())
665 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
666 iface->methods[j].signature);
668 if (meth)
669 break;
672 if (meth && (meth->name->first() == '<'))
674 // leave a placeholder in the itable for hidden init methods.
675 itable[pos] = NULL;
677 else if (meth)
679 if ((meth->accflags & Modifier::STATIC) != 0)
680 throw new java::lang::IncompatibleClassChangeError
681 (_Jv_GetMethodString (klass, meth->name));
682 if ((meth->accflags & Modifier::ABSTRACT) != 0)
683 throw new java::lang::AbstractMethodError
684 (_Jv_GetMethodString (klass, meth->name));
685 if ((meth->accflags & Modifier::PUBLIC) == 0)
686 throw new java::lang::IllegalAccessError
687 (_Jv_GetMethodString (klass, meth->name));
689 itable[pos] = meth->ncode;
691 else
693 // The method doesn't exist in klass. Binary compatibility rules
694 // permit this, so we delay the error until runtime using a pointer
695 // to a method which throws an exception.
696 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
698 pos++;
701 return pos;
704 static _Jv_Mutex_t iindex_mutex;
705 static bool iindex_mutex_initialized = false;
707 // We need to find the correct offset in the Class Interface Dispatch
708 // Table for a given interface. Once we have that, invoking an interface
709 // method just requires combining the Method's index in the interface
710 // (known at compile time) to get the correct method. Doing a type test
711 // (cast or instanceof) is the same problem: Once we have a possible Partial
712 // Interface Dispatch Table, we just compare the first element to see if it
713 // matches the desired interface. So how can we find the correct offset?
714 // Our solution is to keep a vector of candiate offsets in each interface
715 // (idt->iface.ioffsets), and in each class we have an index
716 // (idt->cls.iindex) used to select the correct offset from ioffsets.
718 // Calculate and return iindex for a new class.
719 // ifaces is a vector of num interfaces that the class implements.
720 // offsets[j] is the offset in the interface dispatch table for the
721 // interface corresponding to ifaces[j].
722 // May extend the interface ioffsets if required.
723 jshort
724 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
726 int i;
727 int j;
729 // Acquire a global lock to prevent itable corruption in case of multiple
730 // classes that implement an intersecting set of interfaces being linked
731 // simultaneously. We can assume that the mutex will be initialized
732 // single-threaded.
733 if (! iindex_mutex_initialized)
735 _Jv_MutexInit (&iindex_mutex);
736 iindex_mutex_initialized = true;
739 _Jv_MutexLock (&iindex_mutex);
741 for (i=1;; i++) /* each potential position in ioffsets */
743 for (j=0;; j++) /* each iface */
745 if (j >= num)
746 goto found;
747 if (i >= ifaces[j]->idt->iface.ioffsets[0])
748 continue;
749 int ioffset = ifaces[j]->idt->iface.ioffsets[i];
750 /* We can potentially share this position with another class. */
751 if (ioffset >= 0 && ioffset != offsets[j])
752 break; /* Nope. Try next i. */
755 found:
756 for (j = 0; j < num; j++)
758 int len = ifaces[j]->idt->iface.ioffsets[0];
759 if (i >= len)
761 // Resize ioffsets.
762 int newlen = 2 * len;
763 if (i >= newlen)
764 newlen = i + 3;
765 jshort *old_ioffsets = ifaces[j]->idt->iface.ioffsets;
766 // FIXME: _Jv_AllocBytes
767 jshort *new_ioffsets = (jshort *) _Jv_Malloc (newlen
768 * sizeof(jshort));
769 memcpy (&new_ioffsets[1], &old_ioffsets[1],
770 (len - 1) * sizeof (jshort));
771 new_ioffsets[0] = newlen;
773 while (len < newlen)
774 new_ioffsets[len++] = -1;
776 ifaces[j]->idt->iface.ioffsets = new_ioffsets;
778 ifaces[j]->idt->iface.ioffsets[i] = offsets[j];
781 _Jv_MutexUnlock (&iindex_mutex);
783 return i;
787 // Functions for indirect dispatch (symbolic virtual binding) support.
789 // There are three tables, atable otable and itable. atable is an
790 // array of addresses, and otable is an array of offsets, and these
791 // are used for static and virtual members respectively. itable is an
792 // array of pairs {address, index} where each address is a pointer to
793 // an interface.
795 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
796 // symbol is a tuple of {classname, member name, signature}.
798 // Set this to true to enable debugging of indirect dispatch tables/linking.
799 static bool debug_link = false;
801 // link_symbol_table() scans these two arrays and fills in the
802 // corresponding atable and otable with the addresses of static
803 // members and the offsets of virtual members.
805 // The offset (in bytes) for each resolved method or field is placed
806 // at the corresponding position in the virtual method offset table
807 // (klass->otable).
809 // The same otable and atable may be shared by many classes.
811 // This must be called while holding the class lock.
813 void
814 _Jv_Linker::link_symbol_table (jclass klass)
816 int index = 0;
817 _Jv_MethodSymbol sym;
818 if (klass->otable == NULL
819 || klass->otable->state != 0)
820 goto atable;
822 klass->otable->state = 1;
824 if (debug_link)
825 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
826 for (index = 0;
827 (sym = klass->otable_syms[index]).class_name != NULL;
828 ++index)
830 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
831 _Jv_Method *meth = NULL;
833 _Jv_Utf8Const *signature = sym.signature;
836 static char *bounce = (char *)_Jv_ThrowNoSuchMethodError;
837 ptrdiff_t offset = (char *)(klass->vtable) - bounce;
838 klass->otable->offsets[index] = offset;
841 if (target_class == NULL)
842 throw new java::lang::NoClassDefFoundError
843 (_Jv_NewStringUTF (sym.class_name->chars()));
845 // We're looking for a field or a method, and we can tell
846 // which is needed by looking at the signature.
847 if (signature->first() == '(' && signature->len() >= 2)
849 // Looks like someone is trying to invoke an interface method
850 if (target_class->isInterface())
852 using namespace java::lang;
853 StringBuffer *sb = new StringBuffer();
854 sb->append(JvNewStringLatin1("found interface "));
855 sb->append(target_class->getName());
856 sb->append(JvNewStringLatin1(" when searching for a class"));
857 throw new VerifyError(sb->toString());
860 // If the target class does not have a vtable_method_count yet,
861 // then we can't tell the offsets for its methods, so we must lay
862 // it out now.
863 wait_for_state(target_class, JV_STATE_PREPARED);
865 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
866 sym.signature);
868 if (meth != NULL)
870 int offset = _Jv_VTable::idx_to_offset (meth->index);
871 if (offset == -1)
872 JvFail ("Bad method index");
873 JvAssert (meth->index < target_class->vtable_method_count);
874 klass->otable->offsets[index] = offset;
876 if (debug_link)
877 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
878 (int)index,
879 (int)klass->otable->offsets[index],
880 (const char*)target_class->name->chars(),
881 target_class,
882 (const char*)sym.name->chars(),
883 (const char*)signature->chars());
884 continue;
887 // try fields
889 _Jv_Field *the_field = NULL;
891 wait_for_state(target_class, JV_STATE_PREPARED);
892 for (jclass cls = target_class; cls != 0; cls = cls->getSuperclass ())
894 for (int i = 0; i < cls->field_count; i++)
896 _Jv_Field *field = &cls->fields[i];
897 if (! _Jv_equalUtf8Consts (field->name, sym.name))
898 continue;
900 // FIXME: What access checks should we perform here?
901 // if (_Jv_CheckAccess (klass, cls, field->flags))
902 // {
904 if (!field->isResolved ())
905 resolve_field (field, cls->loader);
907 // if (field_type != 0 && field->type != field_type)
908 // throw new java::lang::LinkageError
909 // (JvNewStringLatin1
910 // ("field type mismatch with different loaders"));
912 the_field = field;
913 if (debug_link)
914 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s)\n",
915 (int)index,
916 (int)field->u.boffset,
917 (const char*)cls->name->chars(),
918 cls,
919 (const char*)field->name->chars());
920 goto end_of_field_search;
923 end_of_field_search:
924 if (the_field != NULL)
926 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
927 throw new java::lang::IncompatibleClassChangeError;
928 else
929 klass->otable->offsets[index] = the_field->u.boffset;
931 else
933 throw new java::lang::NoSuchFieldError
934 (_Jv_NewStringUtf8Const (sym.name));
939 atable:
940 if (klass->atable == NULL || klass->atable->state != 0)
941 goto itable;
943 klass->atable->state = 1;
945 for (index = 0;
946 (sym = klass->atable_syms[index]).class_name != NULL;
947 ++index)
949 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
950 _Jv_Method *meth = NULL;
951 _Jv_Utf8Const *signature = sym.signature;
953 // ??? Setting this pointer to null will at least get us a
954 // NullPointerException
955 klass->atable->addresses[index] = NULL;
957 if (target_class == NULL)
958 throw new java::lang::NoClassDefFoundError
959 (_Jv_NewStringUTF (sym.class_name->chars()));
961 // We're looking for a static field or a static method, and we
962 // can tell which is needed by looking at the signature.
963 if (signature->first() == '(' && signature->len() >= 2)
965 // If the target class does not have a vtable_method_count yet,
966 // then we can't tell the offsets for its methods, so we must lay
967 // it out now.
968 wait_for_state (target_class, JV_STATE_PREPARED);
970 // Interface methods cannot have bodies.
971 if (target_class->isInterface())
973 using namespace java::lang;
974 StringBuffer *sb = new StringBuffer();
975 sb->append(JvNewStringLatin1("class "));
976 sb->append(target_class->getName());
977 sb->append(JvNewStringLatin1(" is an interface: "
978 "class expected"));
979 throw new VerifyError(sb->toString());
982 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
983 sym.signature);
985 if (meth != NULL)
987 if (meth->ncode) // Maybe abstract?
989 klass->atable->addresses[index] = meth->ncode;
990 if (debug_link)
991 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
992 index,
993 &klass->atable->addresses[index],
994 (const char*)target_class->name->chars(),
995 klass,
996 (const char*)sym.name->chars(),
997 (const char*)signature->chars());
1000 else
1001 klass->atable->addresses[index]
1002 = (void *)_Jv_ThrowNoSuchMethodError;
1004 continue;
1007 // try fields
1009 _Jv_Field *the_field = NULL;
1011 wait_for_state(target_class, JV_STATE_PREPARED);
1012 for (jclass cls = target_class; cls != 0; cls = cls->getSuperclass ())
1014 for (int i = 0; i < cls->field_count; i++)
1016 _Jv_Field *field = &cls->fields[i];
1017 if (! _Jv_equalUtf8Consts (field->name, sym.name))
1018 continue;
1020 // FIXME: What access checks should we perform here?
1021 // if (_Jv_CheckAccess (klass, cls, field->flags))
1022 // {
1024 if (!field->isResolved ())
1025 resolve_field (field, cls->loader);
1027 // if (field_type != 0 && field->type != field_type)
1028 // throw new java::lang::LinkageError
1029 // (JvNewStringLatin1
1030 // ("field type mismatch with different loaders"));
1032 the_field = field;
1033 goto end_of_static_field_search;
1036 end_of_static_field_search:
1037 if (the_field != NULL)
1039 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1040 klass->atable->addresses[index] = the_field->u.addr;
1041 else
1042 throw new java::lang::IncompatibleClassChangeError;
1044 else
1046 throw new java::lang::NoSuchFieldError
1047 (_Jv_NewStringUtf8Const (sym.name));
1052 itable:
1053 if (klass->itable == NULL
1054 || klass->itable->state != 0)
1055 return;
1057 klass->itable->state = 1;
1059 for (index = 0;
1060 (sym = klass->itable_syms[index]).class_name != NULL;
1061 ++index)
1063 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1064 _Jv_Utf8Const *signature = sym.signature;
1066 jclass cls;
1067 int i;
1069 wait_for_state(target_class, JV_STATE_LOADED);
1070 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1071 sym.name, sym.signature);
1073 if (found)
1075 klass->itable->addresses[index * 2] = cls;
1076 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1077 if (debug_link)
1079 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1080 index,
1081 klass->itable->addresses[index * 2],
1082 (const char*)cls->name->chars(),
1083 cls,
1084 (const char*)sym.name->chars(),
1085 (const char*)signature->chars());
1086 fprintf (stderr, " [%d] = offset %d\n",
1087 index + 1,
1088 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1092 else
1093 throw new java::lang::IncompatibleClassChangeError;
1098 // For each catch_record in the list of caught classes, fill in the
1099 // address field.
1100 void
1101 _Jv_Linker::link_exception_table (jclass self)
1103 struct _Jv_CatchClass *catch_record = self->catch_classes;
1104 if (!catch_record || catch_record->classname)
1105 return;
1106 catch_record++;
1107 while (catch_record->classname)
1111 jclass target_class
1112 = _Jv_FindClass (catch_record->classname,
1113 self->getClassLoaderInternal ());
1114 *catch_record->address = target_class;
1116 catch (::java::lang::Throwable *t)
1118 // FIXME: We need to do something better here.
1119 *catch_record->address = 0;
1121 catch_record++;
1123 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1126 // This is put in empty vtable slots.
1127 static void
1128 _Jv_abstractMethodError (void)
1130 throw new java::lang::AbstractMethodError();
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->name));
1196 sb->append(JvNewStringLatin1(" overrides final method "));
1197 sb->append(_Jv_GetMethodString(declarer, super_meth->name));
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 vtable->set_method(meth->index, (void *) &_Jv_abstractMethodError);
1225 else
1226 vtable->set_method(meth->index, meth->ncode);
1230 // Allocate and lay out the virtual method table for KLASS. This will
1231 // also cause vtables to be generated for any non-abstract
1232 // superclasses, and virtual method layout to occur for any abstract
1233 // superclasses. Must be called with monitor lock for KLASS held.
1234 void
1235 _Jv_Linker::make_vtable (jclass klass)
1237 using namespace java::lang::reflect;
1239 // If the vtable exists, or for interface classes, do nothing. All
1240 // other classes, including abstract classes, need a vtable.
1241 if (klass->vtable != NULL || klass->isInterface())
1242 return;
1244 // Ensure all the `ncode' entries are set.
1245 klass->engine->create_ncode(klass);
1247 // Class must be laid out before we can create a vtable.
1248 if (klass->vtable_method_count == -1)
1249 layout_vtable_methods (klass);
1251 // Allocate the new vtable.
1252 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1253 klass->vtable = vtable;
1255 // Copy the vtable of the closest superclass.
1256 jclass superclass = klass->superclass;
1258 JvSynchronize sync (superclass);
1259 make_vtable (superclass);
1261 for (int i = 0; i < superclass->vtable_method_count; ++i)
1262 vtable->set_method (i, superclass->vtable->get_method (i));
1264 // Set the class pointer and GC descriptor.
1265 vtable->clas = klass;
1266 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1268 // For each virtual declared in klass, set new vtable entry or
1269 // override an old one.
1270 set_vtable_entries (klass, vtable);
1272 // It is an error to have an abstract method in a concrete class.
1273 if (! (klass->accflags & Modifier::ABSTRACT))
1275 for (int i = 0; i < klass->vtable_method_count; ++i)
1276 if (vtable->get_method(i) == (void *) &_Jv_abstractMethodError)
1278 using namespace java::lang;
1279 while (klass != NULL)
1281 for (int j = 0; j < klass->method_count; ++j)
1283 if (klass->methods[j].index == i)
1285 StringBuffer *buf = new StringBuffer ();
1286 buf->append (_Jv_NewStringUtf8Const (klass->methods[j].name));
1287 buf->append ((jchar) ' ');
1288 buf->append (_Jv_NewStringUtf8Const (klass->methods[j].signature));
1289 throw new AbstractMethodError (buf->toString ());
1292 klass = klass->getSuperclass ();
1294 // Couldn't find the name, which is weird.
1295 // But we still must throw the error.
1296 throw new AbstractMethodError ();
1301 // Lay out the class, allocating space for static fields and computing
1302 // offsets of instance fields. The class lock must be held by the
1303 // caller.
1304 void
1305 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1307 if (klass->size_in_bytes != -1)
1308 return;
1310 // Compute the alignment for this type by searching through the
1311 // superclasses and finding the maximum required alignment. We
1312 // could consider caching this in the Class.
1313 int max_align = __alignof__ (java::lang::Object);
1314 jclass super = klass->getSuperclass();
1315 while (super != NULL)
1317 // Ensure that our super has its super installed before
1318 // recursing.
1319 wait_for_state(super, JV_STATE_LOADING);
1320 ensure_fields_laid_out(super);
1321 int num = JvNumInstanceFields (super);
1322 _Jv_Field *field = JvGetFirstInstanceField (super);
1323 while (num > 0)
1325 int field_align = get_alignment_from_class (field->type);
1326 if (field_align > max_align)
1327 max_align = field_align;
1328 ++field;
1329 --num;
1331 super = super->getSuperclass();
1334 int instance_size;
1335 int static_size = 0;
1337 // Although java.lang.Object is never interpreted, an interface can
1338 // have a null superclass. Note that we have to lay out an
1339 // interface because it might have static fields.
1340 if (klass->superclass)
1341 instance_size = klass->superclass->size();
1342 else
1343 instance_size = java::lang::Object::class$.size();
1345 for (int i = 0; i < klass->field_count; i++)
1347 int field_size;
1348 int field_align;
1350 _Jv_Field *field = &klass->fields[i];
1352 if (! field->isRef ())
1354 // It is safe to resolve the field here, since it's a
1355 // primitive class, which does not cause loading to happen.
1356 resolve_field (field, klass->loader);
1358 field_size = field->type->size ();
1359 field_align = get_alignment_from_class (field->type);
1361 else
1363 field_size = sizeof (jobject);
1364 field_align = __alignof__ (jobject);
1367 field->bsize = field_size;
1369 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1371 if (field->u.addr == NULL)
1373 // This computes an offset into a region we'll allocate
1374 // shortly, and then add this offset to the start
1375 // address.
1376 static_size = ROUND (static_size, field_align);
1377 field->u.boffset = static_size;
1378 static_size += field_size;
1381 else
1383 instance_size = ROUND (instance_size, field_align);
1384 field->u.boffset = instance_size;
1385 instance_size += field_size;
1386 if (field_align > max_align)
1387 max_align = field_align;
1391 if (static_size != 0)
1392 klass->engine->allocate_static_fields (klass, static_size);
1394 // Set the instance size for the class. Note that first we round it
1395 // to the alignment required for this object; this keeps us in sync
1396 // with our current ABI.
1397 instance_size = ROUND (instance_size, max_align);
1398 klass->size_in_bytes = instance_size;
1401 // This takes the class to state JV_STATE_LINKED. The class lock must
1402 // be held when calling this.
1403 void
1404 _Jv_Linker::ensure_class_linked (jclass klass)
1406 if (klass->state >= JV_STATE_LINKED)
1407 return;
1409 int state = klass->state;
1412 // Short-circuit, so that mutually dependent classes are ok.
1413 klass->state = JV_STATE_LINKED;
1415 _Jv_Constants *pool = &klass->constants;
1417 // Compiled classes require that their class constants be
1418 // resolved here. However, interpreted classes need their
1419 // constants to be resolved lazily. If we resolve an
1420 // interpreted class' constants eagerly, we can end up with
1421 // spurious IllegalAccessErrors when the constant pool contains
1422 // a reference to a class we can't access. This can validly
1423 // occur in an obscure case involving the InnerClasses
1424 // attribute.
1425 #ifdef INTERPRETER
1426 if (! _Jv_IsInterpretedClass (klass))
1427 #endif
1429 // Resolve class constants first, since other constant pool
1430 // entries may rely on these.
1431 for (int index = 1; index < pool->size; ++index)
1433 if (pool->tags[index] == JV_CONSTANT_Class)
1434 resolve_pool_entry (klass, index);
1438 #if 0 // Should be redundant now
1439 // If superclass looks like a constant pool entry,
1440 // resolve it now.
1441 if ((uaddr) klass->superclass < (uaddr) pool->size)
1442 klass->superclass = pool->data[(uaddr) klass->superclass].clazz;
1444 // Likewise for interfaces.
1445 for (int i = 0; i < klass->interface_count; i++)
1447 if ((uaddr) klass->interfaces[i] < (uaddr) pool->size)
1448 klass->interfaces[i]
1449 = pool->data[(uaddr) klass->interfaces[i]].clazz;
1451 #endif
1453 // Resolve the remaining constant pool entries.
1454 for (int index = 1; index < pool->size; ++index)
1456 if (pool->tags[index] == JV_CONSTANT_String)
1458 jstring str;
1460 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1461 pool->data[index].o = str;
1462 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1466 if (klass->engine->need_resolve_string_fields())
1468 jfieldID f = JvGetFirstStaticField (klass);
1469 for (int n = JvNumStaticFields (klass); n > 0; --n)
1471 int mod = f->getModifiers ();
1472 // If we have a static String field with a non-null initial
1473 // value, we know it points to a Utf8Const.
1474 resolve_field(f, klass->loader);
1475 if (f->getClass () == &java::lang::String::class$
1476 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1478 jstring *strp = (jstring *) f->u.addr;
1479 if (*strp)
1480 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1482 f = f->getNextField ();
1486 klass->notifyAll ();
1488 _Jv_PushClass (klass);
1490 catch (java::lang::Throwable *t)
1492 klass->state = state;
1493 throw t;
1497 // This ensures that symbolic superclass and superinterface references
1498 // are resolved for the indicated class. This must be called with the
1499 // class lock held.
1500 void
1501 _Jv_Linker::ensure_supers_installed (jclass klass)
1503 resolve_class_ref (klass, &klass->superclass);
1504 // An interface won't have a superclass.
1505 if (klass->superclass)
1506 wait_for_state (klass->superclass, JV_STATE_LOADING);
1508 for (int i = 0; i < klass->interface_count; ++i)
1510 resolve_class_ref (klass, &klass->interfaces[i]);
1511 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1515 // This adds missing `Miranda methods' to a class.
1516 void
1517 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1519 // Note that at this point, all our supers, and the supers of all
1520 // our superclasses and superinterfaces, will have been installed.
1522 for (int i = 0; i < iface_class->interface_count; ++i)
1524 jclass interface = iface_class->interfaces[i];
1526 for (int j = 0; j < interface->method_count; ++j)
1528 _Jv_Method *meth = &interface->methods[j];
1529 // Don't bother with <clinit>.
1530 if (meth->name->first() == '<')
1531 continue;
1532 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1533 meth->signature);
1534 if (! new_meth)
1536 // We assume that such methods are very unlikely, so we
1537 // just reallocate the method array each time one is
1538 // found. This greatly simplifies the searching --
1539 // otherwise we have to make sure that each such method
1540 // found is really unique among all superinterfaces.
1541 int new_count = base->method_count + 1;
1542 _Jv_Method *new_m
1543 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
1544 * new_count);
1545 memcpy (new_m, base->methods,
1546 sizeof (_Jv_Method) * base->method_count);
1548 // Add new method.
1549 new_m[base->method_count] = *meth;
1550 new_m[base->method_count].index = (_Jv_ushort) -1;
1551 new_m[base->method_count].accflags
1552 |= java::lang::reflect::Modifier::INVISIBLE;
1554 base->methods = new_m;
1555 base->method_count = new_count;
1559 wait_for_state (interface, JV_STATE_LOADED);
1560 add_miranda_methods (base, interface);
1564 // This ensures that the class' method table is "complete". This must
1565 // be called with the class lock held.
1566 void
1567 _Jv_Linker::ensure_method_table_complete (jclass klass)
1569 if (klass->vtable != NULL || klass->isInterface())
1570 return;
1572 // We need our superclass to have its own Miranda methods installed.
1573 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1575 // A class might have so-called "Miranda methods". This is a method
1576 // that is declared in an interface and not re-declared in an
1577 // abstract class. Some compilers don't emit declarations for such
1578 // methods in the class; this will give us problems since we expect
1579 // a declaration for any method requiring a vtable entry. We handle
1580 // this here by searching for such methods and constructing new
1581 // internal declarations for them. Note that we do this
1582 // unconditionally, and not just for abstract classes, to correctly
1583 // account for cases where a class is modified to be concrete and
1584 // still incorrectly inherits an abstract method.
1585 int pre_count = klass->method_count;
1586 add_miranda_methods (klass, klass);
1588 // Let the execution engine know that we've added methods.
1589 if (klass->method_count != pre_count)
1590 klass->engine->post_miranda_hook(klass);
1593 // Verify a class. Must be called with class lock held.
1594 void
1595 _Jv_Linker::verify_class (jclass klass)
1597 klass->engine->verify(klass);
1600 // Check the assertions contained in the type assertion table for KLASS.
1601 // This is the equivilent of bytecode verification for native, BC-ABI code.
1602 void
1603 _Jv_Linker::verify_type_assertions (jclass klass)
1605 if (debug_link)
1606 fprintf (stderr, "Evaluating type assertions for %s:\n",
1607 klass->name->chars());
1609 if (klass->assertion_table == NULL)
1610 return;
1612 for (int i = 0;; i++)
1614 int assertion_code = klass->assertion_table[i].assertion_code;
1615 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1616 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1618 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1619 return;
1620 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1622 if (debug_link)
1624 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1625 assertion_code, op1->chars(), op2->chars());
1628 // The operands are class signatures. op1 is the source,
1629 // op2 is the target.
1630 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1631 klass->getClassLoaderInternal());
1632 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1633 klass->getClassLoaderInternal());
1635 // If the class doesn't exist, ignore the assertion. An exception
1636 // will be thrown later if an attempt is made to actually
1637 // instantiate the class.
1638 if (cl1 == NULL || cl2 == NULL)
1639 continue;
1641 if (! _Jv_IsAssignableFromSlow (cl2, cl1))
1643 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1644 s = s->concat (klass->getName());
1645 s = s->concat (JvNewStringUTF (": "));
1646 s = s->concat (cl1->getName());
1647 s = s->concat (JvNewStringUTF (" is not assignable to "));
1648 s = s->concat (cl2->getName());
1649 throw new java::lang::VerifyError (s);
1652 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1654 // TODO: Implement this.
1656 // Unknown assertion codes are ignored, for forwards-compatibility.
1660 void
1661 _Jv_Linker::print_class_loaded (jclass klass)
1663 char *codesource = NULL;
1664 if (klass->protectionDomain != NULL)
1666 java::security::CodeSource *cs
1667 = klass->protectionDomain->getCodeSource();
1668 if (cs != NULL)
1670 jstring css = cs->toString();
1671 int len = JvGetStringUTFLength(css);
1672 codesource = (char *) _Jv_AllocBytes(len + 1);
1673 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1674 codesource[len] = '\0';
1677 if (codesource == NULL)
1678 codesource = "<no code source>";
1680 // We use a somewhat bogus test for the ABI here.
1681 char *abi;
1682 #ifdef INTERPRETER
1683 if (_Jv_IsInterpretedClass (klass))
1684 #else
1685 if (false)
1686 #endif
1687 abi = "bytecode";
1688 else if (klass->state == JV_STATE_PRELOADING)
1689 abi = "BC-compiled";
1690 else
1691 abi = "pre-compiled";
1693 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1694 codesource);
1697 // FIXME: mention invariants and stuff.
1698 void
1699 _Jv_Linker::wait_for_state (jclass klass, int state)
1701 if (klass->state >= state)
1702 return;
1704 JvSynchronize sync (klass);
1706 // This is similar to the strategy for class initialization. If we
1707 // already hold the lock, just leave.
1708 java::lang::Thread *self = java::lang::Thread::currentThread();
1709 while (klass->state <= state
1710 && klass->thread
1711 && klass->thread != self)
1712 klass->wait ();
1714 java::lang::Thread *save = klass->thread;
1715 klass->thread = self;
1717 // Print some debugging info if requested. Interpreted classes are
1718 // handled in defineclass, so we only need to handle the two
1719 // pre-compiled cases here.
1720 if (gcj::verbose_class_flag
1721 && (klass->state == JV_STATE_COMPILED
1722 || klass->state == JV_STATE_PRELOADING)
1723 #ifdef INTERPRETER
1724 && ! _Jv_IsInterpretedClass (klass)
1725 #endif
1727 print_class_loaded (klass);
1731 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
1733 ensure_supers_installed (klass);
1734 klass->set_state(JV_STATE_LOADING);
1737 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
1739 ensure_method_table_complete (klass);
1740 klass->set_state(JV_STATE_LOADED);
1743 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
1745 ensure_fields_laid_out (klass);
1746 make_vtable (klass);
1747 layout_interface_methods (klass);
1748 prepare_constant_time_tables (klass);
1749 klass->set_state(JV_STATE_PREPARED);
1752 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
1754 verify_class (klass);
1756 ensure_class_linked (klass);
1757 link_exception_table (klass);
1758 link_symbol_table (klass);
1759 klass->set_state(JV_STATE_LINKED);
1762 catch (java::lang::Throwable *exc)
1764 klass->thread = save;
1765 klass->set_state(JV_STATE_ERROR);
1766 throw exc;
1769 klass->thread = save;
1771 if (klass->state == JV_STATE_ERROR)
1772 throw new java::lang::LinkageError;