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>
24 // Set GC_DEBUG before including gc.h!
25 #ifdef LIBGCJ_GC_DEBUG
34 #include <java-cpool.h>
35 #include <execution.h>
36 #include <java/lang/Class.h>
37 #include <java/lang/String.h>
38 #include <java/lang/StringBuffer.h>
39 #include <java/lang/Thread.h>
40 #include <java/lang/InternalError.h>
41 #include <java/lang/VirtualMachineError.h>
42 #include <java/lang/VerifyError.h>
43 #include <java/lang/NoSuchFieldError.h>
44 #include <java/lang/NoSuchMethodError.h>
45 #include <java/lang/ClassFormatError.h>
46 #include <java/lang/IllegalAccessError.h>
47 #include <java/lang/InternalError.h>
48 #include <java/lang/AbstractMethodError.h>
49 #include <java/lang/NoClassDefFoundError.h>
50 #include <java/lang/IncompatibleClassChangeError.h>
51 #include <java/lang/VerifyError.h>
52 #include <java/lang/VMClassLoader.h>
53 #include <java/lang/reflect/Modifier.h>
54 #include <java/security/CodeSource.h>
58 typedef unsigned int uaddr
__attribute__ ((mode (pointer
)));
67 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
69 // This returns the alignment of a type as it would appear in a
70 // structure. This can be different from the alignment of the type
71 // itself. For instance on x86 double is 8-aligned but struct{double}
74 _Jv_Linker::get_alignment_from_class (jclass klass
)
76 if (klass
== JvPrimClass (byte
))
77 return ALIGNOF (jbyte
);
78 else if (klass
== JvPrimClass (short))
79 return ALIGNOF (jshort
);
80 else if (klass
== JvPrimClass (int))
81 return ALIGNOF (jint
);
82 else if (klass
== JvPrimClass (long))
83 return ALIGNOF (jlong
);
84 else if (klass
== JvPrimClass (boolean
))
85 return ALIGNOF (jboolean
);
86 else if (klass
== JvPrimClass (char))
87 return ALIGNOF (jchar
);
88 else if (klass
== JvPrimClass (float))
89 return ALIGNOF (jfloat
);
90 else if (klass
== JvPrimClass (double))
91 return ALIGNOF (jdouble
);
93 return ALIGNOF (jobject
);
97 _Jv_Linker::resolve_field (_Jv_Field
*field
, java::lang::ClassLoader
*loader
)
99 if (! field
->isResolved ())
101 _Jv_Utf8Const
*sig
= (_Jv_Utf8Const
*) field
->type
;
102 jclass type
= _Jv_FindClassFromSignature (sig
->chars(), loader
);
104 throw new java::lang::NoClassDefFoundError(field
->name
->toString());
106 field
->flags
&= ~_Jv_FIELD_UNRESOLVED_FLAG
;
110 // A helper for find_field that knows how to recursively search
111 // superclasses and interfaces.
113 _Jv_Linker::find_field_helper (jclass search
, _Jv_Utf8Const
*name
,
114 _Jv_Utf8Const
*type_name
, jclass type
,
119 // From 5.4.3.2. First search class itself.
120 for (int i
= 0; i
< search
->field_count
; ++i
)
122 _Jv_Field
*field
= &search
->fields
[i
];
123 if (! _Jv_equalUtf8Consts (field
->name
, name
))
126 // Checks for the odd situation where we were able to retrieve the
127 // field's class from signature but the resolution of the field itself
128 // failed which means a different class was resolved.
133 resolve_field (field
, search
->loader
);
135 catch (java::lang::Throwable
*exc
)
137 java::lang::LinkageError
*le
= new java::lang::LinkageError
139 ("field type mismatch with different loaders"));
147 // Note that we compare type names and not types. This is
148 // bizarre, but we do it because we want to find a field
149 // (and terminate the search) if it has the correct
150 // descriptor -- but then later reject it if the class
151 // loader check results in different classes. We can't just
152 // pass in the descriptor and check that way, because when
153 // the field is already resolved there is no easy way to
154 // find its descriptor again.
155 if ((field
->isResolved ()
156 ? _Jv_equalUtf8Classnames (type_name
, field
->type
->name
)
157 : _Jv_equalUtf8Classnames (type_name
,
158 (_Jv_Utf8Const
*) field
->type
)))
165 // Next search direct interfaces.
166 for (int i
= 0; i
< search
->interface_count
; ++i
)
168 _Jv_Field
*result
= find_field_helper (search
->interfaces
[i
], name
,
169 type_name
, type
, declarer
);
174 // Now search superclass.
175 search
= search
->superclass
;
182 _Jv_Linker::has_field_p (jclass search
, _Jv_Utf8Const
*field_name
)
184 for (int i
= 0; i
< search
->field_count
; ++i
)
186 _Jv_Field
*field
= &search
->fields
[i
];
187 if (_Jv_equalUtf8Consts (field
->name
, field_name
))
194 // KLASS is the class that is requesting the field.
195 // OWNER is the class in which the field should be found.
196 // FIELD_TYPE_NAME is the type descriptor for the field.
197 // Fill FOUND_CLASS with the address of the class in which the field
198 // is actually declared.
199 // This function does the class loader type checks, and
200 // also access checks. Returns the field, or throws an
201 // exception on error.
203 _Jv_Linker::find_field (jclass klass
, jclass owner
,
205 _Jv_Utf8Const
*field_name
,
206 _Jv_Utf8Const
*field_type_name
)
208 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
210 // Note: This call will resolve the primitive type names ("Z", "B", ...) to
211 // their Java counterparts ("boolean", "byte", ...) if accessed via
212 // field_type->name later. Using these variants of the type name is in turn
213 // important for the find_field_helper function. However if the class
214 // resolution failed then we can only use the already given type name.
216 = _Jv_FindClassFromSignatureNoException (field_type_name
->chars(),
220 = find_field_helper (owner
, field_name
,
224 field_type
, found_class
);
228 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
229 sb
->append(JvNewStringLatin1("field "));
230 sb
->append(owner
->getName());
231 sb
->append(JvNewStringLatin1("."));
232 sb
->append(_Jv_NewStringUTF(field_name
->chars()));
233 sb
->append(JvNewStringLatin1(" was not found."));
234 throw new java::lang::NoSuchFieldError (sb
->toString());
237 // Accept it when the field's class could not be resolved.
238 if (field_type
== NULL
)
239 // Silently ignore that we were not able to retrieve the type to make it
240 // possible to run code which does not access this field.
243 if (_Jv_CheckAccess (klass
, *found_class
, the_field
->flags
))
245 // Note that the field returned by find_field_helper is always
246 // resolved. There's no point checking class loaders here,
247 // since we already did the work to look up all the types.
248 // FIXME: being lazy here would be nice.
249 if (the_field
->type
!= field_type
)
250 throw new java::lang::LinkageError
252 ("field type mismatch with different loaders"));
256 java::lang::StringBuffer
*sb
257 = new java::lang::StringBuffer ();
258 sb
->append(klass
->getName());
259 sb
->append(JvNewStringLatin1(": "));
260 sb
->append((*found_class
)->getName());
261 sb
->append(JvNewStringLatin1("."));
262 sb
->append(_Jv_NewStringUtf8Const (field_name
));
263 throw new java::lang::IllegalAccessError(sb
->toString());
270 _Jv_Linker::resolve_pool_entry (jclass klass
, int index
, bool lazy
)
272 using namespace java::lang::reflect
;
274 if (GC_base (klass
) && klass
->constants
.data
275 && ! GC_base (klass
->constants
.data
))
277 jsize count
= klass
->constants
.size
;
281 = (_Jv_word
*) _Jv_AllocRawObj (count
* sizeof (_Jv_word
));
282 memcpy ((void*)constants
,
283 (void*)klass
->constants
.data
,
284 count
* sizeof (_Jv_word
));
285 klass
->constants
.data
= constants
;
289 _Jv_Constants
*pool
= &klass
->constants
;
291 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
292 return pool
->data
[index
];
294 switch (pool
->tags
[index
])
296 case JV_CONSTANT_Class
:
298 _Jv_Utf8Const
*name
= pool
->data
[index
].utf8
;
301 if (name
->first() == '[')
302 found
= _Jv_FindClassFromSignatureNoException (name
->chars(),
305 found
= _Jv_FindClassNoException (name
, klass
->loader
);
307 // If the class could not be loaded a phantom class is created. Any
308 // function that deals with such a class but cannot do something useful
309 // with it should just throw a NoClassDefFoundError with the class'
314 found
= _Jv_NewClass(name
, NULL
, NULL
);
315 found
->state
= JV_STATE_PHANTOM
;
316 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
317 pool
->data
[index
].clazz
= found
;
321 throw new java::lang::NoClassDefFoundError (name
->toString());
323 // Check accessibility, but first strip array types as
324 // _Jv_ClassNameSamePackage can't handle arrays.
327 check
&& check
->isArray();
328 check
= check
->getComponentType())
330 if ((found
->accflags
& Modifier::PUBLIC
) == Modifier::PUBLIC
331 || (_Jv_ClassNameSamePackage (check
->name
,
334 pool
->data
[index
].clazz
= found
;
335 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
339 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer ();
340 sb
->append(klass
->getName());
341 sb
->append(JvNewStringLatin1(" can't access class "));
342 sb
->append(found
->getName());
343 throw new java::lang::IllegalAccessError(sb
->toString());
348 case JV_CONSTANT_String
:
351 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
352 pool
->data
[index
].o
= str
;
353 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
357 case JV_CONSTANT_Fieldref
:
359 _Jv_ushort class_index
, name_and_type_index
;
360 _Jv_loadIndexes (&pool
->data
[index
],
362 name_and_type_index
);
363 jclass owner
= (resolve_pool_entry (klass
, class_index
, true)).clazz
;
365 // If a phantom class was resolved our field reference is
366 // unusable because of the missing class.
367 if (owner
->state
== JV_STATE_PHANTOM
)
368 throw new java::lang::NoClassDefFoundError(owner
->getName());
370 // We don't initialize 'owner', but we do make sure that its
372 wait_for_state (owner
, JV_STATE_PREPARED
);
374 _Jv_ushort name_index
, type_index
;
375 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
379 _Jv_Utf8Const
*field_name
= pool
->data
[name_index
].utf8
;
380 _Jv_Utf8Const
*field_type_name
= pool
->data
[type_index
].utf8
;
382 jclass found_class
= 0;
383 _Jv_Field
*the_field
= find_field (klass
, owner
,
387 // Initialize the field's declaring class, not its qualifying
389 _Jv_InitClass (found_class
);
390 pool
->data
[index
].field
= the_field
;
391 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
395 case JV_CONSTANT_Methodref
:
396 case JV_CONSTANT_InterfaceMethodref
:
398 _Jv_ushort class_index
, name_and_type_index
;
399 _Jv_loadIndexes (&pool
->data
[index
],
401 name_and_type_index
);
402 jclass owner
= (resolve_pool_entry (klass
, class_index
)).clazz
;
405 _Jv_InitClass (owner
);
407 _Jv_ushort name_index
, type_index
;
408 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
412 _Jv_Utf8Const
*method_name
= pool
->data
[name_index
].utf8
;
413 _Jv_Utf8Const
*method_signature
= pool
->data
[type_index
].utf8
;
415 _Jv_Method
*the_method
= 0;
416 jclass found_class
= 0;
418 // We're going to cache a pointer to the _Jv_Method object
419 // when we find it. So, to ensure this doesn't get moved from
420 // beneath us, we first put all the needed Miranda methods
421 // into the target class.
422 wait_for_state (klass
, JV_STATE_LOADED
);
424 // First search the class itself.
425 the_method
= search_method_in_class (owner
, klass
,
426 method_name
, method_signature
);
431 goto end_of_method_search
;
434 // If we are resolving an interface method, search the
435 // interface's superinterfaces (A superinterface is not an
436 // interface's superclass - a superinterface is implemented by
438 if (pool
->tags
[index
] == JV_CONSTANT_InterfaceMethodref
)
443 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
444 * sizeof (jclass
*));
446 get_interfaces (owner
, &ifaces
);
448 for (int i
= 0; i
< ifaces
.count
; i
++)
450 jclass cls
= ifaces
.list
[i
];
451 the_method
= search_method_in_class (cls
, klass
, method_name
,
460 _Jv_Free (ifaces
.list
);
463 goto end_of_method_search
;
466 // Finally, search superclasses.
467 for (jclass cls
= owner
->getSuperclass (); cls
!= 0;
468 cls
= cls
->getSuperclass ())
470 the_method
= search_method_in_class (cls
, klass
, method_name
,
479 end_of_method_search
:
481 // FIXME: if (cls->loader != klass->loader), then we
482 // must actually check that the types of arguments
483 // correspond. That is, for each argument type, and
484 // the return type, doing _Jv_FindClassFromSignature
485 // with either loader should produce the same result,
486 // i.e., exactly the same jclass object. JVMS 5.4.3.3
490 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
491 sb
->append(JvNewStringLatin1("method "));
492 sb
->append(owner
->getName());
493 sb
->append(JvNewStringLatin1("."));
494 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
495 sb
->append(JvNewStringLatin1(" with signature "));
496 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
497 sb
->append(JvNewStringLatin1(" was not found."));
498 throw new java::lang::NoSuchMethodError (sb
->toString());
501 pool
->data
[index
].rmethod
502 = klass
->engine
->resolve_method(the_method
,
504 ((the_method
->accflags
505 & Modifier::STATIC
) != 0));
506 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
510 return pool
->data
[index
];
513 // This function is used to lazily locate superclasses and
514 // superinterfaces. This must be called with the class lock held.
516 _Jv_Linker::resolve_class_ref (jclass klass
, jclass
*classref
)
518 jclass ret
= *classref
;
520 // If superclass looks like a constant pool entry, resolve it now.
521 if (ret
&& (uaddr
) ret
< (uaddr
) klass
->constants
.size
)
523 if (klass
->state
< JV_STATE_LINKED
)
525 _Jv_Utf8Const
*name
= klass
->constants
.data
[(uaddr
) *classref
].utf8
;
526 ret
= _Jv_FindClass (name
, klass
->loader
);
529 throw new java::lang::NoClassDefFoundError (name
->toString());
533 ret
= klass
->constants
.data
[(uaddr
) classref
].clazz
;
538 // Find a method declared in the cls that is referenced from klass and
539 // perform access checks.
541 _Jv_Linker::search_method_in_class (jclass cls
, jclass klass
,
542 _Jv_Utf8Const
*method_name
,
543 _Jv_Utf8Const
*method_signature
)
545 using namespace java::lang::reflect
;
547 for (int i
= 0; i
< cls
->method_count
; i
++)
549 _Jv_Method
*method
= &cls
->methods
[i
];
550 if ( (!_Jv_equalUtf8Consts (method
->name
,
552 || (!_Jv_equalUtf8Consts (method
->signature
,
556 if (_Jv_CheckAccess (klass
, cls
, method
->accflags
))
560 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
561 sb
->append(klass
->getName());
562 sb
->append(JvNewStringLatin1(": "));
563 sb
->append(cls
->getName());
564 sb
->append(JvNewStringLatin1("."));
565 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
566 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
567 throw new java::lang::IllegalAccessError (sb
->toString());
574 #define INITIAL_IOFFSETS_LEN 4
575 #define INITIAL_IFACES_LEN 4
577 static _Jv_IDispatchTable null_idt
= {SHRT_MAX
, 0, {}};
579 // Generate tables for constant-time assignment testing and interface
580 // method lookup. This implements the technique described by Per Bothner
581 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
582 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
584 _Jv_Linker::prepare_constant_time_tables (jclass klass
)
586 if (klass
->isPrimitive () || klass
->isInterface ())
589 // Short-circuit in case we've been called already.
590 if ((klass
->idt
!= NULL
) || klass
->depth
!= 0)
593 // Calculate the class depth and ancestor table. The depth of a class
594 // is how many "extends" it is removed from Object. Thus the depth of
595 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
596 // is 2. Depth is defined for all regular and array classes, but not
597 // interfaces or primitive types.
599 jclass klass0
= klass
;
600 jboolean has_interfaces
= 0;
601 while (klass0
!= &java::lang::Object::class$
)
603 has_interfaces
+= klass0
->interface_count
;
604 klass0
= klass0
->superclass
;
608 // We do class member testing in constant time by using a small table
609 // of all the ancestor classes within each class. The first element is
610 // a pointer to the current class, and the rest are pointers to the
611 // classes ancestors, ordered from the current class down by decreasing
612 // depth. We do not include java.lang.Object in the table of ancestors,
613 // since it is redundant. Note that the classes pointed to by
614 // 'ancestors' will always be reachable by other paths.
616 klass
->ancestors
= (jclass
*) _Jv_AllocBytes (klass
->depth
619 for (int index
= 0; index
< klass
->depth
; index
++)
621 klass
->ancestors
[index
] = klass0
;
622 klass0
= klass0
->superclass
;
625 if ((klass
->accflags
& java::lang::reflect::Modifier::ABSTRACT
) != 0)
628 // Optimization: If class implements no interfaces, use a common
629 // predefined interface table.
632 klass
->idt
= &null_idt
;
638 ifaces
.len
= INITIAL_IFACES_LEN
;
639 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
* sizeof (jclass
*));
641 int itable_size
= get_interfaces (klass
, &ifaces
);
643 if (ifaces
.count
> 0)
645 // The classes pointed to by the itable will always be reachable
647 int idt_bytes
= sizeof (_Jv_IDispatchTable
) + (itable_size
649 klass
->idt
= (_Jv_IDispatchTable
*) _Jv_AllocBytes (idt_bytes
);
650 klass
->idt
->itable_length
= itable_size
;
652 jshort
*itable_offsets
=
653 (jshort
*) _Jv_Malloc (ifaces
.count
* sizeof (jshort
));
655 generate_itable (klass
, &ifaces
, itable_offsets
);
657 jshort cls_iindex
= find_iindex (ifaces
.list
, itable_offsets
,
660 for (int i
= 0; i
< ifaces
.count
; i
++)
662 ifaces
.list
[i
]->ioffsets
[cls_iindex
] = itable_offsets
[i
];
665 klass
->idt
->iindex
= cls_iindex
;
667 _Jv_Free (ifaces
.list
);
668 _Jv_Free (itable_offsets
);
672 klass
->idt
->iindex
= SHRT_MAX
;
676 // Return index of item in list, or -1 if item is not present.
678 _Jv_Linker::indexof (void *item
, void **list
, jshort list_len
)
680 for (int i
=0; i
< list_len
; i
++)
688 // Find all unique interfaces directly or indirectly implemented by klass.
689 // Returns the size of the interface dispatch table (itable) for klass, which
690 // is the number of unique interfaces plus the total number of methods that
691 // those interfaces declare. May extend ifaces if required.
693 _Jv_Linker::get_interfaces (jclass klass
, _Jv_ifaces
*ifaces
)
697 for (int i
= 0; i
< klass
->interface_count
; i
++)
699 jclass iface
= klass
->interfaces
[i
];
701 /* Make sure interface is linked. */
702 wait_for_state(iface
, JV_STATE_LINKED
);
704 if (indexof (iface
, (void **) ifaces
->list
, ifaces
->count
) == -1)
706 if (ifaces
->count
+ 1 >= ifaces
->len
)
708 /* Resize ifaces list */
709 ifaces
->len
= ifaces
->len
* 2;
711 = (jclass
*) _Jv_Realloc (ifaces
->list
,
712 ifaces
->len
* sizeof(jclass
));
714 ifaces
->list
[ifaces
->count
] = iface
;
717 result
+= get_interfaces (klass
->interfaces
[i
], ifaces
);
721 if (klass
->isInterface())
723 // We want to add 1 plus the number of interface methods here.
724 // But, we take special care to skip <clinit>.
726 for (int i
= 0; i
< klass
->method_count
; ++i
)
728 if (klass
->methods
[i
].name
->first() != '<')
732 else if (klass
->superclass
)
733 result
+= get_interfaces (klass
->superclass
, ifaces
);
737 // Fill out itable in klass, resolving method declarations in each ifaces.
738 // itable_offsets is filled out with the position of each iface in itable,
739 // such that itable[itable_offsets[n]] == ifaces.list[n].
741 _Jv_Linker::generate_itable (jclass klass
, _Jv_ifaces
*ifaces
,
742 jshort
*itable_offsets
)
744 void **itable
= klass
->idt
->itable
;
745 jshort itable_pos
= 0;
747 for (int i
= 0; i
< ifaces
->count
; i
++)
749 jclass iface
= ifaces
->list
[i
];
750 itable_offsets
[i
] = itable_pos
;
751 itable_pos
= append_partial_itable (klass
, iface
, itable
, itable_pos
);
753 /* Create ioffsets table for iface */
754 if (iface
->ioffsets
== NULL
)
756 // The first element of ioffsets is its length (itself included).
757 jshort
*ioffsets
= (jshort
*) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
759 ioffsets
[0] = INITIAL_IOFFSETS_LEN
;
760 for (int i
= 1; i
< INITIAL_IOFFSETS_LEN
; i
++)
763 iface
->ioffsets
= ioffsets
;
768 // Format method name for use in error messages.
770 _Jv_GetMethodString (jclass klass
, _Jv_Method
*meth
,
773 using namespace java::lang
;
774 StringBuffer
*buf
= new StringBuffer (klass
->name
->toString());
775 buf
->append (jchar ('.'));
776 buf
->append (meth
->name
->toString());
777 buf
->append ((jchar
) ' ');
778 buf
->append (meth
->signature
->toString());
781 buf
->append(JvNewStringLatin1(" in "));
782 buf
->append(derived
->name
->toString());
784 return buf
->toString();
788 _Jv_ThrowNoSuchMethodError ()
790 throw new java::lang::NoSuchMethodError
;
794 // A function whose invocation is prepared using libffi. It gets called
795 // whenever a static method of a missing class is invoked. The data argument
796 // holds a reference to a String denoting the missing class.
797 // The prepared function call is stored in a class' atable.
799 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif
*,
804 throw new java::lang::NoClassDefFoundError(
805 _Jv_NewStringUtf8Const((_Jv_Utf8Const
*) data
));
808 // A variant of the NoClassDefFoundError throwing method that can
809 // be used without libffi.
811 _Jv_ThrowNoClassDefFoundError()
813 throw new java::lang::NoClassDefFoundError();
817 // Throw a NoSuchFieldError. Called by compiler-generated code when
818 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
819 // otable that refers to the missing field. This index may be used to
820 // print diagnostic information about the field.
822 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
824 throw new java::lang::NoSuchFieldError
;
827 // This is put in empty vtable slots.
829 _Jv_ThrowAbstractMethodError ()
831 throw new java::lang::AbstractMethodError();
834 // Each superinterface of a class (i.e. each interface that the class
835 // directly or indirectly implements) has a corresponding "Partial
836 // Interface Dispatch Table" whose size is (number of methods + 1) words.
837 // The first word is a pointer to the interface (i.e. the java.lang.Class
838 // instance for that interface). The remaining words are pointers to the
839 // actual methods that implement the methods declared in the interface,
840 // in order of declaration.
842 // Append partial interface dispatch table for "iface" to "itable", at
843 // position itable_pos.
844 // Returns the offset at which the next partial ITable should be appended.
846 _Jv_Linker::append_partial_itable (jclass klass
, jclass iface
,
847 void **itable
, jshort pos
)
849 using namespace java::lang::reflect
;
851 itable
[pos
++] = (void *) iface
;
854 for (int j
=0; j
< iface
->method_count
; j
++)
856 // Skip '<clinit>' here.
857 if (iface
->methods
[j
].name
->first() == '<')
861 for (jclass cl
= klass
; cl
; cl
= cl
->getSuperclass())
863 meth
= _Jv_GetMethodLocal (cl
, iface
->methods
[j
].name
,
864 iface
->methods
[j
].signature
);
872 if ((meth
->accflags
& Modifier::STATIC
) != 0)
873 throw new java::lang::IncompatibleClassChangeError
874 (_Jv_GetMethodString (klass
, meth
));
875 if ((meth
->accflags
& Modifier::PUBLIC
) == 0)
876 throw new java::lang::IllegalAccessError
877 (_Jv_GetMethodString (klass
, meth
));
879 if ((meth
->accflags
& Modifier::ABSTRACT
) != 0)
880 itable
[pos
] = (void *) &_Jv_ThrowAbstractMethodError
;
882 itable
[pos
] = meth
->ncode
;
886 // The method doesn't exist in klass. Binary compatibility rules
887 // permit this, so we delay the error until runtime using a pointer
888 // to a method which throws an exception.
889 itable
[pos
] = (void *) _Jv_ThrowNoSuchMethodError
;
897 static _Jv_Mutex_t iindex_mutex
;
898 static bool iindex_mutex_initialized
= false;
900 // We need to find the correct offset in the Class Interface Dispatch
901 // Table for a given interface. Once we have that, invoking an interface
902 // method just requires combining the Method's index in the interface
903 // (known at compile time) to get the correct method. Doing a type test
904 // (cast or instanceof) is the same problem: Once we have a possible Partial
905 // Interface Dispatch Table, we just compare the first element to see if it
906 // matches the desired interface. So how can we find the correct offset?
907 // Our solution is to keep a vector of candiate offsets in each interface
908 // (ioffsets), and in each class we have an index (idt->iindex) used to
909 // select the correct offset from ioffsets.
911 // Calculate and return iindex for a new class.
912 // ifaces is a vector of num interfaces that the class implements.
913 // offsets[j] is the offset in the interface dispatch table for the
914 // interface corresponding to ifaces[j].
915 // May extend the interface ioffsets if required.
917 _Jv_Linker::find_iindex (jclass
*ifaces
, jshort
*offsets
, jshort num
)
922 // Acquire a global lock to prevent itable corruption in case of multiple
923 // classes that implement an intersecting set of interfaces being linked
924 // simultaneously. We can assume that the mutex will be initialized
926 if (! iindex_mutex_initialized
)
928 _Jv_MutexInit (&iindex_mutex
);
929 iindex_mutex_initialized
= true;
932 _Jv_MutexLock (&iindex_mutex
);
934 for (i
=1;; i
++) /* each potential position in ioffsets */
936 for (j
=0;; j
++) /* each iface */
940 if (i
>= ifaces
[j
]->ioffsets
[0])
942 int ioffset
= ifaces
[j
]->ioffsets
[i
];
943 /* We can potentially share this position with another class. */
944 if (ioffset
>= 0 && ioffset
!= offsets
[j
])
945 break; /* Nope. Try next i. */
949 for (j
= 0; j
< num
; j
++)
951 int len
= ifaces
[j
]->ioffsets
[0];
955 int newlen
= 2 * len
;
959 jshort
*old_ioffsets
= ifaces
[j
]->ioffsets
;
960 jshort
*new_ioffsets
= (jshort
*) _Jv_AllocBytes (newlen
962 memcpy (&new_ioffsets
[1], &old_ioffsets
[1],
963 (len
- 1) * sizeof (jshort
));
964 new_ioffsets
[0] = newlen
;
967 new_ioffsets
[len
++] = -1;
969 ifaces
[j
]->ioffsets
= new_ioffsets
;
971 ifaces
[j
]->ioffsets
[i
] = offsets
[j
];
974 _Jv_MutexUnlock (&iindex_mutex
);
980 // We use a structure of this type to store the closure that
981 // represents a missing method.
982 struct method_closure
984 // This field must come first, since the address of this field will
985 // be the same as the address of the overall structure. This is due
986 // to disabling interior pointers in the GC.
989 ffi_type
*arg_types
[1];
993 _Jv_Linker::create_error_method (_Jv_Utf8Const
*class_name
)
995 method_closure
*closure
996 = (method_closure
*) _Jv_AllocBytes(sizeof (method_closure
));
998 closure
->arg_types
[0] = &ffi_type_void
;
1000 // Initializes the cif and the closure. If that worked the closure
1001 // is returned and can be used as a function pointer in a class'
1003 if ( ffi_prep_cif (&closure
->cif
,
1007 closure
->arg_types
) == FFI_OK
1008 && ffi_prep_closure (&closure
->closure
,
1010 _Jv_ThrowNoClassDefFoundErrorTrampoline
,
1011 class_name
) == FFI_OK
)
1012 return &closure
->closure
;
1015 java::lang::StringBuffer
*buffer
= new java::lang::StringBuffer();
1016 buffer
->append(JvNewStringLatin1("Error setting up FFI closure"
1017 " for static method of"
1018 " missing class: "));
1019 buffer
->append (_Jv_NewStringUtf8Const(class_name
));
1020 throw new java::lang::InternalError(buffer
->toString());
1025 _Jv_Linker::create_error_method (_Jv_Utf8Const
*)
1027 // Codepath for platforms which do not support (or want) libffi.
1028 // You have to accept that it is impossible to provide the name
1029 // of the missing class then.
1030 return (void *) _Jv_ThrowNoClassDefFoundError
;
1032 #endif // USE_LIBFFI
1034 // Functions for indirect dispatch (symbolic virtual binding) support.
1036 // There are three tables, atable otable and itable. atable is an
1037 // array of addresses, and otable is an array of offsets, and these
1038 // are used for static and virtual members respectively. itable is an
1039 // array of pairs {address, index} where each address is a pointer to
1042 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1043 // symbol is a tuple of {classname, member name, signature}.
1045 // Set this to true to enable debugging of indirect dispatch tables/linking.
1046 static bool debug_link
= false;
1048 // link_symbol_table() scans these two arrays and fills in the
1049 // corresponding atable and otable with the addresses of static
1050 // members and the offsets of virtual members.
1052 // The offset (in bytes) for each resolved method or field is placed
1053 // at the corresponding position in the virtual method offset table
1056 // The same otable and atable may be shared by many classes.
1058 // This must be called while holding the class lock.
1061 _Jv_Linker::link_symbol_table (jclass klass
)
1064 _Jv_MethodSymbol sym
;
1065 if (klass
->otable
== NULL
1066 || klass
->otable
->state
!= 0)
1069 klass
->otable
->state
= 1;
1072 fprintf (stderr
, "Fixing up otable in %s:\n", klass
->name
->chars());
1074 (sym
= klass
->otable_syms
[index
]).class_name
!= NULL
;
1077 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1078 _Jv_Method
*meth
= NULL
;
1080 _Jv_Utf8Const
*signature
= sym
.signature
;
1082 if (target_class
== NULL
)
1083 throw new java::lang::NoClassDefFoundError
1084 (_Jv_NewStringUTF (sym
.class_name
->chars()));
1086 // We're looking for a field or a method, and we can tell
1087 // which is needed by looking at the signature.
1088 if (signature
->first() == '(' && signature
->len() >= 2)
1090 // Looks like someone is trying to invoke an interface method
1091 if (target_class
->isInterface())
1093 using namespace java::lang
;
1094 StringBuffer
*sb
= new StringBuffer();
1095 sb
->append(JvNewStringLatin1("found interface "));
1096 sb
->append(target_class
->getName());
1097 sb
->append(JvNewStringLatin1(" when searching for a class"));
1098 throw new VerifyError(sb
->toString());
1101 // If the target class does not have a vtable_method_count yet,
1102 // then we can't tell the offsets for its methods, so we must lay
1104 wait_for_state(target_class
, JV_STATE_PREPARED
);
1106 meth
= _Jv_LookupDeclaredMethod(target_class
, sym
.name
,
1109 // Every class has a throwNoSuchMethodErrorIndex method that
1110 // it inherits from java.lang.Object. Find its vtable
1112 static int throwNoSuchMethodErrorIndex
;
1113 if (throwNoSuchMethodErrorIndex
== 0)
1116 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1117 strlen ("throwNoSuchMethodError"));
1119 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$
,
1120 name
, gcj::void_signature
);
1121 throwNoSuchMethodErrorIndex
1122 = _Jv_VTable::idx_to_offset (meth
->index
);
1125 // If we don't find a nonstatic method, insert the
1126 // vtable index of Object.throwNoSuchMethodError().
1127 // This defers the missing method error until an attempt
1128 // is made to execute it.
1133 offset
= _Jv_VTable::idx_to_offset (meth
->index
);
1135 offset
= throwNoSuchMethodErrorIndex
;
1138 JvFail ("Bad method index");
1139 JvAssert (meth
->index
< target_class
->vtable_method_count
);
1141 klass
->otable
->offsets
[index
] = offset
;
1145 fprintf (stderr
, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1147 (int)klass
->otable
->offsets
[index
],
1148 (const char*)target_class
->name
->chars(),
1150 (const char*)sym
.name
->chars(),
1151 (const char*)signature
->chars());
1157 wait_for_state(target_class
, JV_STATE_PREPARED
);
1159 _Jv_Field
*the_field
= NULL
;
1162 the_field
= find_field (klass
, target_class
, &found_class
,
1163 sym
.name
, sym
.signature
);
1164 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1165 throw new java::lang::IncompatibleClassChangeError
;
1167 klass
->otable
->offsets
[index
] = the_field
->u
.boffset
;
1169 catch (java::lang::NoSuchFieldError
*err
)
1171 klass
->otable
->offsets
[index
] = 0;
1177 if (klass
->atable
== NULL
|| klass
->atable
->state
!= 0)
1180 klass
->atable
->state
= 1;
1183 (sym
= klass
->atable_syms
[index
]).class_name
!= NULL
;
1186 jclass target_class
=
1187 _Jv_FindClassNoException (sym
.class_name
, klass
->loader
);
1189 _Jv_Method
*meth
= NULL
;
1190 _Jv_Utf8Const
*signature
= sym
.signature
;
1192 // ??? Setting this pointer to null will at least get us a
1193 // NullPointerException
1194 klass
->atable
->addresses
[index
] = NULL
;
1196 // If the target class is missing we prepare a function call
1197 // that throws a NoClassDefFoundError and store the address of
1198 // that newly prepare method in the atable. The user can run
1199 // code in classes where the missing class is part of the
1200 // execution environment as long as it is never referenced.
1201 if (target_class
== NULL
)
1202 klass
->atable
->addresses
[index
] = create_error_method(sym
.class_name
);
1203 // We're looking for a static field or a static method, and we
1204 // can tell which is needed by looking at the signature.
1205 else if (signature
->first() == '(' && signature
->len() >= 2)
1207 // If the target class does not have a vtable_method_count yet,
1208 // then we can't tell the offsets for its methods, so we must lay
1210 wait_for_state (target_class
, JV_STATE_PREPARED
);
1212 // Interface methods cannot have bodies.
1213 if (target_class
->isInterface())
1215 using namespace java::lang
;
1216 StringBuffer
*sb
= new StringBuffer();
1217 sb
->append(JvNewStringLatin1("class "));
1218 sb
->append(target_class
->getName());
1219 sb
->append(JvNewStringLatin1(" is an interface: "
1221 throw new VerifyError(sb
->toString());
1224 meth
= _Jv_LookupDeclaredMethod(target_class
, sym
.name
,
1229 if (meth
->ncode
) // Maybe abstract?
1231 klass
->atable
->addresses
[index
] = meth
->ncode
;
1233 fprintf (stderr
, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1235 &klass
->atable
->addresses
[index
],
1236 (const char*)target_class
->name
->chars(),
1238 (const char*)sym
.name
->chars(),
1239 (const char*)signature
->chars());
1243 klass
->atable
->addresses
[index
]
1244 = create_error_method(sym
.class_name
);
1249 // Try fields only if the target class exists.
1250 if (target_class
!= NULL
)
1252 wait_for_state(target_class
, JV_STATE_PREPARED
);
1254 _Jv_Field
*the_field
= find_field (klass
, target_class
, &found_class
,
1255 sym
.name
, sym
.signature
);
1256 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1257 klass
->atable
->addresses
[index
] = the_field
->u
.addr
;
1259 throw new java::lang::IncompatibleClassChangeError
;
1264 if (klass
->itable
== NULL
1265 || klass
->itable
->state
!= 0)
1268 klass
->itable
->state
= 1;
1271 (sym
= klass
->itable_syms
[index
]).class_name
!= NULL
;
1274 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1275 _Jv_Utf8Const
*signature
= sym
.signature
;
1280 wait_for_state(target_class
, JV_STATE_LOADED
);
1281 bool found
= _Jv_getInterfaceMethod (target_class
, cls
, i
,
1282 sym
.name
, sym
.signature
);
1286 klass
->itable
->addresses
[index
* 2] = cls
;
1287 klass
->itable
->addresses
[index
* 2 + 1] = (void *)(unsigned long) i
;
1290 fprintf (stderr
, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1292 klass
->itable
->addresses
[index
* 2],
1293 (const char*)cls
->name
->chars(),
1295 (const char*)sym
.name
->chars(),
1296 (const char*)signature
->chars());
1297 fprintf (stderr
, " [%d] = offset %d\n",
1299 (int)(unsigned long)klass
->itable
->addresses
[index
* 2 + 1]);
1304 throw new java::lang::IncompatibleClassChangeError
;
1309 // For each catch_record in the list of caught classes, fill in the
1312 _Jv_Linker::link_exception_table (jclass self
)
1314 struct _Jv_CatchClass
*catch_record
= self
->catch_classes
;
1315 if (!catch_record
|| catch_record
->classname
)
1318 while (catch_record
->classname
)
1323 = _Jv_FindClass (catch_record
->classname
,
1324 self
->getClassLoaderInternal ());
1325 *catch_record
->address
= target_class
;
1327 catch (::java::lang::Throwable
*t
)
1329 // FIXME: We need to do something better here.
1330 *catch_record
->address
= 0;
1334 self
->catch_classes
->classname
= (_Jv_Utf8Const
*)-1;
1337 // Set itable method indexes for members of interface IFACE.
1339 _Jv_Linker::layout_interface_methods (jclass iface
)
1341 if (! iface
->isInterface())
1344 // itable indexes start at 1.
1345 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1346 // itable so they are also assigned an index here.
1347 for (int i
= 0; i
< iface
->method_count
; i
++)
1348 iface
->methods
[i
].index
= i
+ 1;
1351 // Prepare virtual method declarations in KLASS, and any superclasses
1352 // as required, by determining their vtable index, setting
1353 // method->index, and finally setting the class's vtable_method_count.
1354 // Must be called with the lock for KLASS held.
1356 _Jv_Linker::layout_vtable_methods (jclass klass
)
1358 if (klass
->vtable
!= NULL
|| klass
->isInterface()
1359 || klass
->vtable_method_count
!= -1)
1362 jclass superclass
= klass
->getSuperclass();
1364 if (superclass
!= NULL
&& superclass
->vtable_method_count
== -1)
1366 JvSynchronize
sync (superclass
);
1367 layout_vtable_methods (superclass
);
1370 int index
= (superclass
== NULL
? 0 : superclass
->vtable_method_count
);
1372 for (int i
= 0; i
< klass
->method_count
; ++i
)
1374 _Jv_Method
*meth
= &klass
->methods
[i
];
1375 _Jv_Method
*super_meth
= NULL
;
1377 if (! _Jv_isVirtualMethod (meth
))
1380 if (superclass
!= NULL
)
1383 super_meth
= _Jv_LookupDeclaredMethod (superclass
, meth
->name
,
1384 meth
->signature
, &declarer
);
1385 // See if this method actually overrides the other method
1389 if (! _Jv_isVirtualMethod (super_meth
)
1390 || ! _Jv_CheckAccess (klass
, declarer
,
1391 super_meth
->accflags
))
1393 else if ((super_meth
->accflags
1394 & java::lang::reflect::Modifier::FINAL
) != 0)
1396 using namespace java::lang
;
1397 StringBuffer
*sb
= new StringBuffer();
1398 sb
->append(JvNewStringLatin1("method "));
1399 sb
->append(_Jv_GetMethodString(klass
, meth
));
1400 sb
->append(JvNewStringLatin1(" overrides final method "));
1401 sb
->append(_Jv_GetMethodString(declarer
, super_meth
));
1402 throw new VerifyError(sb
->toString());
1408 meth
->index
= super_meth
->index
;
1410 meth
->index
= index
++;
1413 klass
->vtable_method_count
= index
;
1416 // Set entries in VTABLE for virtual methods declared in KLASS.
1418 _Jv_Linker::set_vtable_entries (jclass klass
, _Jv_VTable
*vtable
)
1420 for (int i
= klass
->method_count
- 1; i
>= 0; i
--)
1422 using namespace java::lang::reflect
;
1424 _Jv_Method
*meth
= &klass
->methods
[i
];
1425 if (meth
->index
== (_Jv_ushort
) -1)
1427 if ((meth
->accflags
& Modifier::ABSTRACT
))
1428 // FIXME: it might be nice to have a libffi trampoline here,
1429 // so we could pass in the method name and other information.
1430 vtable
->set_method(meth
->index
,
1431 (void *) &_Jv_ThrowAbstractMethodError
);
1433 vtable
->set_method(meth
->index
, meth
->ncode
);
1437 // Allocate and lay out the virtual method table for KLASS. This will
1438 // also cause vtables to be generated for any non-abstract
1439 // superclasses, and virtual method layout to occur for any abstract
1440 // superclasses. Must be called with monitor lock for KLASS held.
1442 _Jv_Linker::make_vtable (jclass klass
)
1444 using namespace java::lang::reflect
;
1446 // If the vtable exists, or for interface classes, do nothing. All
1447 // other classes, including abstract classes, need a vtable.
1448 if (klass
->vtable
!= NULL
|| klass
->isInterface())
1451 // Ensure all the `ncode' entries are set.
1452 klass
->engine
->create_ncode(klass
);
1454 // Class must be laid out before we can create a vtable.
1455 if (klass
->vtable_method_count
== -1)
1456 layout_vtable_methods (klass
);
1458 // Allocate the new vtable.
1459 _Jv_VTable
*vtable
= _Jv_VTable::new_vtable (klass
->vtable_method_count
);
1460 klass
->vtable
= vtable
;
1462 // Copy the vtable of the closest superclass.
1463 jclass superclass
= klass
->superclass
;
1465 JvSynchronize
sync (superclass
);
1466 make_vtable (superclass
);
1468 for (int i
= 0; i
< superclass
->vtable_method_count
; ++i
)
1469 vtable
->set_method (i
, superclass
->vtable
->get_method (i
));
1471 // Set the class pointer and GC descriptor.
1472 vtable
->clas
= klass
;
1473 vtable
->gc_descr
= _Jv_BuildGCDescr (klass
);
1475 // For each virtual declared in klass, set new vtable entry or
1476 // override an old one.
1477 set_vtable_entries (klass
, vtable
);
1479 // Note that we don't check for abstract methods here. We used to,
1480 // but there is a JVMS clarification that indicates that a check
1481 // here would be too eager. And, a simple test case confirms this.
1484 // Lay out the class, allocating space for static fields and computing
1485 // offsets of instance fields. The class lock must be held by the
1488 _Jv_Linker::ensure_fields_laid_out (jclass klass
)
1490 if (klass
->size_in_bytes
!= -1)
1493 // Compute the alignment for this type by searching through the
1494 // superclasses and finding the maximum required alignment. We
1495 // could consider caching this in the Class.
1496 int max_align
= __alignof__ (java::lang::Object
);
1497 jclass super
= klass
->getSuperclass();
1498 while (super
!= NULL
)
1500 // Ensure that our super has its super installed before
1502 wait_for_state(super
, JV_STATE_LOADING
);
1503 ensure_fields_laid_out(super
);
1504 int num
= JvNumInstanceFields (super
);
1505 _Jv_Field
*field
= JvGetFirstInstanceField (super
);
1508 int field_align
= get_alignment_from_class (field
->type
);
1509 if (field_align
> max_align
)
1510 max_align
= field_align
;
1514 super
= super
->getSuperclass();
1518 // This is the size of the 'static' non-reference fields.
1519 int non_reference_size
= 0;
1520 // This is the size of the 'static' reference fields. We count
1521 // these separately to make it simpler for the GC to scan them.
1522 int reference_size
= 0;
1524 // Although java.lang.Object is never interpreted, an interface can
1525 // have a null superclass. Note that we have to lay out an
1526 // interface because it might have static fields.
1527 if (klass
->superclass
)
1528 instance_size
= klass
->superclass
->size();
1530 instance_size
= java::lang::Object::class$
.size();
1532 klass
->engine
->allocate_field_initializers (klass
);
1534 for (int i
= 0; i
< klass
->field_count
; i
++)
1539 _Jv_Field
*field
= &klass
->fields
[i
];
1541 if (! field
->isRef ())
1543 // It is safe to resolve the field here, since it's a
1544 // primitive class, which does not cause loading to happen.
1545 resolve_field (field
, klass
->loader
);
1546 field_size
= field
->type
->size ();
1547 field_align
= get_alignment_from_class (field
->type
);
1551 field_size
= sizeof (jobject
);
1552 field_align
= __alignof__ (jobject
);
1555 field
->bsize
= field_size
;
1557 if ((field
->flags
& java::lang::reflect::Modifier::STATIC
))
1559 if (field
->u
.addr
== NULL
)
1561 // This computes an offset into a region we'll allocate
1562 // shortly, and then adds this offset to the start
1566 reference_size
= ROUND (reference_size
, field_align
);
1567 field
->u
.boffset
= reference_size
;
1568 reference_size
+= field_size
;
1572 non_reference_size
= ROUND (non_reference_size
, field_align
);
1573 field
->u
.boffset
= non_reference_size
;
1574 non_reference_size
+= field_size
;
1580 instance_size
= ROUND (instance_size
, field_align
);
1581 field
->u
.boffset
= instance_size
;
1582 instance_size
+= field_size
;
1583 if (field_align
> max_align
)
1584 max_align
= field_align
;
1588 if (reference_size
!= 0 || non_reference_size
!= 0)
1589 klass
->engine
->allocate_static_fields (klass
, reference_size
,
1590 non_reference_size
);
1592 // Set the instance size for the class. Note that first we round it
1593 // to the alignment required for this object; this keeps us in sync
1594 // with our current ABI.
1595 instance_size
= ROUND (instance_size
, max_align
);
1596 klass
->size_in_bytes
= instance_size
;
1599 // This takes the class to state JV_STATE_LINKED. The class lock must
1600 // be held when calling this.
1602 _Jv_Linker::ensure_class_linked (jclass klass
)
1604 if (klass
->state
>= JV_STATE_LINKED
)
1607 int state
= klass
->state
;
1610 // Short-circuit, so that mutually dependent classes are ok.
1611 klass
->state
= JV_STATE_LINKED
;
1613 _Jv_Constants
*pool
= &klass
->constants
;
1615 // Compiled classes require that their class constants be
1616 // resolved here. However, interpreted classes need their
1617 // constants to be resolved lazily. If we resolve an
1618 // interpreted class' constants eagerly, we can end up with
1619 // spurious IllegalAccessErrors when the constant pool contains
1620 // a reference to a class we can't access. This can validly
1621 // occur in an obscure case involving the InnerClasses
1623 if (! _Jv_IsInterpretedClass (klass
))
1625 // Resolve class constants first, since other constant pool
1626 // entries may rely on these.
1627 for (int index
= 1; index
< pool
->size
; ++index
)
1629 if (pool
->tags
[index
] == JV_CONSTANT_Class
)
1630 // Lazily resolve the entries.
1631 resolve_pool_entry (klass
, index
, true);
1635 // Resolve the remaining constant pool entries.
1636 for (int index
= 1; index
< pool
->size
; ++index
)
1638 if (pool
->tags
[index
] == JV_CONSTANT_String
)
1642 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
1643 pool
->data
[index
].o
= str
;
1644 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
1648 if (klass
->engine
->need_resolve_string_fields())
1650 jfieldID f
= JvGetFirstStaticField (klass
);
1651 for (int n
= JvNumStaticFields (klass
); n
> 0; --n
)
1653 int mod
= f
->getModifiers ();
1654 // If we have a static String field with a non-null initial
1655 // value, we know it points to a Utf8Const.
1657 // Finds out whether we have to initialize a String without the
1658 // need to resolve the field.
1659 if ((f
->isResolved()
1660 ? (f
->type
== &java::lang::String::class$
)
1661 : _Jv_equalUtf8Classnames((_Jv_Utf8Const
*) f
->type
,
1662 java::lang::String::class$
.name
))
1663 && (mod
& java::lang::reflect::Modifier::STATIC
) != 0)
1665 jstring
*strp
= (jstring
*) f
->u
.addr
;
1667 *strp
= _Jv_NewStringUtf8Const ((_Jv_Utf8Const
*) *strp
);
1669 f
= f
->getNextField ();
1673 klass
->notifyAll ();
1675 _Jv_PushClass (klass
);
1677 catch (java::lang::Throwable
*t
)
1679 klass
->state
= state
;
1684 // This ensures that symbolic superclass and superinterface references
1685 // are resolved for the indicated class. This must be called with the
1688 _Jv_Linker::ensure_supers_installed (jclass klass
)
1690 resolve_class_ref (klass
, &klass
->superclass
);
1691 // An interface won't have a superclass.
1692 if (klass
->superclass
)
1693 wait_for_state (klass
->superclass
, JV_STATE_LOADING
);
1695 for (int i
= 0; i
< klass
->interface_count
; ++i
)
1697 resolve_class_ref (klass
, &klass
->interfaces
[i
]);
1698 wait_for_state (klass
->interfaces
[i
], JV_STATE_LOADING
);
1702 // This adds missing `Miranda methods' to a class.
1704 _Jv_Linker::add_miranda_methods (jclass base
, jclass iface_class
)
1706 // Note that at this point, all our supers, and the supers of all
1707 // our superclasses and superinterfaces, will have been installed.
1709 for (int i
= 0; i
< iface_class
->interface_count
; ++i
)
1711 jclass interface
= iface_class
->interfaces
[i
];
1713 for (int j
= 0; j
< interface
->method_count
; ++j
)
1715 _Jv_Method
*meth
= &interface
->methods
[j
];
1716 // Don't bother with <clinit>.
1717 if (meth
->name
->first() == '<')
1719 _Jv_Method
*new_meth
= _Jv_LookupDeclaredMethod (base
, meth
->name
,
1723 // We assume that such methods are very unlikely, so we
1724 // just reallocate the method array each time one is
1725 // found. This greatly simplifies the searching --
1726 // otherwise we have to make sure that each such method
1727 // found is really unique among all superinterfaces.
1728 int new_count
= base
->method_count
+ 1;
1730 = (_Jv_Method
*) _Jv_AllocRawObj (sizeof (_Jv_Method
)
1732 memcpy (new_m
, base
->methods
,
1733 sizeof (_Jv_Method
) * base
->method_count
);
1736 new_m
[base
->method_count
] = *meth
;
1737 new_m
[base
->method_count
].index
= (_Jv_ushort
) -1;
1738 new_m
[base
->method_count
].accflags
1739 |= java::lang::reflect::Modifier::INVISIBLE
;
1741 base
->methods
= new_m
;
1742 base
->method_count
= new_count
;
1746 wait_for_state (interface
, JV_STATE_LOADED
);
1747 add_miranda_methods (base
, interface
);
1751 // This ensures that the class' method table is "complete". This must
1752 // be called with the class lock held.
1754 _Jv_Linker::ensure_method_table_complete (jclass klass
)
1756 if (klass
->vtable
!= NULL
)
1759 // We need our superclass to have its own Miranda methods installed.
1760 if (! klass
->isInterface())
1761 wait_for_state (klass
->getSuperclass (), JV_STATE_LOADED
);
1763 // A class might have so-called "Miranda methods". This is a method
1764 // that is declared in an interface and not re-declared in an
1765 // abstract class. Some compilers don't emit declarations for such
1766 // methods in the class; this will give us problems since we expect
1767 // a declaration for any method requiring a vtable entry. We handle
1768 // this here by searching for such methods and constructing new
1769 // internal declarations for them. Note that we do this
1770 // unconditionally, and not just for abstract classes, to correctly
1771 // account for cases where a class is modified to be concrete and
1772 // still incorrectly inherits an abstract method.
1773 int pre_count
= klass
->method_count
;
1774 add_miranda_methods (klass
, klass
);
1776 // Let the execution engine know that we've added methods.
1777 if (klass
->method_count
!= pre_count
)
1778 klass
->engine
->post_miranda_hook(klass
);
1781 // Verify a class. Must be called with class lock held.
1783 _Jv_Linker::verify_class (jclass klass
)
1785 klass
->engine
->verify(klass
);
1788 // Check the assertions contained in the type assertion table for KLASS.
1789 // This is the equivilent of bytecode verification for native, BC-ABI code.
1791 _Jv_Linker::verify_type_assertions (jclass klass
)
1794 fprintf (stderr
, "Evaluating type assertions for %s:\n",
1795 klass
->name
->chars());
1797 if (klass
->assertion_table
== NULL
)
1800 for (int i
= 0;; i
++)
1802 int assertion_code
= klass
->assertion_table
[i
].assertion_code
;
1803 _Jv_Utf8Const
*op1
= klass
->assertion_table
[i
].op1
;
1804 _Jv_Utf8Const
*op2
= klass
->assertion_table
[i
].op2
;
1806 if (assertion_code
== JV_ASSERT_END_OF_TABLE
)
1808 else if (assertion_code
== JV_ASSERT_TYPES_COMPATIBLE
)
1812 fprintf (stderr
, " code=%i, operand A=%s B=%s\n",
1813 assertion_code
, op1
->chars(), op2
->chars());
1816 // The operands are class signatures. op1 is the source,
1817 // op2 is the target.
1818 jclass cl1
= _Jv_FindClassFromSignature (op1
->chars(),
1819 klass
->getClassLoaderInternal());
1820 jclass cl2
= _Jv_FindClassFromSignature (op2
->chars(),
1821 klass
->getClassLoaderInternal());
1823 // If the class doesn't exist, ignore the assertion. An exception
1824 // will be thrown later if an attempt is made to actually
1825 // instantiate the class.
1826 if (cl1
== NULL
|| cl2
== NULL
)
1829 if (! _Jv_IsAssignableFromSlow (cl1
, cl2
))
1831 jstring s
= JvNewStringUTF ("Incompatible types: In class ");
1832 s
= s
->concat (klass
->getName());
1833 s
= s
->concat (JvNewStringUTF (": "));
1834 s
= s
->concat (cl1
->getName());
1835 s
= s
->concat (JvNewStringUTF (" is not assignable to "));
1836 s
= s
->concat (cl2
->getName());
1837 throw new java::lang::VerifyError (s
);
1840 else if (assertion_code
== JV_ASSERT_IS_INSTANTIABLE
)
1842 // TODO: Implement this.
1844 // Unknown assertion codes are ignored, for forwards-compatibility.
1849 _Jv_Linker::print_class_loaded (jclass klass
)
1851 char *codesource
= NULL
;
1852 if (klass
->protectionDomain
!= NULL
)
1854 java::security::CodeSource
*cs
1855 = klass
->protectionDomain
->getCodeSource();
1858 jstring css
= cs
->toString();
1859 int len
= JvGetStringUTFLength(css
);
1860 codesource
= (char *) _Jv_AllocBytes(len
+ 1);
1861 JvGetStringUTFRegion(css
, 0, css
->length(), codesource
);
1862 codesource
[len
] = '\0';
1865 if (codesource
== NULL
)
1866 codesource
= (char *) "<no code source>";
1869 if (_Jv_IsInterpretedClass (klass
))
1871 else if (_Jv_IsBinaryCompatibilityABI (klass
))
1872 abi
= "BC-compiled";
1874 abi
= "pre-compiled";
1876 fprintf (stderr
, "[Loaded (%s) %s from %s]\n", abi
, klass
->name
->chars(),
1880 // FIXME: mention invariants and stuff.
1882 _Jv_Linker::wait_for_state (jclass klass
, int state
)
1884 if (klass
->state
>= state
)
1887 JvSynchronize
sync (klass
);
1889 // This is similar to the strategy for class initialization. If we
1890 // already hold the lock, just leave.
1891 java::lang::Thread
*self
= java::lang::Thread::currentThread();
1892 while (klass
->state
<= state
1894 && klass
->thread
!= self
)
1897 java::lang::Thread
*save
= klass
->thread
;
1898 klass
->thread
= self
;
1900 // Allocate memory for static fields and constants.
1901 if (GC_base (klass
) && klass
->fields
&& ! GC_base (klass
->fields
))
1903 jsize count
= klass
->field_count
;
1907 = (_Jv_Field
*) _Jv_AllocRawObj (count
* sizeof (_Jv_Field
));
1908 memcpy ((void*)fields
,
1909 (void*)klass
->fields
,
1910 count
* sizeof (_Jv_Field
));
1911 klass
->fields
= fields
;
1915 // Print some debugging info if requested. Interpreted classes are
1916 // handled in defineclass, so we only need to handle the two
1917 // pre-compiled cases here.
1918 if (gcj::verbose_class_flag
1919 && (klass
->state
== JV_STATE_COMPILED
1920 || klass
->state
== JV_STATE_PRELOADING
)
1921 && ! _Jv_IsInterpretedClass (klass
))
1922 print_class_loaded (klass
);
1926 if (state
>= JV_STATE_LOADING
&& klass
->state
< JV_STATE_LOADING
)
1928 ensure_supers_installed (klass
);
1929 klass
->set_state(JV_STATE_LOADING
);
1932 if (state
>= JV_STATE_LOADED
&& klass
->state
< JV_STATE_LOADED
)
1934 ensure_method_table_complete (klass
);
1935 klass
->set_state(JV_STATE_LOADED
);
1938 if (state
>= JV_STATE_PREPARED
&& klass
->state
< JV_STATE_PREPARED
)
1940 ensure_fields_laid_out (klass
);
1941 make_vtable (klass
);
1942 layout_interface_methods (klass
);
1943 prepare_constant_time_tables (klass
);
1944 klass
->set_state(JV_STATE_PREPARED
);
1947 if (state
>= JV_STATE_LINKED
&& klass
->state
< JV_STATE_LINKED
)
1949 if (gcj::verifyClasses
)
1950 verify_class (klass
);
1952 ensure_class_linked (klass
);
1953 link_exception_table (klass
);
1954 link_symbol_table (klass
);
1955 klass
->set_state(JV_STATE_LINKED
);
1958 catch (java::lang::Throwable
*exc
)
1960 klass
->thread
= save
;
1961 klass
->set_state(JV_STATE_ERROR
);
1965 klass
->thread
= save
;
1967 if (klass
->state
== JV_STATE_ERROR
)
1968 throw new java::lang::LinkageError
;