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> */
22 #include <java-interp.h>
28 #include <java-cpool.h>
29 #include <execution.h>
30 #include <java/lang/Class.h>
31 #include <java/lang/String.h>
32 #include <java/lang/StringBuffer.h>
33 #include <java/lang/Thread.h>
34 #include <java/lang/InternalError.h>
35 #include <java/lang/VirtualMachineError.h>
36 #include <java/lang/VerifyError.h>
37 #include <java/lang/NoSuchFieldError.h>
38 #include <java/lang/NoSuchMethodError.h>
39 #include <java/lang/ClassFormatError.h>
40 #include <java/lang/IllegalAccessError.h>
41 #include <java/lang/InternalError.h>
42 #include <java/lang/AbstractMethodError.h>
43 #include <java/lang/NoClassDefFoundError.h>
44 #include <java/lang/IncompatibleClassChangeError.h>
45 #include <java/lang/VerifyError.h>
46 #include <java/lang/VMClassLoader.h>
47 #include <java/lang/reflect/Modifier.h>
48 #include <java/security/CodeSource.h>
52 typedef unsigned int uaddr
__attribute__ ((mode (pointer
)));
61 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
63 // This returns the alignment of a type as it would appear in a
64 // structure. This can be different from the alignment of the type
65 // itself. For instance on x86 double is 8-aligned but struct{double}
68 _Jv_Linker::get_alignment_from_class (jclass klass
)
70 if (klass
== JvPrimClass (byte
))
71 return ALIGNOF (jbyte
);
72 else if (klass
== JvPrimClass (short))
73 return ALIGNOF (jshort
);
74 else if (klass
== JvPrimClass (int))
75 return ALIGNOF (jint
);
76 else if (klass
== JvPrimClass (long))
77 return ALIGNOF (jlong
);
78 else if (klass
== JvPrimClass (boolean
))
79 return ALIGNOF (jboolean
);
80 else if (klass
== JvPrimClass (char))
81 return ALIGNOF (jchar
);
82 else if (klass
== JvPrimClass (float))
83 return ALIGNOF (jfloat
);
84 else if (klass
== JvPrimClass (double))
85 return ALIGNOF (jdouble
);
87 return ALIGNOF (jobject
);
91 _Jv_Linker::resolve_field (_Jv_Field
*field
, java::lang::ClassLoader
*loader
)
93 if (! field
->isResolved ())
95 _Jv_Utf8Const
*sig
= (_Jv_Utf8Const
*) field
->type
;
96 jclass type
= _Jv_FindClassFromSignature (sig
->chars(), loader
);
98 throw new java::lang::NoClassDefFoundError(field
->name
->toString());
100 field
->flags
&= ~_Jv_FIELD_UNRESOLVED_FLAG
;
104 // A helper for find_field that knows how to recursively search
105 // superclasses and interfaces.
107 _Jv_Linker::find_field_helper (jclass search
, _Jv_Utf8Const
*name
,
108 _Jv_Utf8Const
*type_name
, jclass type
,
113 // From 5.4.3.2. First search class itself.
114 for (int i
= 0; i
< search
->field_count
; ++i
)
116 _Jv_Field
*field
= &search
->fields
[i
];
117 if (! _Jv_equalUtf8Consts (field
->name
, name
))
120 // Checks for the odd situation where we were able to retrieve the
121 // field's class from signature but the resolution of the field itself
122 // failed which means a different class was resolved.
127 resolve_field (field
, search
->loader
);
129 catch (java::lang::Throwable
*exc
)
131 java::lang::LinkageError
*le
= new java::lang::LinkageError
133 ("field type mismatch with different loaders"));
141 // Note that we compare type names and not types. This is
142 // bizarre, but we do it because we want to find a field
143 // (and terminate the search) if it has the correct
144 // descriptor -- but then later reject it if the class
145 // loader check results in different classes. We can't just
146 // pass in the descriptor and check that way, because when
147 // the field is already resolved there is no easy way to
148 // find its descriptor again.
149 if ((field
->isResolved ()
150 ? _Jv_equalUtf8Classnames (type_name
, field
->type
->name
)
151 : _Jv_equalUtf8Classnames (type_name
,
152 (_Jv_Utf8Const
*) field
->type
)))
159 // Next search direct interfaces.
160 for (int i
= 0; i
< search
->interface_count
; ++i
)
162 _Jv_Field
*result
= find_field_helper (search
->interfaces
[i
], name
,
163 type_name
, type
, declarer
);
168 // Now search superclass.
169 search
= search
->superclass
;
176 _Jv_Linker::has_field_p (jclass search
, _Jv_Utf8Const
*field_name
)
178 for (int i
= 0; i
< search
->field_count
; ++i
)
180 _Jv_Field
*field
= &search
->fields
[i
];
181 if (_Jv_equalUtf8Consts (field
->name
, field_name
))
188 // KLASS is the class that is requesting the field.
189 // OWNER is the class in which the field should be found.
190 // FIELD_TYPE_NAME is the type descriptor for the field.
191 // Fill FOUND_CLASS with the address of the class in which the field
192 // is actually declared.
193 // This function does the class loader type checks, and
194 // also access checks. Returns the field, or throws an
195 // exception on error.
197 _Jv_Linker::find_field (jclass klass
, jclass owner
,
199 _Jv_Utf8Const
*field_name
,
200 _Jv_Utf8Const
*field_type_name
)
202 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
204 // Note: This call will resolve the primitive type names ("Z", "B", ...) to
205 // their Java counterparts ("boolean", "byte", ...) if accessed via
206 // field_type->name later. Using these variants of the type name is in turn
207 // important for the find_field_helper function. However if the class
208 // resolution failed then we can only use the already given type name.
210 = _Jv_FindClassFromSignatureNoException (field_type_name
->chars(),
214 = find_field_helper (owner
, field_name
,
218 field_type
, found_class
);
222 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
223 sb
->append(JvNewStringLatin1("field "));
224 sb
->append(owner
->getName());
225 sb
->append(JvNewStringLatin1("."));
226 sb
->append(_Jv_NewStringUTF(field_name
->chars()));
227 sb
->append(JvNewStringLatin1(" was not found."));
228 throw new java::lang::NoSuchFieldError (sb
->toString());
231 // Accept it when the field's class could not be resolved.
232 if (field_type
== NULL
)
233 // Silently ignore that we were not able to retrieve the type to make it
234 // possible to run code which does not access this field.
237 if (_Jv_CheckAccess (klass
, *found_class
, the_field
->flags
))
239 // Note that the field returned by find_field_helper is always
240 // resolved. There's no point checking class loaders here,
241 // since we already did the work to look up all the types.
242 // FIXME: being lazy here would be nice.
243 if (the_field
->type
!= field_type
)
244 throw new java::lang::LinkageError
246 ("field type mismatch with different loaders"));
250 java::lang::StringBuffer
*sb
251 = new java::lang::StringBuffer ();
252 sb
->append(klass
->getName());
253 sb
->append(JvNewStringLatin1(": "));
254 sb
->append((*found_class
)->getName());
255 sb
->append(JvNewStringLatin1("."));
256 sb
->append(_Jv_NewStringUtf8Const (field_name
));
257 throw new java::lang::IllegalAccessError(sb
->toString());
264 _Jv_Linker::resolve_pool_entry (jclass klass
, int index
, bool lazy
)
266 using namespace java::lang::reflect
;
268 _Jv_Constants
*pool
= &klass
->constants
;
270 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
271 return pool
->data
[index
];
273 switch (pool
->tags
[index
])
275 case JV_CONSTANT_Class
:
277 _Jv_Utf8Const
*name
= pool
->data
[index
].utf8
;
280 if (name
->first() == '[')
281 found
= _Jv_FindClassFromSignatureNoException (name
->chars(),
284 found
= _Jv_FindClassNoException (name
, klass
->loader
);
286 // If the class could not be loaded a phantom class is created. Any
287 // function that deals with such a class but cannot do something useful
288 // with it should just throw a NoClassDefFoundError with the class'
293 found
= _Jv_NewClass(name
, NULL
, NULL
);
294 found
->state
= JV_STATE_PHANTOM
;
295 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
296 pool
->data
[index
].clazz
= found
;
300 throw new java::lang::NoClassDefFoundError (name
->toString());
302 // Check accessibility, but first strip array types as
303 // _Jv_ClassNameSamePackage can't handle arrays.
306 check
&& check
->isArray();
307 check
= check
->getComponentType())
309 if ((found
->accflags
& Modifier::PUBLIC
) == Modifier::PUBLIC
310 || (_Jv_ClassNameSamePackage (check
->name
,
313 pool
->data
[index
].clazz
= found
;
314 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
318 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer ();
319 sb
->append(klass
->getName());
320 sb
->append(JvNewStringLatin1(" can't access class "));
321 sb
->append(found
->getName());
322 throw new java::lang::IllegalAccessError(sb
->toString());
327 case JV_CONSTANT_String
:
330 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
331 pool
->data
[index
].o
= str
;
332 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
336 case JV_CONSTANT_Fieldref
:
338 _Jv_ushort class_index
, name_and_type_index
;
339 _Jv_loadIndexes (&pool
->data
[index
],
341 name_and_type_index
);
342 jclass owner
= (resolve_pool_entry (klass
, class_index
, true)).clazz
;
344 // If a phantom class was resolved our field reference is
345 // unusable because of the missing class.
346 if (owner
->state
== JV_STATE_PHANTOM
)
347 throw new java::lang::NoClassDefFoundError(owner
->getName());
350 _Jv_InitClass (owner
);
352 _Jv_ushort name_index
, type_index
;
353 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
357 _Jv_Utf8Const
*field_name
= pool
->data
[name_index
].utf8
;
358 _Jv_Utf8Const
*field_type_name
= pool
->data
[type_index
].utf8
;
360 jclass found_class
= 0;
361 _Jv_Field
*the_field
= find_field (klass
, owner
,
365 if (owner
!= found_class
)
366 _Jv_InitClass (found_class
);
367 pool
->data
[index
].field
= the_field
;
368 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
372 case JV_CONSTANT_Methodref
:
373 case JV_CONSTANT_InterfaceMethodref
:
375 _Jv_ushort class_index
, name_and_type_index
;
376 _Jv_loadIndexes (&pool
->data
[index
],
378 name_and_type_index
);
379 jclass owner
= (resolve_pool_entry (klass
, class_index
)).clazz
;
382 _Jv_InitClass (owner
);
384 _Jv_ushort name_index
, type_index
;
385 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
389 _Jv_Utf8Const
*method_name
= pool
->data
[name_index
].utf8
;
390 _Jv_Utf8Const
*method_signature
= pool
->data
[type_index
].utf8
;
392 _Jv_Method
*the_method
= 0;
393 jclass found_class
= 0;
395 // We're going to cache a pointer to the _Jv_Method object
396 // when we find it. So, to ensure this doesn't get moved from
397 // beneath us, we first put all the needed Miranda methods
398 // into the target class.
399 wait_for_state (klass
, JV_STATE_LOADED
);
401 // First search the class itself.
402 the_method
= search_method_in_class (owner
, klass
,
403 method_name
, method_signature
);
408 goto end_of_method_search
;
411 // If we are resolving an interface method, search the
412 // interface's superinterfaces (A superinterface is not an
413 // interface's superclass - a superinterface is implemented by
415 if (pool
->tags
[index
] == JV_CONSTANT_InterfaceMethodref
)
420 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
421 * sizeof (jclass
*));
423 get_interfaces (owner
, &ifaces
);
425 for (int i
= 0; i
< ifaces
.count
; i
++)
427 jclass cls
= ifaces
.list
[i
];
428 the_method
= search_method_in_class (cls
, klass
, method_name
,
437 _Jv_Free (ifaces
.list
);
440 goto end_of_method_search
;
443 // Finally, search superclasses.
444 for (jclass cls
= owner
->getSuperclass (); cls
!= 0;
445 cls
= cls
->getSuperclass ())
447 the_method
= search_method_in_class (cls
, klass
, method_name
,
456 end_of_method_search
:
458 // FIXME: if (cls->loader != klass->loader), then we
459 // must actually check that the types of arguments
460 // correspond. That is, for each argument type, and
461 // the return type, doing _Jv_FindClassFromSignature
462 // with either loader should produce the same result,
463 // i.e., exactly the same jclass object. JVMS 5.4.3.3
467 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
468 sb
->append(JvNewStringLatin1("method "));
469 sb
->append(owner
->getName());
470 sb
->append(JvNewStringLatin1("."));
471 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
472 sb
->append(JvNewStringLatin1(" with signature "));
473 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
474 sb
->append(JvNewStringLatin1(" was not found."));
475 throw new java::lang::NoSuchMethodError (sb
->toString());
478 int vtable_index
= -1;
479 if (pool
->tags
[index
] != JV_CONSTANT_InterfaceMethodref
)
480 vtable_index
= (jshort
)the_method
->index
;
482 pool
->data
[index
].rmethod
483 = klass
->engine
->resolve_method(the_method
,
485 ((the_method
->accflags
486 & Modifier::STATIC
) != 0),
488 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
492 return pool
->data
[index
];
495 // This function is used to lazily locate superclasses and
496 // superinterfaces. This must be called with the class lock held.
498 _Jv_Linker::resolve_class_ref (jclass klass
, jclass
*classref
)
500 jclass ret
= *classref
;
502 // If superclass looks like a constant pool entry, resolve it now.
503 if (ret
&& (uaddr
) ret
< (uaddr
) klass
->constants
.size
)
505 if (klass
->state
< JV_STATE_LINKED
)
507 _Jv_Utf8Const
*name
= klass
->constants
.data
[(uaddr
) *classref
].utf8
;
508 ret
= _Jv_FindClass (name
, klass
->loader
);
511 throw new java::lang::NoClassDefFoundError (name
->toString());
515 ret
= klass
->constants
.data
[(uaddr
) classref
].clazz
;
520 // Find a method declared in the cls that is referenced from klass and
521 // perform access checks.
523 _Jv_Linker::search_method_in_class (jclass cls
, jclass klass
,
524 _Jv_Utf8Const
*method_name
,
525 _Jv_Utf8Const
*method_signature
)
527 using namespace java::lang::reflect
;
529 for (int i
= 0; i
< cls
->method_count
; i
++)
531 _Jv_Method
*method
= &cls
->methods
[i
];
532 if ( (!_Jv_equalUtf8Consts (method
->name
,
534 || (!_Jv_equalUtf8Consts (method
->signature
,
538 if (_Jv_CheckAccess (klass
, cls
, method
->accflags
))
542 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
543 sb
->append(klass
->getName());
544 sb
->append(JvNewStringLatin1(": "));
545 sb
->append(cls
->getName());
546 sb
->append(JvNewStringLatin1("."));
547 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
548 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
549 throw new java::lang::IllegalAccessError (sb
->toString());
556 #define INITIAL_IOFFSETS_LEN 4
557 #define INITIAL_IFACES_LEN 4
559 static _Jv_IDispatchTable null_idt
= {SHRT_MAX
, 0, {}};
561 // Generate tables for constant-time assignment testing and interface
562 // method lookup. This implements the technique described by Per Bothner
563 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
564 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
566 _Jv_Linker::prepare_constant_time_tables (jclass klass
)
568 if (klass
->isPrimitive () || klass
->isInterface ())
571 // Short-circuit in case we've been called already.
572 if ((klass
->idt
!= NULL
) || klass
->depth
!= 0)
575 // Calculate the class depth and ancestor table. The depth of a class
576 // is how many "extends" it is removed from Object. Thus the depth of
577 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
578 // is 2. Depth is defined for all regular and array classes, but not
579 // interfaces or primitive types.
581 jclass klass0
= klass
;
582 jboolean has_interfaces
= 0;
583 while (klass0
!= &java::lang::Object::class$
)
585 has_interfaces
+= klass0
->interface_count
;
586 klass0
= klass0
->superclass
;
590 // We do class member testing in constant time by using a small table
591 // of all the ancestor classes within each class. The first element is
592 // a pointer to the current class, and the rest are pointers to the
593 // classes ancestors, ordered from the current class down by decreasing
594 // depth. We do not include java.lang.Object in the table of ancestors,
595 // since it is redundant. Note that the classes pointed to by
596 // 'ancestors' will always be reachable by other paths.
598 klass
->ancestors
= (jclass
*) _Jv_AllocBytes (klass
->depth
601 for (int index
= 0; index
< klass
->depth
; index
++)
603 klass
->ancestors
[index
] = klass0
;
604 klass0
= klass0
->superclass
;
607 if ((klass
->accflags
& java::lang::reflect::Modifier::ABSTRACT
) != 0)
610 // Optimization: If class implements no interfaces, use a common
611 // predefined interface table.
614 klass
->idt
= &null_idt
;
620 ifaces
.len
= INITIAL_IFACES_LEN
;
621 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
* sizeof (jclass
*));
623 int itable_size
= get_interfaces (klass
, &ifaces
);
625 if (ifaces
.count
> 0)
627 // The classes pointed to by the itable will always be reachable
629 int idt_bytes
= sizeof (_Jv_IDispatchTable
) + (itable_size
631 klass
->idt
= (_Jv_IDispatchTable
*) _Jv_AllocBytes (idt_bytes
);
632 klass
->idt
->itable_length
= itable_size
;
634 jshort
*itable_offsets
=
635 (jshort
*) _Jv_Malloc (ifaces
.count
* sizeof (jshort
));
637 generate_itable (klass
, &ifaces
, itable_offsets
);
639 jshort cls_iindex
= find_iindex (ifaces
.list
, itable_offsets
,
642 for (int i
= 0; i
< ifaces
.count
; i
++)
644 ifaces
.list
[i
]->ioffsets
[cls_iindex
] = itable_offsets
[i
];
647 klass
->idt
->iindex
= cls_iindex
;
649 _Jv_Free (ifaces
.list
);
650 _Jv_Free (itable_offsets
);
654 klass
->idt
->iindex
= SHRT_MAX
;
658 // Return index of item in list, or -1 if item is not present.
660 _Jv_Linker::indexof (void *item
, void **list
, jshort list_len
)
662 for (int i
=0; i
< list_len
; i
++)
670 // Find all unique interfaces directly or indirectly implemented by klass.
671 // Returns the size of the interface dispatch table (itable) for klass, which
672 // is the number of unique interfaces plus the total number of methods that
673 // those interfaces declare. May extend ifaces if required.
675 _Jv_Linker::get_interfaces (jclass klass
, _Jv_ifaces
*ifaces
)
679 for (int i
= 0; i
< klass
->interface_count
; i
++)
681 jclass iface
= klass
->interfaces
[i
];
683 /* Make sure interface is linked. */
684 wait_for_state(iface
, JV_STATE_LINKED
);
686 if (indexof (iface
, (void **) ifaces
->list
, ifaces
->count
) == -1)
688 if (ifaces
->count
+ 1 >= ifaces
->len
)
690 /* Resize ifaces list */
691 ifaces
->len
= ifaces
->len
* 2;
693 = (jclass
*) _Jv_Realloc (ifaces
->list
,
694 ifaces
->len
* sizeof(jclass
));
696 ifaces
->list
[ifaces
->count
] = iface
;
699 result
+= get_interfaces (klass
->interfaces
[i
], ifaces
);
703 if (klass
->isInterface())
704 result
+= klass
->method_count
+ 1;
705 else if (klass
->superclass
)
706 result
+= get_interfaces (klass
->superclass
, ifaces
);
710 // Fill out itable in klass, resolving method declarations in each ifaces.
711 // itable_offsets is filled out with the position of each iface in itable,
712 // such that itable[itable_offsets[n]] == ifaces.list[n].
714 _Jv_Linker::generate_itable (jclass klass
, _Jv_ifaces
*ifaces
,
715 jshort
*itable_offsets
)
717 void **itable
= klass
->idt
->itable
;
718 jshort itable_pos
= 0;
720 for (int i
= 0; i
< ifaces
->count
; i
++)
722 jclass iface
= ifaces
->list
[i
];
723 itable_offsets
[i
] = itable_pos
;
724 itable_pos
= append_partial_itable (klass
, iface
, itable
, itable_pos
);
726 /* Create ioffsets table for iface */
727 if (iface
->ioffsets
== NULL
)
729 // The first element of ioffsets is its length (itself included).
730 jshort
*ioffsets
= (jshort
*) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
732 ioffsets
[0] = INITIAL_IOFFSETS_LEN
;
733 for (int i
= 1; i
< INITIAL_IOFFSETS_LEN
; i
++)
736 iface
->ioffsets
= ioffsets
;
741 // Format method name for use in error messages.
743 _Jv_GetMethodString (jclass klass
, _Jv_Method
*meth
,
746 using namespace java::lang
;
747 StringBuffer
*buf
= new StringBuffer (klass
->name
->toString());
748 buf
->append (jchar ('.'));
749 buf
->append (meth
->name
->toString());
750 buf
->append ((jchar
) ' ');
751 buf
->append (meth
->signature
->toString());
754 buf
->append(JvNewStringLatin1(" in "));
755 buf
->append(derived
->name
->toString());
757 return buf
->toString();
761 _Jv_ThrowNoSuchMethodError ()
763 throw new java::lang::NoSuchMethodError
;
767 // A function whose invocation is prepared using libffi. It gets called
768 // whenever a static method of a missing class is invoked. The data argument
769 // holds a reference to a String denoting the missing class.
770 // The prepared function call is stored in a class' atable.
772 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif
*,
777 throw new java::lang::NoClassDefFoundError(
778 _Jv_NewStringUtf8Const((_Jv_Utf8Const
*) data
));
781 // A variant of the NoClassDefFoundError throwing method that can
782 // be used without libffi.
784 _Jv_ThrowNoClassDefFoundError()
786 throw new java::lang::NoClassDefFoundError();
790 // Throw a NoSuchFieldError. Called by compiler-generated code when
791 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
792 // otable that refers to the missing field. This index may be used to
793 // print diagnostic information about the field.
795 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
797 throw new java::lang::NoSuchFieldError
;
800 // This is put in empty vtable slots.
802 _Jv_ThrowAbstractMethodError ()
804 throw new java::lang::AbstractMethodError();
807 // Each superinterface of a class (i.e. each interface that the class
808 // directly or indirectly implements) has a corresponding "Partial
809 // Interface Dispatch Table" whose size is (number of methods + 1) words.
810 // The first word is a pointer to the interface (i.e. the java.lang.Class
811 // instance for that interface). The remaining words are pointers to the
812 // actual methods that implement the methods declared in the interface,
813 // in order of declaration.
815 // Append partial interface dispatch table for "iface" to "itable", at
816 // position itable_pos.
817 // Returns the offset at which the next partial ITable should be appended.
819 _Jv_Linker::append_partial_itable (jclass klass
, jclass iface
,
820 void **itable
, jshort pos
)
822 using namespace java::lang::reflect
;
824 itable
[pos
++] = (void *) iface
;
827 for (int j
=0; j
< iface
->method_count
; j
++)
830 for (jclass cl
= klass
; cl
; cl
= cl
->getSuperclass())
832 meth
= _Jv_GetMethodLocal (cl
, iface
->methods
[j
].name
,
833 iface
->methods
[j
].signature
);
839 if (meth
&& (meth
->name
->first() == '<'))
841 // leave a placeholder in the itable for hidden init methods.
846 if ((meth
->accflags
& Modifier::STATIC
) != 0)
847 throw new java::lang::IncompatibleClassChangeError
848 (_Jv_GetMethodString (klass
, meth
));
849 if ((meth
->accflags
& Modifier::PUBLIC
) == 0)
850 throw new java::lang::IllegalAccessError
851 (_Jv_GetMethodString (klass
, meth
));
853 if ((meth
->accflags
& Modifier::ABSTRACT
) != 0)
854 itable
[pos
] = (void *) &_Jv_ThrowAbstractMethodError
;
856 itable
[pos
] = meth
->ncode
;
860 // The method doesn't exist in klass. Binary compatibility rules
861 // permit this, so we delay the error until runtime using a pointer
862 // to a method which throws an exception.
863 itable
[pos
] = (void *) _Jv_ThrowNoSuchMethodError
;
871 static _Jv_Mutex_t iindex_mutex
;
872 static bool iindex_mutex_initialized
= false;
874 // We need to find the correct offset in the Class Interface Dispatch
875 // Table for a given interface. Once we have that, invoking an interface
876 // method just requires combining the Method's index in the interface
877 // (known at compile time) to get the correct method. Doing a type test
878 // (cast or instanceof) is the same problem: Once we have a possible Partial
879 // Interface Dispatch Table, we just compare the first element to see if it
880 // matches the desired interface. So how can we find the correct offset?
881 // Our solution is to keep a vector of candiate offsets in each interface
882 // (ioffsets), and in each class we have an index (idt->iindex) used to
883 // select the correct offset from ioffsets.
885 // Calculate and return iindex for a new class.
886 // ifaces is a vector of num interfaces that the class implements.
887 // offsets[j] is the offset in the interface dispatch table for the
888 // interface corresponding to ifaces[j].
889 // May extend the interface ioffsets if required.
891 _Jv_Linker::find_iindex (jclass
*ifaces
, jshort
*offsets
, jshort num
)
896 // Acquire a global lock to prevent itable corruption in case of multiple
897 // classes that implement an intersecting set of interfaces being linked
898 // simultaneously. We can assume that the mutex will be initialized
900 if (! iindex_mutex_initialized
)
902 _Jv_MutexInit (&iindex_mutex
);
903 iindex_mutex_initialized
= true;
906 _Jv_MutexLock (&iindex_mutex
);
908 for (i
=1;; i
++) /* each potential position in ioffsets */
910 for (j
=0;; j
++) /* each iface */
914 if (i
>= ifaces
[j
]->ioffsets
[0])
916 int ioffset
= ifaces
[j
]->ioffsets
[i
];
917 /* We can potentially share this position with another class. */
918 if (ioffset
>= 0 && ioffset
!= offsets
[j
])
919 break; /* Nope. Try next i. */
923 for (j
= 0; j
< num
; j
++)
925 int len
= ifaces
[j
]->ioffsets
[0];
929 int newlen
= 2 * len
;
933 jshort
*old_ioffsets
= ifaces
[j
]->ioffsets
;
934 jshort
*new_ioffsets
= (jshort
*) _Jv_AllocBytes (newlen
936 memcpy (&new_ioffsets
[1], &old_ioffsets
[1],
937 (len
- 1) * sizeof (jshort
));
938 new_ioffsets
[0] = newlen
;
941 new_ioffsets
[len
++] = -1;
943 ifaces
[j
]->ioffsets
= new_ioffsets
;
945 ifaces
[j
]->ioffsets
[i
] = offsets
[j
];
948 _Jv_MutexUnlock (&iindex_mutex
);
954 // We use a structure of this type to store the closure that
955 // represents a missing method.
956 struct method_closure
958 // This field must come first, since the address of this field will
959 // be the same as the address of the overall structure. This is due
960 // to disabling interior pointers in the GC.
963 ffi_type
*arg_types
[1];
967 _Jv_Linker::create_error_method (_Jv_Utf8Const
*class_name
)
969 method_closure
*closure
970 = (method_closure
*) _Jv_AllocBytes(sizeof (method_closure
));
972 closure
->arg_types
[0] = &ffi_type_void
;
974 // Initializes the cif and the closure. If that worked the closure
975 // is returned and can be used as a function pointer in a class'
977 if ( ffi_prep_cif (&closure
->cif
,
981 closure
->arg_types
) == FFI_OK
982 && ffi_prep_closure (&closure
->closure
,
984 _Jv_ThrowNoClassDefFoundErrorTrampoline
,
985 class_name
) == FFI_OK
)
986 return &closure
->closure
;
989 java::lang::StringBuffer
*buffer
= new java::lang::StringBuffer();
990 buffer
->append(JvNewStringLatin1("Error setting up FFI closure"
991 " for static method of"
992 " missing class: "));
993 buffer
->append (_Jv_NewStringUtf8Const(class_name
));
994 throw new java::lang::InternalError(buffer
->toString());
999 _Jv_Linker::create_error_method (_Jv_Utf8Const
*)
1001 // Codepath for platforms which do not support (or want) libffi.
1002 // You have to accept that it is impossible to provide the name
1003 // of the missing class then.
1004 return (void *) _Jv_ThrowNoClassDefFoundError
;
1006 #endif // USE_LIBFFI
1008 // Functions for indirect dispatch (symbolic virtual binding) support.
1010 // There are three tables, atable otable and itable. atable is an
1011 // array of addresses, and otable is an array of offsets, and these
1012 // are used for static and virtual members respectively. itable is an
1013 // array of pairs {address, index} where each address is a pointer to
1016 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1017 // symbol is a tuple of {classname, member name, signature}.
1019 // Set this to true to enable debugging of indirect dispatch tables/linking.
1020 static bool debug_link
= false;
1022 // link_symbol_table() scans these two arrays and fills in the
1023 // corresponding atable and otable with the addresses of static
1024 // members and the offsets of virtual members.
1026 // The offset (in bytes) for each resolved method or field is placed
1027 // at the corresponding position in the virtual method offset table
1030 // The same otable and atable may be shared by many classes.
1032 // This must be called while holding the class lock.
1035 _Jv_Linker::link_symbol_table (jclass klass
)
1038 _Jv_MethodSymbol sym
;
1039 if (klass
->otable
== NULL
1040 || klass
->otable
->state
!= 0)
1043 klass
->otable
->state
= 1;
1046 fprintf (stderr
, "Fixing up otable in %s:\n", klass
->name
->chars());
1048 (sym
= klass
->otable_syms
[index
]).class_name
!= NULL
;
1051 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1052 _Jv_Method
*meth
= NULL
;
1054 _Jv_Utf8Const
*signature
= sym
.signature
;
1056 if (target_class
== NULL
)
1057 throw new java::lang::NoClassDefFoundError
1058 (_Jv_NewStringUTF (sym
.class_name
->chars()));
1060 // We're looking for a field or a method, and we can tell
1061 // which is needed by looking at the signature.
1062 if (signature
->first() == '(' && signature
->len() >= 2)
1064 // Looks like someone is trying to invoke an interface method
1065 if (target_class
->isInterface())
1067 using namespace java::lang
;
1068 StringBuffer
*sb
= new StringBuffer();
1069 sb
->append(JvNewStringLatin1("found interface "));
1070 sb
->append(target_class
->getName());
1071 sb
->append(JvNewStringLatin1(" when searching for a class"));
1072 throw new VerifyError(sb
->toString());
1075 // If the target class does not have a vtable_method_count yet,
1076 // then we can't tell the offsets for its methods, so we must lay
1078 wait_for_state(target_class
, JV_STATE_PREPARED
);
1080 meth
= _Jv_LookupDeclaredMethod(target_class
, sym
.name
,
1083 // Every class has a throwNoSuchMethodErrorIndex method that
1084 // it inherits from java.lang.Object. Find its vtable
1086 static int throwNoSuchMethodErrorIndex
;
1087 if (throwNoSuchMethodErrorIndex
== 0)
1090 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1091 strlen ("throwNoSuchMethodError"));
1093 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$
,
1094 name
, gcj::void_signature
);
1095 throwNoSuchMethodErrorIndex
1096 = _Jv_VTable::idx_to_offset (meth
->index
);
1099 // If we don't find a nonstatic method, insert the
1100 // vtable index of Object.throwNoSuchMethodError().
1101 // This defers the missing method error until an attempt
1102 // is made to execute it.
1107 offset
= _Jv_VTable::idx_to_offset (meth
->index
);
1109 offset
= throwNoSuchMethodErrorIndex
;
1112 JvFail ("Bad method index");
1113 JvAssert (meth
->index
< target_class
->vtable_method_count
);
1115 klass
->otable
->offsets
[index
] = offset
;
1119 fprintf (stderr
, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1121 (int)klass
->otable
->offsets
[index
],
1122 (const char*)target_class
->name
->chars(),
1124 (const char*)sym
.name
->chars(),
1125 (const char*)signature
->chars());
1131 wait_for_state(target_class
, JV_STATE_PREPARED
);
1133 _Jv_Field
*the_field
= NULL
;
1136 the_field
= find_field (klass
, target_class
, &found_class
,
1137 sym
.name
, sym
.signature
);
1138 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1139 throw new java::lang::IncompatibleClassChangeError
;
1141 klass
->otable
->offsets
[index
] = the_field
->u
.boffset
;
1143 catch (java::lang::NoSuchFieldError
*err
)
1145 klass
->otable
->offsets
[index
] = 0;
1151 if (klass
->atable
== NULL
|| klass
->atable
->state
!= 0)
1154 klass
->atable
->state
= 1;
1157 (sym
= klass
->atable_syms
[index
]).class_name
!= NULL
;
1160 jclass target_class
=
1161 _Jv_FindClassNoException (sym
.class_name
, klass
->loader
);
1163 _Jv_Method
*meth
= NULL
;
1164 _Jv_Utf8Const
*signature
= sym
.signature
;
1166 // ??? Setting this pointer to null will at least get us a
1167 // NullPointerException
1168 klass
->atable
->addresses
[index
] = NULL
;
1170 // If the target class is missing we prepare a function call
1171 // that throws a NoClassDefFoundError and store the address of
1172 // that newly prepare method in the atable. The user can run
1173 // code in classes where the missing class is part of the
1174 // execution environment as long as it is never referenced.
1175 if (target_class
== NULL
)
1176 klass
->atable
->addresses
[index
] = create_error_method(sym
.class_name
);
1177 // We're looking for a static field or a static method, and we
1178 // can tell which is needed by looking at the signature.
1179 else if (signature
->first() == '(' && signature
->len() >= 2)
1181 // If the target class does not have a vtable_method_count yet,
1182 // then we can't tell the offsets for its methods, so we must lay
1184 wait_for_state (target_class
, JV_STATE_PREPARED
);
1186 // Interface methods cannot have bodies.
1187 if (target_class
->isInterface())
1189 using namespace java::lang
;
1190 StringBuffer
*sb
= new StringBuffer();
1191 sb
->append(JvNewStringLatin1("class "));
1192 sb
->append(target_class
->getName());
1193 sb
->append(JvNewStringLatin1(" is an interface: "
1195 throw new VerifyError(sb
->toString());
1198 meth
= _Jv_LookupDeclaredMethod(target_class
, sym
.name
,
1203 if (meth
->ncode
) // Maybe abstract?
1205 klass
->atable
->addresses
[index
] = meth
->ncode
;
1207 fprintf (stderr
, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1209 &klass
->atable
->addresses
[index
],
1210 (const char*)target_class
->name
->chars(),
1212 (const char*)sym
.name
->chars(),
1213 (const char*)signature
->chars());
1217 klass
->atable
->addresses
[index
]
1218 = create_error_method(sym
.class_name
);
1223 // Try fields only if the target class exists.
1224 if (target_class
!= NULL
)
1226 wait_for_state(target_class
, JV_STATE_PREPARED
);
1228 _Jv_Field
*the_field
= find_field (klass
, target_class
, &found_class
,
1229 sym
.name
, sym
.signature
);
1230 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1231 klass
->atable
->addresses
[index
] = the_field
->u
.addr
;
1233 throw new java::lang::IncompatibleClassChangeError
;
1238 if (klass
->itable
== NULL
1239 || klass
->itable
->state
!= 0)
1242 klass
->itable
->state
= 1;
1245 (sym
= klass
->itable_syms
[index
]).class_name
!= NULL
;
1248 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1249 _Jv_Utf8Const
*signature
= sym
.signature
;
1254 wait_for_state(target_class
, JV_STATE_LOADED
);
1255 bool found
= _Jv_getInterfaceMethod (target_class
, cls
, i
,
1256 sym
.name
, sym
.signature
);
1260 klass
->itable
->addresses
[index
* 2] = cls
;
1261 klass
->itable
->addresses
[index
* 2 + 1] = (void *)(unsigned long) i
;
1264 fprintf (stderr
, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1266 klass
->itable
->addresses
[index
* 2],
1267 (const char*)cls
->name
->chars(),
1269 (const char*)sym
.name
->chars(),
1270 (const char*)signature
->chars());
1271 fprintf (stderr
, " [%d] = offset %d\n",
1273 (int)(unsigned long)klass
->itable
->addresses
[index
* 2 + 1]);
1278 throw new java::lang::IncompatibleClassChangeError
;
1283 // For each catch_record in the list of caught classes, fill in the
1286 _Jv_Linker::link_exception_table (jclass self
)
1288 struct _Jv_CatchClass
*catch_record
= self
->catch_classes
;
1289 if (!catch_record
|| catch_record
->classname
)
1292 while (catch_record
->classname
)
1297 = _Jv_FindClass (catch_record
->classname
,
1298 self
->getClassLoaderInternal ());
1299 *catch_record
->address
= target_class
;
1301 catch (::java::lang::Throwable
*t
)
1303 // FIXME: We need to do something better here.
1304 *catch_record
->address
= 0;
1308 self
->catch_classes
->classname
= (_Jv_Utf8Const
*)-1;
1311 // Set itable method indexes for members of interface IFACE.
1313 _Jv_Linker::layout_interface_methods (jclass iface
)
1315 if (! iface
->isInterface())
1318 // itable indexes start at 1.
1319 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1320 // itable so they are also assigned an index here.
1321 for (int i
= 0; i
< iface
->method_count
; i
++)
1322 iface
->methods
[i
].index
= i
+ 1;
1325 // Prepare virtual method declarations in KLASS, and any superclasses
1326 // as required, by determining their vtable index, setting
1327 // method->index, and finally setting the class's vtable_method_count.
1328 // Must be called with the lock for KLASS held.
1330 _Jv_Linker::layout_vtable_methods (jclass klass
)
1332 if (klass
->vtable
!= NULL
|| klass
->isInterface()
1333 || klass
->vtable_method_count
!= -1)
1336 jclass superclass
= klass
->getSuperclass();
1338 if (superclass
!= NULL
&& superclass
->vtable_method_count
== -1)
1340 JvSynchronize
sync (superclass
);
1341 layout_vtable_methods (superclass
);
1344 int index
= (superclass
== NULL
? 0 : superclass
->vtable_method_count
);
1346 for (int i
= 0; i
< klass
->method_count
; ++i
)
1348 _Jv_Method
*meth
= &klass
->methods
[i
];
1349 _Jv_Method
*super_meth
= NULL
;
1351 if (! _Jv_isVirtualMethod (meth
))
1354 if (superclass
!= NULL
)
1357 super_meth
= _Jv_LookupDeclaredMethod (superclass
, meth
->name
,
1358 meth
->signature
, &declarer
);
1359 // See if this method actually overrides the other method
1363 if (! _Jv_isVirtualMethod (super_meth
)
1364 || ! _Jv_CheckAccess (klass
, declarer
,
1365 super_meth
->accflags
))
1367 else if ((super_meth
->accflags
1368 & java::lang::reflect::Modifier::FINAL
) != 0)
1370 using namespace java::lang
;
1371 StringBuffer
*sb
= new StringBuffer();
1372 sb
->append(JvNewStringLatin1("method "));
1373 sb
->append(_Jv_GetMethodString(klass
, meth
));
1374 sb
->append(JvNewStringLatin1(" overrides final method "));
1375 sb
->append(_Jv_GetMethodString(declarer
, super_meth
));
1376 throw new VerifyError(sb
->toString());
1382 meth
->index
= super_meth
->index
;
1384 meth
->index
= index
++;
1387 klass
->vtable_method_count
= index
;
1390 // Set entries in VTABLE for virtual methods declared in KLASS.
1392 _Jv_Linker::set_vtable_entries (jclass klass
, _Jv_VTable
*vtable
)
1394 for (int i
= klass
->method_count
- 1; i
>= 0; i
--)
1396 using namespace java::lang::reflect
;
1398 _Jv_Method
*meth
= &klass
->methods
[i
];
1399 if (meth
->index
== (_Jv_ushort
) -1)
1401 if ((meth
->accflags
& Modifier::ABSTRACT
))
1402 // FIXME: it might be nice to have a libffi trampoline here,
1403 // so we could pass in the method name and other information.
1404 vtable
->set_method(meth
->index
,
1405 (void *) &_Jv_ThrowAbstractMethodError
);
1407 vtable
->set_method(meth
->index
, meth
->ncode
);
1411 // Allocate and lay out the virtual method table for KLASS. This will
1412 // also cause vtables to be generated for any non-abstract
1413 // superclasses, and virtual method layout to occur for any abstract
1414 // superclasses. Must be called with monitor lock for KLASS held.
1416 _Jv_Linker::make_vtable (jclass klass
)
1418 using namespace java::lang::reflect
;
1420 // If the vtable exists, or for interface classes, do nothing. All
1421 // other classes, including abstract classes, need a vtable.
1422 if (klass
->vtable
!= NULL
|| klass
->isInterface())
1425 // Ensure all the `ncode' entries are set.
1426 klass
->engine
->create_ncode(klass
);
1428 // Class must be laid out before we can create a vtable.
1429 if (klass
->vtable_method_count
== -1)
1430 layout_vtable_methods (klass
);
1432 // Allocate the new vtable.
1433 _Jv_VTable
*vtable
= _Jv_VTable::new_vtable (klass
->vtable_method_count
);
1434 klass
->vtable
= vtable
;
1436 // Copy the vtable of the closest superclass.
1437 jclass superclass
= klass
->superclass
;
1439 JvSynchronize
sync (superclass
);
1440 make_vtable (superclass
);
1442 for (int i
= 0; i
< superclass
->vtable_method_count
; ++i
)
1443 vtable
->set_method (i
, superclass
->vtable
->get_method (i
));
1445 // Set the class pointer and GC descriptor.
1446 vtable
->clas
= klass
;
1447 vtable
->gc_descr
= _Jv_BuildGCDescr (klass
);
1449 // For each virtual declared in klass, set new vtable entry or
1450 // override an old one.
1451 set_vtable_entries (klass
, vtable
);
1453 // Note that we don't check for abstract methods here. We used to,
1454 // but there is a JVMS clarification that indicates that a check
1455 // here would be too eager. And, a simple test case confirms this.
1458 // Lay out the class, allocating space for static fields and computing
1459 // offsets of instance fields. The class lock must be held by the
1462 _Jv_Linker::ensure_fields_laid_out (jclass klass
)
1464 if (klass
->size_in_bytes
!= -1)
1467 // Compute the alignment for this type by searching through the
1468 // superclasses and finding the maximum required alignment. We
1469 // could consider caching this in the Class.
1470 int max_align
= __alignof__ (java::lang::Object
);
1471 jclass super
= klass
->getSuperclass();
1472 while (super
!= NULL
)
1474 // Ensure that our super has its super installed before
1476 wait_for_state(super
, JV_STATE_LOADING
);
1477 ensure_fields_laid_out(super
);
1478 int num
= JvNumInstanceFields (super
);
1479 _Jv_Field
*field
= JvGetFirstInstanceField (super
);
1482 int field_align
= get_alignment_from_class (field
->type
);
1483 if (field_align
> max_align
)
1484 max_align
= field_align
;
1488 super
= super
->getSuperclass();
1492 // This is the size of the 'static' non-reference fields.
1493 int non_reference_size
= 0;
1494 // This is the size of the 'static' reference fields. We count
1495 // these separately to make it simpler for the GC to scan them.
1496 int reference_size
= 0;
1498 // Although java.lang.Object is never interpreted, an interface can
1499 // have a null superclass. Note that we have to lay out an
1500 // interface because it might have static fields.
1501 if (klass
->superclass
)
1502 instance_size
= klass
->superclass
->size();
1504 instance_size
= java::lang::Object::class$
.size();
1506 for (int i
= 0; i
< klass
->field_count
; i
++)
1511 _Jv_Field
*field
= &klass
->fields
[i
];
1513 if (! field
->isRef ())
1515 // It is safe to resolve the field here, since it's a
1516 // primitive class, which does not cause loading to happen.
1517 resolve_field (field
, klass
->loader
);
1519 field_size
= field
->type
->size ();
1520 field_align
= get_alignment_from_class (field
->type
);
1524 field_size
= sizeof (jobject
);
1525 field_align
= __alignof__ (jobject
);
1528 field
->bsize
= field_size
;
1530 if ((field
->flags
& java::lang::reflect::Modifier::STATIC
))
1532 if (field
->u
.addr
== NULL
)
1534 // This computes an offset into a region we'll allocate
1535 // shortly, and then adds this offset to the start
1539 reference_size
= ROUND (reference_size
, field_align
);
1540 field
->u
.boffset
= reference_size
;
1541 reference_size
+= field_size
;
1545 non_reference_size
= ROUND (non_reference_size
, field_align
);
1546 field
->u
.boffset
= non_reference_size
;
1547 non_reference_size
+= field_size
;
1553 instance_size
= ROUND (instance_size
, field_align
);
1554 field
->u
.boffset
= instance_size
;
1555 instance_size
+= field_size
;
1556 if (field_align
> max_align
)
1557 max_align
= field_align
;
1561 if (reference_size
!= 0 || non_reference_size
!= 0)
1562 klass
->engine
->allocate_static_fields (klass
, reference_size
,
1563 non_reference_size
);
1565 // Set the instance size for the class. Note that first we round it
1566 // to the alignment required for this object; this keeps us in sync
1567 // with our current ABI.
1568 instance_size
= ROUND (instance_size
, max_align
);
1569 klass
->size_in_bytes
= instance_size
;
1572 // This takes the class to state JV_STATE_LINKED. The class lock must
1573 // be held when calling this.
1575 _Jv_Linker::ensure_class_linked (jclass klass
)
1577 if (klass
->state
>= JV_STATE_LINKED
)
1580 int state
= klass
->state
;
1583 // Short-circuit, so that mutually dependent classes are ok.
1584 klass
->state
= JV_STATE_LINKED
;
1586 _Jv_Constants
*pool
= &klass
->constants
;
1588 // Compiled classes require that their class constants be
1589 // resolved here. However, interpreted classes need their
1590 // constants to be resolved lazily. If we resolve an
1591 // interpreted class' constants eagerly, we can end up with
1592 // spurious IllegalAccessErrors when the constant pool contains
1593 // a reference to a class we can't access. This can validly
1594 // occur in an obscure case involving the InnerClasses
1596 if (! _Jv_IsInterpretedClass (klass
))
1598 // Resolve class constants first, since other constant pool
1599 // entries may rely on these.
1600 for (int index
= 1; index
< pool
->size
; ++index
)
1602 if (pool
->tags
[index
] == JV_CONSTANT_Class
)
1603 // Lazily resolve the entries.
1604 resolve_pool_entry (klass
, index
, true);
1608 #if 0 // Should be redundant now
1609 // If superclass looks like a constant pool entry,
1611 if ((uaddr
) klass
->superclass
< (uaddr
) pool
->size
)
1612 klass
->superclass
= pool
->data
[(uaddr
) klass
->superclass
].clazz
;
1614 // Likewise for interfaces.
1615 for (int i
= 0; i
< klass
->interface_count
; i
++)
1617 if ((uaddr
) klass
->interfaces
[i
] < (uaddr
) pool
->size
)
1618 klass
->interfaces
[i
]
1619 = pool
->data
[(uaddr
) klass
->interfaces
[i
]].clazz
;
1623 // Resolve the remaining constant pool entries.
1624 for (int index
= 1; index
< pool
->size
; ++index
)
1626 if (pool
->tags
[index
] == JV_CONSTANT_String
)
1630 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
1631 pool
->data
[index
].o
= str
;
1632 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
1636 if (klass
->engine
->need_resolve_string_fields())
1638 jfieldID f
= JvGetFirstStaticField (klass
);
1639 for (int n
= JvNumStaticFields (klass
); n
> 0; --n
)
1641 int mod
= f
->getModifiers ();
1642 // If we have a static String field with a non-null initial
1643 // value, we know it points to a Utf8Const.
1645 // Finds out whether we have to initialize a String without the
1646 // need to resolve the field.
1647 if ((f
->isResolved()
1648 ? (f
->type
== &java::lang::String::class$
)
1649 : _Jv_equalUtf8Classnames((_Jv_Utf8Const
*) f
->type
,
1650 java::lang::String::class$
.name
))
1651 && (mod
& java::lang::reflect::Modifier::STATIC
) != 0)
1653 jstring
*strp
= (jstring
*) f
->u
.addr
;
1655 *strp
= _Jv_NewStringUtf8Const ((_Jv_Utf8Const
*) *strp
);
1657 f
= f
->getNextField ();
1661 klass
->notifyAll ();
1663 _Jv_PushClass (klass
);
1665 catch (java::lang::Throwable
*t
)
1667 klass
->state
= state
;
1672 // This ensures that symbolic superclass and superinterface references
1673 // are resolved for the indicated class. This must be called with the
1676 _Jv_Linker::ensure_supers_installed (jclass klass
)
1678 resolve_class_ref (klass
, &klass
->superclass
);
1679 // An interface won't have a superclass.
1680 if (klass
->superclass
)
1681 wait_for_state (klass
->superclass
, JV_STATE_LOADING
);
1683 for (int i
= 0; i
< klass
->interface_count
; ++i
)
1685 resolve_class_ref (klass
, &klass
->interfaces
[i
]);
1686 wait_for_state (klass
->interfaces
[i
], JV_STATE_LOADING
);
1690 // This adds missing `Miranda methods' to a class.
1692 _Jv_Linker::add_miranda_methods (jclass base
, jclass iface_class
)
1694 // Note that at this point, all our supers, and the supers of all
1695 // our superclasses and superinterfaces, will have been installed.
1697 for (int i
= 0; i
< iface_class
->interface_count
; ++i
)
1699 jclass interface
= iface_class
->interfaces
[i
];
1701 for (int j
= 0; j
< interface
->method_count
; ++j
)
1703 _Jv_Method
*meth
= &interface
->methods
[j
];
1704 // Don't bother with <clinit>.
1705 if (meth
->name
->first() == '<')
1707 _Jv_Method
*new_meth
= _Jv_LookupDeclaredMethod (base
, meth
->name
,
1711 // We assume that such methods are very unlikely, so we
1712 // just reallocate the method array each time one is
1713 // found. This greatly simplifies the searching --
1714 // otherwise we have to make sure that each such method
1715 // found is really unique among all superinterfaces.
1716 int new_count
= base
->method_count
+ 1;
1718 = (_Jv_Method
*) _Jv_AllocRawObj (sizeof (_Jv_Method
)
1720 memcpy (new_m
, base
->methods
,
1721 sizeof (_Jv_Method
) * base
->method_count
);
1724 new_m
[base
->method_count
] = *meth
;
1725 new_m
[base
->method_count
].index
= (_Jv_ushort
) -1;
1726 new_m
[base
->method_count
].accflags
1727 |= java::lang::reflect::Modifier::INVISIBLE
;
1729 base
->methods
= new_m
;
1730 base
->method_count
= new_count
;
1734 wait_for_state (interface
, JV_STATE_LOADED
);
1735 add_miranda_methods (base
, interface
);
1739 // This ensures that the class' method table is "complete". This must
1740 // be called with the class lock held.
1742 _Jv_Linker::ensure_method_table_complete (jclass klass
)
1744 if (klass
->vtable
!= NULL
)
1747 // We need our superclass to have its own Miranda methods installed.
1748 if (! klass
->isInterface())
1749 wait_for_state (klass
->getSuperclass (), JV_STATE_LOADED
);
1751 // A class might have so-called "Miranda methods". This is a method
1752 // that is declared in an interface and not re-declared in an
1753 // abstract class. Some compilers don't emit declarations for such
1754 // methods in the class; this will give us problems since we expect
1755 // a declaration for any method requiring a vtable entry. We handle
1756 // this here by searching for such methods and constructing new
1757 // internal declarations for them. Note that we do this
1758 // unconditionally, and not just for abstract classes, to correctly
1759 // account for cases where a class is modified to be concrete and
1760 // still incorrectly inherits an abstract method.
1761 int pre_count
= klass
->method_count
;
1762 add_miranda_methods (klass
, klass
);
1764 // Let the execution engine know that we've added methods.
1765 if (klass
->method_count
!= pre_count
)
1766 klass
->engine
->post_miranda_hook(klass
);
1769 // Verify a class. Must be called with class lock held.
1771 _Jv_Linker::verify_class (jclass klass
)
1773 klass
->engine
->verify(klass
);
1776 // Check the assertions contained in the type assertion table for KLASS.
1777 // This is the equivilent of bytecode verification for native, BC-ABI code.
1779 _Jv_Linker::verify_type_assertions (jclass klass
)
1782 fprintf (stderr
, "Evaluating type assertions for %s:\n",
1783 klass
->name
->chars());
1785 if (klass
->assertion_table
== NULL
)
1788 for (int i
= 0;; i
++)
1790 int assertion_code
= klass
->assertion_table
[i
].assertion_code
;
1791 _Jv_Utf8Const
*op1
= klass
->assertion_table
[i
].op1
;
1792 _Jv_Utf8Const
*op2
= klass
->assertion_table
[i
].op2
;
1794 if (assertion_code
== JV_ASSERT_END_OF_TABLE
)
1796 else if (assertion_code
== JV_ASSERT_TYPES_COMPATIBLE
)
1800 fprintf (stderr
, " code=%i, operand A=%s B=%s\n",
1801 assertion_code
, op1
->chars(), op2
->chars());
1804 // The operands are class signatures. op1 is the source,
1805 // op2 is the target.
1806 jclass cl1
= _Jv_FindClassFromSignature (op1
->chars(),
1807 klass
->getClassLoaderInternal());
1808 jclass cl2
= _Jv_FindClassFromSignature (op2
->chars(),
1809 klass
->getClassLoaderInternal());
1811 // If the class doesn't exist, ignore the assertion. An exception
1812 // will be thrown later if an attempt is made to actually
1813 // instantiate the class.
1814 if (cl1
== NULL
|| cl2
== NULL
)
1817 if (! _Jv_IsAssignableFromSlow (cl1
, cl2
))
1819 jstring s
= JvNewStringUTF ("Incompatible types: In class ");
1820 s
= s
->concat (klass
->getName());
1821 s
= s
->concat (JvNewStringUTF (": "));
1822 s
= s
->concat (cl1
->getName());
1823 s
= s
->concat (JvNewStringUTF (" is not assignable to "));
1824 s
= s
->concat (cl2
->getName());
1825 throw new java::lang::VerifyError (s
);
1828 else if (assertion_code
== JV_ASSERT_IS_INSTANTIABLE
)
1830 // TODO: Implement this.
1832 // Unknown assertion codes are ignored, for forwards-compatibility.
1837 _Jv_Linker::print_class_loaded (jclass klass
)
1839 char *codesource
= NULL
;
1840 if (klass
->protectionDomain
!= NULL
)
1842 java::security::CodeSource
*cs
1843 = klass
->protectionDomain
->getCodeSource();
1846 jstring css
= cs
->toString();
1847 int len
= JvGetStringUTFLength(css
);
1848 codesource
= (char *) _Jv_AllocBytes(len
+ 1);
1849 JvGetStringUTFRegion(css
, 0, css
->length(), codesource
);
1850 codesource
[len
] = '\0';
1853 if (codesource
== NULL
)
1854 codesource
= (char *) "<no code source>";
1857 if (_Jv_IsInterpretedClass (klass
))
1859 else if (_Jv_IsBinaryCompatibilityABI (klass
))
1860 abi
= "BC-compiled";
1862 abi
= "pre-compiled";
1864 fprintf (stderr
, "[Loaded (%s) %s from %s]\n", abi
, klass
->name
->chars(),
1868 // FIXME: mention invariants and stuff.
1870 _Jv_Linker::wait_for_state (jclass klass
, int state
)
1872 if (klass
->state
>= state
)
1875 JvSynchronize
sync (klass
);
1877 // This is similar to the strategy for class initialization. If we
1878 // already hold the lock, just leave.
1879 java::lang::Thread
*self
= java::lang::Thread::currentThread();
1880 while (klass
->state
<= state
1882 && klass
->thread
!= self
)
1885 java::lang::Thread
*save
= klass
->thread
;
1886 klass
->thread
= self
;
1888 // Print some debugging info if requested. Interpreted classes are
1889 // handled in defineclass, so we only need to handle the two
1890 // pre-compiled cases here.
1891 if (gcj::verbose_class_flag
1892 && (klass
->state
== JV_STATE_COMPILED
1893 || klass
->state
== JV_STATE_PRELOADING
)
1894 && ! _Jv_IsInterpretedClass (klass
))
1895 print_class_loaded (klass
);
1899 if (state
>= JV_STATE_LOADING
&& klass
->state
< JV_STATE_LOADING
)
1901 ensure_supers_installed (klass
);
1902 klass
->set_state(JV_STATE_LOADING
);
1905 if (state
>= JV_STATE_LOADED
&& klass
->state
< JV_STATE_LOADED
)
1907 ensure_method_table_complete (klass
);
1908 klass
->set_state(JV_STATE_LOADED
);
1911 if (state
>= JV_STATE_PREPARED
&& klass
->state
< JV_STATE_PREPARED
)
1913 ensure_fields_laid_out (klass
);
1914 make_vtable (klass
);
1915 layout_interface_methods (klass
);
1916 prepare_constant_time_tables (klass
);
1917 klass
->set_state(JV_STATE_PREPARED
);
1920 if (state
>= JV_STATE_LINKED
&& klass
->state
< JV_STATE_LINKED
)
1922 if (gcj::verifyClasses
)
1923 verify_class (klass
);
1925 ensure_class_linked (klass
);
1926 link_exception_table (klass
);
1927 link_symbol_table (klass
);
1928 klass
->set_state(JV_STATE_LINKED
);
1931 catch (java::lang::Throwable
*exc
)
1933 klass
->thread
= save
;
1934 klass
->set_state(JV_STATE_ERROR
);
1938 klass
->thread
= save
;
1940 if (klass
->state
== JV_STATE_ERROR
)
1941 throw new java::lang::LinkageError
;