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>
65 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
67 // This returns the alignment of a type as it would appear in a
68 // structure. This can be different from the alignment of the type
69 // itself. For instance on x86 double is 8-aligned but struct{double}
72 _Jv_Linker::get_alignment_from_class (jclass klass
)
74 if (klass
== JvPrimClass (byte
))
75 return ALIGNOF (jbyte
);
76 else if (klass
== JvPrimClass (short))
77 return ALIGNOF (jshort
);
78 else if (klass
== JvPrimClass (int))
79 return ALIGNOF (jint
);
80 else if (klass
== JvPrimClass (long))
81 return ALIGNOF (jlong
);
82 else if (klass
== JvPrimClass (boolean
))
83 return ALIGNOF (jboolean
);
84 else if (klass
== JvPrimClass (char))
85 return ALIGNOF (jchar
);
86 else if (klass
== JvPrimClass (float))
87 return ALIGNOF (jfloat
);
88 else if (klass
== JvPrimClass (double))
89 return ALIGNOF (jdouble
);
91 return ALIGNOF (jobject
);
95 _Jv_Linker::resolve_field (_Jv_Field
*field
, java::lang::ClassLoader
*loader
)
97 if (! field
->isResolved ())
99 _Jv_Utf8Const
*sig
= (_Jv_Utf8Const
*) field
->type
;
100 jclass type
= _Jv_FindClassFromSignature (sig
->chars(), loader
);
102 throw new java::lang::NoClassDefFoundError(field
->name
->toString());
104 field
->flags
&= ~_Jv_FIELD_UNRESOLVED_FLAG
;
108 // A helper for find_field that knows how to recursively search
109 // superclasses and interfaces.
111 _Jv_Linker::find_field_helper (jclass search
, _Jv_Utf8Const
*name
,
112 _Jv_Utf8Const
*type_name
, jclass type
,
117 // From 5.4.3.2. First search class itself.
118 for (int i
= 0; i
< search
->field_count
; ++i
)
120 _Jv_Field
*field
= &search
->fields
[i
];
121 if (! _Jv_equalUtf8Consts (field
->name
, name
))
124 // Checks for the odd situation where we were able to retrieve the
125 // field's class from signature but the resolution of the field itself
126 // failed which means a different class was resolved.
131 resolve_field (field
, search
->loader
);
133 catch (java::lang::Throwable
*exc
)
135 java::lang::LinkageError
*le
= new java::lang::LinkageError
137 ("field type mismatch with different loaders"));
145 // Note that we compare type names and not types. This is
146 // bizarre, but we do it because we want to find a field
147 // (and terminate the search) if it has the correct
148 // descriptor -- but then later reject it if the class
149 // loader check results in different classes. We can't just
150 // pass in the descriptor and check that way, because when
151 // the field is already resolved there is no easy way to
152 // find its descriptor again.
153 if ((field
->isResolved ()
154 ? _Jv_equalUtf8Classnames (type_name
, field
->type
->name
)
155 : _Jv_equalUtf8Classnames (type_name
,
156 (_Jv_Utf8Const
*) field
->type
)))
163 // Next search direct interfaces.
164 for (int i
= 0; i
< search
->interface_count
; ++i
)
166 _Jv_Field
*result
= find_field_helper (search
->interfaces
[i
], name
,
167 type_name
, type
, declarer
);
172 // Now search superclass.
173 search
= search
->superclass
;
180 _Jv_Linker::has_field_p (jclass search
, _Jv_Utf8Const
*field_name
)
182 for (int i
= 0; i
< search
->field_count
; ++i
)
184 _Jv_Field
*field
= &search
->fields
[i
];
185 if (_Jv_equalUtf8Consts (field
->name
, field_name
))
192 // KLASS is the class that is requesting the field.
193 // OWNER is the class in which the field should be found.
194 // FIELD_TYPE_NAME is the type descriptor for the field.
195 // Fill FOUND_CLASS with the address of the class in which the field
196 // is actually declared.
197 // This function does the class loader type checks, and
198 // also access checks. Returns the field, or throws an
199 // exception on error.
201 _Jv_Linker::find_field (jclass klass
, jclass owner
,
203 _Jv_Utf8Const
*field_name
,
204 _Jv_Utf8Const
*field_type_name
)
206 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
208 // Note: This call will resolve the primitive type names ("Z", "B", ...) to
209 // their Java counterparts ("boolean", "byte", ...) if accessed via
210 // field_type->name later. Using these variants of the type name is in turn
211 // important for the find_field_helper function. However if the class
212 // resolution failed then we can only use the already given type name.
214 = _Jv_FindClassFromSignatureNoException (field_type_name
->chars(),
218 = find_field_helper (owner
, field_name
,
222 field_type
, found_class
);
226 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
227 sb
->append(JvNewStringLatin1("field "));
228 sb
->append(owner
->getName());
229 sb
->append(JvNewStringLatin1("."));
230 sb
->append(_Jv_NewStringUTF(field_name
->chars()));
231 sb
->append(JvNewStringLatin1(" was not found."));
232 throw new java::lang::NoSuchFieldError (sb
->toString());
235 // Accept it when the field's class could not be resolved.
236 if (field_type
== NULL
)
237 // Silently ignore that we were not able to retrieve the type to make it
238 // possible to run code which does not access this field.
241 if (_Jv_CheckAccess (klass
, *found_class
, the_field
->flags
))
243 // Note that the field returned by find_field_helper is always
244 // resolved. There's no point checking class loaders here,
245 // since we already did the work to look up all the types.
246 // FIXME: being lazy here would be nice.
247 if (the_field
->type
!= field_type
)
248 throw new java::lang::LinkageError
250 ("field type mismatch with different loaders"));
254 java::lang::StringBuffer
*sb
255 = new java::lang::StringBuffer ();
256 sb
->append(klass
->getName());
257 sb
->append(JvNewStringLatin1(": "));
258 sb
->append((*found_class
)->getName());
259 sb
->append(JvNewStringLatin1("."));
260 sb
->append(_Jv_NewStringUtf8Const (field_name
));
261 throw new java::lang::IllegalAccessError(sb
->toString());
268 _Jv_Linker::resolve_pool_entry (jclass klass
, int index
, bool lazy
)
270 using namespace java::lang::reflect
;
272 if (GC_base (klass
) && klass
->constants
.data
273 && ! GC_base (klass
->constants
.data
))
275 jsize count
= klass
->constants
.size
;
279 = (_Jv_word
*) _Jv_AllocRawObj (count
* sizeof (_Jv_word
));
280 memcpy ((void*)constants
,
281 (void*)klass
->constants
.data
,
282 count
* sizeof (_Jv_word
));
283 klass
->constants
.data
= constants
;
287 _Jv_Constants
*pool
= &klass
->constants
;
289 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
290 return pool
->data
[index
];
292 switch (pool
->tags
[index
])
294 case JV_CONSTANT_Class
:
296 _Jv_Utf8Const
*name
= pool
->data
[index
].utf8
;
299 if (name
->first() == '[')
300 found
= _Jv_FindClassFromSignatureNoException (name
->chars(),
303 found
= _Jv_FindClassNoException (name
, klass
->loader
);
305 // If the class could not be loaded a phantom class is created. Any
306 // function that deals with such a class but cannot do something useful
307 // with it should just throw a NoClassDefFoundError with the class'
312 found
= _Jv_NewClass(name
, NULL
, NULL
);
313 found
->state
= JV_STATE_PHANTOM
;
314 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
315 pool
->data
[index
].clazz
= found
;
319 throw new java::lang::NoClassDefFoundError (name
->toString());
321 // Check accessibility, but first strip array types as
322 // _Jv_ClassNameSamePackage can't handle arrays.
325 check
&& check
->isArray();
326 check
= check
->getComponentType())
328 if ((found
->accflags
& Modifier::PUBLIC
) == Modifier::PUBLIC
329 || (_Jv_ClassNameSamePackage (check
->name
,
332 pool
->data
[index
].clazz
= found
;
333 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
337 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer ();
338 sb
->append(klass
->getName());
339 sb
->append(JvNewStringLatin1(" can't access class "));
340 sb
->append(found
->getName());
341 throw new java::lang::IllegalAccessError(sb
->toString());
346 case JV_CONSTANT_String
:
349 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
350 pool
->data
[index
].o
= str
;
351 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
355 case JV_CONSTANT_Fieldref
:
357 _Jv_ushort class_index
, name_and_type_index
;
358 _Jv_loadIndexes (&pool
->data
[index
],
360 name_and_type_index
);
361 jclass owner
= (resolve_pool_entry (klass
, class_index
, true)).clazz
;
363 // If a phantom class was resolved our field reference is
364 // unusable because of the missing class.
365 if (owner
->state
== JV_STATE_PHANTOM
)
366 throw new java::lang::NoClassDefFoundError(owner
->getName());
369 _Jv_InitClass (owner
);
371 _Jv_ushort name_index
, type_index
;
372 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
376 _Jv_Utf8Const
*field_name
= pool
->data
[name_index
].utf8
;
377 _Jv_Utf8Const
*field_type_name
= pool
->data
[type_index
].utf8
;
379 jclass found_class
= 0;
380 _Jv_Field
*the_field
= find_field (klass
, owner
,
384 if (owner
!= found_class
)
385 _Jv_InitClass (found_class
);
386 pool
->data
[index
].field
= the_field
;
387 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
391 case JV_CONSTANT_Methodref
:
392 case JV_CONSTANT_InterfaceMethodref
:
394 _Jv_ushort class_index
, name_and_type_index
;
395 _Jv_loadIndexes (&pool
->data
[index
],
397 name_and_type_index
);
398 jclass owner
= (resolve_pool_entry (klass
, class_index
)).clazz
;
401 _Jv_InitClass (owner
);
403 _Jv_ushort name_index
, type_index
;
404 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
408 _Jv_Utf8Const
*method_name
= pool
->data
[name_index
].utf8
;
409 _Jv_Utf8Const
*method_signature
= pool
->data
[type_index
].utf8
;
411 _Jv_Method
*the_method
= 0;
412 jclass found_class
= 0;
414 // We're going to cache a pointer to the _Jv_Method object
415 // when we find it. So, to ensure this doesn't get moved from
416 // beneath us, we first put all the needed Miranda methods
417 // into the target class.
418 wait_for_state (klass
, JV_STATE_LOADED
);
420 // First search the class itself.
421 the_method
= search_method_in_class (owner
, klass
,
422 method_name
, method_signature
);
427 goto end_of_method_search
;
430 // If we are resolving an interface method, search the
431 // interface's superinterfaces (A superinterface is not an
432 // interface's superclass - a superinterface is implemented by
434 if (pool
->tags
[index
] == JV_CONSTANT_InterfaceMethodref
)
439 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
440 * sizeof (jclass
*));
442 get_interfaces (owner
, &ifaces
);
444 for (int i
= 0; i
< ifaces
.count
; i
++)
446 jclass cls
= ifaces
.list
[i
];
447 the_method
= search_method_in_class (cls
, klass
, method_name
,
456 _Jv_Free (ifaces
.list
);
459 goto end_of_method_search
;
462 // Finally, search superclasses.
463 the_method
= (search_method_in_superclasses
464 (owner
->getSuperclass (), klass
, method_name
,
465 method_signature
, &found_class
));
467 end_of_method_search
:
469 // FIXME: if (cls->loader != klass->loader), then we
470 // must actually check that the types of arguments
471 // correspond. That is, for each argument type, and
472 // the return type, doing _Jv_FindClassFromSignature
473 // with either loader should produce the same result,
474 // i.e., exactly the same jclass object. JVMS 5.4.3.3
478 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
479 sb
->append(JvNewStringLatin1("method "));
480 sb
->append(owner
->getName());
481 sb
->append(JvNewStringLatin1("."));
482 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
483 sb
->append(JvNewStringLatin1(" with signature "));
484 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
485 sb
->append(JvNewStringLatin1(" was not found."));
486 throw new java::lang::NoSuchMethodError (sb
->toString());
489 pool
->data
[index
].rmethod
490 = klass
->engine
->resolve_method(the_method
,
492 ((the_method
->accflags
493 & Modifier::STATIC
) != 0));
494 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
498 return pool
->data
[index
];
501 // This function is used to lazily locate superclasses and
502 // superinterfaces. This must be called with the class lock held.
504 _Jv_Linker::resolve_class_ref (jclass klass
, jclass
*classref
)
506 jclass ret
= *classref
;
508 // If superclass looks like a constant pool entry, resolve it now.
509 if (ret
&& (uaddr
) ret
< (uaddr
) klass
->constants
.size
)
511 if (klass
->state
< JV_STATE_LINKED
)
513 _Jv_Utf8Const
*name
= klass
->constants
.data
[(uaddr
) *classref
].utf8
;
514 ret
= _Jv_FindClass (name
, klass
->loader
);
517 throw new java::lang::NoClassDefFoundError (name
->toString());
521 ret
= klass
->constants
.data
[(uaddr
) classref
].clazz
;
526 // Find a method declared in the cls that is referenced from klass and
527 // perform access checks if CHECK_PERMS is true.
529 _Jv_Linker::search_method_in_class (jclass cls
, jclass klass
,
530 _Jv_Utf8Const
*method_name
,
531 _Jv_Utf8Const
*method_signature
,
534 using namespace java::lang::reflect
;
536 for (int i
= 0; i
< cls
->method_count
; i
++)
538 _Jv_Method
*method
= &cls
->methods
[i
];
539 if ( (!_Jv_equalUtf8Consts (method
->name
,
541 || (!_Jv_equalUtf8Consts (method
->signature
,
545 if (!check_perms
|| _Jv_CheckAccess (klass
, cls
, method
->accflags
))
549 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
550 sb
->append(klass
->getName());
551 sb
->append(JvNewStringLatin1(": "));
552 sb
->append(cls
->getName());
553 sb
->append(JvNewStringLatin1("."));
554 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
555 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
556 throw new java::lang::IllegalAccessError (sb
->toString());
562 // Like search_method_in_class, but work our way up the superclass
565 _Jv_Linker::search_method_in_superclasses (jclass cls
, jclass klass
,
566 _Jv_Utf8Const
*method_name
,
567 _Jv_Utf8Const
*method_signature
,
568 jclass
*found_class
, bool check_perms
)
570 _Jv_Method
*the_method
= NULL
;
572 for ( ; cls
!= 0; cls
= cls
->getSuperclass ())
574 the_method
= search_method_in_class (cls
, klass
, method_name
,
575 method_signature
, check_perms
);
587 #define INITIAL_IOFFSETS_LEN 4
588 #define INITIAL_IFACES_LEN 4
590 static _Jv_IDispatchTable null_idt
= {SHRT_MAX
, 0, {}};
592 // Generate tables for constant-time assignment testing and interface
593 // method lookup. This implements the technique described by Per Bothner
594 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
595 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
597 _Jv_Linker::prepare_constant_time_tables (jclass klass
)
599 if (klass
->isPrimitive () || klass
->isInterface ())
602 // Short-circuit in case we've been called already.
603 if ((klass
->idt
!= NULL
) || klass
->depth
!= 0)
606 // Calculate the class depth and ancestor table. The depth of a class
607 // is how many "extends" it is removed from Object. Thus the depth of
608 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
609 // is 2. Depth is defined for all regular and array classes, but not
610 // interfaces or primitive types.
612 jclass klass0
= klass
;
613 jboolean has_interfaces
= 0;
614 while (klass0
!= &java::lang::Object::class$
)
616 has_interfaces
+= klass0
->interface_count
;
617 klass0
= klass0
->superclass
;
621 // We do class member testing in constant time by using a small table
622 // of all the ancestor classes within each class. The first element is
623 // a pointer to the current class, and the rest are pointers to the
624 // classes ancestors, ordered from the current class down by decreasing
625 // depth. We do not include java.lang.Object in the table of ancestors,
626 // since it is redundant. Note that the classes pointed to by
627 // 'ancestors' will always be reachable by other paths.
629 klass
->ancestors
= (jclass
*) _Jv_AllocBytes (klass
->depth
632 for (int index
= 0; index
< klass
->depth
; index
++)
634 klass
->ancestors
[index
] = klass0
;
635 klass0
= klass0
->superclass
;
638 if ((klass
->accflags
& java::lang::reflect::Modifier::ABSTRACT
) != 0)
641 // Optimization: If class implements no interfaces, use a common
642 // predefined interface table.
645 klass
->idt
= &null_idt
;
651 ifaces
.len
= INITIAL_IFACES_LEN
;
652 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
* sizeof (jclass
*));
654 int itable_size
= get_interfaces (klass
, &ifaces
);
656 if (ifaces
.count
> 0)
658 // The classes pointed to by the itable will always be reachable
660 int idt_bytes
= sizeof (_Jv_IDispatchTable
) + (itable_size
662 klass
->idt
= (_Jv_IDispatchTable
*) _Jv_AllocBytes (idt_bytes
);
663 klass
->idt
->itable_length
= itable_size
;
665 jshort
*itable_offsets
=
666 (jshort
*) _Jv_Malloc (ifaces
.count
* sizeof (jshort
));
668 generate_itable (klass
, &ifaces
, itable_offsets
);
670 jshort cls_iindex
= find_iindex (ifaces
.list
, itable_offsets
,
673 for (int i
= 0; i
< ifaces
.count
; i
++)
675 ifaces
.list
[i
]->ioffsets
[cls_iindex
] = itable_offsets
[i
];
678 klass
->idt
->iindex
= cls_iindex
;
680 _Jv_Free (ifaces
.list
);
681 _Jv_Free (itable_offsets
);
685 klass
->idt
->iindex
= SHRT_MAX
;
689 // Return index of item in list, or -1 if item is not present.
691 _Jv_Linker::indexof (void *item
, void **list
, jshort list_len
)
693 for (int i
=0; i
< list_len
; i
++)
701 // Find all unique interfaces directly or indirectly implemented by klass.
702 // Returns the size of the interface dispatch table (itable) for klass, which
703 // is the number of unique interfaces plus the total number of methods that
704 // those interfaces declare. May extend ifaces if required.
706 _Jv_Linker::get_interfaces (jclass klass
, _Jv_ifaces
*ifaces
)
710 for (int i
= 0; i
< klass
->interface_count
; i
++)
712 jclass iface
= klass
->interfaces
[i
];
714 /* Make sure interface is linked. */
715 wait_for_state(iface
, JV_STATE_LINKED
);
717 if (indexof (iface
, (void **) ifaces
->list
, ifaces
->count
) == -1)
719 if (ifaces
->count
+ 1 >= ifaces
->len
)
721 /* Resize ifaces list */
722 ifaces
->len
= ifaces
->len
* 2;
724 = (jclass
*) _Jv_Realloc (ifaces
->list
,
725 ifaces
->len
* sizeof(jclass
));
727 ifaces
->list
[ifaces
->count
] = iface
;
730 result
+= get_interfaces (klass
->interfaces
[i
], ifaces
);
734 if (klass
->isInterface())
736 // We want to add 1 plus the number of interface methods here.
737 // But, we take special care to skip <clinit>.
739 for (int i
= 0; i
< klass
->method_count
; ++i
)
741 if (klass
->methods
[i
].name
->first() != '<')
745 else if (klass
->superclass
)
746 result
+= get_interfaces (klass
->superclass
, ifaces
);
750 // Fill out itable in klass, resolving method declarations in each ifaces.
751 // itable_offsets is filled out with the position of each iface in itable,
752 // such that itable[itable_offsets[n]] == ifaces.list[n].
754 _Jv_Linker::generate_itable (jclass klass
, _Jv_ifaces
*ifaces
,
755 jshort
*itable_offsets
)
757 void **itable
= klass
->idt
->itable
;
758 jshort itable_pos
= 0;
760 for (int i
= 0; i
< ifaces
->count
; i
++)
762 jclass iface
= ifaces
->list
[i
];
763 itable_offsets
[i
] = itable_pos
;
764 itable_pos
= append_partial_itable (klass
, iface
, itable
, itable_pos
);
766 /* Create ioffsets table for iface */
767 if (iface
->ioffsets
== NULL
)
769 // The first element of ioffsets is its length (itself included).
770 jshort
*ioffsets
= (jshort
*) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
772 ioffsets
[0] = INITIAL_IOFFSETS_LEN
;
773 for (int i
= 1; i
< INITIAL_IOFFSETS_LEN
; i
++)
776 iface
->ioffsets
= ioffsets
;
781 // Format method name for use in error messages.
783 _Jv_GetMethodString (jclass klass
, _Jv_Method
*meth
,
786 using namespace java::lang
;
787 StringBuffer
*buf
= new StringBuffer (klass
->name
->toString());
788 buf
->append (jchar ('.'));
789 buf
->append (meth
->name
->toString());
790 buf
->append ((jchar
) ' ');
791 buf
->append (meth
->signature
->toString());
794 buf
->append(JvNewStringLatin1(" in "));
795 buf
->append(derived
->name
->toString());
797 return buf
->toString();
801 _Jv_ThrowNoSuchMethodError ()
803 throw new java::lang::NoSuchMethodError
;
806 #if defined USE_LIBFFI && FFI_CLOSURES
807 // A function whose invocation is prepared using libffi. It gets called
808 // whenever a static method of a missing class is invoked. The data argument
809 // holds a reference to a String denoting the missing class.
810 // The prepared function call is stored in a class' atable.
812 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif
*,
817 throw new java::lang::NoClassDefFoundError(
818 _Jv_NewStringUtf8Const((_Jv_Utf8Const
*) data
));
821 // A variant of the NoClassDefFoundError throwing method that can
822 // be used without libffi.
824 _Jv_ThrowNoClassDefFoundError()
826 throw new java::lang::NoClassDefFoundError();
830 // Throw a NoSuchFieldError. Called by compiler-generated code when
831 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
832 // otable that refers to the missing field. This index may be used to
833 // print diagnostic information about the field.
835 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
837 throw new java::lang::NoSuchFieldError
;
840 // This is put in empty vtable slots.
842 _Jv_ThrowAbstractMethodError ()
844 throw new java::lang::AbstractMethodError();
847 // Each superinterface of a class (i.e. each interface that the class
848 // directly or indirectly implements) has a corresponding "Partial
849 // Interface Dispatch Table" whose size is (number of methods + 1) words.
850 // The first word is a pointer to the interface (i.e. the java.lang.Class
851 // instance for that interface). The remaining words are pointers to the
852 // actual methods that implement the methods declared in the interface,
853 // in order of declaration.
855 // Append partial interface dispatch table for "iface" to "itable", at
856 // position itable_pos.
857 // Returns the offset at which the next partial ITable should be appended.
859 _Jv_Linker::append_partial_itable (jclass klass
, jclass iface
,
860 void **itable
, jshort pos
)
862 using namespace java::lang::reflect
;
864 itable
[pos
++] = (void *) iface
;
867 for (int j
=0; j
< iface
->method_count
; j
++)
869 // Skip '<clinit>' here.
870 if (iface
->methods
[j
].name
->first() == '<')
874 for (jclass cl
= klass
; cl
; cl
= cl
->getSuperclass())
876 meth
= _Jv_GetMethodLocal (cl
, iface
->methods
[j
].name
,
877 iface
->methods
[j
].signature
);
885 if ((meth
->accflags
& Modifier::STATIC
) != 0)
886 throw new java::lang::IncompatibleClassChangeError
887 (_Jv_GetMethodString (klass
, meth
));
888 if ((meth
->accflags
& Modifier::PUBLIC
) == 0)
889 throw new java::lang::IllegalAccessError
890 (_Jv_GetMethodString (klass
, meth
));
892 if ((meth
->accflags
& Modifier::ABSTRACT
) != 0)
893 itable
[pos
] = (void *) &_Jv_ThrowAbstractMethodError
;
895 itable
[pos
] = meth
->ncode
;
899 // The method doesn't exist in klass. Binary compatibility rules
900 // permit this, so we delay the error until runtime using a pointer
901 // to a method which throws an exception.
902 itable
[pos
] = (void *) _Jv_ThrowNoSuchMethodError
;
910 static _Jv_Mutex_t iindex_mutex
;
911 static bool iindex_mutex_initialized
= false;
913 // We need to find the correct offset in the Class Interface Dispatch
914 // Table for a given interface. Once we have that, invoking an interface
915 // method just requires combining the Method's index in the interface
916 // (known at compile time) to get the correct method. Doing a type test
917 // (cast or instanceof) is the same problem: Once we have a possible Partial
918 // Interface Dispatch Table, we just compare the first element to see if it
919 // matches the desired interface. So how can we find the correct offset?
920 // Our solution is to keep a vector of candiate offsets in each interface
921 // (ioffsets), and in each class we have an index (idt->iindex) used to
922 // select the correct offset from ioffsets.
924 // Calculate and return iindex for a new class.
925 // ifaces is a vector of num interfaces that the class implements.
926 // offsets[j] is the offset in the interface dispatch table for the
927 // interface corresponding to ifaces[j].
928 // May extend the interface ioffsets if required.
930 _Jv_Linker::find_iindex (jclass
*ifaces
, jshort
*offsets
, jshort num
)
935 // Acquire a global lock to prevent itable corruption in case of multiple
936 // classes that implement an intersecting set of interfaces being linked
937 // simultaneously. We can assume that the mutex will be initialized
939 if (! iindex_mutex_initialized
)
941 _Jv_MutexInit (&iindex_mutex
);
942 iindex_mutex_initialized
= true;
945 _Jv_MutexLock (&iindex_mutex
);
947 for (i
=1;; i
++) /* each potential position in ioffsets */
949 for (j
=0;; j
++) /* each iface */
953 if (i
>= ifaces
[j
]->ioffsets
[0])
955 int ioffset
= ifaces
[j
]->ioffsets
[i
];
956 /* We can potentially share this position with another class. */
957 if (ioffset
>= 0 && ioffset
!= offsets
[j
])
958 break; /* Nope. Try next i. */
962 for (j
= 0; j
< num
; j
++)
964 int len
= ifaces
[j
]->ioffsets
[0];
968 int newlen
= 2 * len
;
972 jshort
*old_ioffsets
= ifaces
[j
]->ioffsets
;
973 jshort
*new_ioffsets
= (jshort
*) _Jv_AllocBytes (newlen
975 memcpy (&new_ioffsets
[1], &old_ioffsets
[1],
976 (len
- 1) * sizeof (jshort
));
977 new_ioffsets
[0] = newlen
;
980 new_ioffsets
[len
++] = -1;
982 ifaces
[j
]->ioffsets
= new_ioffsets
;
984 ifaces
[j
]->ioffsets
[i
] = offsets
[j
];
987 _Jv_MutexUnlock (&iindex_mutex
);
992 #if defined USE_LIBFFI && FFI_CLOSURES
993 // We use a structure of this type to store the closure that
994 // represents a missing method.
995 struct method_closure
997 // This field must come first, since the address of this field will
998 // be the same as the address of the overall structure. This is due
999 // to disabling interior pointers in the GC.
1000 ffi_closure closure
;
1002 ffi_type
*arg_types
[1];
1006 _Jv_Linker::create_error_method (_Jv_Utf8Const
*class_name
)
1008 method_closure
*closure
1009 = (method_closure
*) _Jv_AllocBytes(sizeof (method_closure
));
1011 closure
->arg_types
[0] = &ffi_type_void
;
1013 // Initializes the cif and the closure. If that worked the closure
1014 // is returned and can be used as a function pointer in a class'
1016 if ( ffi_prep_cif (&closure
->cif
,
1020 closure
->arg_types
) == FFI_OK
1021 && ffi_prep_closure (&closure
->closure
,
1023 _Jv_ThrowNoClassDefFoundErrorTrampoline
,
1024 class_name
) == FFI_OK
)
1025 return &closure
->closure
;
1028 java::lang::StringBuffer
*buffer
= new java::lang::StringBuffer();
1029 buffer
->append(JvNewStringLatin1("Error setting up FFI closure"
1030 " for static method of"
1031 " missing class: "));
1032 buffer
->append (_Jv_NewStringUtf8Const(class_name
));
1033 throw new java::lang::InternalError(buffer
->toString());
1038 _Jv_Linker::create_error_method (_Jv_Utf8Const
*)
1040 // Codepath for platforms which do not support (or want) libffi.
1041 // You have to accept that it is impossible to provide the name
1042 // of the missing class then.
1043 return (void *) _Jv_ThrowNoClassDefFoundError
;
1045 #endif // USE_LIBFFI && FFI_CLOSURES
1047 // Functions for indirect dispatch (symbolic virtual binding) support.
1049 // There are three tables, atable otable and itable. atable is an
1050 // array of addresses, and otable is an array of offsets, and these
1051 // are used for static and virtual members respectively. itable is an
1052 // array of pairs {address, index} where each address is a pointer to
1055 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1056 // symbol is a tuple of {classname, member name, signature}.
1058 // Set this to true to enable debugging of indirect dispatch tables/linking.
1059 static bool debug_link
= false;
1061 // link_symbol_table() scans these two arrays and fills in the
1062 // corresponding atable and otable with the addresses of static
1063 // members and the offsets of virtual members.
1065 // The offset (in bytes) for each resolved method or field is placed
1066 // at the corresponding position in the virtual method offset table
1069 // The same otable and atable may be shared by many classes.
1071 // This must be called while holding the class lock.
1074 _Jv_Linker::link_symbol_table (jclass klass
)
1077 _Jv_MethodSymbol sym
;
1078 if (klass
->otable
== NULL
1079 || klass
->otable
->state
!= 0)
1082 klass
->otable
->state
= 1;
1085 fprintf (stderr
, "Fixing up otable in %s:\n", klass
->name
->chars());
1087 (sym
= klass
->otable_syms
[index
]).class_name
!= NULL
;
1090 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1091 _Jv_Method
*meth
= NULL
;
1093 _Jv_Utf8Const
*signature
= sym
.signature
;
1095 maybe_adjust_signature (signature
, special
);
1097 if (target_class
== NULL
)
1098 throw new java::lang::NoClassDefFoundError
1099 (_Jv_NewStringUTF (sym
.class_name
->chars()));
1101 // We're looking for a field or a method, and we can tell
1102 // which is needed by looking at the signature.
1103 if (signature
->first() == '(' && signature
->len() >= 2)
1105 // Looks like someone is trying to invoke an interface method
1106 if (target_class
->isInterface())
1108 using namespace java::lang
;
1109 StringBuffer
*sb
= new StringBuffer();
1110 sb
->append(JvNewStringLatin1("found interface "));
1111 sb
->append(target_class
->getName());
1112 sb
->append(JvNewStringLatin1(" when searching for a class"));
1113 throw new VerifyError(sb
->toString());
1116 // If the target class does not have a vtable_method_count yet,
1117 // then we can't tell the offsets for its methods, so we must lay
1119 wait_for_state(target_class
, JV_STATE_PREPARED
);
1123 meth
= (search_method_in_superclasses
1124 (target_class
, klass
, sym
.name
, signature
,
1125 NULL
, special
== 0));
1127 catch (::java::lang::IllegalAccessError
*e
)
1131 // Every class has a throwNoSuchMethodErrorIndex method that
1132 // it inherits from java.lang.Object. Find its vtable
1134 static int throwNoSuchMethodErrorIndex
;
1135 if (throwNoSuchMethodErrorIndex
== 0)
1138 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1139 strlen ("throwNoSuchMethodError"));
1141 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$
,
1142 name
, gcj::void_signature
);
1143 throwNoSuchMethodErrorIndex
1144 = _Jv_VTable::idx_to_offset (meth
->index
);
1147 // If we don't find a nonstatic method, insert the
1148 // vtable index of Object.throwNoSuchMethodError().
1149 // This defers the missing method error until an attempt
1150 // is made to execute it.
1155 offset
= _Jv_VTable::idx_to_offset (meth
->index
);
1157 offset
= throwNoSuchMethodErrorIndex
;
1160 JvFail ("Bad method index");
1161 JvAssert (meth
->index
< target_class
->vtable_method_count
);
1163 klass
->otable
->offsets
[index
] = offset
;
1167 fprintf (stderr
, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1169 (int)klass
->otable
->offsets
[index
],
1170 (const char*)target_class
->name
->chars(),
1172 (const char*)sym
.name
->chars(),
1173 (const char*)signature
->chars());
1179 wait_for_state(target_class
, JV_STATE_PREPARED
);
1181 _Jv_Field
*the_field
= NULL
;
1184 the_field
= find_field (klass
, target_class
, &found_class
,
1185 sym
.name
, signature
);
1186 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1187 throw new java::lang::IncompatibleClassChangeError
;
1189 klass
->otable
->offsets
[index
] = the_field
->u
.boffset
;
1191 catch (java::lang::NoSuchFieldError
*err
)
1193 klass
->otable
->offsets
[index
] = 0;
1199 if (klass
->atable
== NULL
|| klass
->atable
->state
!= 0)
1202 klass
->atable
->state
= 1;
1205 (sym
= klass
->atable_syms
[index
]).class_name
!= NULL
;
1208 jclass target_class
=
1209 _Jv_FindClassNoException (sym
.class_name
, klass
->loader
);
1211 _Jv_Method
*meth
= NULL
;
1213 _Jv_Utf8Const
*signature
= sym
.signature
;
1215 maybe_adjust_signature (signature
, special
);
1217 // ??? Setting this pointer to null will at least get us a
1218 // NullPointerException
1219 klass
->atable
->addresses
[index
] = NULL
;
1221 // If the target class is missing we prepare a function call
1222 // that throws a NoClassDefFoundError and store the address of
1223 // that newly prepared method in the atable. The user can run
1224 // code in classes where the missing class is part of the
1225 // execution environment as long as it is never referenced.
1226 if (target_class
== NULL
)
1227 klass
->atable
->addresses
[index
] = create_error_method(sym
.class_name
);
1228 // We're looking for a static field or a static method, and we
1229 // can tell which is needed by looking at the signature.
1230 else if (signature
->first() == '(' && signature
->len() >= 2)
1232 // If the target class does not have a vtable_method_count yet,
1233 // then we can't tell the offsets for its methods, so we must lay
1235 wait_for_state (target_class
, JV_STATE_PREPARED
);
1237 // Interface methods cannot have bodies.
1238 if (target_class
->isInterface())
1240 using namespace java::lang
;
1241 StringBuffer
*sb
= new StringBuffer();
1242 sb
->append(JvNewStringLatin1("class "));
1243 sb
->append(target_class
->getName());
1244 sb
->append(JvNewStringLatin1(" is an interface: "
1246 throw new VerifyError(sb
->toString());
1251 meth
= (search_method_in_superclasses
1252 (target_class
, klass
, sym
.name
, signature
,
1253 NULL
, special
== 0));
1255 catch (::java::lang::IllegalAccessError
*e
)
1261 if (meth
->ncode
) // Maybe abstract?
1263 klass
->atable
->addresses
[index
] = meth
->ncode
;
1265 fprintf (stderr
, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1267 &klass
->atable
->addresses
[index
],
1268 (const char*)target_class
->name
->chars(),
1270 (const char*)sym
.name
->chars(),
1271 (const char*)signature
->chars());
1275 klass
->atable
->addresses
[index
]
1276 = create_error_method(sym
.class_name
);
1281 // Try fields only if the target class exists.
1282 if (target_class
!= NULL
)
1284 wait_for_state(target_class
, JV_STATE_PREPARED
);
1286 _Jv_Field
*the_field
= find_field (klass
, target_class
, &found_class
,
1287 sym
.name
, signature
);
1288 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1289 klass
->atable
->addresses
[index
] = the_field
->u
.addr
;
1291 throw new java::lang::IncompatibleClassChangeError
;
1296 if (klass
->itable
== NULL
1297 || klass
->itable
->state
!= 0)
1300 klass
->itable
->state
= 1;
1303 (sym
= klass
->itable_syms
[index
]).class_name
!= NULL
;
1306 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1308 _Jv_Utf8Const
*signature
= sym
.signature
;
1310 maybe_adjust_signature (signature
, special
);
1315 wait_for_state(target_class
, JV_STATE_LOADED
);
1316 bool found
= _Jv_getInterfaceMethod (target_class
, cls
, i
,
1317 sym
.name
, signature
);
1321 klass
->itable
->addresses
[index
* 2] = cls
;
1322 klass
->itable
->addresses
[index
* 2 + 1] = (void *)(unsigned long) i
;
1325 fprintf (stderr
, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1327 klass
->itable
->addresses
[index
* 2],
1328 (const char*)cls
->name
->chars(),
1330 (const char*)sym
.name
->chars(),
1331 (const char*)signature
->chars());
1332 fprintf (stderr
, " [%d] = offset %d\n",
1334 (int)(unsigned long)klass
->itable
->addresses
[index
* 2 + 1]);
1339 throw new java::lang::IncompatibleClassChangeError
;
1344 // For each catch_record in the list of caught classes, fill in the
1347 _Jv_Linker::link_exception_table (jclass self
)
1349 struct _Jv_CatchClass
*catch_record
= self
->catch_classes
;
1350 if (!catch_record
|| catch_record
->classname
)
1353 while (catch_record
->classname
)
1358 = _Jv_FindClass (catch_record
->classname
,
1359 self
->getClassLoaderInternal ());
1360 *catch_record
->address
= target_class
;
1362 catch (::java::lang::Throwable
*t
)
1364 // FIXME: We need to do something better here.
1365 *catch_record
->address
= 0;
1369 self
->catch_classes
->classname
= (_Jv_Utf8Const
*)-1;
1372 // Set itable method indexes for members of interface IFACE.
1374 _Jv_Linker::layout_interface_methods (jclass iface
)
1376 if (! iface
->isInterface())
1379 // itable indexes start at 1.
1380 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1381 // itable so they are also assigned an index here.
1382 for (int i
= 0; i
< iface
->method_count
; i
++)
1383 iface
->methods
[i
].index
= i
+ 1;
1386 // Prepare virtual method declarations in KLASS, and any superclasses
1387 // as required, by determining their vtable index, setting
1388 // method->index, and finally setting the class's vtable_method_count.
1389 // Must be called with the lock for KLASS held.
1391 _Jv_Linker::layout_vtable_methods (jclass klass
)
1393 if (klass
->vtable
!= NULL
|| klass
->isInterface()
1394 || klass
->vtable_method_count
!= -1)
1397 jclass superclass
= klass
->getSuperclass();
1399 if (superclass
!= NULL
&& superclass
->vtable_method_count
== -1)
1401 JvSynchronize
sync (superclass
);
1402 layout_vtable_methods (superclass
);
1405 int index
= (superclass
== NULL
? 0 : superclass
->vtable_method_count
);
1407 for (int i
= 0; i
< klass
->method_count
; ++i
)
1409 _Jv_Method
*meth
= &klass
->methods
[i
];
1410 _Jv_Method
*super_meth
= NULL
;
1412 if (! _Jv_isVirtualMethod (meth
))
1415 if (superclass
!= NULL
)
1418 super_meth
= _Jv_LookupDeclaredMethod (superclass
, meth
->name
,
1419 meth
->signature
, &declarer
);
1420 // See if this method actually overrides the other method
1424 if (! _Jv_isVirtualMethod (super_meth
)
1425 || ! _Jv_CheckAccess (klass
, declarer
,
1426 super_meth
->accflags
))
1428 else if ((super_meth
->accflags
1429 & java::lang::reflect::Modifier::FINAL
) != 0)
1431 using namespace java::lang
;
1432 StringBuffer
*sb
= new StringBuffer();
1433 sb
->append(JvNewStringLatin1("method "));
1434 sb
->append(_Jv_GetMethodString(klass
, meth
));
1435 sb
->append(JvNewStringLatin1(" overrides final method "));
1436 sb
->append(_Jv_GetMethodString(declarer
, super_meth
));
1437 throw new VerifyError(sb
->toString());
1443 meth
->index
= super_meth
->index
;
1445 meth
->index
= index
++;
1448 klass
->vtable_method_count
= index
;
1451 // Set entries in VTABLE for virtual methods declared in KLASS.
1453 _Jv_Linker::set_vtable_entries (jclass klass
, _Jv_VTable
*vtable
)
1455 for (int i
= klass
->method_count
- 1; i
>= 0; i
--)
1457 using namespace java::lang::reflect
;
1459 _Jv_Method
*meth
= &klass
->methods
[i
];
1460 if (meth
->index
== (_Jv_ushort
) -1)
1462 if ((meth
->accflags
& Modifier::ABSTRACT
))
1463 // FIXME: it might be nice to have a libffi trampoline here,
1464 // so we could pass in the method name and other information.
1465 vtable
->set_method(meth
->index
,
1466 (void *) &_Jv_ThrowAbstractMethodError
);
1468 vtable
->set_method(meth
->index
, meth
->ncode
);
1472 // Allocate and lay out the virtual method table for KLASS. This will
1473 // also cause vtables to be generated for any non-abstract
1474 // superclasses, and virtual method layout to occur for any abstract
1475 // superclasses. Must be called with monitor lock for KLASS held.
1477 _Jv_Linker::make_vtable (jclass klass
)
1479 using namespace java::lang::reflect
;
1481 // If the vtable exists, or for interface classes, do nothing. All
1482 // other classes, including abstract classes, need a vtable.
1483 if (klass
->vtable
!= NULL
|| klass
->isInterface())
1486 // Ensure all the `ncode' entries are set.
1487 klass
->engine
->create_ncode(klass
);
1489 // Class must be laid out before we can create a vtable.
1490 if (klass
->vtable_method_count
== -1)
1491 layout_vtable_methods (klass
);
1493 // Allocate the new vtable.
1494 _Jv_VTable
*vtable
= _Jv_VTable::new_vtable (klass
->vtable_method_count
);
1495 klass
->vtable
= vtable
;
1497 // Copy the vtable of the closest superclass.
1498 jclass superclass
= klass
->superclass
;
1500 JvSynchronize
sync (superclass
);
1501 make_vtable (superclass
);
1503 for (int i
= 0; i
< superclass
->vtable_method_count
; ++i
)
1504 vtable
->set_method (i
, superclass
->vtable
->get_method (i
));
1506 // Set the class pointer and GC descriptor.
1507 vtable
->clas
= klass
;
1508 vtable
->gc_descr
= _Jv_BuildGCDescr (klass
);
1510 // For each virtual declared in klass, set new vtable entry or
1511 // override an old one.
1512 set_vtable_entries (klass
, vtable
);
1514 // Note that we don't check for abstract methods here. We used to,
1515 // but there is a JVMS clarification that indicates that a check
1516 // here would be too eager. And, a simple test case confirms this.
1519 // Lay out the class, allocating space for static fields and computing
1520 // offsets of instance fields. The class lock must be held by the
1523 _Jv_Linker::ensure_fields_laid_out (jclass klass
)
1525 if (klass
->size_in_bytes
!= -1)
1528 // Compute the alignment for this type by searching through the
1529 // superclasses and finding the maximum required alignment. We
1530 // could consider caching this in the Class.
1531 int max_align
= __alignof__ (java::lang::Object
);
1532 jclass super
= klass
->getSuperclass();
1533 while (super
!= NULL
)
1535 // Ensure that our super has its super installed before
1537 wait_for_state(super
, JV_STATE_LOADING
);
1538 ensure_fields_laid_out(super
);
1539 int num
= JvNumInstanceFields (super
);
1540 _Jv_Field
*field
= JvGetFirstInstanceField (super
);
1543 int field_align
= get_alignment_from_class (field
->type
);
1544 if (field_align
> max_align
)
1545 max_align
= field_align
;
1549 super
= super
->getSuperclass();
1553 // This is the size of the 'static' non-reference fields.
1554 int non_reference_size
= 0;
1555 // This is the size of the 'static' reference fields. We count
1556 // these separately to make it simpler for the GC to scan them.
1557 int reference_size
= 0;
1559 // Although java.lang.Object is never interpreted, an interface can
1560 // have a null superclass. Note that we have to lay out an
1561 // interface because it might have static fields.
1562 if (klass
->superclass
)
1563 instance_size
= klass
->superclass
->size();
1565 instance_size
= java::lang::Object::class$
.size();
1567 klass
->engine
->allocate_field_initializers (klass
);
1569 for (int i
= 0; i
< klass
->field_count
; i
++)
1574 _Jv_Field
*field
= &klass
->fields
[i
];
1576 if (! field
->isRef ())
1578 // It is safe to resolve the field here, since it's a
1579 // primitive class, which does not cause loading to happen.
1580 resolve_field (field
, klass
->loader
);
1581 field_size
= field
->type
->size ();
1582 field_align
= get_alignment_from_class (field
->type
);
1586 field_size
= sizeof (jobject
);
1587 field_align
= __alignof__ (jobject
);
1590 field
->bsize
= field_size
;
1592 if ((field
->flags
& java::lang::reflect::Modifier::STATIC
))
1594 if (field
->u
.addr
== NULL
)
1596 // This computes an offset into a region we'll allocate
1597 // shortly, and then adds this offset to the start
1601 reference_size
= ROUND (reference_size
, field_align
);
1602 field
->u
.boffset
= reference_size
;
1603 reference_size
+= field_size
;
1607 non_reference_size
= ROUND (non_reference_size
, field_align
);
1608 field
->u
.boffset
= non_reference_size
;
1609 non_reference_size
+= field_size
;
1615 instance_size
= ROUND (instance_size
, field_align
);
1616 field
->u
.boffset
= instance_size
;
1617 instance_size
+= field_size
;
1618 if (field_align
> max_align
)
1619 max_align
= field_align
;
1623 if (reference_size
!= 0 || non_reference_size
!= 0)
1624 klass
->engine
->allocate_static_fields (klass
, reference_size
,
1625 non_reference_size
);
1627 // Set the instance size for the class. Note that first we round it
1628 // to the alignment required for this object; this keeps us in sync
1629 // with our current ABI.
1630 instance_size
= ROUND (instance_size
, max_align
);
1631 klass
->size_in_bytes
= instance_size
;
1634 // This takes the class to state JV_STATE_LINKED. The class lock must
1635 // be held when calling this.
1637 _Jv_Linker::ensure_class_linked (jclass klass
)
1639 if (klass
->state
>= JV_STATE_LINKED
)
1642 int state
= klass
->state
;
1645 // Short-circuit, so that mutually dependent classes are ok.
1646 klass
->state
= JV_STATE_LINKED
;
1648 _Jv_Constants
*pool
= &klass
->constants
;
1650 // Compiled classes require that their class constants be
1651 // resolved here. However, interpreted classes need their
1652 // constants to be resolved lazily. If we resolve an
1653 // interpreted class' constants eagerly, we can end up with
1654 // spurious IllegalAccessErrors when the constant pool contains
1655 // a reference to a class we can't access. This can validly
1656 // occur in an obscure case involving the InnerClasses
1658 if (! _Jv_IsInterpretedClass (klass
))
1660 // Resolve class constants first, since other constant pool
1661 // entries may rely on these.
1662 for (int index
= 1; index
< pool
->size
; ++index
)
1664 if (pool
->tags
[index
] == JV_CONSTANT_Class
)
1665 // Lazily resolve the entries.
1666 resolve_pool_entry (klass
, index
, true);
1670 // Resolve the remaining constant pool entries.
1671 for (int index
= 1; index
< pool
->size
; ++index
)
1673 if (pool
->tags
[index
] == JV_CONSTANT_String
)
1677 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
1678 pool
->data
[index
].o
= str
;
1679 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
1683 if (klass
->engine
->need_resolve_string_fields())
1685 jfieldID f
= JvGetFirstStaticField (klass
);
1686 for (int n
= JvNumStaticFields (klass
); n
> 0; --n
)
1688 int mod
= f
->getModifiers ();
1689 // If we have a static String field with a non-null initial
1690 // value, we know it points to a Utf8Const.
1692 // Finds out whether we have to initialize a String without the
1693 // need to resolve the field.
1694 if ((f
->isResolved()
1695 ? (f
->type
== &java::lang::String::class$
)
1696 : _Jv_equalUtf8Classnames((_Jv_Utf8Const
*) f
->type
,
1697 java::lang::String::class$
.name
))
1698 && (mod
& java::lang::reflect::Modifier::STATIC
) != 0)
1700 jstring
*strp
= (jstring
*) f
->u
.addr
;
1702 *strp
= _Jv_NewStringUtf8Const ((_Jv_Utf8Const
*) *strp
);
1704 f
= f
->getNextField ();
1708 klass
->notifyAll ();
1710 _Jv_PushClass (klass
);
1712 catch (java::lang::Throwable
*t
)
1714 klass
->state
= state
;
1719 // This ensures that symbolic superclass and superinterface references
1720 // are resolved for the indicated class. This must be called with the
1723 _Jv_Linker::ensure_supers_installed (jclass klass
)
1725 resolve_class_ref (klass
, &klass
->superclass
);
1726 // An interface won't have a superclass.
1727 if (klass
->superclass
)
1728 wait_for_state (klass
->superclass
, JV_STATE_LOADING
);
1730 for (int i
= 0; i
< klass
->interface_count
; ++i
)
1732 resolve_class_ref (klass
, &klass
->interfaces
[i
]);
1733 wait_for_state (klass
->interfaces
[i
], JV_STATE_LOADING
);
1737 // This adds missing `Miranda methods' to a class.
1739 _Jv_Linker::add_miranda_methods (jclass base
, jclass iface_class
)
1741 // Note that at this point, all our supers, and the supers of all
1742 // our superclasses and superinterfaces, will have been installed.
1744 for (int i
= 0; i
< iface_class
->interface_count
; ++i
)
1746 jclass interface
= iface_class
->interfaces
[i
];
1748 for (int j
= 0; j
< interface
->method_count
; ++j
)
1750 _Jv_Method
*meth
= &interface
->methods
[j
];
1751 // Don't bother with <clinit>.
1752 if (meth
->name
->first() == '<')
1754 _Jv_Method
*new_meth
= _Jv_LookupDeclaredMethod (base
, meth
->name
,
1758 // We assume that such methods are very unlikely, so we
1759 // just reallocate the method array each time one is
1760 // found. This greatly simplifies the searching --
1761 // otherwise we have to make sure that each such method
1762 // found is really unique among all superinterfaces.
1763 int new_count
= base
->method_count
+ 1;
1765 = (_Jv_Method
*) _Jv_AllocRawObj (sizeof (_Jv_Method
)
1767 memcpy (new_m
, base
->methods
,
1768 sizeof (_Jv_Method
) * base
->method_count
);
1771 new_m
[base
->method_count
] = *meth
;
1772 new_m
[base
->method_count
].index
= (_Jv_ushort
) -1;
1773 new_m
[base
->method_count
].accflags
1774 |= java::lang::reflect::Modifier::INVISIBLE
;
1776 base
->methods
= new_m
;
1777 base
->method_count
= new_count
;
1781 wait_for_state (interface
, JV_STATE_LOADED
);
1782 add_miranda_methods (base
, interface
);
1786 // This ensures that the class' method table is "complete". This must
1787 // be called with the class lock held.
1789 _Jv_Linker::ensure_method_table_complete (jclass klass
)
1791 if (klass
->vtable
!= NULL
)
1794 // We need our superclass to have its own Miranda methods installed.
1795 if (! klass
->isInterface())
1796 wait_for_state (klass
->getSuperclass (), JV_STATE_LOADED
);
1798 // A class might have so-called "Miranda methods". This is a method
1799 // that is declared in an interface and not re-declared in an
1800 // abstract class. Some compilers don't emit declarations for such
1801 // methods in the class; this will give us problems since we expect
1802 // a declaration for any method requiring a vtable entry. We handle
1803 // this here by searching for such methods and constructing new
1804 // internal declarations for them. Note that we do this
1805 // unconditionally, and not just for abstract classes, to correctly
1806 // account for cases where a class is modified to be concrete and
1807 // still incorrectly inherits an abstract method.
1808 int pre_count
= klass
->method_count
;
1809 add_miranda_methods (klass
, klass
);
1811 // Let the execution engine know that we've added methods.
1812 if (klass
->method_count
!= pre_count
)
1813 klass
->engine
->post_miranda_hook(klass
);
1816 // Verify a class. Must be called with class lock held.
1818 _Jv_Linker::verify_class (jclass klass
)
1820 klass
->engine
->verify(klass
);
1823 // Check the assertions contained in the type assertion table for KLASS.
1824 // This is the equivilent of bytecode verification for native, BC-ABI code.
1826 _Jv_Linker::verify_type_assertions (jclass klass
)
1829 fprintf (stderr
, "Evaluating type assertions for %s:\n",
1830 klass
->name
->chars());
1832 if (klass
->assertion_table
== NULL
)
1835 for (int i
= 0;; i
++)
1837 int assertion_code
= klass
->assertion_table
[i
].assertion_code
;
1838 _Jv_Utf8Const
*op1
= klass
->assertion_table
[i
].op1
;
1839 _Jv_Utf8Const
*op2
= klass
->assertion_table
[i
].op2
;
1841 if (assertion_code
== JV_ASSERT_END_OF_TABLE
)
1843 else if (assertion_code
== JV_ASSERT_TYPES_COMPATIBLE
)
1847 fprintf (stderr
, " code=%i, operand A=%s B=%s\n",
1848 assertion_code
, op1
->chars(), op2
->chars());
1851 // The operands are class signatures. op1 is the source,
1852 // op2 is the target.
1853 jclass cl1
= _Jv_FindClassFromSignature (op1
->chars(),
1854 klass
->getClassLoaderInternal());
1855 jclass cl2
= _Jv_FindClassFromSignature (op2
->chars(),
1856 klass
->getClassLoaderInternal());
1858 // If the class doesn't exist, ignore the assertion. An exception
1859 // will be thrown later if an attempt is made to actually
1860 // instantiate the class.
1861 if (cl1
== NULL
|| cl2
== NULL
)
1864 if (! _Jv_IsAssignableFromSlow (cl1
, cl2
))
1866 jstring s
= JvNewStringUTF ("Incompatible types: In class ");
1867 s
= s
->concat (klass
->getName());
1868 s
= s
->concat (JvNewStringUTF (": "));
1869 s
= s
->concat (cl1
->getName());
1870 s
= s
->concat (JvNewStringUTF (" is not assignable to "));
1871 s
= s
->concat (cl2
->getName());
1872 throw new java::lang::VerifyError (s
);
1875 else if (assertion_code
== JV_ASSERT_IS_INSTANTIABLE
)
1877 // TODO: Implement this.
1879 // Unknown assertion codes are ignored, for forwards-compatibility.
1884 _Jv_Linker::print_class_loaded (jclass klass
)
1886 char *codesource
= NULL
;
1887 if (klass
->protectionDomain
!= NULL
)
1889 java::security::CodeSource
*cs
1890 = klass
->protectionDomain
->getCodeSource();
1893 jstring css
= cs
->toString();
1894 int len
= JvGetStringUTFLength(css
);
1895 codesource
= (char *) _Jv_AllocBytes(len
+ 1);
1896 JvGetStringUTFRegion(css
, 0, css
->length(), codesource
);
1897 codesource
[len
] = '\0';
1900 if (codesource
== NULL
)
1901 codesource
= (char *) "<no code source>";
1904 if (_Jv_IsInterpretedClass (klass
))
1906 else if (_Jv_IsBinaryCompatibilityABI (klass
))
1907 abi
= "BC-compiled";
1909 abi
= "pre-compiled";
1911 fprintf (stderr
, "[Loaded (%s) %s from %s]\n", abi
, klass
->name
->chars(),
1915 // FIXME: mention invariants and stuff.
1917 _Jv_Linker::wait_for_state (jclass klass
, int state
)
1919 if (klass
->state
>= state
)
1922 JvSynchronize
sync (klass
);
1924 // This is similar to the strategy for class initialization. If we
1925 // already hold the lock, just leave.
1926 java::lang::Thread
*self
= java::lang::Thread::currentThread();
1927 while (klass
->state
<= state
1929 && klass
->thread
!= self
)
1932 java::lang::Thread
*save
= klass
->thread
;
1933 klass
->thread
= self
;
1935 // Allocate memory for static fields and constants.
1936 if (GC_base (klass
) && klass
->fields
&& ! GC_base (klass
->fields
))
1938 jsize count
= klass
->field_count
;
1942 = (_Jv_Field
*) _Jv_AllocRawObj (count
* sizeof (_Jv_Field
));
1943 memcpy ((void*)fields
,
1944 (void*)klass
->fields
,
1945 count
* sizeof (_Jv_Field
));
1946 klass
->fields
= fields
;
1950 // Print some debugging info if requested. Interpreted classes are
1951 // handled in defineclass, so we only need to handle the two
1952 // pre-compiled cases here.
1953 if (gcj::verbose_class_flag
1954 && (klass
->state
== JV_STATE_COMPILED
1955 || klass
->state
== JV_STATE_PRELOADING
)
1956 && ! _Jv_IsInterpretedClass (klass
))
1957 print_class_loaded (klass
);
1961 if (state
>= JV_STATE_LOADING
&& klass
->state
< JV_STATE_LOADING
)
1963 ensure_supers_installed (klass
);
1964 klass
->set_state(JV_STATE_LOADING
);
1967 if (state
>= JV_STATE_LOADED
&& klass
->state
< JV_STATE_LOADED
)
1969 ensure_method_table_complete (klass
);
1970 klass
->set_state(JV_STATE_LOADED
);
1973 if (state
>= JV_STATE_PREPARED
&& klass
->state
< JV_STATE_PREPARED
)
1975 ensure_fields_laid_out (klass
);
1976 make_vtable (klass
);
1977 layout_interface_methods (klass
);
1978 prepare_constant_time_tables (klass
);
1979 klass
->set_state(JV_STATE_PREPARED
);
1982 if (state
>= JV_STATE_LINKED
&& klass
->state
< JV_STATE_LINKED
)
1984 if (gcj::verifyClasses
)
1985 verify_class (klass
);
1987 ensure_class_linked (klass
);
1988 link_exception_table (klass
);
1989 link_symbol_table (klass
);
1990 klass
->set_state(JV_STATE_LINKED
);
1993 catch (java::lang::Throwable
*exc
)
1995 klass
->thread
= save
;
1996 klass
->set_state(JV_STATE_ERROR
);
2000 klass
->thread
= save
;
2002 if (klass
->state
== JV_STATE_ERROR
)
2003 throw new java::lang::LinkageError
;