1 // link.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 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>
37 #include "jvmti-int.h"
38 #include <java/lang/Class.h>
39 #include <java/lang/String.h>
40 #include <java/lang/StringBuffer.h>
41 #include <java/lang/Thread.h>
42 #include <java/lang/InternalError.h>
43 #include <java/lang/VirtualMachineError.h>
44 #include <java/lang/VerifyError.h>
45 #include <java/lang/NoSuchFieldError.h>
46 #include <java/lang/NoSuchMethodError.h>
47 #include <java/lang/ClassFormatError.h>
48 #include <java/lang/IllegalAccessError.h>
49 #include <java/lang/InternalError.h>
50 #include <java/lang/AbstractMethodError.h>
51 #include <java/lang/NoClassDefFoundError.h>
52 #include <java/lang/IncompatibleClassChangeError.h>
53 #include <java/lang/VerifyError.h>
54 #include <java/lang/VMClassLoader.h>
55 #include <java/lang/reflect/Modifier.h>
56 #include <java/security/CodeSource.h>
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 the_method
= (search_method_in_superclasses
341 (owner
->getSuperclass (), klass
, method_name
,
342 method_signature
, &found_class
));
345 end_of_method_search
:
347 // FIXME: if (cls->loader != klass->loader), then we
348 // must actually check that the types of arguments
349 // correspond. That is, for each argument type, and
350 // the return type, doing _Jv_FindClassFromSignature
351 // with either loader should produce the same result,
352 // i.e., exactly the same jclass object. JVMS 5.4.3.3
356 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
357 sb
->append(JvNewStringLatin1("method "));
358 sb
->append(owner
->getName());
359 sb
->append(JvNewStringLatin1("."));
360 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
361 sb
->append(JvNewStringLatin1(" with signature "));
362 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
363 sb
->append(JvNewStringLatin1(" was not found."));
364 throw new java::lang::NoSuchMethodError (sb
->toString());
371 _Jv_Linker::resolve_pool_entry (jclass klass
, int index
, bool lazy
)
373 using namespace java::lang::reflect
;
375 if (GC_base (klass
) && klass
->constants
.data
376 && ! GC_base (klass
->constants
.data
))
378 jsize count
= klass
->constants
.size
;
382 = (_Jv_word
*) _Jv_AllocRawObj (count
* sizeof (_Jv_word
));
383 memcpy ((void*)constants
,
384 (void*)klass
->constants
.data
,
385 count
* sizeof (_Jv_word
));
386 klass
->constants
.data
= constants
;
390 _Jv_Constants
*pool
= &klass
->constants
;
392 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
393 return pool
->data
[index
];
395 switch (pool
->tags
[index
] & ~JV_CONSTANT_LazyFlag
)
397 case JV_CONSTANT_Class
:
399 _Jv_Utf8Const
*name
= pool
->data
[index
].utf8
;
402 if (name
->first() == '[')
403 found
= _Jv_FindClassFromSignatureNoException (name
->chars(),
406 found
= _Jv_FindClassNoException (name
, klass
->loader
);
408 // If the class could not be loaded a phantom class is created. Any
409 // function that deals with such a class but cannot do something useful
410 // with it should just throw a NoClassDefFoundError with the class'
416 found
= _Jv_NewClass(name
, NULL
, NULL
);
417 found
->state
= JV_STATE_PHANTOM
;
418 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
419 pool
->data
[index
].clazz
= found
;
423 throw new java::lang::NoClassDefFoundError (name
->toString());
426 // Check accessibility, but first strip array types as
427 // _Jv_ClassNameSamePackage can't handle arrays.
430 check
&& check
->isArray();
431 check
= check
->getComponentType())
433 if ((found
->accflags
& Modifier::PUBLIC
) == Modifier::PUBLIC
434 || (_Jv_ClassNameSamePackage (check
->name
,
437 pool
->data
[index
].clazz
= found
;
438 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
442 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer ();
443 sb
->append(klass
->getName());
444 sb
->append(JvNewStringLatin1(" can't access class "));
445 sb
->append(found
->getName());
446 throw new java::lang::IllegalAccessError(sb
->toString());
451 case JV_CONSTANT_String
:
454 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
455 pool
->data
[index
].o
= str
;
456 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
460 case JV_CONSTANT_Fieldref
:
462 _Jv_ushort class_index
, name_and_type_index
;
463 _Jv_loadIndexes (&pool
->data
[index
],
465 name_and_type_index
);
466 jclass owner
= (resolve_pool_entry (klass
, class_index
, true)).clazz
;
468 // If a phantom class was resolved our field reference is
469 // unusable because of the missing class.
470 if (owner
->state
== JV_STATE_PHANTOM
)
471 throw new java::lang::NoClassDefFoundError(owner
->getName());
473 // We don't initialize 'owner', but we do make sure that its
475 wait_for_state (owner
, JV_STATE_PREPARED
);
477 _Jv_ushort name_index
, type_index
;
478 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
482 _Jv_Utf8Const
*field_name
= pool
->data
[name_index
].utf8
;
483 _Jv_Utf8Const
*field_type_name
= pool
->data
[type_index
].utf8
;
485 jclass found_class
= 0;
486 _Jv_Field
*the_field
= find_field (klass
, owner
,
490 // Initialize the field's declaring class, not its qualifying
492 _Jv_InitClass (found_class
);
493 pool
->data
[index
].field
= the_field
;
494 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
498 case JV_CONSTANT_Methodref
:
499 case JV_CONSTANT_InterfaceMethodref
:
501 _Jv_ushort class_index
, name_and_type_index
;
502 _Jv_loadIndexes (&pool
->data
[index
],
504 name_and_type_index
);
506 _Jv_Method
*the_method
;
508 the_method
= resolve_method_entry (klass
, found_class
,
509 class_index
, name_and_type_index
,
511 pool
->tags
[index
] == JV_CONSTANT_InterfaceMethodref
);
513 pool
->data
[index
].rmethod
514 = klass
->engine
->resolve_method(the_method
,
516 ((the_method
->accflags
517 & Modifier::STATIC
) != 0));
518 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
522 return pool
->data
[index
];
525 // This function is used to lazily locate superclasses and
526 // superinterfaces. This must be called with the class lock held.
528 _Jv_Linker::resolve_class_ref (jclass klass
, jclass
*classref
)
530 jclass ret
= *classref
;
532 // If superclass looks like a constant pool entry, resolve it now.
533 if (ret
&& (uaddr
) ret
< (uaddr
) klass
->constants
.size
)
535 if (klass
->state
< JV_STATE_LINKED
)
537 _Jv_Utf8Const
*name
= klass
->constants
.data
[(uaddr
) *classref
].utf8
;
538 ret
= _Jv_FindClass (name
, klass
->loader
);
541 throw new java::lang::NoClassDefFoundError (name
->toString());
545 ret
= klass
->constants
.data
[(uaddr
) classref
].clazz
;
550 // Find a method declared in the cls that is referenced from klass and
551 // perform access checks if CHECK_PERMS is true.
553 _Jv_Linker::search_method_in_class (jclass cls
, jclass klass
,
554 _Jv_Utf8Const
*method_name
,
555 _Jv_Utf8Const
*method_signature
,
558 using namespace java::lang::reflect
;
560 for (int i
= 0; i
< cls
->method_count
; i
++)
562 _Jv_Method
*method
= &cls
->methods
[i
];
563 if ( (!_Jv_equalUtf8Consts (method
->name
,
565 || (!_Jv_equalUtf8Consts (method
->signature
,
569 if (!check_perms
|| _Jv_CheckAccess (klass
, cls
, method
->accflags
))
573 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
574 sb
->append(klass
->getName());
575 sb
->append(JvNewStringLatin1(": "));
576 sb
->append(cls
->getName());
577 sb
->append(JvNewStringLatin1("."));
578 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
579 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
580 throw new java::lang::IllegalAccessError (sb
->toString());
586 // Like search_method_in_class, but work our way up the superclass
589 _Jv_Linker::search_method_in_superclasses (jclass cls
, jclass klass
,
590 _Jv_Utf8Const
*method_name
,
591 _Jv_Utf8Const
*method_signature
,
592 jclass
*found_class
, bool check_perms
)
594 _Jv_Method
*the_method
= NULL
;
596 for ( ; cls
!= 0; cls
= cls
->getSuperclass ())
598 the_method
= search_method_in_class (cls
, klass
, method_name
,
599 method_signature
, check_perms
);
611 #define INITIAL_IOFFSETS_LEN 4
612 #define INITIAL_IFACES_LEN 4
614 static _Jv_IDispatchTable null_idt
= {SHRT_MAX
, 0, {}};
616 // Generate tables for constant-time assignment testing and interface
617 // method lookup. This implements the technique described by Per Bothner
618 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
619 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
621 _Jv_Linker::prepare_constant_time_tables (jclass klass
)
623 if (klass
->isPrimitive () || klass
->isInterface ())
626 // Short-circuit in case we've been called already.
627 if ((klass
->idt
!= NULL
) || klass
->depth
!= 0)
630 // Calculate the class depth and ancestor table. The depth of a class
631 // is how many "extends" it is removed from Object. Thus the depth of
632 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
633 // is 2. Depth is defined for all regular and array classes, but not
634 // interfaces or primitive types.
636 jclass klass0
= klass
;
637 jboolean has_interfaces
= 0;
638 while (klass0
!= &java::lang::Object::class$
)
640 has_interfaces
+= klass0
->interface_count
;
641 klass0
= klass0
->superclass
;
645 // We do class member testing in constant time by using a small table
646 // of all the ancestor classes within each class. The first element is
647 // a pointer to the current class, and the rest are pointers to the
648 // classes ancestors, ordered from the current class down by decreasing
649 // depth. We do not include java.lang.Object in the table of ancestors,
650 // since it is redundant. Note that the classes pointed to by
651 // 'ancestors' will always be reachable by other paths.
653 klass
->ancestors
= (jclass
*) _Jv_AllocBytes (klass
->depth
656 for (int index
= 0; index
< klass
->depth
; index
++)
658 klass
->ancestors
[index
] = klass0
;
659 klass0
= klass0
->superclass
;
662 if ((klass
->accflags
& java::lang::reflect::Modifier::ABSTRACT
) != 0)
665 // Optimization: If class implements no interfaces, use a common
666 // predefined interface table.
669 klass
->idt
= &null_idt
;
675 ifaces
.len
= INITIAL_IFACES_LEN
;
676 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
* sizeof (jclass
*));
678 int itable_size
= get_interfaces (klass
, &ifaces
);
680 if (ifaces
.count
> 0)
682 // The classes pointed to by the itable will always be reachable
684 int idt_bytes
= sizeof (_Jv_IDispatchTable
) + (itable_size
686 klass
->idt
= (_Jv_IDispatchTable
*) _Jv_AllocBytes (idt_bytes
);
687 klass
->idt
->itable_length
= itable_size
;
689 jshort
*itable_offsets
=
690 (jshort
*) _Jv_Malloc (ifaces
.count
* sizeof (jshort
));
692 generate_itable (klass
, &ifaces
, itable_offsets
);
694 jshort cls_iindex
= find_iindex (ifaces
.list
, itable_offsets
,
697 for (int i
= 0; i
< ifaces
.count
; i
++)
699 ifaces
.list
[i
]->ioffsets
[cls_iindex
] = itable_offsets
[i
];
702 klass
->idt
->iindex
= cls_iindex
;
704 _Jv_Free (ifaces
.list
);
705 _Jv_Free (itable_offsets
);
709 klass
->idt
->iindex
= SHRT_MAX
;
713 // Return index of item in list, or -1 if item is not present.
715 _Jv_Linker::indexof (void *item
, void **list
, jshort list_len
)
717 for (int i
=0; i
< list_len
; i
++)
725 // Find all unique interfaces directly or indirectly implemented by klass.
726 // Returns the size of the interface dispatch table (itable) for klass, which
727 // is the number of unique interfaces plus the total number of methods that
728 // those interfaces declare. May extend ifaces if required.
730 _Jv_Linker::get_interfaces (jclass klass
, _Jv_ifaces
*ifaces
)
734 for (int i
= 0; i
< klass
->interface_count
; i
++)
736 jclass iface
= klass
->interfaces
[i
];
738 /* Make sure interface is linked. */
739 wait_for_state(iface
, JV_STATE_LINKED
);
741 if (indexof (iface
, (void **) ifaces
->list
, ifaces
->count
) == -1)
743 if (ifaces
->count
+ 1 >= ifaces
->len
)
745 /* Resize ifaces list */
746 ifaces
->len
= ifaces
->len
* 2;
748 = (jclass
*) _Jv_Realloc (ifaces
->list
,
749 ifaces
->len
* sizeof(jclass
));
751 ifaces
->list
[ifaces
->count
] = iface
;
754 result
+= get_interfaces (klass
->interfaces
[i
], ifaces
);
758 if (klass
->isInterface())
760 // We want to add 1 plus the number of interface methods here.
761 // But, we take special care to skip <clinit>.
763 for (int i
= 0; i
< klass
->method_count
; ++i
)
765 if (klass
->methods
[i
].name
->first() != '<')
769 else if (klass
->superclass
)
770 result
+= get_interfaces (klass
->superclass
, ifaces
);
774 // Fill out itable in klass, resolving method declarations in each ifaces.
775 // itable_offsets is filled out with the position of each iface in itable,
776 // such that itable[itable_offsets[n]] == ifaces.list[n].
778 _Jv_Linker::generate_itable (jclass klass
, _Jv_ifaces
*ifaces
,
779 jshort
*itable_offsets
)
781 void **itable
= klass
->idt
->itable
;
782 jshort itable_pos
= 0;
784 for (int i
= 0; i
< ifaces
->count
; i
++)
786 jclass iface
= ifaces
->list
[i
];
787 itable_offsets
[i
] = itable_pos
;
788 itable_pos
= append_partial_itable (klass
, iface
, itable
, itable_pos
);
790 /* Create ioffsets table for iface */
791 if (iface
->ioffsets
== NULL
)
793 // The first element of ioffsets is its length (itself included).
794 jshort
*ioffsets
= (jshort
*) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
796 ioffsets
[0] = INITIAL_IOFFSETS_LEN
;
797 for (int i
= 1; i
< INITIAL_IOFFSETS_LEN
; i
++)
800 iface
->ioffsets
= ioffsets
;
805 // Format method name for use in error messages.
807 _Jv_GetMethodString (jclass klass
, _Jv_Method
*meth
,
810 using namespace java::lang
;
811 StringBuffer
*buf
= new StringBuffer (klass
->name
->toString());
812 buf
->append (jchar ('.'));
813 buf
->append (meth
->name
->toString());
814 buf
->append ((jchar
) ' ');
815 buf
->append (meth
->signature
->toString());
818 buf
->append(JvNewStringLatin1(" in "));
819 buf
->append(derived
->name
->toString());
821 return buf
->toString();
825 _Jv_ThrowNoSuchMethodError ()
827 throw new java::lang::NoSuchMethodError
;
830 #if defined USE_LIBFFI && FFI_CLOSURES
831 // A function whose invocation is prepared using libffi. It gets called
832 // whenever a static method of a missing class is invoked. The data argument
833 // holds a reference to a String denoting the missing class.
834 // The prepared function call is stored in a class' atable.
836 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif
*,
841 throw new java::lang::NoClassDefFoundError(
842 _Jv_NewStringUtf8Const((_Jv_Utf8Const
*) data
));
845 // A variant of the NoClassDefFoundError throwing method that can
846 // be used without libffi.
848 _Jv_ThrowNoClassDefFoundError()
850 throw new java::lang::NoClassDefFoundError();
854 // Throw a NoSuchFieldError. Called by compiler-generated code when
855 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
856 // otable that refers to the missing field. This index may be used to
857 // print diagnostic information about the field.
859 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
861 throw new java::lang::NoSuchFieldError
;
864 // This is put in empty vtable slots.
866 _Jv_ThrowAbstractMethodError ()
868 throw new java::lang::AbstractMethodError();
871 // Each superinterface of a class (i.e. each interface that the class
872 // directly or indirectly implements) has a corresponding "Partial
873 // Interface Dispatch Table" whose size is (number of methods + 1) words.
874 // The first word is a pointer to the interface (i.e. the java.lang.Class
875 // instance for that interface). The remaining words are pointers to the
876 // actual methods that implement the methods declared in the interface,
877 // in order of declaration.
879 // Append partial interface dispatch table for "iface" to "itable", at
880 // position itable_pos.
881 // Returns the offset at which the next partial ITable should be appended.
883 _Jv_Linker::append_partial_itable (jclass klass
, jclass iface
,
884 void **itable
, jshort pos
)
886 using namespace java::lang::reflect
;
888 itable
[pos
++] = (void *) iface
;
891 for (int j
=0; j
< iface
->method_count
; j
++)
893 // Skip '<clinit>' here.
894 if (iface
->methods
[j
].name
->first() == '<')
898 for (jclass cl
= klass
; cl
; cl
= cl
->getSuperclass())
900 meth
= _Jv_GetMethodLocal (cl
, iface
->methods
[j
].name
,
901 iface
->methods
[j
].signature
);
909 if ((meth
->accflags
& Modifier::STATIC
) != 0)
910 throw new java::lang::IncompatibleClassChangeError
911 (_Jv_GetMethodString (klass
, meth
));
912 if ((meth
->accflags
& Modifier::PUBLIC
) == 0)
913 throw new java::lang::IllegalAccessError
914 (_Jv_GetMethodString (klass
, meth
));
916 if ((meth
->accflags
& Modifier::ABSTRACT
) != 0)
917 itable
[pos
] = (void *) &_Jv_ThrowAbstractMethodError
;
919 itable
[pos
] = meth
->ncode
;
923 // The method doesn't exist in klass. Binary compatibility rules
924 // permit this, so we delay the error until runtime using a pointer
925 // to a method which throws an exception.
926 itable
[pos
] = (void *) _Jv_ThrowNoSuchMethodError
;
934 static _Jv_Mutex_t iindex_mutex
;
935 static bool iindex_mutex_initialized
= false;
937 // We need to find the correct offset in the Class Interface Dispatch
938 // Table for a given interface. Once we have that, invoking an interface
939 // method just requires combining the Method's index in the interface
940 // (known at compile time) to get the correct method. Doing a type test
941 // (cast or instanceof) is the same problem: Once we have a possible Partial
942 // Interface Dispatch Table, we just compare the first element to see if it
943 // matches the desired interface. So how can we find the correct offset?
944 // Our solution is to keep a vector of candiate offsets in each interface
945 // (ioffsets), and in each class we have an index (idt->iindex) used to
946 // select the correct offset from ioffsets.
948 // Calculate and return iindex for a new class.
949 // ifaces is a vector of num interfaces that the class implements.
950 // offsets[j] is the offset in the interface dispatch table for the
951 // interface corresponding to ifaces[j].
952 // May extend the interface ioffsets if required.
954 _Jv_Linker::find_iindex (jclass
*ifaces
, jshort
*offsets
, jshort num
)
959 // Acquire a global lock to prevent itable corruption in case of multiple
960 // classes that implement an intersecting set of interfaces being linked
961 // simultaneously. We can assume that the mutex will be initialized
963 if (! iindex_mutex_initialized
)
965 _Jv_MutexInit (&iindex_mutex
);
966 iindex_mutex_initialized
= true;
969 _Jv_MutexLock (&iindex_mutex
);
971 for (i
=1;; i
++) /* each potential position in ioffsets */
973 for (j
=0;; j
++) /* each iface */
977 if (i
>= ifaces
[j
]->ioffsets
[0])
979 int ioffset
= ifaces
[j
]->ioffsets
[i
];
980 /* We can potentially share this position with another class. */
981 if (ioffset
>= 0 && ioffset
!= offsets
[j
])
982 break; /* Nope. Try next i. */
986 for (j
= 0; j
< num
; j
++)
988 int len
= ifaces
[j
]->ioffsets
[0];
992 int newlen
= 2 * len
;
996 jshort
*old_ioffsets
= ifaces
[j
]->ioffsets
;
997 jshort
*new_ioffsets
= (jshort
*) _Jv_AllocBytes (newlen
999 memcpy (&new_ioffsets
[1], &old_ioffsets
[1],
1000 (len
- 1) * sizeof (jshort
));
1001 new_ioffsets
[0] = newlen
;
1003 while (len
< newlen
)
1004 new_ioffsets
[len
++] = -1;
1006 ifaces
[j
]->ioffsets
= new_ioffsets
;
1008 ifaces
[j
]->ioffsets
[i
] = offsets
[j
];
1011 _Jv_MutexUnlock (&iindex_mutex
);
1016 #if defined USE_LIBFFI && FFI_CLOSURES
1017 // We use a structure of this type to store the closure that
1018 // represents a missing method.
1019 struct method_closure
1021 // This field must come first, since the address of this field will
1022 // be the same as the address of the overall structure. This is due
1023 // to disabling interior pointers in the GC.
1024 ffi_closure closure
;
1026 ffi_type
*arg_types
[1];
1030 _Jv_Linker::create_error_method (_Jv_Utf8Const
*class_name
)
1032 method_closure
*closure
1033 = (method_closure
*) _Jv_AllocBytes(sizeof (method_closure
));
1035 closure
->arg_types
[0] = &ffi_type_void
;
1037 // Initializes the cif and the closure. If that worked the closure
1038 // is returned and can be used as a function pointer in a class'
1040 if ( ffi_prep_cif (&closure
->cif
,
1044 closure
->arg_types
) == FFI_OK
1045 && ffi_prep_closure (&closure
->closure
,
1047 _Jv_ThrowNoClassDefFoundErrorTrampoline
,
1048 class_name
) == FFI_OK
)
1049 return &closure
->closure
;
1052 java::lang::StringBuffer
*buffer
= new java::lang::StringBuffer();
1053 buffer
->append(JvNewStringLatin1("Error setting up FFI closure"
1054 " for static method of"
1055 " missing class: "));
1056 buffer
->append (_Jv_NewStringUtf8Const(class_name
));
1057 throw new java::lang::InternalError(buffer
->toString());
1062 _Jv_Linker::create_error_method (_Jv_Utf8Const
*)
1064 // Codepath for platforms which do not support (or want) libffi.
1065 // You have to accept that it is impossible to provide the name
1066 // of the missing class then.
1067 return (void *) _Jv_ThrowNoClassDefFoundError
;
1069 #endif // USE_LIBFFI && FFI_CLOSURES
1071 // Functions for indirect dispatch (symbolic virtual binding) support.
1073 // There are three tables, atable otable and itable. atable is an
1074 // array of addresses, and otable is an array of offsets, and these
1075 // are used for static and virtual members respectively. itable is an
1076 // array of pairs {address, index} where each address is a pointer to
1079 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1080 // symbol is a tuple of {classname, member name, signature}.
1082 // Set this to true to enable debugging of indirect dispatch tables/linking.
1083 static bool debug_link
= false;
1085 // link_symbol_table() scans these two arrays and fills in the
1086 // corresponding atable and otable with the addresses of static
1087 // members and the offsets of virtual members.
1089 // The offset (in bytes) for each resolved method or field is placed
1090 // at the corresponding position in the virtual method offset table
1093 // The same otable and atable may be shared by many classes.
1095 // This must be called while holding the class lock.
1098 _Jv_Linker::link_symbol_table (jclass klass
)
1101 _Jv_MethodSymbol sym
;
1102 if (klass
->otable
== NULL
1103 || klass
->otable
->state
!= 0)
1106 klass
->otable
->state
= 1;
1109 fprintf (stderr
, "Fixing up otable in %s:\n", klass
->name
->chars());
1111 (sym
= klass
->otable_syms
[index
]).class_name
!= NULL
;
1114 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1115 _Jv_Method
*meth
= NULL
;
1117 _Jv_Utf8Const
*signature
= sym
.signature
;
1119 maybe_adjust_signature (signature
, special
);
1121 if (target_class
== NULL
)
1122 throw new java::lang::NoClassDefFoundError
1123 (_Jv_NewStringUTF (sym
.class_name
->chars()));
1125 // We're looking for a field or a method, and we can tell
1126 // which is needed by looking at the signature.
1127 if (signature
->first() == '(' && signature
->len() >= 2)
1129 // Looks like someone is trying to invoke an interface method
1130 if (target_class
->isInterface())
1132 using namespace java::lang
;
1133 StringBuffer
*sb
= new StringBuffer();
1134 sb
->append(JvNewStringLatin1("found interface "));
1135 sb
->append(target_class
->getName());
1136 sb
->append(JvNewStringLatin1(" when searching for a class"));
1137 throw new VerifyError(sb
->toString());
1140 // If the target class does not have a vtable_method_count yet,
1141 // then we can't tell the offsets for its methods, so we must lay
1143 wait_for_state(target_class
, JV_STATE_PREPARED
);
1147 meth
= (search_method_in_superclasses
1148 (target_class
, klass
, sym
.name
, signature
,
1149 NULL
, special
== 0));
1151 catch (::java::lang::IllegalAccessError
*e
)
1155 // Every class has a throwNoSuchMethodErrorIndex method that
1156 // it inherits from java.lang.Object. Find its vtable
1158 static int throwNoSuchMethodErrorIndex
;
1159 if (throwNoSuchMethodErrorIndex
== 0)
1162 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1163 strlen ("throwNoSuchMethodError"));
1165 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$
,
1166 name
, gcj::void_signature
);
1167 throwNoSuchMethodErrorIndex
1168 = _Jv_VTable::idx_to_offset (meth
->index
);
1171 // If we don't find a nonstatic method, insert the
1172 // vtable index of Object.throwNoSuchMethodError().
1173 // This defers the missing method error until an attempt
1174 // is made to execute it.
1179 offset
= _Jv_VTable::idx_to_offset (meth
->index
);
1181 offset
= throwNoSuchMethodErrorIndex
;
1184 JvFail ("Bad method index");
1185 JvAssert (meth
->index
< target_class
->vtable_method_count
);
1187 klass
->otable
->offsets
[index
] = offset
;
1191 fprintf (stderr
, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1193 (int)klass
->otable
->offsets
[index
],
1194 (const char*)target_class
->name
->chars(),
1196 (const char*)sym
.name
->chars(),
1197 (const char*)signature
->chars());
1203 wait_for_state(target_class
, JV_STATE_PREPARED
);
1205 _Jv_Field
*the_field
= NULL
;
1208 the_field
= find_field (klass
, target_class
, &found_class
,
1209 sym
.name
, signature
);
1210 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1211 throw new java::lang::IncompatibleClassChangeError
;
1213 klass
->otable
->offsets
[index
] = the_field
->u
.boffset
;
1215 catch (java::lang::NoSuchFieldError
*err
)
1217 klass
->otable
->offsets
[index
] = 0;
1223 if (klass
->atable
== NULL
|| klass
->atable
->state
!= 0)
1226 klass
->atable
->state
= 1;
1229 (sym
= klass
->atable_syms
[index
]).class_name
!= NULL
;
1232 jclass target_class
=
1233 _Jv_FindClassNoException (sym
.class_name
, klass
->loader
);
1235 _Jv_Method
*meth
= NULL
;
1237 _Jv_Utf8Const
*signature
= sym
.signature
;
1239 maybe_adjust_signature (signature
, special
);
1241 // ??? Setting this pointer to null will at least get us a
1242 // NullPointerException
1243 klass
->atable
->addresses
[index
] = NULL
;
1245 // If the target class is missing we prepare a function call
1246 // that throws a NoClassDefFoundError and store the address of
1247 // that newly prepared method in the atable. The user can run
1248 // code in classes where the missing class is part of the
1249 // execution environment as long as it is never referenced.
1250 if (target_class
== NULL
)
1251 klass
->atable
->addresses
[index
] = create_error_method(sym
.class_name
);
1252 // We're looking for a static field or a static method, and we
1253 // can tell which is needed by looking at the signature.
1254 else if (signature
->first() == '(' && signature
->len() >= 2)
1256 // If the target class does not have a vtable_method_count yet,
1257 // then we can't tell the offsets for its methods, so we must lay
1259 wait_for_state (target_class
, JV_STATE_PREPARED
);
1261 // Interface methods cannot have bodies.
1262 if (target_class
->isInterface())
1264 using namespace java::lang
;
1265 StringBuffer
*sb
= new StringBuffer();
1266 sb
->append(JvNewStringLatin1("class "));
1267 sb
->append(target_class
->getName());
1268 sb
->append(JvNewStringLatin1(" is an interface: "
1270 throw new VerifyError(sb
->toString());
1275 meth
= (search_method_in_superclasses
1276 (target_class
, klass
, sym
.name
, signature
,
1277 NULL
, special
== 0));
1279 catch (::java::lang::IllegalAccessError
*e
)
1285 if (meth
->ncode
) // Maybe abstract?
1287 klass
->atable
->addresses
[index
] = meth
->ncode
;
1289 fprintf (stderr
, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1291 &klass
->atable
->addresses
[index
],
1292 (const char*)target_class
->name
->chars(),
1294 (const char*)sym
.name
->chars(),
1295 (const char*)signature
->chars());
1299 klass
->atable
->addresses
[index
]
1300 = create_error_method(sym
.class_name
);
1305 // Try fields only if the target class exists.
1306 if (target_class
!= NULL
)
1308 wait_for_state(target_class
, JV_STATE_PREPARED
);
1310 _Jv_Field
*the_field
= find_field (klass
, target_class
, &found_class
,
1311 sym
.name
, signature
);
1312 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1313 klass
->atable
->addresses
[index
] = the_field
->u
.addr
;
1315 throw new java::lang::IncompatibleClassChangeError
;
1320 if (klass
->itable
== NULL
1321 || klass
->itable
->state
!= 0)
1324 klass
->itable
->state
= 1;
1327 (sym
= klass
->itable_syms
[index
]).class_name
!= NULL
;
1330 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1332 _Jv_Utf8Const
*signature
= sym
.signature
;
1334 maybe_adjust_signature (signature
, special
);
1339 wait_for_state(target_class
, JV_STATE_LOADED
);
1340 bool found
= _Jv_getInterfaceMethod (target_class
, cls
, i
,
1341 sym
.name
, signature
);
1345 klass
->itable
->addresses
[index
* 2] = cls
;
1346 klass
->itable
->addresses
[index
* 2 + 1] = (void *)(unsigned long) i
;
1349 fprintf (stderr
, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1351 klass
->itable
->addresses
[index
* 2],
1352 (const char*)cls
->name
->chars(),
1354 (const char*)sym
.name
->chars(),
1355 (const char*)signature
->chars());
1356 fprintf (stderr
, " [%d] = offset %d\n",
1358 (int)(unsigned long)klass
->itable
->addresses
[index
* 2 + 1]);
1363 throw new java::lang::IncompatibleClassChangeError
;
1368 // For each catch_record in the list of caught classes, fill in the
1371 _Jv_Linker::link_exception_table (jclass self
)
1373 struct _Jv_CatchClass
*catch_record
= self
->catch_classes
;
1374 if (!catch_record
|| catch_record
->classname
)
1377 while (catch_record
->classname
)
1382 = _Jv_FindClass (catch_record
->classname
,
1383 self
->getClassLoaderInternal ());
1384 *catch_record
->address
= target_class
;
1386 catch (::java::lang::Throwable
*t
)
1388 // FIXME: We need to do something better here.
1389 *catch_record
->address
= 0;
1393 self
->catch_classes
->classname
= (_Jv_Utf8Const
*)-1;
1396 // Set itable method indexes for members of interface IFACE.
1398 _Jv_Linker::layout_interface_methods (jclass iface
)
1400 if (! iface
->isInterface())
1403 // itable indexes start at 1.
1404 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1405 // itable so they are also assigned an index here.
1406 for (int i
= 0; i
< iface
->method_count
; i
++)
1407 iface
->methods
[i
].index
= i
+ 1;
1410 // Prepare virtual method declarations in KLASS, and any superclasses
1411 // as required, by determining their vtable index, setting
1412 // method->index, and finally setting the class's vtable_method_count.
1413 // Must be called with the lock for KLASS held.
1415 _Jv_Linker::layout_vtable_methods (jclass klass
)
1417 if (klass
->vtable
!= NULL
|| klass
->isInterface()
1418 || klass
->vtable_method_count
!= -1)
1421 jclass superclass
= klass
->getSuperclass();
1423 if (superclass
!= NULL
&& superclass
->vtable_method_count
== -1)
1425 JvSynchronize
sync (superclass
);
1426 layout_vtable_methods (superclass
);
1429 int index
= (superclass
== NULL
? 0 : superclass
->vtable_method_count
);
1431 for (int i
= 0; i
< klass
->method_count
; ++i
)
1433 _Jv_Method
*meth
= &klass
->methods
[i
];
1434 _Jv_Method
*super_meth
= NULL
;
1436 if (! _Jv_isVirtualMethod (meth
))
1439 if (superclass
!= NULL
)
1442 super_meth
= _Jv_LookupDeclaredMethod (superclass
, meth
->name
,
1443 meth
->signature
, &declarer
);
1444 // See if this method actually overrides the other method
1448 if (! _Jv_isVirtualMethod (super_meth
)
1449 || ! _Jv_CheckAccess (klass
, declarer
,
1450 super_meth
->accflags
))
1452 else if ((super_meth
->accflags
1453 & java::lang::reflect::Modifier::FINAL
) != 0)
1455 using namespace java::lang
;
1456 StringBuffer
*sb
= new StringBuffer();
1457 sb
->append(JvNewStringLatin1("method "));
1458 sb
->append(_Jv_GetMethodString(klass
, meth
));
1459 sb
->append(JvNewStringLatin1(" overrides final method "));
1460 sb
->append(_Jv_GetMethodString(declarer
, super_meth
));
1461 throw new VerifyError(sb
->toString());
1467 meth
->index
= super_meth
->index
;
1469 meth
->index
= index
++;
1472 klass
->vtable_method_count
= index
;
1475 // Set entries in VTABLE for virtual methods declared in KLASS.
1477 _Jv_Linker::set_vtable_entries (jclass klass
, _Jv_VTable
*vtable
)
1479 for (int i
= klass
->method_count
- 1; i
>= 0; i
--)
1481 using namespace java::lang::reflect
;
1483 _Jv_Method
*meth
= &klass
->methods
[i
];
1484 if (meth
->index
== (_Jv_ushort
) -1)
1486 if ((meth
->accflags
& Modifier::ABSTRACT
))
1487 // FIXME: it might be nice to have a libffi trampoline here,
1488 // so we could pass in the method name and other information.
1489 vtable
->set_method(meth
->index
,
1490 (void *) &_Jv_ThrowAbstractMethodError
);
1492 vtable
->set_method(meth
->index
, meth
->ncode
);
1496 // Allocate and lay out the virtual method table for KLASS. This will
1497 // also cause vtables to be generated for any non-abstract
1498 // superclasses, and virtual method layout to occur for any abstract
1499 // superclasses. Must be called with monitor lock for KLASS held.
1501 _Jv_Linker::make_vtable (jclass klass
)
1503 using namespace java::lang::reflect
;
1505 // If the vtable exists, or for interface classes, do nothing. All
1506 // other classes, including abstract classes, need a vtable.
1507 if (klass
->vtable
!= NULL
|| klass
->isInterface())
1510 // Ensure all the `ncode' entries are set.
1511 klass
->engine
->create_ncode(klass
);
1513 // Class must be laid out before we can create a vtable.
1514 if (klass
->vtable_method_count
== -1)
1515 layout_vtable_methods (klass
);
1517 // Allocate the new vtable.
1518 _Jv_VTable
*vtable
= _Jv_VTable::new_vtable (klass
->vtable_method_count
);
1519 klass
->vtable
= vtable
;
1521 // Copy the vtable of the closest superclass.
1522 jclass superclass
= klass
->superclass
;
1524 JvSynchronize
sync (superclass
);
1525 make_vtable (superclass
);
1527 for (int i
= 0; i
< superclass
->vtable_method_count
; ++i
)
1528 vtable
->set_method (i
, superclass
->vtable
->get_method (i
));
1530 // Set the class pointer and GC descriptor.
1531 vtable
->clas
= klass
;
1532 vtable
->gc_descr
= _Jv_BuildGCDescr (klass
);
1534 // For each virtual declared in klass, set new vtable entry or
1535 // override an old one.
1536 set_vtable_entries (klass
, vtable
);
1538 // Note that we don't check for abstract methods here. We used to,
1539 // but there is a JVMS clarification that indicates that a check
1540 // here would be too eager. And, a simple test case confirms this.
1543 // Lay out the class, allocating space for static fields and computing
1544 // offsets of instance fields. The class lock must be held by the
1547 _Jv_Linker::ensure_fields_laid_out (jclass klass
)
1549 if (klass
->size_in_bytes
!= -1)
1552 // Compute the alignment for this type by searching through the
1553 // superclasses and finding the maximum required alignment. We
1554 // could consider caching this in the Class.
1555 int max_align
= __alignof__ (java::lang::Object
);
1556 jclass super
= klass
->getSuperclass();
1557 while (super
!= NULL
)
1559 // Ensure that our super has its super installed before
1561 wait_for_state(super
, JV_STATE_LOADING
);
1562 ensure_fields_laid_out(super
);
1563 int num
= JvNumInstanceFields (super
);
1564 _Jv_Field
*field
= JvGetFirstInstanceField (super
);
1567 int field_align
= get_alignment_from_class (field
->type
);
1568 if (field_align
> max_align
)
1569 max_align
= field_align
;
1573 super
= super
->getSuperclass();
1577 // This is the size of the 'static' non-reference fields.
1578 int non_reference_size
= 0;
1579 // This is the size of the 'static' reference fields. We count
1580 // these separately to make it simpler for the GC to scan them.
1581 int reference_size
= 0;
1583 // Although java.lang.Object is never interpreted, an interface can
1584 // have a null superclass. Note that we have to lay out an
1585 // interface because it might have static fields.
1586 if (klass
->superclass
)
1587 instance_size
= klass
->superclass
->size();
1589 instance_size
= java::lang::Object::class$
.size();
1591 klass
->engine
->allocate_field_initializers (klass
);
1593 for (int i
= 0; i
< klass
->field_count
; i
++)
1598 _Jv_Field
*field
= &klass
->fields
[i
];
1600 if (! field
->isRef ())
1602 // It is safe to resolve the field here, since it's a
1603 // primitive class, which does not cause loading to happen.
1604 resolve_field (field
, klass
->loader
);
1605 field_size
= field
->type
->size ();
1606 field_align
= get_alignment_from_class (field
->type
);
1610 field_size
= sizeof (jobject
);
1611 field_align
= __alignof__ (jobject
);
1614 field
->bsize
= field_size
;
1616 if ((field
->flags
& java::lang::reflect::Modifier::STATIC
))
1618 if (field
->u
.addr
== NULL
)
1620 // This computes an offset into a region we'll allocate
1621 // shortly, and then adds this offset to the start
1625 reference_size
= ROUND (reference_size
, field_align
);
1626 field
->u
.boffset
= reference_size
;
1627 reference_size
+= field_size
;
1631 non_reference_size
= ROUND (non_reference_size
, field_align
);
1632 field
->u
.boffset
= non_reference_size
;
1633 non_reference_size
+= field_size
;
1639 instance_size
= ROUND (instance_size
, field_align
);
1640 field
->u
.boffset
= instance_size
;
1641 instance_size
+= field_size
;
1642 if (field_align
> max_align
)
1643 max_align
= field_align
;
1647 if (reference_size
!= 0 || non_reference_size
!= 0)
1648 klass
->engine
->allocate_static_fields (klass
, reference_size
,
1649 non_reference_size
);
1651 // Set the instance size for the class. Note that first we round it
1652 // to the alignment required for this object; this keeps us in sync
1653 // with our current ABI.
1654 instance_size
= ROUND (instance_size
, max_align
);
1655 klass
->size_in_bytes
= instance_size
;
1658 // This takes the class to state JV_STATE_LINKED. The class lock must
1659 // be held when calling this.
1661 _Jv_Linker::ensure_class_linked (jclass klass
)
1663 if (klass
->state
>= JV_STATE_LINKED
)
1666 int state
= klass
->state
;
1669 // Short-circuit, so that mutually dependent classes are ok.
1670 klass
->state
= JV_STATE_LINKED
;
1672 _Jv_Constants
*pool
= &klass
->constants
;
1674 // Compiled classes require that their class constants be
1675 // resolved here. However, interpreted classes need their
1676 // constants to be resolved lazily. If we resolve an
1677 // interpreted class' constants eagerly, we can end up with
1678 // spurious IllegalAccessErrors when the constant pool contains
1679 // a reference to a class we can't access. This can validly
1680 // occur in an obscure case involving the InnerClasses
1682 if (! _Jv_IsInterpretedClass (klass
))
1684 // Resolve class constants first, since other constant pool
1685 // entries may rely on these.
1686 for (int index
= 1; index
< pool
->size
; ++index
)
1688 if (pool
->tags
[index
] == JV_CONSTANT_Class
)
1689 // Lazily resolve the entries.
1690 resolve_pool_entry (klass
, index
, true);
1694 // Resolve the remaining constant pool entries.
1695 for (int index
= 1; index
< pool
->size
; ++index
)
1697 if (pool
->tags
[index
] == JV_CONSTANT_String
)
1701 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
1702 pool
->data
[index
].o
= str
;
1703 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
1707 if (klass
->engine
->need_resolve_string_fields())
1709 jfieldID f
= JvGetFirstStaticField (klass
);
1710 for (int n
= JvNumStaticFields (klass
); n
> 0; --n
)
1712 int mod
= f
->getModifiers ();
1713 // If we have a static String field with a non-null initial
1714 // value, we know it points to a Utf8Const.
1716 // Finds out whether we have to initialize a String without the
1717 // need to resolve the field.
1718 if ((f
->isResolved()
1719 ? (f
->type
== &java::lang::String::class$
)
1720 : _Jv_equalUtf8Classnames((_Jv_Utf8Const
*) f
->type
,
1721 java::lang::String::class$
.name
))
1722 && (mod
& java::lang::reflect::Modifier::STATIC
) != 0)
1724 jstring
*strp
= (jstring
*) f
->u
.addr
;
1726 *strp
= _Jv_NewStringUtf8Const ((_Jv_Utf8Const
*) *strp
);
1728 f
= f
->getNextField ();
1732 klass
->notifyAll ();
1734 _Jv_PushClass (klass
);
1736 catch (java::lang::Throwable
*t
)
1738 klass
->state
= state
;
1743 // This ensures that symbolic superclass and superinterface references
1744 // are resolved for the indicated class. This must be called with the
1747 _Jv_Linker::ensure_supers_installed (jclass klass
)
1749 resolve_class_ref (klass
, &klass
->superclass
);
1750 // An interface won't have a superclass.
1751 if (klass
->superclass
)
1752 wait_for_state (klass
->superclass
, JV_STATE_LOADING
);
1754 for (int i
= 0; i
< klass
->interface_count
; ++i
)
1756 resolve_class_ref (klass
, &klass
->interfaces
[i
]);
1757 wait_for_state (klass
->interfaces
[i
], JV_STATE_LOADING
);
1761 // This adds missing `Miranda methods' to a class.
1763 _Jv_Linker::add_miranda_methods (jclass base
, jclass iface_class
)
1765 // Note that at this point, all our supers, and the supers of all
1766 // our superclasses and superinterfaces, will have been installed.
1768 for (int i
= 0; i
< iface_class
->interface_count
; ++i
)
1770 jclass interface
= iface_class
->interfaces
[i
];
1772 for (int j
= 0; j
< interface
->method_count
; ++j
)
1774 _Jv_Method
*meth
= &interface
->methods
[j
];
1775 // Don't bother with <clinit>.
1776 if (meth
->name
->first() == '<')
1778 _Jv_Method
*new_meth
= _Jv_LookupDeclaredMethod (base
, meth
->name
,
1782 // We assume that such methods are very unlikely, so we
1783 // just reallocate the method array each time one is
1784 // found. This greatly simplifies the searching --
1785 // otherwise we have to make sure that each such method
1786 // found is really unique among all superinterfaces.
1787 int new_count
= base
->method_count
+ 1;
1789 = (_Jv_Method
*) _Jv_AllocRawObj (sizeof (_Jv_Method
)
1791 memcpy (new_m
, base
->methods
,
1792 sizeof (_Jv_Method
) * base
->method_count
);
1795 new_m
[base
->method_count
] = *meth
;
1796 new_m
[base
->method_count
].index
= (_Jv_ushort
) -1;
1797 new_m
[base
->method_count
].accflags
1798 |= java::lang::reflect::Modifier::INVISIBLE
;
1800 base
->methods
= new_m
;
1801 base
->method_count
= new_count
;
1805 wait_for_state (interface
, JV_STATE_LOADED
);
1806 add_miranda_methods (base
, interface
);
1810 // This ensures that the class' method table is "complete". This must
1811 // be called with the class lock held.
1813 _Jv_Linker::ensure_method_table_complete (jclass klass
)
1815 if (klass
->vtable
!= NULL
)
1818 // We need our superclass to have its own Miranda methods installed.
1819 if (! klass
->isInterface())
1820 wait_for_state (klass
->getSuperclass (), JV_STATE_LOADED
);
1822 // A class might have so-called "Miranda methods". This is a method
1823 // that is declared in an interface and not re-declared in an
1824 // abstract class. Some compilers don't emit declarations for such
1825 // methods in the class; this will give us problems since we expect
1826 // a declaration for any method requiring a vtable entry. We handle
1827 // this here by searching for such methods and constructing new
1828 // internal declarations for them. Note that we do this
1829 // unconditionally, and not just for abstract classes, to correctly
1830 // account for cases where a class is modified to be concrete and
1831 // still incorrectly inherits an abstract method.
1832 int pre_count
= klass
->method_count
;
1833 add_miranda_methods (klass
, klass
);
1835 // Let the execution engine know that we've added methods.
1836 if (klass
->method_count
!= pre_count
)
1837 klass
->engine
->post_miranda_hook(klass
);
1840 // Verify a class. Must be called with class lock held.
1842 _Jv_Linker::verify_class (jclass klass
)
1844 klass
->engine
->verify(klass
);
1847 // Check the assertions contained in the type assertion table for KLASS.
1848 // This is the equivilent of bytecode verification for native, BC-ABI code.
1850 _Jv_Linker::verify_type_assertions (jclass klass
)
1853 fprintf (stderr
, "Evaluating type assertions for %s:\n",
1854 klass
->name
->chars());
1856 if (klass
->assertion_table
== NULL
)
1859 for (int i
= 0;; i
++)
1861 int assertion_code
= klass
->assertion_table
[i
].assertion_code
;
1862 _Jv_Utf8Const
*op1
= klass
->assertion_table
[i
].op1
;
1863 _Jv_Utf8Const
*op2
= klass
->assertion_table
[i
].op2
;
1865 if (assertion_code
== JV_ASSERT_END_OF_TABLE
)
1867 else if (assertion_code
== JV_ASSERT_TYPES_COMPATIBLE
)
1871 fprintf (stderr
, " code=%i, operand A=%s B=%s\n",
1872 assertion_code
, op1
->chars(), op2
->chars());
1875 // The operands are class signatures. op1 is the source,
1876 // op2 is the target.
1877 jclass cl1
= _Jv_FindClassFromSignature (op1
->chars(),
1878 klass
->getClassLoaderInternal());
1879 jclass cl2
= _Jv_FindClassFromSignature (op2
->chars(),
1880 klass
->getClassLoaderInternal());
1882 // If the class doesn't exist, ignore the assertion. An exception
1883 // will be thrown later if an attempt is made to actually
1884 // instantiate the class.
1885 if (cl1
== NULL
|| cl2
== NULL
)
1888 if (! _Jv_IsAssignableFromSlow (cl1
, cl2
))
1890 jstring s
= JvNewStringUTF ("Incompatible types: In class ");
1891 s
= s
->concat (klass
->getName());
1892 s
= s
->concat (JvNewStringUTF (": "));
1893 s
= s
->concat (cl1
->getName());
1894 s
= s
->concat (JvNewStringUTF (" is not assignable to "));
1895 s
= s
->concat (cl2
->getName());
1896 throw new java::lang::VerifyError (s
);
1899 else if (assertion_code
== JV_ASSERT_IS_INSTANTIABLE
)
1901 // TODO: Implement this.
1903 // Unknown assertion codes are ignored, for forwards-compatibility.
1908 _Jv_Linker::print_class_loaded (jclass klass
)
1910 char *codesource
= NULL
;
1911 if (klass
->protectionDomain
!= NULL
)
1913 java::security::CodeSource
*cs
1914 = klass
->protectionDomain
->getCodeSource();
1917 jstring css
= cs
->toString();
1918 int len
= JvGetStringUTFLength(css
);
1919 codesource
= (char *) _Jv_AllocBytes(len
+ 1);
1920 JvGetStringUTFRegion(css
, 0, css
->length(), codesource
);
1921 codesource
[len
] = '\0';
1924 if (codesource
== NULL
)
1925 codesource
= (char *) "<no code source>";
1928 if (_Jv_IsInterpretedClass (klass
))
1930 else if (_Jv_IsBinaryCompatibilityABI (klass
))
1931 abi
= "BC-compiled";
1933 abi
= "pre-compiled";
1935 fprintf (stderr
, "[Loaded (%s) %s from %s]\n", abi
, klass
->name
->chars(),
1939 // FIXME: mention invariants and stuff.
1941 _Jv_Linker::wait_for_state (jclass klass
, int state
)
1943 if (klass
->state
>= state
)
1946 java::lang::Thread
*self
= java::lang::Thread::currentThread();
1949 JvSynchronize
sync (klass
);
1951 // This is similar to the strategy for class initialization. If we
1952 // already hold the lock, just leave.
1953 while (klass
->state
<= state
1955 && klass
->thread
!= self
)
1958 java::lang::Thread
*save
= klass
->thread
;
1959 klass
->thread
= self
;
1961 // Allocate memory for static fields and constants.
1962 if (GC_base (klass
) && klass
->fields
&& ! GC_base (klass
->fields
))
1964 jsize count
= klass
->field_count
;
1968 = (_Jv_Field
*) _Jv_AllocRawObj (count
* sizeof (_Jv_Field
));
1969 memcpy ((void*)fields
,
1970 (void*)klass
->fields
,
1971 count
* sizeof (_Jv_Field
));
1972 klass
->fields
= fields
;
1976 // Print some debugging info if requested. Interpreted classes are
1977 // handled in defineclass, so we only need to handle the two
1978 // pre-compiled cases here.
1979 if ((klass
->state
== JV_STATE_COMPILED
1980 || klass
->state
== JV_STATE_PRELOADING
)
1981 && ! _Jv_IsInterpretedClass (klass
))
1983 if (gcj::verbose_class_flag
)
1984 print_class_loaded (klass
);
1985 ++gcj::loadedClasses
;
1990 if (state
>= JV_STATE_LOADING
&& klass
->state
< JV_STATE_LOADING
)
1992 ensure_supers_installed (klass
);
1993 klass
->set_state(JV_STATE_LOADING
);
1996 if (state
>= JV_STATE_LOADED
&& klass
->state
< JV_STATE_LOADED
)
1998 ensure_method_table_complete (klass
);
1999 klass
->set_state(JV_STATE_LOADED
);
2002 if (state
>= JV_STATE_PREPARED
&& klass
->state
< JV_STATE_PREPARED
)
2004 ensure_fields_laid_out (klass
);
2005 make_vtable (klass
);
2006 layout_interface_methods (klass
);
2007 prepare_constant_time_tables (klass
);
2008 klass
->set_state(JV_STATE_PREPARED
);
2011 if (state
>= JV_STATE_LINKED
&& klass
->state
< JV_STATE_LINKED
)
2013 if (gcj::verifyClasses
)
2014 verify_class (klass
);
2016 ensure_class_linked (klass
);
2017 link_exception_table (klass
);
2018 link_symbol_table (klass
);
2019 klass
->set_state(JV_STATE_LINKED
);
2022 catch (java::lang::Throwable
*exc
)
2024 klass
->thread
= save
;
2025 klass
->set_state(JV_STATE_ERROR
);
2029 klass
->thread
= save
;
2031 if (klass
->state
== JV_STATE_ERROR
)
2032 throw new java::lang::LinkageError
;
2035 if (__builtin_expect (klass
->state
== JV_STATE_LINKED
, false)
2036 && state
>= JV_STATE_LINKED
2037 && JVMTI_REQUESTED_EVENT (ClassPrepare
))
2039 JNIEnv
*jni_env
= _Jv_GetCurrentJNIEnv ();
2040 _Jv_JVMTI_PostEvent (JVMTI_EVENT_CLASS_PREPARE
, self
, jni_env
,