1 // link.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 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
11 /* Author: Kresten Krab Thorup <krab@gnu.org> */
18 #include <java-interp.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/InternalError.h>
38 #include <java/lang/AbstractMethodError.h>
39 #include <java/lang/NoClassDefFoundError.h>
40 #include <java/lang/IncompatibleClassChangeError.h>
41 #include <java/lang/VerifyError.h>
42 #include <java/lang/VMClassLoader.h>
43 #include <java/lang/reflect/Modifier.h>
44 #include <java/security/CodeSource.h>
48 typedef unsigned int uaddr
__attribute__ ((mode (pointer
)));
57 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
59 // This returns the alignment of a type as it would appear in a
60 // structure. This can be different from the alignment of the type
61 // itself. For instance on x86 double is 8-aligned but struct{double}
64 _Jv_Linker::get_alignment_from_class (jclass klass
)
66 if (klass
== JvPrimClass (byte
))
67 return ALIGNOF (jbyte
);
68 else if (klass
== JvPrimClass (short))
69 return ALIGNOF (jshort
);
70 else if (klass
== JvPrimClass (int))
71 return ALIGNOF (jint
);
72 else if (klass
== JvPrimClass (long))
73 return ALIGNOF (jlong
);
74 else if (klass
== JvPrimClass (boolean
))
75 return ALIGNOF (jboolean
);
76 else if (klass
== JvPrimClass (char))
77 return ALIGNOF (jchar
);
78 else if (klass
== JvPrimClass (float))
79 return ALIGNOF (jfloat
);
80 else if (klass
== JvPrimClass (double))
81 return ALIGNOF (jdouble
);
83 return ALIGNOF (jobject
);
87 _Jv_Linker::resolve_field (_Jv_Field
*field
, java::lang::ClassLoader
*loader
)
89 if (! field
->isResolved ())
91 _Jv_Utf8Const
*sig
= (_Jv_Utf8Const
*) field
->type
;
92 jclass type
= _Jv_FindClassFromSignature (sig
->chars(), loader
);
94 throw new java::lang::NoClassDefFoundError(field
->name
->toString());
96 field
->flags
&= ~_Jv_FIELD_UNRESOLVED_FLAG
;
100 // A helper for find_field that knows how to recursively search
101 // superclasses and interfaces.
103 _Jv_Linker::find_field_helper (jclass search
, _Jv_Utf8Const
*name
,
104 _Jv_Utf8Const
*type_name
, jclass type
,
109 // From 5.4.3.2. First search class itself.
110 for (int i
= 0; i
< search
->field_count
; ++i
)
112 _Jv_Field
*field
= &search
->fields
[i
];
113 if (! _Jv_equalUtf8Consts (field
->name
, name
))
116 // Checks for the odd situation where we were able to retrieve the
117 // field's class from signature but the resolution of the field itself
118 // failed which means a different class was resolved.
123 resolve_field (field
, search
->loader
);
125 catch (java::lang::Throwable
*exc
)
127 java::lang::LinkageError
*le
= new java::lang::LinkageError
129 ("field type mismatch with different loaders"));
137 // Note that we compare type names and not types. This is
138 // bizarre, but we do it because we want to find a field
139 // (and terminate the search) if it has the correct
140 // descriptor -- but then later reject it if the class
141 // loader check results in different classes. We can't just
142 // pass in the descriptor and check that way, because when
143 // the field is already resolved there is no easy way to
144 // find its descriptor again.
145 if ((field
->isResolved ()
146 ? _Jv_equalUtf8Classnames (type_name
, field
->type
->name
)
147 : _Jv_equalUtf8Classnames (type_name
,
148 (_Jv_Utf8Const
*) field
->type
)))
155 // Next search direct interfaces.
156 for (int i
= 0; i
< search
->interface_count
; ++i
)
158 _Jv_Field
*result
= find_field_helper (search
->interfaces
[i
], name
,
159 type_name
, type
, declarer
);
164 // Now search superclass.
165 search
= search
->superclass
;
172 _Jv_Linker::has_field_p (jclass search
, _Jv_Utf8Const
*field_name
)
174 for (int i
= 0; i
< search
->field_count
; ++i
)
176 _Jv_Field
*field
= &search
->fields
[i
];
177 if (_Jv_equalUtf8Consts (field
->name
, field_name
))
184 // KLASS is the class that is requesting the field.
185 // OWNER is the class in which the field should be found.
186 // FIELD_TYPE_NAME is the type descriptor for the field.
187 // Fill FOUND_CLASS with the address of the class in which the field
188 // is actually declared.
189 // This function does the class loader type checks, and
190 // also access checks. Returns the field, or throws an
191 // exception on error.
193 _Jv_Linker::find_field (jclass klass
, jclass owner
,
195 _Jv_Utf8Const
*field_name
,
196 _Jv_Utf8Const
*field_type_name
)
198 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
200 // Note: This call will resolve the primitive type names ("Z", "B", ...) to
201 // their Java counterparts ("boolean", "byte", ...) if accessed via
202 // field_type->name later. Using these variants of the type name is in turn
203 // important for the find_field_helper function. However if the class
204 // resolution failed then we can only use the already given type name.
206 = _Jv_FindClassFromSignatureNoException (field_type_name
->chars(),
210 = find_field_helper (owner
, field_name
,
214 field_type
, found_class
);
218 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
219 sb
->append(JvNewStringLatin1("field "));
220 sb
->append(owner
->getName());
221 sb
->append(JvNewStringLatin1("."));
222 sb
->append(_Jv_NewStringUTF(field_name
->chars()));
223 sb
->append(JvNewStringLatin1(" was not found."));
224 throw new java::lang::NoSuchFieldError (sb
->toString());
227 // Accept it when the field's class could not be resolved.
228 if (field_type
== NULL
)
229 // Silently ignore that we were not able to retrieve the type to make it
230 // possible to run code which does not access this field.
233 if (_Jv_CheckAccess (klass
, *found_class
, the_field
->flags
))
235 // Note that the field returned by find_field_helper is always
236 // resolved. There's no point checking class loaders here,
237 // since we already did the work to look up all the types.
238 // FIXME: being lazy here would be nice.
239 if (the_field
->type
!= field_type
)
240 throw new java::lang::LinkageError
242 ("field type mismatch with different loaders"));
246 java::lang::StringBuffer
*sb
247 = new java::lang::StringBuffer ();
248 sb
->append(klass
->getName());
249 sb
->append(JvNewStringLatin1(": "));
250 sb
->append((*found_class
)->getName());
251 sb
->append(JvNewStringLatin1("."));
252 sb
->append(_Jv_NewStringUtf8Const (field_name
));
253 throw new java::lang::IllegalAccessError(sb
->toString());
260 _Jv_Linker::resolve_pool_entry (jclass klass
, int index
, bool lazy
)
262 using namespace java::lang::reflect
;
264 _Jv_Constants
*pool
= &klass
->constants
;
266 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
267 return pool
->data
[index
];
269 switch (pool
->tags
[index
])
271 case JV_CONSTANT_Class
:
273 _Jv_Utf8Const
*name
= pool
->data
[index
].utf8
;
276 if (name
->first() == '[')
277 found
= _Jv_FindClassFromSignatureNoException (name
->chars(),
280 found
= _Jv_FindClassNoException (name
, klass
->loader
);
282 // If the class could not be loaded a phantom class is created. Any
283 // function that deals with such a class but cannot do something useful
284 // with it should just throw a NoClassDefFoundError with the class'
289 found
= _Jv_NewClass(name
, NULL
, NULL
);
290 found
->state
= JV_STATE_PHANTOM
;
291 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
292 pool
->data
[index
].clazz
= found
;
296 throw new java::lang::NoClassDefFoundError (name
->toString());
298 // Check accessibility, but first strip array types as
299 // _Jv_ClassNameSamePackage can't handle arrays.
302 check
&& check
->isArray();
303 check
= check
->getComponentType())
305 if ((found
->accflags
& Modifier::PUBLIC
) == Modifier::PUBLIC
306 || (_Jv_ClassNameSamePackage (check
->name
,
309 pool
->data
[index
].clazz
= found
;
310 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
314 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer ();
315 sb
->append(klass
->getName());
316 sb
->append(JvNewStringLatin1(" can't access class "));
317 sb
->append(found
->getName());
318 throw new java::lang::IllegalAccessError(sb
->toString());
323 case JV_CONSTANT_String
:
326 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
327 pool
->data
[index
].o
= str
;
328 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
332 case JV_CONSTANT_Fieldref
:
334 _Jv_ushort class_index
, name_and_type_index
;
335 _Jv_loadIndexes (&pool
->data
[index
],
337 name_and_type_index
);
338 jclass owner
= (resolve_pool_entry (klass
, class_index
, true)).clazz
;
340 // If a phantom class was resolved our field reference is
341 // unusable because of the missing class.
342 if (owner
->state
== JV_STATE_PHANTOM
)
343 throw new java::lang::NoClassDefFoundError(owner
->getName());
346 _Jv_InitClass (owner
);
348 _Jv_ushort name_index
, type_index
;
349 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
353 _Jv_Utf8Const
*field_name
= pool
->data
[name_index
].utf8
;
354 _Jv_Utf8Const
*field_type_name
= pool
->data
[type_index
].utf8
;
356 jclass found_class
= 0;
357 _Jv_Field
*the_field
= find_field (klass
, owner
,
361 if (owner
!= found_class
)
362 _Jv_InitClass (found_class
);
363 pool
->data
[index
].field
= the_field
;
364 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
368 case JV_CONSTANT_Methodref
:
369 case JV_CONSTANT_InterfaceMethodref
:
371 _Jv_ushort class_index
, name_and_type_index
;
372 _Jv_loadIndexes (&pool
->data
[index
],
374 name_and_type_index
);
375 jclass owner
= (resolve_pool_entry (klass
, class_index
)).clazz
;
378 _Jv_InitClass (owner
);
380 _Jv_ushort name_index
, type_index
;
381 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
385 _Jv_Utf8Const
*method_name
= pool
->data
[name_index
].utf8
;
386 _Jv_Utf8Const
*method_signature
= pool
->data
[type_index
].utf8
;
388 _Jv_Method
*the_method
= 0;
389 jclass found_class
= 0;
391 // We're going to cache a pointer to the _Jv_Method object
392 // when we find it. So, to ensure this doesn't get moved from
393 // beneath us, we first put all the needed Miranda methods
394 // into the target class.
395 wait_for_state (klass
, JV_STATE_LOADED
);
397 // First search the class itself.
398 the_method
= search_method_in_class (owner
, klass
,
399 method_name
, method_signature
);
404 goto end_of_method_search
;
407 // If we are resolving an interface method, search the
408 // interface's superinterfaces (A superinterface is not an
409 // interface's superclass - a superinterface is implemented by
411 if (pool
->tags
[index
] == JV_CONSTANT_InterfaceMethodref
)
416 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
417 * sizeof (jclass
*));
419 get_interfaces (owner
, &ifaces
);
421 for (int i
= 0; i
< ifaces
.count
; i
++)
423 jclass cls
= ifaces
.list
[i
];
424 the_method
= search_method_in_class (cls
, klass
, method_name
,
433 _Jv_Free (ifaces
.list
);
436 goto end_of_method_search
;
439 // Finally, search superclasses.
440 for (jclass cls
= owner
->getSuperclass (); cls
!= 0;
441 cls
= cls
->getSuperclass ())
443 the_method
= search_method_in_class (cls
, klass
, method_name
,
452 end_of_method_search
:
454 // FIXME: if (cls->loader != klass->loader), then we
455 // must actually check that the types of arguments
456 // correspond. That is, for each argument type, and
457 // the return type, doing _Jv_FindClassFromSignature
458 // with either loader should produce the same result,
459 // i.e., exactly the same jclass object. JVMS 5.4.3.3
463 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
464 sb
->append(JvNewStringLatin1("method "));
465 sb
->append(owner
->getName());
466 sb
->append(JvNewStringLatin1("."));
467 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
468 sb
->append(JvNewStringLatin1(" with signature "));
469 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
470 sb
->append(JvNewStringLatin1(" was not found."));
471 throw new java::lang::NoSuchMethodError (sb
->toString());
474 int vtable_index
= -1;
475 if (pool
->tags
[index
] != JV_CONSTANT_InterfaceMethodref
)
476 vtable_index
= (jshort
)the_method
->index
;
478 pool
->data
[index
].rmethod
479 = klass
->engine
->resolve_method(the_method
,
481 ((the_method
->accflags
482 & Modifier::STATIC
) != 0),
484 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
488 return pool
->data
[index
];
491 // This function is used to lazily locate superclasses and
492 // superinterfaces. This must be called with the class lock held.
494 _Jv_Linker::resolve_class_ref (jclass klass
, jclass
*classref
)
496 jclass ret
= *classref
;
498 // If superclass looks like a constant pool entry, resolve it now.
499 if (ret
&& (uaddr
) ret
< (uaddr
) klass
->constants
.size
)
501 if (klass
->state
< JV_STATE_LINKED
)
503 _Jv_Utf8Const
*name
= klass
->constants
.data
[(uaddr
) *classref
].utf8
;
504 ret
= _Jv_FindClass (name
, klass
->loader
);
507 throw new java::lang::NoClassDefFoundError (name
->toString());
511 ret
= klass
->constants
.data
[(uaddr
) classref
].clazz
;
516 // Find a method declared in the cls that is referenced from klass and
517 // perform access checks.
519 _Jv_Linker::search_method_in_class (jclass cls
, jclass klass
,
520 _Jv_Utf8Const
*method_name
,
521 _Jv_Utf8Const
*method_signature
)
523 using namespace java::lang::reflect
;
525 for (int i
= 0; i
< cls
->method_count
; i
++)
527 _Jv_Method
*method
= &cls
->methods
[i
];
528 if ( (!_Jv_equalUtf8Consts (method
->name
,
530 || (!_Jv_equalUtf8Consts (method
->signature
,
534 if (_Jv_CheckAccess (klass
, cls
, method
->accflags
))
538 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
539 sb
->append(klass
->getName());
540 sb
->append(JvNewStringLatin1(": "));
541 sb
->append(cls
->getName());
542 sb
->append(JvNewStringLatin1("."));
543 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
544 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
545 throw new java::lang::IllegalAccessError (sb
->toString());
552 #define INITIAL_IOFFSETS_LEN 4
553 #define INITIAL_IFACES_LEN 4
555 static _Jv_IDispatchTable null_idt
= {SHRT_MAX
, 0, {}};
557 // Generate tables for constant-time assignment testing and interface
558 // method lookup. This implements the technique described by Per Bothner
559 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
560 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
562 _Jv_Linker::prepare_constant_time_tables (jclass klass
)
564 if (klass
->isPrimitive () || klass
->isInterface ())
567 // Short-circuit in case we've been called already.
568 if ((klass
->idt
!= NULL
) || klass
->depth
!= 0)
571 // Calculate the class depth and ancestor table. The depth of a class
572 // is how many "extends" it is removed from Object. Thus the depth of
573 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
574 // is 2. Depth is defined for all regular and array classes, but not
575 // interfaces or primitive types.
577 jclass klass0
= klass
;
578 jboolean has_interfaces
= 0;
579 while (klass0
!= &java::lang::Object::class$
)
581 has_interfaces
+= klass0
->interface_count
;
582 klass0
= klass0
->superclass
;
586 // We do class member testing in constant time by using a small table
587 // of all the ancestor classes within each class. The first element is
588 // a pointer to the current class, and the rest are pointers to the
589 // classes ancestors, ordered from the current class down by decreasing
590 // depth. We do not include java.lang.Object in the table of ancestors,
591 // since it is redundant. Note that the classes pointed to by
592 // 'ancestors' will always be reachable by other paths.
594 klass
->ancestors
= (jclass
*) _Jv_AllocBytes (klass
->depth
597 for (int index
= 0; index
< klass
->depth
; index
++)
599 klass
->ancestors
[index
] = klass0
;
600 klass0
= klass0
->superclass
;
603 if ((klass
->accflags
& java::lang::reflect::Modifier::ABSTRACT
) != 0)
606 // Optimization: If class implements no interfaces, use a common
607 // predefined interface table.
610 klass
->idt
= &null_idt
;
616 ifaces
.len
= INITIAL_IFACES_LEN
;
617 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
* sizeof (jclass
*));
619 int itable_size
= get_interfaces (klass
, &ifaces
);
621 if (ifaces
.count
> 0)
623 // The classes pointed to by the itable will always be reachable
625 int idt_bytes
= sizeof (_Jv_IDispatchTable
) + (itable_size
627 klass
->idt
= (_Jv_IDispatchTable
*) _Jv_AllocBytes (idt_bytes
);
628 klass
->idt
->itable_length
= itable_size
;
630 jshort
*itable_offsets
=
631 (jshort
*) _Jv_Malloc (ifaces
.count
* sizeof (jshort
));
633 generate_itable (klass
, &ifaces
, itable_offsets
);
635 jshort cls_iindex
= find_iindex (ifaces
.list
, itable_offsets
,
638 for (int i
= 0; i
< ifaces
.count
; i
++)
640 ifaces
.list
[i
]->ioffsets
[cls_iindex
] = itable_offsets
[i
];
643 klass
->idt
->iindex
= cls_iindex
;
645 _Jv_Free (ifaces
.list
);
646 _Jv_Free (itable_offsets
);
650 klass
->idt
->iindex
= SHRT_MAX
;
654 // Return index of item in list, or -1 if item is not present.
656 _Jv_Linker::indexof (void *item
, void **list
, jshort list_len
)
658 for (int i
=0; i
< list_len
; i
++)
666 // Find all unique interfaces directly or indirectly implemented by klass.
667 // Returns the size of the interface dispatch table (itable) for klass, which
668 // is the number of unique interfaces plus the total number of methods that
669 // those interfaces declare. May extend ifaces if required.
671 _Jv_Linker::get_interfaces (jclass klass
, _Jv_ifaces
*ifaces
)
675 for (int i
= 0; i
< klass
->interface_count
; i
++)
677 jclass iface
= klass
->interfaces
[i
];
679 /* Make sure interface is linked. */
680 wait_for_state(iface
, JV_STATE_LINKED
);
682 if (indexof (iface
, (void **) ifaces
->list
, ifaces
->count
) == -1)
684 if (ifaces
->count
+ 1 >= ifaces
->len
)
686 /* Resize ifaces list */
687 ifaces
->len
= ifaces
->len
* 2;
689 = (jclass
*) _Jv_Realloc (ifaces
->list
,
690 ifaces
->len
* sizeof(jclass
));
692 ifaces
->list
[ifaces
->count
] = iface
;
695 result
+= get_interfaces (klass
->interfaces
[i
], ifaces
);
699 if (klass
->isInterface())
700 result
+= klass
->method_count
+ 1;
701 else if (klass
->superclass
)
702 result
+= get_interfaces (klass
->superclass
, ifaces
);
706 // Fill out itable in klass, resolving method declarations in each ifaces.
707 // itable_offsets is filled out with the position of each iface in itable,
708 // such that itable[itable_offsets[n]] == ifaces.list[n].
710 _Jv_Linker::generate_itable (jclass klass
, _Jv_ifaces
*ifaces
,
711 jshort
*itable_offsets
)
713 void **itable
= klass
->idt
->itable
;
714 jshort itable_pos
= 0;
716 for (int i
= 0; i
< ifaces
->count
; i
++)
718 jclass iface
= ifaces
->list
[i
];
719 itable_offsets
[i
] = itable_pos
;
720 itable_pos
= append_partial_itable (klass
, iface
, itable
, itable_pos
);
722 /* Create ioffsets table for iface */
723 if (iface
->ioffsets
== NULL
)
725 // The first element of ioffsets is its length (itself included).
726 jshort
*ioffsets
= (jshort
*) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
728 ioffsets
[0] = INITIAL_IOFFSETS_LEN
;
729 for (int i
= 1; i
< INITIAL_IOFFSETS_LEN
; i
++)
732 iface
->ioffsets
= ioffsets
;
737 // Format method name for use in error messages.
739 _Jv_GetMethodString (jclass klass
, _Jv_Method
*meth
,
742 using namespace java::lang
;
743 StringBuffer
*buf
= new StringBuffer (klass
->name
->toString());
744 buf
->append (jchar ('.'));
745 buf
->append (meth
->name
->toString());
746 buf
->append ((jchar
) ' ');
747 buf
->append (meth
->signature
->toString());
750 buf
->append(JvNewStringLatin1(" in "));
751 buf
->append(derived
->name
->toString());
753 return buf
->toString();
757 _Jv_ThrowNoSuchMethodError ()
759 throw new java::lang::NoSuchMethodError
;
763 // A function whose invocation is prepared using libffi. It gets called
764 // whenever a static method of a missing class is invoked. The data argument
765 // holds a reference to a String denoting the missing class.
766 // The prepared function call is stored in a class' atable.
768 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif
*,
773 throw new java::lang::NoClassDefFoundError(
774 _Jv_NewStringUtf8Const((_Jv_Utf8Const
*) data
));
777 // A variant of the NoClassDefFoundError throwing method that can
778 // be used without libffi.
780 _Jv_ThrowNoClassDefFoundError()
782 throw new java::lang::NoClassDefFoundError();
786 // Throw a NoSuchFieldError. Called by compiler-generated code when
787 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
788 // otable that refers to the missing field. This index may be used to
789 // print diagnostic information about the field.
791 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
793 throw new java::lang::NoSuchFieldError
;
796 // This is put in empty vtable slots.
798 _Jv_ThrowAbstractMethodError ()
800 throw new java::lang::AbstractMethodError();
803 // Each superinterface of a class (i.e. each interface that the class
804 // directly or indirectly implements) has a corresponding "Partial
805 // Interface Dispatch Table" whose size is (number of methods + 1) words.
806 // The first word is a pointer to the interface (i.e. the java.lang.Class
807 // instance for that interface). The remaining words are pointers to the
808 // actual methods that implement the methods declared in the interface,
809 // in order of declaration.
811 // Append partial interface dispatch table for "iface" to "itable", at
812 // position itable_pos.
813 // Returns the offset at which the next partial ITable should be appended.
815 _Jv_Linker::append_partial_itable (jclass klass
, jclass iface
,
816 void **itable
, jshort pos
)
818 using namespace java::lang::reflect
;
820 itable
[pos
++] = (void *) iface
;
823 for (int j
=0; j
< iface
->method_count
; j
++)
826 for (jclass cl
= klass
; cl
; cl
= cl
->getSuperclass())
828 meth
= _Jv_GetMethodLocal (cl
, iface
->methods
[j
].name
,
829 iface
->methods
[j
].signature
);
835 if (meth
&& (meth
->name
->first() == '<'))
837 // leave a placeholder in the itable for hidden init methods.
842 if ((meth
->accflags
& Modifier::STATIC
) != 0)
843 throw new java::lang::IncompatibleClassChangeError
844 (_Jv_GetMethodString (klass
, meth
));
845 if ((meth
->accflags
& Modifier::PUBLIC
) == 0)
846 throw new java::lang::IllegalAccessError
847 (_Jv_GetMethodString (klass
, meth
));
849 if ((meth
->accflags
& Modifier::ABSTRACT
) != 0)
850 itable
[pos
] = (void *) &_Jv_ThrowAbstractMethodError
;
852 itable
[pos
] = meth
->ncode
;
856 // The method doesn't exist in klass. Binary compatibility rules
857 // permit this, so we delay the error until runtime using a pointer
858 // to a method which throws an exception.
859 itable
[pos
] = (void *) _Jv_ThrowNoSuchMethodError
;
867 static _Jv_Mutex_t iindex_mutex
;
868 static bool iindex_mutex_initialized
= false;
870 // We need to find the correct offset in the Class Interface Dispatch
871 // Table for a given interface. Once we have that, invoking an interface
872 // method just requires combining the Method's index in the interface
873 // (known at compile time) to get the correct method. Doing a type test
874 // (cast or instanceof) is the same problem: Once we have a possible Partial
875 // Interface Dispatch Table, we just compare the first element to see if it
876 // matches the desired interface. So how can we find the correct offset?
877 // Our solution is to keep a vector of candiate offsets in each interface
878 // (ioffsets), and in each class we have an index (idt->iindex) used to
879 // select the correct offset from ioffsets.
881 // Calculate and return iindex for a new class.
882 // ifaces is a vector of num interfaces that the class implements.
883 // offsets[j] is the offset in the interface dispatch table for the
884 // interface corresponding to ifaces[j].
885 // May extend the interface ioffsets if required.
887 _Jv_Linker::find_iindex (jclass
*ifaces
, jshort
*offsets
, jshort num
)
892 // Acquire a global lock to prevent itable corruption in case of multiple
893 // classes that implement an intersecting set of interfaces being linked
894 // simultaneously. We can assume that the mutex will be initialized
896 if (! iindex_mutex_initialized
)
898 _Jv_MutexInit (&iindex_mutex
);
899 iindex_mutex_initialized
= true;
902 _Jv_MutexLock (&iindex_mutex
);
904 for (i
=1;; i
++) /* each potential position in ioffsets */
906 for (j
=0;; j
++) /* each iface */
910 if (i
>= ifaces
[j
]->ioffsets
[0])
912 int ioffset
= ifaces
[j
]->ioffsets
[i
];
913 /* We can potentially share this position with another class. */
914 if (ioffset
>= 0 && ioffset
!= offsets
[j
])
915 break; /* Nope. Try next i. */
919 for (j
= 0; j
< num
; j
++)
921 int len
= ifaces
[j
]->ioffsets
[0];
925 int newlen
= 2 * len
;
929 jshort
*old_ioffsets
= ifaces
[j
]->ioffsets
;
930 jshort
*new_ioffsets
= (jshort
*) _Jv_AllocBytes (newlen
932 memcpy (&new_ioffsets
[1], &old_ioffsets
[1],
933 (len
- 1) * sizeof (jshort
));
934 new_ioffsets
[0] = newlen
;
937 new_ioffsets
[len
++] = -1;
939 ifaces
[j
]->ioffsets
= new_ioffsets
;
941 ifaces
[j
]->ioffsets
[i
] = offsets
[j
];
944 _Jv_MutexUnlock (&iindex_mutex
);
950 // We use a structure of this type to store the closure that
951 // represents a missing method.
952 struct method_closure
954 // This field must come first, since the address of this field will
955 // be the same as the address of the overall structure. This is due
956 // to disabling interior pointers in the GC.
959 ffi_type
*arg_types
[1];
963 _Jv_Linker::create_error_method (_Jv_Utf8Const
*class_name
)
965 method_closure
*closure
966 = (method_closure
*) _Jv_AllocBytes(sizeof (method_closure
));
968 closure
->arg_types
[0] = &ffi_type_void
;
970 // Initializes the cif and the closure. If that worked the closure
971 // is returned and can be used as a function pointer in a class'
973 if ( ffi_prep_cif (&closure
->cif
,
977 closure
->arg_types
) == FFI_OK
978 && ffi_prep_closure (&closure
->closure
,
980 _Jv_ThrowNoClassDefFoundErrorTrampoline
,
981 class_name
) == FFI_OK
)
982 return &closure
->closure
;
985 java::lang::StringBuffer
*buffer
= new java::lang::StringBuffer();
986 buffer
->append(JvNewStringLatin1("Error setting up FFI closure"
987 " for static method of"
988 " missing class: "));
989 buffer
->append (_Jv_NewStringUtf8Const(class_name
));
990 throw new java::lang::InternalError(buffer
->toString());
995 _Jv_Linker::create_error_method (_Jv_Utf8Const
*)
997 // Codepath for platforms which do not support (or want) libffi.
998 // You have to accept that it is impossible to provide the name
999 // of the missing class then.
1000 return (void *) _Jv_ThrowNoClassDefFoundError
;
1002 #endif // USE_LIBFFI
1004 // Functions for indirect dispatch (symbolic virtual binding) support.
1006 // There are three tables, atable otable and itable. atable is an
1007 // array of addresses, and otable is an array of offsets, and these
1008 // are used for static and virtual members respectively. itable is an
1009 // array of pairs {address, index} where each address is a pointer to
1012 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1013 // symbol is a tuple of {classname, member name, signature}.
1015 // Set this to true to enable debugging of indirect dispatch tables/linking.
1016 static bool debug_link
= false;
1018 // link_symbol_table() scans these two arrays and fills in the
1019 // corresponding atable and otable with the addresses of static
1020 // members and the offsets of virtual members.
1022 // The offset (in bytes) for each resolved method or field is placed
1023 // at the corresponding position in the virtual method offset table
1026 // The same otable and atable may be shared by many classes.
1028 // This must be called while holding the class lock.
1031 _Jv_Linker::link_symbol_table (jclass klass
)
1034 _Jv_MethodSymbol sym
;
1035 if (klass
->otable
== NULL
1036 || klass
->otable
->state
!= 0)
1039 klass
->otable
->state
= 1;
1042 fprintf (stderr
, "Fixing up otable in %s:\n", klass
->name
->chars());
1044 (sym
= klass
->otable_syms
[index
]).class_name
!= NULL
;
1047 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1048 _Jv_Method
*meth
= NULL
;
1050 _Jv_Utf8Const
*signature
= sym
.signature
;
1052 if (target_class
== NULL
)
1053 throw new java::lang::NoClassDefFoundError
1054 (_Jv_NewStringUTF (sym
.class_name
->chars()));
1056 // We're looking for a field or a method, and we can tell
1057 // which is needed by looking at the signature.
1058 if (signature
->first() == '(' && signature
->len() >= 2)
1060 // Looks like someone is trying to invoke an interface method
1061 if (target_class
->isInterface())
1063 using namespace java::lang
;
1064 StringBuffer
*sb
= new StringBuffer();
1065 sb
->append(JvNewStringLatin1("found interface "));
1066 sb
->append(target_class
->getName());
1067 sb
->append(JvNewStringLatin1(" when searching for a class"));
1068 throw new VerifyError(sb
->toString());
1071 // If the target class does not have a vtable_method_count yet,
1072 // then we can't tell the offsets for its methods, so we must lay
1074 wait_for_state(target_class
, JV_STATE_PREPARED
);
1076 meth
= _Jv_LookupDeclaredMethod(target_class
, sym
.name
,
1079 // Every class has a throwNoSuchMethodErrorIndex method that
1080 // it inherits from java.lang.Object. Find its vtable
1082 static int throwNoSuchMethodErrorIndex
;
1083 if (throwNoSuchMethodErrorIndex
== 0)
1086 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1087 strlen ("throwNoSuchMethodError"));
1089 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$
,
1090 name
, gcj::void_signature
);
1091 throwNoSuchMethodErrorIndex
1092 = _Jv_VTable::idx_to_offset (meth
->index
);
1095 // If we don't find a nonstatic method, insert the
1096 // vtable index of Object.throwNoSuchMethodError().
1097 // This defers the missing method error until an attempt
1098 // is made to execute it.
1103 offset
= _Jv_VTable::idx_to_offset (meth
->index
);
1105 offset
= throwNoSuchMethodErrorIndex
;
1108 JvFail ("Bad method index");
1109 JvAssert (meth
->index
< target_class
->vtable_method_count
);
1111 klass
->otable
->offsets
[index
] = offset
;
1115 fprintf (stderr
, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1117 (int)klass
->otable
->offsets
[index
],
1118 (const char*)target_class
->name
->chars(),
1120 (const char*)sym
.name
->chars(),
1121 (const char*)signature
->chars());
1127 wait_for_state(target_class
, JV_STATE_PREPARED
);
1129 _Jv_Field
*the_field
= NULL
;
1132 the_field
= find_field (klass
, target_class
, &found_class
,
1133 sym
.name
, sym
.signature
);
1134 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1135 throw new java::lang::IncompatibleClassChangeError
;
1137 klass
->otable
->offsets
[index
] = the_field
->u
.boffset
;
1139 catch (java::lang::NoSuchFieldError
*err
)
1141 klass
->otable
->offsets
[index
] = 0;
1147 if (klass
->atable
== NULL
|| klass
->atable
->state
!= 0)
1150 klass
->atable
->state
= 1;
1153 (sym
= klass
->atable_syms
[index
]).class_name
!= NULL
;
1156 jclass target_class
=
1157 _Jv_FindClassNoException (sym
.class_name
, klass
->loader
);
1159 _Jv_Method
*meth
= NULL
;
1160 _Jv_Utf8Const
*signature
= sym
.signature
;
1162 // ??? Setting this pointer to null will at least get us a
1163 // NullPointerException
1164 klass
->atable
->addresses
[index
] = NULL
;
1166 // If the target class is missing we prepare a function call
1167 // that throws a NoClassDefFoundError and store the address of
1168 // that newly prepare method in the atable. The user can run
1169 // code in classes where the missing class is part of the
1170 // execution environment as long as it is never referenced.
1171 if (target_class
== NULL
)
1172 klass
->atable
->addresses
[index
] = create_error_method(sym
.class_name
);
1173 // We're looking for a static field or a static method, and we
1174 // can tell which is needed by looking at the signature.
1175 else if (signature
->first() == '(' && signature
->len() >= 2)
1177 // If the target class does not have a vtable_method_count yet,
1178 // then we can't tell the offsets for its methods, so we must lay
1180 wait_for_state (target_class
, JV_STATE_PREPARED
);
1182 // Interface methods cannot have bodies.
1183 if (target_class
->isInterface())
1185 using namespace java::lang
;
1186 StringBuffer
*sb
= new StringBuffer();
1187 sb
->append(JvNewStringLatin1("class "));
1188 sb
->append(target_class
->getName());
1189 sb
->append(JvNewStringLatin1(" is an interface: "
1191 throw new VerifyError(sb
->toString());
1194 meth
= _Jv_LookupDeclaredMethod(target_class
, sym
.name
,
1199 if (meth
->ncode
) // Maybe abstract?
1201 klass
->atable
->addresses
[index
] = meth
->ncode
;
1203 fprintf (stderr
, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1205 &klass
->atable
->addresses
[index
],
1206 (const char*)target_class
->name
->chars(),
1208 (const char*)sym
.name
->chars(),
1209 (const char*)signature
->chars());
1213 klass
->atable
->addresses
[index
]
1214 = create_error_method(sym
.class_name
);
1219 // Try fields only if the target class exists.
1220 if (target_class
!= NULL
)
1222 wait_for_state(target_class
, JV_STATE_PREPARED
);
1224 _Jv_Field
*the_field
= find_field (klass
, target_class
, &found_class
,
1225 sym
.name
, sym
.signature
);
1226 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1227 klass
->atable
->addresses
[index
] = the_field
->u
.addr
;
1229 throw new java::lang::IncompatibleClassChangeError
;
1234 if (klass
->itable
== NULL
1235 || klass
->itable
->state
!= 0)
1238 klass
->itable
->state
= 1;
1241 (sym
= klass
->itable_syms
[index
]).class_name
!= NULL
;
1244 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1245 _Jv_Utf8Const
*signature
= sym
.signature
;
1250 wait_for_state(target_class
, JV_STATE_LOADED
);
1251 bool found
= _Jv_getInterfaceMethod (target_class
, cls
, i
,
1252 sym
.name
, sym
.signature
);
1256 klass
->itable
->addresses
[index
* 2] = cls
;
1257 klass
->itable
->addresses
[index
* 2 + 1] = (void *)(unsigned long) i
;
1260 fprintf (stderr
, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1262 klass
->itable
->addresses
[index
* 2],
1263 (const char*)cls
->name
->chars(),
1265 (const char*)sym
.name
->chars(),
1266 (const char*)signature
->chars());
1267 fprintf (stderr
, " [%d] = offset %d\n",
1269 (int)(unsigned long)klass
->itable
->addresses
[index
* 2 + 1]);
1274 throw new java::lang::IncompatibleClassChangeError
;
1279 // For each catch_record in the list of caught classes, fill in the
1282 _Jv_Linker::link_exception_table (jclass self
)
1284 struct _Jv_CatchClass
*catch_record
= self
->catch_classes
;
1285 if (!catch_record
|| catch_record
->classname
)
1288 while (catch_record
->classname
)
1293 = _Jv_FindClass (catch_record
->classname
,
1294 self
->getClassLoaderInternal ());
1295 *catch_record
->address
= target_class
;
1297 catch (::java::lang::Throwable
*t
)
1299 // FIXME: We need to do something better here.
1300 *catch_record
->address
= 0;
1304 self
->catch_classes
->classname
= (_Jv_Utf8Const
*)-1;
1307 // Set itable method indexes for members of interface IFACE.
1309 _Jv_Linker::layout_interface_methods (jclass iface
)
1311 if (! iface
->isInterface())
1314 // itable indexes start at 1.
1315 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1316 // itable so they are also assigned an index here.
1317 for (int i
= 0; i
< iface
->method_count
; i
++)
1318 iface
->methods
[i
].index
= i
+ 1;
1321 // Prepare virtual method declarations in KLASS, and any superclasses
1322 // as required, by determining their vtable index, setting
1323 // method->index, and finally setting the class's vtable_method_count.
1324 // Must be called with the lock for KLASS held.
1326 _Jv_Linker::layout_vtable_methods (jclass klass
)
1328 if (klass
->vtable
!= NULL
|| klass
->isInterface()
1329 || klass
->vtable_method_count
!= -1)
1332 jclass superclass
= klass
->getSuperclass();
1334 if (superclass
!= NULL
&& superclass
->vtable_method_count
== -1)
1336 JvSynchronize
sync (superclass
);
1337 layout_vtable_methods (superclass
);
1340 int index
= (superclass
== NULL
? 0 : superclass
->vtable_method_count
);
1342 for (int i
= 0; i
< klass
->method_count
; ++i
)
1344 _Jv_Method
*meth
= &klass
->methods
[i
];
1345 _Jv_Method
*super_meth
= NULL
;
1347 if (! _Jv_isVirtualMethod (meth
))
1350 if (superclass
!= NULL
)
1353 super_meth
= _Jv_LookupDeclaredMethod (superclass
, meth
->name
,
1354 meth
->signature
, &declarer
);
1355 // See if this method actually overrides the other method
1359 if (! _Jv_isVirtualMethod (super_meth
)
1360 || ! _Jv_CheckAccess (klass
, declarer
,
1361 super_meth
->accflags
))
1363 else if ((super_meth
->accflags
1364 & java::lang::reflect::Modifier::FINAL
) != 0)
1366 using namespace java::lang
;
1367 StringBuffer
*sb
= new StringBuffer();
1368 sb
->append(JvNewStringLatin1("method "));
1369 sb
->append(_Jv_GetMethodString(klass
, meth
));
1370 sb
->append(JvNewStringLatin1(" overrides final method "));
1371 sb
->append(_Jv_GetMethodString(declarer
, super_meth
));
1372 throw new VerifyError(sb
->toString());
1378 meth
->index
= super_meth
->index
;
1380 meth
->index
= index
++;
1383 klass
->vtable_method_count
= index
;
1386 // Set entries in VTABLE for virtual methods declared in KLASS.
1388 _Jv_Linker::set_vtable_entries (jclass klass
, _Jv_VTable
*vtable
)
1390 for (int i
= klass
->method_count
- 1; i
>= 0; i
--)
1392 using namespace java::lang::reflect
;
1394 _Jv_Method
*meth
= &klass
->methods
[i
];
1395 if (meth
->index
== (_Jv_ushort
) -1)
1397 if ((meth
->accflags
& Modifier::ABSTRACT
))
1398 // FIXME: it might be nice to have a libffi trampoline here,
1399 // so we could pass in the method name and other information.
1400 vtable
->set_method(meth
->index
,
1401 (void *) &_Jv_ThrowAbstractMethodError
);
1403 vtable
->set_method(meth
->index
, meth
->ncode
);
1407 // Allocate and lay out the virtual method table for KLASS. This will
1408 // also cause vtables to be generated for any non-abstract
1409 // superclasses, and virtual method layout to occur for any abstract
1410 // superclasses. Must be called with monitor lock for KLASS held.
1412 _Jv_Linker::make_vtable (jclass klass
)
1414 using namespace java::lang::reflect
;
1416 // If the vtable exists, or for interface classes, do nothing. All
1417 // other classes, including abstract classes, need a vtable.
1418 if (klass
->vtable
!= NULL
|| klass
->isInterface())
1421 // Ensure all the `ncode' entries are set.
1422 klass
->engine
->create_ncode(klass
);
1424 // Class must be laid out before we can create a vtable.
1425 if (klass
->vtable_method_count
== -1)
1426 layout_vtable_methods (klass
);
1428 // Allocate the new vtable.
1429 _Jv_VTable
*vtable
= _Jv_VTable::new_vtable (klass
->vtable_method_count
);
1430 klass
->vtable
= vtable
;
1432 // Copy the vtable of the closest superclass.
1433 jclass superclass
= klass
->superclass
;
1435 JvSynchronize
sync (superclass
);
1436 make_vtable (superclass
);
1438 for (int i
= 0; i
< superclass
->vtable_method_count
; ++i
)
1439 vtable
->set_method (i
, superclass
->vtable
->get_method (i
));
1441 // Set the class pointer and GC descriptor.
1442 vtable
->clas
= klass
;
1443 vtable
->gc_descr
= _Jv_BuildGCDescr (klass
);
1445 // For each virtual declared in klass, set new vtable entry or
1446 // override an old one.
1447 set_vtable_entries (klass
, vtable
);
1449 // Note that we don't check for abstract methods here. We used to,
1450 // but there is a JVMS clarification that indicates that a check
1451 // here would be too eager. And, a simple test case confirms this.
1454 // Lay out the class, allocating space for static fields and computing
1455 // offsets of instance fields. The class lock must be held by the
1458 _Jv_Linker::ensure_fields_laid_out (jclass klass
)
1460 if (klass
->size_in_bytes
!= -1)
1463 // Compute the alignment for this type by searching through the
1464 // superclasses and finding the maximum required alignment. We
1465 // could consider caching this in the Class.
1466 int max_align
= __alignof__ (java::lang::Object
);
1467 jclass super
= klass
->getSuperclass();
1468 while (super
!= NULL
)
1470 // Ensure that our super has its super installed before
1472 wait_for_state(super
, JV_STATE_LOADING
);
1473 ensure_fields_laid_out(super
);
1474 int num
= JvNumInstanceFields (super
);
1475 _Jv_Field
*field
= JvGetFirstInstanceField (super
);
1478 int field_align
= get_alignment_from_class (field
->type
);
1479 if (field_align
> max_align
)
1480 max_align
= field_align
;
1484 super
= super
->getSuperclass();
1488 // This is the size of the 'static' non-reference fields.
1489 int non_reference_size
= 0;
1490 // This is the size of the 'static' reference fields. We count
1491 // these separately to make it simpler for the GC to scan them.
1492 int reference_size
= 0;
1494 // Although java.lang.Object is never interpreted, an interface can
1495 // have a null superclass. Note that we have to lay out an
1496 // interface because it might have static fields.
1497 if (klass
->superclass
)
1498 instance_size
= klass
->superclass
->size();
1500 instance_size
= java::lang::Object::class$
.size();
1502 for (int i
= 0; i
< klass
->field_count
; i
++)
1507 _Jv_Field
*field
= &klass
->fields
[i
];
1509 if (! field
->isRef ())
1511 // It is safe to resolve the field here, since it's a
1512 // primitive class, which does not cause loading to happen.
1513 resolve_field (field
, klass
->loader
);
1515 field_size
= field
->type
->size ();
1516 field_align
= get_alignment_from_class (field
->type
);
1520 field_size
= sizeof (jobject
);
1521 field_align
= __alignof__ (jobject
);
1524 field
->bsize
= field_size
;
1526 if ((field
->flags
& java::lang::reflect::Modifier::STATIC
))
1528 if (field
->u
.addr
== NULL
)
1530 // This computes an offset into a region we'll allocate
1531 // shortly, and then adds this offset to the start
1535 reference_size
= ROUND (reference_size
, field_align
);
1536 field
->u
.boffset
= reference_size
;
1537 reference_size
+= field_size
;
1541 non_reference_size
= ROUND (non_reference_size
, field_align
);
1542 field
->u
.boffset
= non_reference_size
;
1543 non_reference_size
+= field_size
;
1549 instance_size
= ROUND (instance_size
, field_align
);
1550 field
->u
.boffset
= instance_size
;
1551 instance_size
+= field_size
;
1552 if (field_align
> max_align
)
1553 max_align
= field_align
;
1557 if (reference_size
!= 0 || non_reference_size
!= 0)
1558 klass
->engine
->allocate_static_fields (klass
, reference_size
,
1559 non_reference_size
);
1561 // Set the instance size for the class. Note that first we round it
1562 // to the alignment required for this object; this keeps us in sync
1563 // with our current ABI.
1564 instance_size
= ROUND (instance_size
, max_align
);
1565 klass
->size_in_bytes
= instance_size
;
1568 // This takes the class to state JV_STATE_LINKED. The class lock must
1569 // be held when calling this.
1571 _Jv_Linker::ensure_class_linked (jclass klass
)
1573 if (klass
->state
>= JV_STATE_LINKED
)
1576 int state
= klass
->state
;
1579 // Short-circuit, so that mutually dependent classes are ok.
1580 klass
->state
= JV_STATE_LINKED
;
1582 _Jv_Constants
*pool
= &klass
->constants
;
1584 // Compiled classes require that their class constants be
1585 // resolved here. However, interpreted classes need their
1586 // constants to be resolved lazily. If we resolve an
1587 // interpreted class' constants eagerly, we can end up with
1588 // spurious IllegalAccessErrors when the constant pool contains
1589 // a reference to a class we can't access. This can validly
1590 // occur in an obscure case involving the InnerClasses
1592 if (! _Jv_IsInterpretedClass (klass
))
1594 // Resolve class constants first, since other constant pool
1595 // entries may rely on these.
1596 for (int index
= 1; index
< pool
->size
; ++index
)
1598 if (pool
->tags
[index
] == JV_CONSTANT_Class
)
1599 // Lazily resolve the entries.
1600 resolve_pool_entry (klass
, index
, true);
1604 #if 0 // Should be redundant now
1605 // If superclass looks like a constant pool entry,
1607 if ((uaddr
) klass
->superclass
< (uaddr
) pool
->size
)
1608 klass
->superclass
= pool
->data
[(uaddr
) klass
->superclass
].clazz
;
1610 // Likewise for interfaces.
1611 for (int i
= 0; i
< klass
->interface_count
; i
++)
1613 if ((uaddr
) klass
->interfaces
[i
] < (uaddr
) pool
->size
)
1614 klass
->interfaces
[i
]
1615 = pool
->data
[(uaddr
) klass
->interfaces
[i
]].clazz
;
1619 // Resolve the remaining constant pool entries.
1620 for (int index
= 1; index
< pool
->size
; ++index
)
1622 if (pool
->tags
[index
] == JV_CONSTANT_String
)
1626 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
1627 pool
->data
[index
].o
= str
;
1628 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
1632 if (klass
->engine
->need_resolve_string_fields())
1634 jfieldID f
= JvGetFirstStaticField (klass
);
1635 for (int n
= JvNumStaticFields (klass
); n
> 0; --n
)
1637 int mod
= f
->getModifiers ();
1638 // If we have a static String field with a non-null initial
1639 // value, we know it points to a Utf8Const.
1641 // Finds out whether we have to initialize a String without the
1642 // need to resolve the field.
1643 if ((f
->isResolved()
1644 ? (f
->type
== &java::lang::String::class$
)
1645 : _Jv_equalUtf8Classnames((_Jv_Utf8Const
*) f
->type
,
1646 java::lang::String::class$
.name
))
1647 && (mod
& java::lang::reflect::Modifier::STATIC
) != 0)
1649 jstring
*strp
= (jstring
*) f
->u
.addr
;
1651 *strp
= _Jv_NewStringUtf8Const ((_Jv_Utf8Const
*) *strp
);
1653 f
= f
->getNextField ();
1657 klass
->notifyAll ();
1659 _Jv_PushClass (klass
);
1661 catch (java::lang::Throwable
*t
)
1663 klass
->state
= state
;
1668 // This ensures that symbolic superclass and superinterface references
1669 // are resolved for the indicated class. This must be called with the
1672 _Jv_Linker::ensure_supers_installed (jclass klass
)
1674 resolve_class_ref (klass
, &klass
->superclass
);
1675 // An interface won't have a superclass.
1676 if (klass
->superclass
)
1677 wait_for_state (klass
->superclass
, JV_STATE_LOADING
);
1679 for (int i
= 0; i
< klass
->interface_count
; ++i
)
1681 resolve_class_ref (klass
, &klass
->interfaces
[i
]);
1682 wait_for_state (klass
->interfaces
[i
], JV_STATE_LOADING
);
1686 // This adds missing `Miranda methods' to a class.
1688 _Jv_Linker::add_miranda_methods (jclass base
, jclass iface_class
)
1690 // Note that at this point, all our supers, and the supers of all
1691 // our superclasses and superinterfaces, will have been installed.
1693 for (int i
= 0; i
< iface_class
->interface_count
; ++i
)
1695 jclass interface
= iface_class
->interfaces
[i
];
1697 for (int j
= 0; j
< interface
->method_count
; ++j
)
1699 _Jv_Method
*meth
= &interface
->methods
[j
];
1700 // Don't bother with <clinit>.
1701 if (meth
->name
->first() == '<')
1703 _Jv_Method
*new_meth
= _Jv_LookupDeclaredMethod (base
, meth
->name
,
1707 // We assume that such methods are very unlikely, so we
1708 // just reallocate the method array each time one is
1709 // found. This greatly simplifies the searching --
1710 // otherwise we have to make sure that each such method
1711 // found is really unique among all superinterfaces.
1712 int new_count
= base
->method_count
+ 1;
1714 = (_Jv_Method
*) _Jv_AllocRawObj (sizeof (_Jv_Method
)
1716 memcpy (new_m
, base
->methods
,
1717 sizeof (_Jv_Method
) * base
->method_count
);
1720 new_m
[base
->method_count
] = *meth
;
1721 new_m
[base
->method_count
].index
= (_Jv_ushort
) -1;
1722 new_m
[base
->method_count
].accflags
1723 |= java::lang::reflect::Modifier::INVISIBLE
;
1725 base
->methods
= new_m
;
1726 base
->method_count
= new_count
;
1730 wait_for_state (interface
, JV_STATE_LOADED
);
1731 add_miranda_methods (base
, interface
);
1735 // This ensures that the class' method table is "complete". This must
1736 // be called with the class lock held.
1738 _Jv_Linker::ensure_method_table_complete (jclass klass
)
1740 if (klass
->vtable
!= NULL
)
1743 // We need our superclass to have its own Miranda methods installed.
1744 if (! klass
->isInterface())
1745 wait_for_state (klass
->getSuperclass (), JV_STATE_LOADED
);
1747 // A class might have so-called "Miranda methods". This is a method
1748 // that is declared in an interface and not re-declared in an
1749 // abstract class. Some compilers don't emit declarations for such
1750 // methods in the class; this will give us problems since we expect
1751 // a declaration for any method requiring a vtable entry. We handle
1752 // this here by searching for such methods and constructing new
1753 // internal declarations for them. Note that we do this
1754 // unconditionally, and not just for abstract classes, to correctly
1755 // account for cases where a class is modified to be concrete and
1756 // still incorrectly inherits an abstract method.
1757 int pre_count
= klass
->method_count
;
1758 add_miranda_methods (klass
, klass
);
1760 // Let the execution engine know that we've added methods.
1761 if (klass
->method_count
!= pre_count
)
1762 klass
->engine
->post_miranda_hook(klass
);
1765 // Verify a class. Must be called with class lock held.
1767 _Jv_Linker::verify_class (jclass klass
)
1769 klass
->engine
->verify(klass
);
1772 // Check the assertions contained in the type assertion table for KLASS.
1773 // This is the equivilent of bytecode verification for native, BC-ABI code.
1775 _Jv_Linker::verify_type_assertions (jclass klass
)
1778 fprintf (stderr
, "Evaluating type assertions for %s:\n",
1779 klass
->name
->chars());
1781 if (klass
->assertion_table
== NULL
)
1784 for (int i
= 0;; i
++)
1786 int assertion_code
= klass
->assertion_table
[i
].assertion_code
;
1787 _Jv_Utf8Const
*op1
= klass
->assertion_table
[i
].op1
;
1788 _Jv_Utf8Const
*op2
= klass
->assertion_table
[i
].op2
;
1790 if (assertion_code
== JV_ASSERT_END_OF_TABLE
)
1792 else if (assertion_code
== JV_ASSERT_TYPES_COMPATIBLE
)
1796 fprintf (stderr
, " code=%i, operand A=%s B=%s\n",
1797 assertion_code
, op1
->chars(), op2
->chars());
1800 // The operands are class signatures. op1 is the source,
1801 // op2 is the target.
1802 jclass cl1
= _Jv_FindClassFromSignature (op1
->chars(),
1803 klass
->getClassLoaderInternal());
1804 jclass cl2
= _Jv_FindClassFromSignature (op2
->chars(),
1805 klass
->getClassLoaderInternal());
1807 // If the class doesn't exist, ignore the assertion. An exception
1808 // will be thrown later if an attempt is made to actually
1809 // instantiate the class.
1810 if (cl1
== NULL
|| cl2
== NULL
)
1813 if (! _Jv_IsAssignableFromSlow (cl1
, cl2
))
1815 jstring s
= JvNewStringUTF ("Incompatible types: In class ");
1816 s
= s
->concat (klass
->getName());
1817 s
= s
->concat (JvNewStringUTF (": "));
1818 s
= s
->concat (cl1
->getName());
1819 s
= s
->concat (JvNewStringUTF (" is not assignable to "));
1820 s
= s
->concat (cl2
->getName());
1821 throw new java::lang::VerifyError (s
);
1824 else if (assertion_code
== JV_ASSERT_IS_INSTANTIABLE
)
1826 // TODO: Implement this.
1828 // Unknown assertion codes are ignored, for forwards-compatibility.
1833 _Jv_Linker::print_class_loaded (jclass klass
)
1835 char *codesource
= NULL
;
1836 if (klass
->protectionDomain
!= NULL
)
1838 java::security::CodeSource
*cs
1839 = klass
->protectionDomain
->getCodeSource();
1842 jstring css
= cs
->toString();
1843 int len
= JvGetStringUTFLength(css
);
1844 codesource
= (char *) _Jv_AllocBytes(len
+ 1);
1845 JvGetStringUTFRegion(css
, 0, css
->length(), codesource
);
1846 codesource
[len
] = '\0';
1849 if (codesource
== NULL
)
1850 codesource
= (char *) "<no code source>";
1853 if (_Jv_IsInterpretedClass (klass
))
1855 else if (_Jv_IsBinaryCompatibilityABI (klass
))
1856 abi
= "BC-compiled";
1858 abi
= "pre-compiled";
1860 fprintf (stderr
, "[Loaded (%s) %s from %s]\n", abi
, klass
->name
->chars(),
1864 // FIXME: mention invariants and stuff.
1866 _Jv_Linker::wait_for_state (jclass klass
, int state
)
1868 if (klass
->state
>= state
)
1871 JvSynchronize
sync (klass
);
1873 // This is similar to the strategy for class initialization. If we
1874 // already hold the lock, just leave.
1875 java::lang::Thread
*self
= java::lang::Thread::currentThread();
1876 while (klass
->state
<= state
1878 && klass
->thread
!= self
)
1881 java::lang::Thread
*save
= klass
->thread
;
1882 klass
->thread
= self
;
1884 // Print some debugging info if requested. Interpreted classes are
1885 // handled in defineclass, so we only need to handle the two
1886 // pre-compiled cases here.
1887 if (gcj::verbose_class_flag
1888 && (klass
->state
== JV_STATE_COMPILED
1889 || klass
->state
== JV_STATE_PRELOADING
)
1890 && ! _Jv_IsInterpretedClass (klass
))
1891 print_class_loaded (klass
);
1895 if (state
>= JV_STATE_LOADING
&& klass
->state
< JV_STATE_LOADING
)
1897 ensure_supers_installed (klass
);
1898 klass
->set_state(JV_STATE_LOADING
);
1901 if (state
>= JV_STATE_LOADED
&& klass
->state
< JV_STATE_LOADED
)
1903 ensure_method_table_complete (klass
);
1904 klass
->set_state(JV_STATE_LOADED
);
1907 if (state
>= JV_STATE_PREPARED
&& klass
->state
< JV_STATE_PREPARED
)
1909 ensure_fields_laid_out (klass
);
1910 make_vtable (klass
);
1911 layout_interface_methods (klass
);
1912 prepare_constant_time_tables (klass
);
1913 klass
->set_state(JV_STATE_PREPARED
);
1916 if (state
>= JV_STATE_LINKED
&& klass
->state
< JV_STATE_LINKED
)
1918 if (gcj::verifyClasses
)
1919 verify_class (klass
);
1921 ensure_class_linked (klass
);
1922 link_exception_table (klass
);
1923 link_symbol_table (klass
);
1924 klass
->set_state(JV_STATE_LINKED
);
1927 catch (java::lang::Throwable
*exc
)
1929 klass
->thread
= save
;
1930 klass
->set_state(JV_STATE_ERROR
);
1934 klass
->thread
= save
;
1936 if (klass
->state
== JV_STATE_ERROR
)
1937 throw new java::lang::LinkageError
;