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_method_entry (jclass klass
, jclass
&found_class
,
271 int class_index
, int name_and_type_index
,
272 bool init
, bool is_iface
)
274 _Jv_Constants
*pool
= &klass
->constants
;
275 jclass owner
= resolve_pool_entry (klass
, class_index
).clazz
;
277 if (init
&& owner
!= klass
)
278 _Jv_InitClass (owner
);
280 _Jv_ushort name_index
, type_index
;
281 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
285 _Jv_Utf8Const
*method_name
= pool
->data
[name_index
].utf8
;
286 _Jv_Utf8Const
*method_signature
= pool
->data
[type_index
].utf8
;
288 _Jv_Method
*the_method
= 0;
291 // We're going to cache a pointer to the _Jv_Method object
292 // when we find it. So, to ensure this doesn't get moved from
293 // beneath us, we first put all the needed Miranda methods
294 // into the target class.
295 wait_for_state (klass
, JV_STATE_LOADED
);
297 // First search the class itself.
298 the_method
= search_method_in_class (owner
, klass
,
299 method_name
, method_signature
);
304 goto end_of_method_search
;
307 // If we are resolving an interface method, search the
308 // interface's superinterfaces (A superinterface is not an
309 // interface's superclass - a superinterface is implemented by
316 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
317 * sizeof (jclass
*));
319 get_interfaces (owner
, &ifaces
);
321 for (int i
= 0; i
< ifaces
.count
; i
++)
323 jclass cls
= ifaces
.list
[i
];
324 the_method
= search_method_in_class (cls
, klass
, method_name
,
333 _Jv_Free (ifaces
.list
);
336 goto end_of_method_search
;
339 // Finally, search superclasses.
340 for (jclass cls
= owner
->getSuperclass (); cls
!= 0;
341 cls
= cls
->getSuperclass ())
343 the_method
= search_method_in_class (cls
, klass
, method_name
,
352 end_of_method_search
:
354 // FIXME: if (cls->loader != klass->loader), then we
355 // must actually check that the types of arguments
356 // correspond. That is, for each argument type, and
357 // the return type, doing _Jv_FindClassFromSignature
358 // with either loader should produce the same result,
359 // i.e., exactly the same jclass object. JVMS 5.4.3.3
363 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
364 sb
->append(JvNewStringLatin1("method "));
365 sb
->append(owner
->getName());
366 sb
->append(JvNewStringLatin1("."));
367 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
368 sb
->append(JvNewStringLatin1(" with signature "));
369 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
370 sb
->append(JvNewStringLatin1(" was not found."));
371 throw new java::lang::NoSuchMethodError (sb
->toString());
378 _Jv_Linker::resolve_pool_entry (jclass klass
, int index
, bool lazy
)
380 using namespace java::lang::reflect
;
382 if (GC_base (klass
) && klass
->constants
.data
383 && ! GC_base (klass
->constants
.data
))
385 jsize count
= klass
->constants
.size
;
389 = (_Jv_word
*) _Jv_AllocRawObj (count
* sizeof (_Jv_word
));
390 memcpy ((void*)constants
,
391 (void*)klass
->constants
.data
,
392 count
* sizeof (_Jv_word
));
393 klass
->constants
.data
= constants
;
397 _Jv_Constants
*pool
= &klass
->constants
;
399 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
400 return pool
->data
[index
];
402 switch (pool
->tags
[index
])
404 case JV_CONSTANT_Class
:
406 _Jv_Utf8Const
*name
= pool
->data
[index
].utf8
;
409 if (name
->first() == '[')
410 found
= _Jv_FindClassFromSignatureNoException (name
->chars(),
413 found
= _Jv_FindClassNoException (name
, klass
->loader
);
415 // If the class could not be loaded a phantom class is created. Any
416 // function that deals with such a class but cannot do something useful
417 // with it should just throw a NoClassDefFoundError with the class'
422 found
= _Jv_NewClass(name
, NULL
, NULL
);
423 found
->state
= JV_STATE_PHANTOM
;
424 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
425 pool
->data
[index
].clazz
= found
;
429 throw new java::lang::NoClassDefFoundError (name
->toString());
431 // Check accessibility, but first strip array types as
432 // _Jv_ClassNameSamePackage can't handle arrays.
435 check
&& check
->isArray();
436 check
= check
->getComponentType())
438 if ((found
->accflags
& Modifier::PUBLIC
) == Modifier::PUBLIC
439 || (_Jv_ClassNameSamePackage (check
->name
,
442 pool
->data
[index
].clazz
= found
;
443 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
447 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer ();
448 sb
->append(klass
->getName());
449 sb
->append(JvNewStringLatin1(" can't access class "));
450 sb
->append(found
->getName());
451 throw new java::lang::IllegalAccessError(sb
->toString());
456 case JV_CONSTANT_String
:
459 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
460 pool
->data
[index
].o
= str
;
461 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
465 case JV_CONSTANT_Fieldref
:
467 _Jv_ushort class_index
, name_and_type_index
;
468 _Jv_loadIndexes (&pool
->data
[index
],
470 name_and_type_index
);
471 jclass owner
= (resolve_pool_entry (klass
, class_index
, true)).clazz
;
473 // If a phantom class was resolved our field reference is
474 // unusable because of the missing class.
475 if (owner
->state
== JV_STATE_PHANTOM
)
476 throw new java::lang::NoClassDefFoundError(owner
->getName());
478 // We don't initialize 'owner', but we do make sure that its
480 wait_for_state (owner
, JV_STATE_PREPARED
);
482 _Jv_ushort name_index
, type_index
;
483 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
487 _Jv_Utf8Const
*field_name
= pool
->data
[name_index
].utf8
;
488 _Jv_Utf8Const
*field_type_name
= pool
->data
[type_index
].utf8
;
490 jclass found_class
= 0;
491 _Jv_Field
*the_field
= find_field (klass
, owner
,
495 // Initialize the field's declaring class, not its qualifying
497 _Jv_InitClass (found_class
);
498 pool
->data
[index
].field
= the_field
;
499 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
503 case JV_CONSTANT_Methodref
:
504 case JV_CONSTANT_InterfaceMethodref
:
506 _Jv_ushort class_index
, name_and_type_index
;
507 _Jv_loadIndexes (&pool
->data
[index
],
509 name_and_type_index
);
511 _Jv_Method
*the_method
;
513 the_method
= resolve_method_entry (klass
, found_class
,
514 class_index
, name_and_type_index
,
516 pool
->tags
[index
] == JV_CONSTANT_InterfaceMethodref
);
518 pool
->data
[index
].rmethod
519 = klass
->engine
->resolve_method(the_method
,
521 ((the_method
->accflags
522 & Modifier::STATIC
) != 0));
523 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
527 return pool
->data
[index
];
530 // This function is used to lazily locate superclasses and
531 // superinterfaces. This must be called with the class lock held.
533 _Jv_Linker::resolve_class_ref (jclass klass
, jclass
*classref
)
535 jclass ret
= *classref
;
537 // If superclass looks like a constant pool entry, resolve it now.
538 if (ret
&& (uaddr
) ret
< (uaddr
) klass
->constants
.size
)
540 if (klass
->state
< JV_STATE_LINKED
)
542 _Jv_Utf8Const
*name
= klass
->constants
.data
[(uaddr
) *classref
].utf8
;
543 ret
= _Jv_FindClass (name
, klass
->loader
);
546 throw new java::lang::NoClassDefFoundError (name
->toString());
550 ret
= klass
->constants
.data
[(uaddr
) classref
].clazz
;
555 // Find a method declared in the cls that is referenced from klass and
556 // perform access checks.
558 _Jv_Linker::search_method_in_class (jclass cls
, jclass klass
,
559 _Jv_Utf8Const
*method_name
,
560 _Jv_Utf8Const
*method_signature
)
562 using namespace java::lang::reflect
;
564 for (int i
= 0; i
< cls
->method_count
; i
++)
566 _Jv_Method
*method
= &cls
->methods
[i
];
567 if ( (!_Jv_equalUtf8Consts (method
->name
,
569 || (!_Jv_equalUtf8Consts (method
->signature
,
573 if (_Jv_CheckAccess (klass
, cls
, method
->accflags
))
577 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
578 sb
->append(klass
->getName());
579 sb
->append(JvNewStringLatin1(": "));
580 sb
->append(cls
->getName());
581 sb
->append(JvNewStringLatin1("."));
582 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
583 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
584 throw new java::lang::IllegalAccessError (sb
->toString());
591 #define INITIAL_IOFFSETS_LEN 4
592 #define INITIAL_IFACES_LEN 4
594 static _Jv_IDispatchTable null_idt
= {SHRT_MAX
, 0, {}};
596 // Generate tables for constant-time assignment testing and interface
597 // method lookup. This implements the technique described by Per Bothner
598 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
599 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
601 _Jv_Linker::prepare_constant_time_tables (jclass klass
)
603 if (klass
->isPrimitive () || klass
->isInterface ())
606 // Short-circuit in case we've been called already.
607 if ((klass
->idt
!= NULL
) || klass
->depth
!= 0)
610 // Calculate the class depth and ancestor table. The depth of a class
611 // is how many "extends" it is removed from Object. Thus the depth of
612 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
613 // is 2. Depth is defined for all regular and array classes, but not
614 // interfaces or primitive types.
616 jclass klass0
= klass
;
617 jboolean has_interfaces
= 0;
618 while (klass0
!= &java::lang::Object::class$
)
620 has_interfaces
+= klass0
->interface_count
;
621 klass0
= klass0
->superclass
;
625 // We do class member testing in constant time by using a small table
626 // of all the ancestor classes within each class. The first element is
627 // a pointer to the current class, and the rest are pointers to the
628 // classes ancestors, ordered from the current class down by decreasing
629 // depth. We do not include java.lang.Object in the table of ancestors,
630 // since it is redundant. Note that the classes pointed to by
631 // 'ancestors' will always be reachable by other paths.
633 klass
->ancestors
= (jclass
*) _Jv_AllocBytes (klass
->depth
636 for (int index
= 0; index
< klass
->depth
; index
++)
638 klass
->ancestors
[index
] = klass0
;
639 klass0
= klass0
->superclass
;
642 if ((klass
->accflags
& java::lang::reflect::Modifier::ABSTRACT
) != 0)
645 // Optimization: If class implements no interfaces, use a common
646 // predefined interface table.
649 klass
->idt
= &null_idt
;
655 ifaces
.len
= INITIAL_IFACES_LEN
;
656 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
* sizeof (jclass
*));
658 int itable_size
= get_interfaces (klass
, &ifaces
);
660 if (ifaces
.count
> 0)
662 // The classes pointed to by the itable will always be reachable
664 int idt_bytes
= sizeof (_Jv_IDispatchTable
) + (itable_size
666 klass
->idt
= (_Jv_IDispatchTable
*) _Jv_AllocBytes (idt_bytes
);
667 klass
->idt
->itable_length
= itable_size
;
669 jshort
*itable_offsets
=
670 (jshort
*) _Jv_Malloc (ifaces
.count
* sizeof (jshort
));
672 generate_itable (klass
, &ifaces
, itable_offsets
);
674 jshort cls_iindex
= find_iindex (ifaces
.list
, itable_offsets
,
677 for (int i
= 0; i
< ifaces
.count
; i
++)
679 ifaces
.list
[i
]->ioffsets
[cls_iindex
] = itable_offsets
[i
];
682 klass
->idt
->iindex
= cls_iindex
;
684 _Jv_Free (ifaces
.list
);
685 _Jv_Free (itable_offsets
);
689 klass
->idt
->iindex
= SHRT_MAX
;
693 // Return index of item in list, or -1 if item is not present.
695 _Jv_Linker::indexof (void *item
, void **list
, jshort list_len
)
697 for (int i
=0; i
< list_len
; i
++)
705 // Find all unique interfaces directly or indirectly implemented by klass.
706 // Returns the size of the interface dispatch table (itable) for klass, which
707 // is the number of unique interfaces plus the total number of methods that
708 // those interfaces declare. May extend ifaces if required.
710 _Jv_Linker::get_interfaces (jclass klass
, _Jv_ifaces
*ifaces
)
714 for (int i
= 0; i
< klass
->interface_count
; i
++)
716 jclass iface
= klass
->interfaces
[i
];
718 /* Make sure interface is linked. */
719 wait_for_state(iface
, JV_STATE_LINKED
);
721 if (indexof (iface
, (void **) ifaces
->list
, ifaces
->count
) == -1)
723 if (ifaces
->count
+ 1 >= ifaces
->len
)
725 /* Resize ifaces list */
726 ifaces
->len
= ifaces
->len
* 2;
728 = (jclass
*) _Jv_Realloc (ifaces
->list
,
729 ifaces
->len
* sizeof(jclass
));
731 ifaces
->list
[ifaces
->count
] = iface
;
734 result
+= get_interfaces (klass
->interfaces
[i
], ifaces
);
738 if (klass
->isInterface())
740 // We want to add 1 plus the number of interface methods here.
741 // But, we take special care to skip <clinit>.
743 for (int i
= 0; i
< klass
->method_count
; ++i
)
745 if (klass
->methods
[i
].name
->first() != '<')
749 else if (klass
->superclass
)
750 result
+= get_interfaces (klass
->superclass
, ifaces
);
754 // Fill out itable in klass, resolving method declarations in each ifaces.
755 // itable_offsets is filled out with the position of each iface in itable,
756 // such that itable[itable_offsets[n]] == ifaces.list[n].
758 _Jv_Linker::generate_itable (jclass klass
, _Jv_ifaces
*ifaces
,
759 jshort
*itable_offsets
)
761 void **itable
= klass
->idt
->itable
;
762 jshort itable_pos
= 0;
764 for (int i
= 0; i
< ifaces
->count
; i
++)
766 jclass iface
= ifaces
->list
[i
];
767 itable_offsets
[i
] = itable_pos
;
768 itable_pos
= append_partial_itable (klass
, iface
, itable
, itable_pos
);
770 /* Create ioffsets table for iface */
771 if (iface
->ioffsets
== NULL
)
773 // The first element of ioffsets is its length (itself included).
774 jshort
*ioffsets
= (jshort
*) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
776 ioffsets
[0] = INITIAL_IOFFSETS_LEN
;
777 for (int i
= 1; i
< INITIAL_IOFFSETS_LEN
; i
++)
780 iface
->ioffsets
= ioffsets
;
785 // Format method name for use in error messages.
787 _Jv_GetMethodString (jclass klass
, _Jv_Method
*meth
,
790 using namespace java::lang
;
791 StringBuffer
*buf
= new StringBuffer (klass
->name
->toString());
792 buf
->append (jchar ('.'));
793 buf
->append (meth
->name
->toString());
794 buf
->append ((jchar
) ' ');
795 buf
->append (meth
->signature
->toString());
798 buf
->append(JvNewStringLatin1(" in "));
799 buf
->append(derived
->name
->toString());
801 return buf
->toString();
805 _Jv_ThrowNoSuchMethodError ()
807 throw new java::lang::NoSuchMethodError
;
811 // A function whose invocation is prepared using libffi. It gets called
812 // whenever a static method of a missing class is invoked. The data argument
813 // holds a reference to a String denoting the missing class.
814 // The prepared function call is stored in a class' atable.
816 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif
*,
821 throw new java::lang::NoClassDefFoundError(
822 _Jv_NewStringUtf8Const((_Jv_Utf8Const
*) data
));
825 // A variant of the NoClassDefFoundError throwing method that can
826 // be used without libffi.
828 _Jv_ThrowNoClassDefFoundError()
830 throw new java::lang::NoClassDefFoundError();
834 // Throw a NoSuchFieldError. Called by compiler-generated code when
835 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
836 // otable that refers to the missing field. This index may be used to
837 // print diagnostic information about the field.
839 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
841 throw new java::lang::NoSuchFieldError
;
844 // This is put in empty vtable slots.
846 _Jv_ThrowAbstractMethodError ()
848 throw new java::lang::AbstractMethodError();
851 // Each superinterface of a class (i.e. each interface that the class
852 // directly or indirectly implements) has a corresponding "Partial
853 // Interface Dispatch Table" whose size is (number of methods + 1) words.
854 // The first word is a pointer to the interface (i.e. the java.lang.Class
855 // instance for that interface). The remaining words are pointers to the
856 // actual methods that implement the methods declared in the interface,
857 // in order of declaration.
859 // Append partial interface dispatch table for "iface" to "itable", at
860 // position itable_pos.
861 // Returns the offset at which the next partial ITable should be appended.
863 _Jv_Linker::append_partial_itable (jclass klass
, jclass iface
,
864 void **itable
, jshort pos
)
866 using namespace java::lang::reflect
;
868 itable
[pos
++] = (void *) iface
;
871 for (int j
=0; j
< iface
->method_count
; j
++)
873 // Skip '<clinit>' here.
874 if (iface
->methods
[j
].name
->first() == '<')
878 for (jclass cl
= klass
; cl
; cl
= cl
->getSuperclass())
880 meth
= _Jv_GetMethodLocal (cl
, iface
->methods
[j
].name
,
881 iface
->methods
[j
].signature
);
889 if ((meth
->accflags
& Modifier::STATIC
) != 0)
890 throw new java::lang::IncompatibleClassChangeError
891 (_Jv_GetMethodString (klass
, meth
));
892 if ((meth
->accflags
& Modifier::PUBLIC
) == 0)
893 throw new java::lang::IllegalAccessError
894 (_Jv_GetMethodString (klass
, meth
));
896 if ((meth
->accflags
& Modifier::ABSTRACT
) != 0)
897 itable
[pos
] = (void *) &_Jv_ThrowAbstractMethodError
;
899 itable
[pos
] = meth
->ncode
;
903 // The method doesn't exist in klass. Binary compatibility rules
904 // permit this, so we delay the error until runtime using a pointer
905 // to a method which throws an exception.
906 itable
[pos
] = (void *) _Jv_ThrowNoSuchMethodError
;
914 static _Jv_Mutex_t iindex_mutex
;
915 static bool iindex_mutex_initialized
= false;
917 // We need to find the correct offset in the Class Interface Dispatch
918 // Table for a given interface. Once we have that, invoking an interface
919 // method just requires combining the Method's index in the interface
920 // (known at compile time) to get the correct method. Doing a type test
921 // (cast or instanceof) is the same problem: Once we have a possible Partial
922 // Interface Dispatch Table, we just compare the first element to see if it
923 // matches the desired interface. So how can we find the correct offset?
924 // Our solution is to keep a vector of candiate offsets in each interface
925 // (ioffsets), and in each class we have an index (idt->iindex) used to
926 // select the correct offset from ioffsets.
928 // Calculate and return iindex for a new class.
929 // ifaces is a vector of num interfaces that the class implements.
930 // offsets[j] is the offset in the interface dispatch table for the
931 // interface corresponding to ifaces[j].
932 // May extend the interface ioffsets if required.
934 _Jv_Linker::find_iindex (jclass
*ifaces
, jshort
*offsets
, jshort num
)
939 // Acquire a global lock to prevent itable corruption in case of multiple
940 // classes that implement an intersecting set of interfaces being linked
941 // simultaneously. We can assume that the mutex will be initialized
943 if (! iindex_mutex_initialized
)
945 _Jv_MutexInit (&iindex_mutex
);
946 iindex_mutex_initialized
= true;
949 _Jv_MutexLock (&iindex_mutex
);
951 for (i
=1;; i
++) /* each potential position in ioffsets */
953 for (j
=0;; j
++) /* each iface */
957 if (i
>= ifaces
[j
]->ioffsets
[0])
959 int ioffset
= ifaces
[j
]->ioffsets
[i
];
960 /* We can potentially share this position with another class. */
961 if (ioffset
>= 0 && ioffset
!= offsets
[j
])
962 break; /* Nope. Try next i. */
966 for (j
= 0; j
< num
; j
++)
968 int len
= ifaces
[j
]->ioffsets
[0];
972 int newlen
= 2 * len
;
976 jshort
*old_ioffsets
= ifaces
[j
]->ioffsets
;
977 jshort
*new_ioffsets
= (jshort
*) _Jv_AllocBytes (newlen
979 memcpy (&new_ioffsets
[1], &old_ioffsets
[1],
980 (len
- 1) * sizeof (jshort
));
981 new_ioffsets
[0] = newlen
;
984 new_ioffsets
[len
++] = -1;
986 ifaces
[j
]->ioffsets
= new_ioffsets
;
988 ifaces
[j
]->ioffsets
[i
] = offsets
[j
];
991 _Jv_MutexUnlock (&iindex_mutex
);
997 // We use a structure of this type to store the closure that
998 // represents a missing method.
999 struct method_closure
1001 // This field must come first, since the address of this field will
1002 // be the same as the address of the overall structure. This is due
1003 // to disabling interior pointers in the GC.
1004 ffi_closure closure
;
1006 ffi_type
*arg_types
[1];
1010 _Jv_Linker::create_error_method (_Jv_Utf8Const
*class_name
)
1012 method_closure
*closure
1013 = (method_closure
*) _Jv_AllocBytes(sizeof (method_closure
));
1015 closure
->arg_types
[0] = &ffi_type_void
;
1017 // Initializes the cif and the closure. If that worked the closure
1018 // is returned and can be used as a function pointer in a class'
1020 if ( ffi_prep_cif (&closure
->cif
,
1024 closure
->arg_types
) == FFI_OK
1025 && ffi_prep_closure (&closure
->closure
,
1027 _Jv_ThrowNoClassDefFoundErrorTrampoline
,
1028 class_name
) == FFI_OK
)
1029 return &closure
->closure
;
1032 java::lang::StringBuffer
*buffer
= new java::lang::StringBuffer();
1033 buffer
->append(JvNewStringLatin1("Error setting up FFI closure"
1034 " for static method of"
1035 " missing class: "));
1036 buffer
->append (_Jv_NewStringUtf8Const(class_name
));
1037 throw new java::lang::InternalError(buffer
->toString());
1042 _Jv_Linker::create_error_method (_Jv_Utf8Const
*)
1044 // Codepath for platforms which do not support (or want) libffi.
1045 // You have to accept that it is impossible to provide the name
1046 // of the missing class then.
1047 return (void *) _Jv_ThrowNoClassDefFoundError
;
1049 #endif // USE_LIBFFI
1051 // Functions for indirect dispatch (symbolic virtual binding) support.
1053 // There are three tables, atable otable and itable. atable is an
1054 // array of addresses, and otable is an array of offsets, and these
1055 // are used for static and virtual members respectively. itable is an
1056 // array of pairs {address, index} where each address is a pointer to
1059 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1060 // symbol is a tuple of {classname, member name, signature}.
1062 // Set this to true to enable debugging of indirect dispatch tables/linking.
1063 static bool debug_link
= false;
1065 // link_symbol_table() scans these two arrays and fills in the
1066 // corresponding atable and otable with the addresses of static
1067 // members and the offsets of virtual members.
1069 // The offset (in bytes) for each resolved method or field is placed
1070 // at the corresponding position in the virtual method offset table
1073 // The same otable and atable may be shared by many classes.
1075 // This must be called while holding the class lock.
1078 _Jv_Linker::link_symbol_table (jclass klass
)
1081 _Jv_MethodSymbol sym
;
1082 if (klass
->otable
== NULL
1083 || klass
->otable
->state
!= 0)
1086 klass
->otable
->state
= 1;
1089 fprintf (stderr
, "Fixing up otable in %s:\n", klass
->name
->chars());
1091 (sym
= klass
->otable_syms
[index
]).class_name
!= NULL
;
1094 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1095 _Jv_Method
*meth
= NULL
;
1097 _Jv_Utf8Const
*signature
= sym
.signature
;
1099 if (target_class
== NULL
)
1100 throw new java::lang::NoClassDefFoundError
1101 (_Jv_NewStringUTF (sym
.class_name
->chars()));
1103 // We're looking for a field or a method, and we can tell
1104 // which is needed by looking at the signature.
1105 if (signature
->first() == '(' && signature
->len() >= 2)
1107 // Looks like someone is trying to invoke an interface method
1108 if (target_class
->isInterface())
1110 using namespace java::lang
;
1111 StringBuffer
*sb
= new StringBuffer();
1112 sb
->append(JvNewStringLatin1("found interface "));
1113 sb
->append(target_class
->getName());
1114 sb
->append(JvNewStringLatin1(" when searching for a class"));
1115 throw new VerifyError(sb
->toString());
1118 // If the target class does not have a vtable_method_count yet,
1119 // then we can't tell the offsets for its methods, so we must lay
1121 wait_for_state(target_class
, JV_STATE_PREPARED
);
1123 meth
= _Jv_LookupDeclaredMethod(target_class
, sym
.name
,
1126 // Every class has a throwNoSuchMethodErrorIndex method that
1127 // it inherits from java.lang.Object. Find its vtable
1129 static int throwNoSuchMethodErrorIndex
;
1130 if (throwNoSuchMethodErrorIndex
== 0)
1133 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1134 strlen ("throwNoSuchMethodError"));
1136 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$
,
1137 name
, gcj::void_signature
);
1138 throwNoSuchMethodErrorIndex
1139 = _Jv_VTable::idx_to_offset (meth
->index
);
1142 // If we don't find a nonstatic method, insert the
1143 // vtable index of Object.throwNoSuchMethodError().
1144 // This defers the missing method error until an attempt
1145 // is made to execute it.
1150 offset
= _Jv_VTable::idx_to_offset (meth
->index
);
1152 offset
= throwNoSuchMethodErrorIndex
;
1155 JvFail ("Bad method index");
1156 JvAssert (meth
->index
< target_class
->vtable_method_count
);
1158 klass
->otable
->offsets
[index
] = offset
;
1162 fprintf (stderr
, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1164 (int)klass
->otable
->offsets
[index
],
1165 (const char*)target_class
->name
->chars(),
1167 (const char*)sym
.name
->chars(),
1168 (const char*)signature
->chars());
1174 wait_for_state(target_class
, JV_STATE_PREPARED
);
1176 _Jv_Field
*the_field
= NULL
;
1179 the_field
= find_field (klass
, target_class
, &found_class
,
1180 sym
.name
, sym
.signature
);
1181 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1182 throw new java::lang::IncompatibleClassChangeError
;
1184 klass
->otable
->offsets
[index
] = the_field
->u
.boffset
;
1186 catch (java::lang::NoSuchFieldError
*err
)
1188 klass
->otable
->offsets
[index
] = 0;
1194 if (klass
->atable
== NULL
|| klass
->atable
->state
!= 0)
1197 klass
->atable
->state
= 1;
1200 (sym
= klass
->atable_syms
[index
]).class_name
!= NULL
;
1203 jclass target_class
=
1204 _Jv_FindClassNoException (sym
.class_name
, klass
->loader
);
1206 _Jv_Method
*meth
= NULL
;
1207 _Jv_Utf8Const
*signature
= sym
.signature
;
1209 // ??? Setting this pointer to null will at least get us a
1210 // NullPointerException
1211 klass
->atable
->addresses
[index
] = NULL
;
1213 // If the target class is missing we prepare a function call
1214 // that throws a NoClassDefFoundError and store the address of
1215 // that newly prepare method in the atable. The user can run
1216 // code in classes where the missing class is part of the
1217 // execution environment as long as it is never referenced.
1218 if (target_class
== NULL
)
1219 klass
->atable
->addresses
[index
] = create_error_method(sym
.class_name
);
1220 // We're looking for a static field or a static method, and we
1221 // can tell which is needed by looking at the signature.
1222 else if (signature
->first() == '(' && signature
->len() >= 2)
1224 // If the target class does not have a vtable_method_count yet,
1225 // then we can't tell the offsets for its methods, so we must lay
1227 wait_for_state (target_class
, JV_STATE_PREPARED
);
1229 // Interface methods cannot have bodies.
1230 if (target_class
->isInterface())
1232 using namespace java::lang
;
1233 StringBuffer
*sb
= new StringBuffer();
1234 sb
->append(JvNewStringLatin1("class "));
1235 sb
->append(target_class
->getName());
1236 sb
->append(JvNewStringLatin1(" is an interface: "
1238 throw new VerifyError(sb
->toString());
1241 meth
= _Jv_LookupDeclaredMethod(target_class
, sym
.name
,
1246 if (meth
->ncode
) // Maybe abstract?
1248 klass
->atable
->addresses
[index
] = meth
->ncode
;
1250 fprintf (stderr
, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1252 &klass
->atable
->addresses
[index
],
1253 (const char*)target_class
->name
->chars(),
1255 (const char*)sym
.name
->chars(),
1256 (const char*)signature
->chars());
1260 klass
->atable
->addresses
[index
]
1261 = create_error_method(sym
.class_name
);
1266 // Try fields only if the target class exists.
1267 if (target_class
!= NULL
)
1269 wait_for_state(target_class
, JV_STATE_PREPARED
);
1271 _Jv_Field
*the_field
= find_field (klass
, target_class
, &found_class
,
1272 sym
.name
, sym
.signature
);
1273 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1274 klass
->atable
->addresses
[index
] = the_field
->u
.addr
;
1276 throw new java::lang::IncompatibleClassChangeError
;
1281 if (klass
->itable
== NULL
1282 || klass
->itable
->state
!= 0)
1285 klass
->itable
->state
= 1;
1288 (sym
= klass
->itable_syms
[index
]).class_name
!= NULL
;
1291 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1292 _Jv_Utf8Const
*signature
= sym
.signature
;
1297 wait_for_state(target_class
, JV_STATE_LOADED
);
1298 bool found
= _Jv_getInterfaceMethod (target_class
, cls
, i
,
1299 sym
.name
, sym
.signature
);
1303 klass
->itable
->addresses
[index
* 2] = cls
;
1304 klass
->itable
->addresses
[index
* 2 + 1] = (void *)(unsigned long) i
;
1307 fprintf (stderr
, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1309 klass
->itable
->addresses
[index
* 2],
1310 (const char*)cls
->name
->chars(),
1312 (const char*)sym
.name
->chars(),
1313 (const char*)signature
->chars());
1314 fprintf (stderr
, " [%d] = offset %d\n",
1316 (int)(unsigned long)klass
->itable
->addresses
[index
* 2 + 1]);
1321 throw new java::lang::IncompatibleClassChangeError
;
1326 // For each catch_record in the list of caught classes, fill in the
1329 _Jv_Linker::link_exception_table (jclass self
)
1331 struct _Jv_CatchClass
*catch_record
= self
->catch_classes
;
1332 if (!catch_record
|| catch_record
->classname
)
1335 while (catch_record
->classname
)
1340 = _Jv_FindClass (catch_record
->classname
,
1341 self
->getClassLoaderInternal ());
1342 *catch_record
->address
= target_class
;
1344 catch (::java::lang::Throwable
*t
)
1346 // FIXME: We need to do something better here.
1347 *catch_record
->address
= 0;
1351 self
->catch_classes
->classname
= (_Jv_Utf8Const
*)-1;
1354 // Set itable method indexes for members of interface IFACE.
1356 _Jv_Linker::layout_interface_methods (jclass iface
)
1358 if (! iface
->isInterface())
1361 // itable indexes start at 1.
1362 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1363 // itable so they are also assigned an index here.
1364 for (int i
= 0; i
< iface
->method_count
; i
++)
1365 iface
->methods
[i
].index
= i
+ 1;
1368 // Prepare virtual method declarations in KLASS, and any superclasses
1369 // as required, by determining their vtable index, setting
1370 // method->index, and finally setting the class's vtable_method_count.
1371 // Must be called with the lock for KLASS held.
1373 _Jv_Linker::layout_vtable_methods (jclass klass
)
1375 if (klass
->vtable
!= NULL
|| klass
->isInterface()
1376 || klass
->vtable_method_count
!= -1)
1379 jclass superclass
= klass
->getSuperclass();
1381 if (superclass
!= NULL
&& superclass
->vtable_method_count
== -1)
1383 JvSynchronize
sync (superclass
);
1384 layout_vtable_methods (superclass
);
1387 int index
= (superclass
== NULL
? 0 : superclass
->vtable_method_count
);
1389 for (int i
= 0; i
< klass
->method_count
; ++i
)
1391 _Jv_Method
*meth
= &klass
->methods
[i
];
1392 _Jv_Method
*super_meth
= NULL
;
1394 if (! _Jv_isVirtualMethod (meth
))
1397 if (superclass
!= NULL
)
1400 super_meth
= _Jv_LookupDeclaredMethod (superclass
, meth
->name
,
1401 meth
->signature
, &declarer
);
1402 // See if this method actually overrides the other method
1406 if (! _Jv_isVirtualMethod (super_meth
)
1407 || ! _Jv_CheckAccess (klass
, declarer
,
1408 super_meth
->accflags
))
1410 else if ((super_meth
->accflags
1411 & java::lang::reflect::Modifier::FINAL
) != 0)
1413 using namespace java::lang
;
1414 StringBuffer
*sb
= new StringBuffer();
1415 sb
->append(JvNewStringLatin1("method "));
1416 sb
->append(_Jv_GetMethodString(klass
, meth
));
1417 sb
->append(JvNewStringLatin1(" overrides final method "));
1418 sb
->append(_Jv_GetMethodString(declarer
, super_meth
));
1419 throw new VerifyError(sb
->toString());
1425 meth
->index
= super_meth
->index
;
1427 meth
->index
= index
++;
1430 klass
->vtable_method_count
= index
;
1433 // Set entries in VTABLE for virtual methods declared in KLASS.
1435 _Jv_Linker::set_vtable_entries (jclass klass
, _Jv_VTable
*vtable
)
1437 for (int i
= klass
->method_count
- 1; i
>= 0; i
--)
1439 using namespace java::lang::reflect
;
1441 _Jv_Method
*meth
= &klass
->methods
[i
];
1442 if (meth
->index
== (_Jv_ushort
) -1)
1444 if ((meth
->accflags
& Modifier::ABSTRACT
))
1445 // FIXME: it might be nice to have a libffi trampoline here,
1446 // so we could pass in the method name and other information.
1447 vtable
->set_method(meth
->index
,
1448 (void *) &_Jv_ThrowAbstractMethodError
);
1450 vtable
->set_method(meth
->index
, meth
->ncode
);
1454 // Allocate and lay out the virtual method table for KLASS. This will
1455 // also cause vtables to be generated for any non-abstract
1456 // superclasses, and virtual method layout to occur for any abstract
1457 // superclasses. Must be called with monitor lock for KLASS held.
1459 _Jv_Linker::make_vtable (jclass klass
)
1461 using namespace java::lang::reflect
;
1463 // If the vtable exists, or for interface classes, do nothing. All
1464 // other classes, including abstract classes, need a vtable.
1465 if (klass
->vtable
!= NULL
|| klass
->isInterface())
1468 // Ensure all the `ncode' entries are set.
1469 klass
->engine
->create_ncode(klass
);
1471 // Class must be laid out before we can create a vtable.
1472 if (klass
->vtable_method_count
== -1)
1473 layout_vtable_methods (klass
);
1475 // Allocate the new vtable.
1476 _Jv_VTable
*vtable
= _Jv_VTable::new_vtable (klass
->vtable_method_count
);
1477 klass
->vtable
= vtable
;
1479 // Copy the vtable of the closest superclass.
1480 jclass superclass
= klass
->superclass
;
1482 JvSynchronize
sync (superclass
);
1483 make_vtable (superclass
);
1485 for (int i
= 0; i
< superclass
->vtable_method_count
; ++i
)
1486 vtable
->set_method (i
, superclass
->vtable
->get_method (i
));
1488 // Set the class pointer and GC descriptor.
1489 vtable
->clas
= klass
;
1490 vtable
->gc_descr
= _Jv_BuildGCDescr (klass
);
1492 // For each virtual declared in klass, set new vtable entry or
1493 // override an old one.
1494 set_vtable_entries (klass
, vtable
);
1496 // Note that we don't check for abstract methods here. We used to,
1497 // but there is a JVMS clarification that indicates that a check
1498 // here would be too eager. And, a simple test case confirms this.
1501 // Lay out the class, allocating space for static fields and computing
1502 // offsets of instance fields. The class lock must be held by the
1505 _Jv_Linker::ensure_fields_laid_out (jclass klass
)
1507 if (klass
->size_in_bytes
!= -1)
1510 // Compute the alignment for this type by searching through the
1511 // superclasses and finding the maximum required alignment. We
1512 // could consider caching this in the Class.
1513 int max_align
= __alignof__ (java::lang::Object
);
1514 jclass super
= klass
->getSuperclass();
1515 while (super
!= NULL
)
1517 // Ensure that our super has its super installed before
1519 wait_for_state(super
, JV_STATE_LOADING
);
1520 ensure_fields_laid_out(super
);
1521 int num
= JvNumInstanceFields (super
);
1522 _Jv_Field
*field
= JvGetFirstInstanceField (super
);
1525 int field_align
= get_alignment_from_class (field
->type
);
1526 if (field_align
> max_align
)
1527 max_align
= field_align
;
1531 super
= super
->getSuperclass();
1535 // This is the size of the 'static' non-reference fields.
1536 int non_reference_size
= 0;
1537 // This is the size of the 'static' reference fields. We count
1538 // these separately to make it simpler for the GC to scan them.
1539 int reference_size
= 0;
1541 // Although java.lang.Object is never interpreted, an interface can
1542 // have a null superclass. Note that we have to lay out an
1543 // interface because it might have static fields.
1544 if (klass
->superclass
)
1545 instance_size
= klass
->superclass
->size();
1547 instance_size
= java::lang::Object::class$
.size();
1549 klass
->engine
->allocate_field_initializers (klass
);
1551 for (int i
= 0; i
< klass
->field_count
; i
++)
1556 _Jv_Field
*field
= &klass
->fields
[i
];
1558 if (! field
->isRef ())
1560 // It is safe to resolve the field here, since it's a
1561 // primitive class, which does not cause loading to happen.
1562 resolve_field (field
, klass
->loader
);
1563 field_size
= field
->type
->size ();
1564 field_align
= get_alignment_from_class (field
->type
);
1568 field_size
= sizeof (jobject
);
1569 field_align
= __alignof__ (jobject
);
1572 field
->bsize
= field_size
;
1574 if ((field
->flags
& java::lang::reflect::Modifier::STATIC
))
1576 if (field
->u
.addr
== NULL
)
1578 // This computes an offset into a region we'll allocate
1579 // shortly, and then adds this offset to the start
1583 reference_size
= ROUND (reference_size
, field_align
);
1584 field
->u
.boffset
= reference_size
;
1585 reference_size
+= field_size
;
1589 non_reference_size
= ROUND (non_reference_size
, field_align
);
1590 field
->u
.boffset
= non_reference_size
;
1591 non_reference_size
+= field_size
;
1597 instance_size
= ROUND (instance_size
, field_align
);
1598 field
->u
.boffset
= instance_size
;
1599 instance_size
+= field_size
;
1600 if (field_align
> max_align
)
1601 max_align
= field_align
;
1605 if (reference_size
!= 0 || non_reference_size
!= 0)
1606 klass
->engine
->allocate_static_fields (klass
, reference_size
,
1607 non_reference_size
);
1609 // Set the instance size for the class. Note that first we round it
1610 // to the alignment required for this object; this keeps us in sync
1611 // with our current ABI.
1612 instance_size
= ROUND (instance_size
, max_align
);
1613 klass
->size_in_bytes
= instance_size
;
1616 // This takes the class to state JV_STATE_LINKED. The class lock must
1617 // be held when calling this.
1619 _Jv_Linker::ensure_class_linked (jclass klass
)
1621 if (klass
->state
>= JV_STATE_LINKED
)
1624 int state
= klass
->state
;
1627 // Short-circuit, so that mutually dependent classes are ok.
1628 klass
->state
= JV_STATE_LINKED
;
1630 _Jv_Constants
*pool
= &klass
->constants
;
1632 // Compiled classes require that their class constants be
1633 // resolved here. However, interpreted classes need their
1634 // constants to be resolved lazily. If we resolve an
1635 // interpreted class' constants eagerly, we can end up with
1636 // spurious IllegalAccessErrors when the constant pool contains
1637 // a reference to a class we can't access. This can validly
1638 // occur in an obscure case involving the InnerClasses
1640 if (! _Jv_IsInterpretedClass (klass
))
1642 // Resolve class constants first, since other constant pool
1643 // entries may rely on these.
1644 for (int index
= 1; index
< pool
->size
; ++index
)
1646 if (pool
->tags
[index
] == JV_CONSTANT_Class
)
1647 // Lazily resolve the entries.
1648 resolve_pool_entry (klass
, index
, true);
1652 // Resolve the remaining constant pool entries.
1653 for (int index
= 1; index
< pool
->size
; ++index
)
1655 if (pool
->tags
[index
] == JV_CONSTANT_String
)
1659 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
1660 pool
->data
[index
].o
= str
;
1661 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
1665 if (klass
->engine
->need_resolve_string_fields())
1667 jfieldID f
= JvGetFirstStaticField (klass
);
1668 for (int n
= JvNumStaticFields (klass
); n
> 0; --n
)
1670 int mod
= f
->getModifiers ();
1671 // If we have a static String field with a non-null initial
1672 // value, we know it points to a Utf8Const.
1674 // Finds out whether we have to initialize a String without the
1675 // need to resolve the field.
1676 if ((f
->isResolved()
1677 ? (f
->type
== &java::lang::String::class$
)
1678 : _Jv_equalUtf8Classnames((_Jv_Utf8Const
*) f
->type
,
1679 java::lang::String::class$
.name
))
1680 && (mod
& java::lang::reflect::Modifier::STATIC
) != 0)
1682 jstring
*strp
= (jstring
*) f
->u
.addr
;
1684 *strp
= _Jv_NewStringUtf8Const ((_Jv_Utf8Const
*) *strp
);
1686 f
= f
->getNextField ();
1690 klass
->notifyAll ();
1692 _Jv_PushClass (klass
);
1694 catch (java::lang::Throwable
*t
)
1696 klass
->state
= state
;
1701 // This ensures that symbolic superclass and superinterface references
1702 // are resolved for the indicated class. This must be called with the
1705 _Jv_Linker::ensure_supers_installed (jclass klass
)
1707 resolve_class_ref (klass
, &klass
->superclass
);
1708 // An interface won't have a superclass.
1709 if (klass
->superclass
)
1710 wait_for_state (klass
->superclass
, JV_STATE_LOADING
);
1712 for (int i
= 0; i
< klass
->interface_count
; ++i
)
1714 resolve_class_ref (klass
, &klass
->interfaces
[i
]);
1715 wait_for_state (klass
->interfaces
[i
], JV_STATE_LOADING
);
1719 // This adds missing `Miranda methods' to a class.
1721 _Jv_Linker::add_miranda_methods (jclass base
, jclass iface_class
)
1723 // Note that at this point, all our supers, and the supers of all
1724 // our superclasses and superinterfaces, will have been installed.
1726 for (int i
= 0; i
< iface_class
->interface_count
; ++i
)
1728 jclass interface
= iface_class
->interfaces
[i
];
1730 for (int j
= 0; j
< interface
->method_count
; ++j
)
1732 _Jv_Method
*meth
= &interface
->methods
[j
];
1733 // Don't bother with <clinit>.
1734 if (meth
->name
->first() == '<')
1736 _Jv_Method
*new_meth
= _Jv_LookupDeclaredMethod (base
, meth
->name
,
1740 // We assume that such methods are very unlikely, so we
1741 // just reallocate the method array each time one is
1742 // found. This greatly simplifies the searching --
1743 // otherwise we have to make sure that each such method
1744 // found is really unique among all superinterfaces.
1745 int new_count
= base
->method_count
+ 1;
1747 = (_Jv_Method
*) _Jv_AllocRawObj (sizeof (_Jv_Method
)
1749 memcpy (new_m
, base
->methods
,
1750 sizeof (_Jv_Method
) * base
->method_count
);
1753 new_m
[base
->method_count
] = *meth
;
1754 new_m
[base
->method_count
].index
= (_Jv_ushort
) -1;
1755 new_m
[base
->method_count
].accflags
1756 |= java::lang::reflect::Modifier::INVISIBLE
;
1758 base
->methods
= new_m
;
1759 base
->method_count
= new_count
;
1763 wait_for_state (interface
, JV_STATE_LOADED
);
1764 add_miranda_methods (base
, interface
);
1768 // This ensures that the class' method table is "complete". This must
1769 // be called with the class lock held.
1771 _Jv_Linker::ensure_method_table_complete (jclass klass
)
1773 if (klass
->vtable
!= NULL
)
1776 // We need our superclass to have its own Miranda methods installed.
1777 if (! klass
->isInterface())
1778 wait_for_state (klass
->getSuperclass (), JV_STATE_LOADED
);
1780 // A class might have so-called "Miranda methods". This is a method
1781 // that is declared in an interface and not re-declared in an
1782 // abstract class. Some compilers don't emit declarations for such
1783 // methods in the class; this will give us problems since we expect
1784 // a declaration for any method requiring a vtable entry. We handle
1785 // this here by searching for such methods and constructing new
1786 // internal declarations for them. Note that we do this
1787 // unconditionally, and not just for abstract classes, to correctly
1788 // account for cases where a class is modified to be concrete and
1789 // still incorrectly inherits an abstract method.
1790 int pre_count
= klass
->method_count
;
1791 add_miranda_methods (klass
, klass
);
1793 // Let the execution engine know that we've added methods.
1794 if (klass
->method_count
!= pre_count
)
1795 klass
->engine
->post_miranda_hook(klass
);
1798 // Verify a class. Must be called with class lock held.
1800 _Jv_Linker::verify_class (jclass klass
)
1802 klass
->engine
->verify(klass
);
1805 // Check the assertions contained in the type assertion table for KLASS.
1806 // This is the equivilent of bytecode verification for native, BC-ABI code.
1808 _Jv_Linker::verify_type_assertions (jclass klass
)
1811 fprintf (stderr
, "Evaluating type assertions for %s:\n",
1812 klass
->name
->chars());
1814 if (klass
->assertion_table
== NULL
)
1817 for (int i
= 0;; i
++)
1819 int assertion_code
= klass
->assertion_table
[i
].assertion_code
;
1820 _Jv_Utf8Const
*op1
= klass
->assertion_table
[i
].op1
;
1821 _Jv_Utf8Const
*op2
= klass
->assertion_table
[i
].op2
;
1823 if (assertion_code
== JV_ASSERT_END_OF_TABLE
)
1825 else if (assertion_code
== JV_ASSERT_TYPES_COMPATIBLE
)
1829 fprintf (stderr
, " code=%i, operand A=%s B=%s\n",
1830 assertion_code
, op1
->chars(), op2
->chars());
1833 // The operands are class signatures. op1 is the source,
1834 // op2 is the target.
1835 jclass cl1
= _Jv_FindClassFromSignature (op1
->chars(),
1836 klass
->getClassLoaderInternal());
1837 jclass cl2
= _Jv_FindClassFromSignature (op2
->chars(),
1838 klass
->getClassLoaderInternal());
1840 // If the class doesn't exist, ignore the assertion. An exception
1841 // will be thrown later if an attempt is made to actually
1842 // instantiate the class.
1843 if (cl1
== NULL
|| cl2
== NULL
)
1846 if (! _Jv_IsAssignableFromSlow (cl1
, cl2
))
1848 jstring s
= JvNewStringUTF ("Incompatible types: In class ");
1849 s
= s
->concat (klass
->getName());
1850 s
= s
->concat (JvNewStringUTF (": "));
1851 s
= s
->concat (cl1
->getName());
1852 s
= s
->concat (JvNewStringUTF (" is not assignable to "));
1853 s
= s
->concat (cl2
->getName());
1854 throw new java::lang::VerifyError (s
);
1857 else if (assertion_code
== JV_ASSERT_IS_INSTANTIABLE
)
1859 // TODO: Implement this.
1861 // Unknown assertion codes are ignored, for forwards-compatibility.
1866 _Jv_Linker::print_class_loaded (jclass klass
)
1868 char *codesource
= NULL
;
1869 if (klass
->protectionDomain
!= NULL
)
1871 java::security::CodeSource
*cs
1872 = klass
->protectionDomain
->getCodeSource();
1875 jstring css
= cs
->toString();
1876 int len
= JvGetStringUTFLength(css
);
1877 codesource
= (char *) _Jv_AllocBytes(len
+ 1);
1878 JvGetStringUTFRegion(css
, 0, css
->length(), codesource
);
1879 codesource
[len
] = '\0';
1882 if (codesource
== NULL
)
1883 codesource
= (char *) "<no code source>";
1886 if (_Jv_IsInterpretedClass (klass
))
1888 else if (_Jv_IsBinaryCompatibilityABI (klass
))
1889 abi
= "BC-compiled";
1891 abi
= "pre-compiled";
1893 fprintf (stderr
, "[Loaded (%s) %s from %s]\n", abi
, klass
->name
->chars(),
1897 // FIXME: mention invariants and stuff.
1899 _Jv_Linker::wait_for_state (jclass klass
, int state
)
1901 if (klass
->state
>= state
)
1904 JvSynchronize
sync (klass
);
1906 // This is similar to the strategy for class initialization. If we
1907 // already hold the lock, just leave.
1908 java::lang::Thread
*self
= java::lang::Thread::currentThread();
1909 while (klass
->state
<= state
1911 && klass
->thread
!= self
)
1914 java::lang::Thread
*save
= klass
->thread
;
1915 klass
->thread
= self
;
1917 // Allocate memory for static fields and constants.
1918 if (GC_base (klass
) && klass
->fields
&& ! GC_base (klass
->fields
))
1920 jsize count
= klass
->field_count
;
1924 = (_Jv_Field
*) _Jv_AllocRawObj (count
* sizeof (_Jv_Field
));
1925 memcpy ((void*)fields
,
1926 (void*)klass
->fields
,
1927 count
* sizeof (_Jv_Field
));
1928 klass
->fields
= fields
;
1932 // Print some debugging info if requested. Interpreted classes are
1933 // handled in defineclass, so we only need to handle the two
1934 // pre-compiled cases here.
1935 if (gcj::verbose_class_flag
1936 && (klass
->state
== JV_STATE_COMPILED
1937 || klass
->state
== JV_STATE_PRELOADING
)
1938 && ! _Jv_IsInterpretedClass (klass
))
1939 print_class_loaded (klass
);
1943 if (state
>= JV_STATE_LOADING
&& klass
->state
< JV_STATE_LOADING
)
1945 ensure_supers_installed (klass
);
1946 klass
->set_state(JV_STATE_LOADING
);
1949 if (state
>= JV_STATE_LOADED
&& klass
->state
< JV_STATE_LOADED
)
1951 ensure_method_table_complete (klass
);
1952 klass
->set_state(JV_STATE_LOADED
);
1955 if (state
>= JV_STATE_PREPARED
&& klass
->state
< JV_STATE_PREPARED
)
1957 ensure_fields_laid_out (klass
);
1958 make_vtable (klass
);
1959 layout_interface_methods (klass
);
1960 prepare_constant_time_tables (klass
);
1961 klass
->set_state(JV_STATE_PREPARED
);
1964 if (state
>= JV_STATE_LINKED
&& klass
->state
< JV_STATE_LINKED
)
1966 if (gcj::verifyClasses
)
1967 verify_class (klass
);
1969 ensure_class_linked (klass
);
1970 link_exception_table (klass
);
1971 link_symbol_table (klass
);
1972 klass
->set_state(JV_STATE_LINKED
);
1975 catch (java::lang::Throwable
*exc
)
1977 klass
->thread
= save
;
1978 klass
->set_state(JV_STATE_ERROR
);
1982 klass
->thread
= save
;
1984 if (klass
->state
== JV_STATE_ERROR
)
1985 throw new java::lang::LinkageError
;