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>
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_method_entry (jclass klass
, jclass
&found_class
,
269 int class_index
, int name_and_type_index
,
270 bool init
, bool is_iface
)
272 _Jv_Constants
*pool
= &klass
->constants
;
273 jclass owner
= resolve_pool_entry (klass
, class_index
).clazz
;
275 if (init
&& owner
!= klass
)
276 _Jv_InitClass (owner
);
278 _Jv_ushort name_index
, type_index
;
279 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
283 _Jv_Utf8Const
*method_name
= pool
->data
[name_index
].utf8
;
284 _Jv_Utf8Const
*method_signature
= pool
->data
[type_index
].utf8
;
286 _Jv_Method
*the_method
= 0;
289 // We're going to cache a pointer to the _Jv_Method object
290 // when we find it. So, to ensure this doesn't get moved from
291 // beneath us, we first put all the needed Miranda methods
292 // into the target class.
293 wait_for_state (klass
, JV_STATE_LOADED
);
295 // First search the class itself.
296 the_method
= search_method_in_class (owner
, klass
,
297 method_name
, method_signature
);
302 goto end_of_method_search
;
305 // If we are resolving an interface method, search the
306 // interface's superinterfaces (A superinterface is not an
307 // interface's superclass - a superinterface is implemented by
314 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
315 * sizeof (jclass
*));
317 get_interfaces (owner
, &ifaces
);
319 for (int i
= 0; i
< ifaces
.count
; i
++)
321 jclass cls
= ifaces
.list
[i
];
322 the_method
= search_method_in_class (cls
, klass
, method_name
,
331 _Jv_Free (ifaces
.list
);
334 goto end_of_method_search
;
337 // Finally, search superclasses.
338 the_method
= (search_method_in_superclasses
339 (owner
->getSuperclass (), klass
, method_name
,
340 method_signature
, &found_class
));
343 end_of_method_search
:
345 // FIXME: if (cls->loader != klass->loader), then we
346 // must actually check that the types of arguments
347 // correspond. That is, for each argument type, and
348 // the return type, doing _Jv_FindClassFromSignature
349 // with either loader should produce the same result,
350 // i.e., exactly the same jclass object. JVMS 5.4.3.3
354 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
355 sb
->append(JvNewStringLatin1("method "));
356 sb
->append(owner
->getName());
357 sb
->append(JvNewStringLatin1("."));
358 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
359 sb
->append(JvNewStringLatin1(" with signature "));
360 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
361 sb
->append(JvNewStringLatin1(" was not found."));
362 throw new java::lang::NoSuchMethodError (sb
->toString());
369 _Jv_Linker::resolve_pool_entry (jclass klass
, int index
, bool lazy
)
371 using namespace java::lang::reflect
;
373 if (GC_base (klass
) && klass
->constants
.data
374 && ! GC_base (klass
->constants
.data
))
376 jsize count
= klass
->constants
.size
;
380 = (_Jv_word
*) _Jv_AllocRawObj (count
* sizeof (_Jv_word
));
381 memcpy ((void*)constants
,
382 (void*)klass
->constants
.data
,
383 count
* sizeof (_Jv_word
));
384 klass
->constants
.data
= constants
;
388 _Jv_Constants
*pool
= &klass
->constants
;
390 if ((pool
->tags
[index
] & JV_CONSTANT_ResolvedFlag
) != 0)
391 return pool
->data
[index
];
393 switch (pool
->tags
[index
] & ~JV_CONSTANT_LazyFlag
)
395 case JV_CONSTANT_Class
:
397 _Jv_Utf8Const
*name
= pool
->data
[index
].utf8
;
400 if (name
->first() == '[')
401 found
= _Jv_FindClassFromSignatureNoException (name
->chars(),
404 found
= _Jv_FindClassNoException (name
, klass
->loader
);
406 // If the class could not be loaded a phantom class is created. Any
407 // function that deals with such a class but cannot do something useful
408 // with it should just throw a NoClassDefFoundError with the class'
414 found
= _Jv_NewClass(name
, NULL
, NULL
);
415 found
->state
= JV_STATE_PHANTOM
;
416 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
417 pool
->data
[index
].clazz
= found
;
421 throw new java::lang::NoClassDefFoundError (name
->toString());
424 // Check accessibility, but first strip array types as
425 // _Jv_ClassNameSamePackage can't handle arrays.
428 check
&& check
->isArray();
429 check
= check
->getComponentType())
431 if ((found
->accflags
& Modifier::PUBLIC
) == Modifier::PUBLIC
432 || (_Jv_ClassNameSamePackage (check
->name
,
435 pool
->data
[index
].clazz
= found
;
436 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
440 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer ();
441 sb
->append(klass
->getName());
442 sb
->append(JvNewStringLatin1(" can't access class "));
443 sb
->append(found
->getName());
444 throw new java::lang::IllegalAccessError(sb
->toString());
449 case JV_CONSTANT_String
:
452 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
453 pool
->data
[index
].o
= str
;
454 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
458 case JV_CONSTANT_Fieldref
:
460 _Jv_ushort class_index
, name_and_type_index
;
461 _Jv_loadIndexes (&pool
->data
[index
],
463 name_and_type_index
);
464 jclass owner
= (resolve_pool_entry (klass
, class_index
, true)).clazz
;
466 // If a phantom class was resolved our field reference is
467 // unusable because of the missing class.
468 if (owner
->state
== JV_STATE_PHANTOM
)
469 throw new java::lang::NoClassDefFoundError(owner
->getName());
471 // We don't initialize 'owner', but we do make sure that its
473 wait_for_state (owner
, JV_STATE_PREPARED
);
475 _Jv_ushort name_index
, type_index
;
476 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
480 _Jv_Utf8Const
*field_name
= pool
->data
[name_index
].utf8
;
481 _Jv_Utf8Const
*field_type_name
= pool
->data
[type_index
].utf8
;
483 jclass found_class
= 0;
484 _Jv_Field
*the_field
= find_field (klass
, owner
,
488 // Initialize the field's declaring class, not its qualifying
490 _Jv_InitClass (found_class
);
491 pool
->data
[index
].field
= the_field
;
492 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
496 case JV_CONSTANT_Methodref
:
497 case JV_CONSTANT_InterfaceMethodref
:
499 _Jv_ushort class_index
, name_and_type_index
;
500 _Jv_loadIndexes (&pool
->data
[index
],
502 name_and_type_index
);
504 _Jv_Method
*the_method
;
506 the_method
= resolve_method_entry (klass
, found_class
,
507 class_index
, name_and_type_index
,
509 pool
->tags
[index
] == JV_CONSTANT_InterfaceMethodref
);
511 pool
->data
[index
].rmethod
512 = klass
->engine
->resolve_method(the_method
,
514 ((the_method
->accflags
515 & Modifier::STATIC
) != 0));
516 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
520 return pool
->data
[index
];
523 // This function is used to lazily locate superclasses and
524 // superinterfaces. This must be called with the class lock held.
526 _Jv_Linker::resolve_class_ref (jclass klass
, jclass
*classref
)
528 jclass ret
= *classref
;
530 // If superclass looks like a constant pool entry, resolve it now.
531 if (ret
&& (uaddr
) ret
< (uaddr
) klass
->constants
.size
)
533 if (klass
->state
< JV_STATE_LINKED
)
535 _Jv_Utf8Const
*name
= klass
->constants
.data
[(uaddr
) *classref
].utf8
;
536 ret
= _Jv_FindClass (name
, klass
->loader
);
539 throw new java::lang::NoClassDefFoundError (name
->toString());
543 ret
= klass
->constants
.data
[(uaddr
) classref
].clazz
;
548 // Find a method declared in the cls that is referenced from klass and
549 // perform access checks if CHECK_PERMS is true.
551 _Jv_Linker::search_method_in_class (jclass cls
, jclass klass
,
552 _Jv_Utf8Const
*method_name
,
553 _Jv_Utf8Const
*method_signature
,
556 using namespace java::lang::reflect
;
558 for (int i
= 0; i
< cls
->method_count
; i
++)
560 _Jv_Method
*method
= &cls
->methods
[i
];
561 if ( (!_Jv_equalUtf8Consts (method
->name
,
563 || (!_Jv_equalUtf8Consts (method
->signature
,
567 if (!check_perms
|| _Jv_CheckAccess (klass
, cls
, method
->accflags
))
571 java::lang::StringBuffer
*sb
= new java::lang::StringBuffer();
572 sb
->append(klass
->getName());
573 sb
->append(JvNewStringLatin1(": "));
574 sb
->append(cls
->getName());
575 sb
->append(JvNewStringLatin1("."));
576 sb
->append(_Jv_NewStringUTF(method_name
->chars()));
577 sb
->append(_Jv_NewStringUTF(method_signature
->chars()));
578 throw new java::lang::IllegalAccessError (sb
->toString());
584 // Like search_method_in_class, but work our way up the superclass
587 _Jv_Linker::search_method_in_superclasses (jclass cls
, jclass klass
,
588 _Jv_Utf8Const
*method_name
,
589 _Jv_Utf8Const
*method_signature
,
590 jclass
*found_class
, bool check_perms
)
592 _Jv_Method
*the_method
= NULL
;
594 for ( ; cls
!= 0; cls
= cls
->getSuperclass ())
596 the_method
= search_method_in_class (cls
, klass
, method_name
,
597 method_signature
, check_perms
);
609 #define INITIAL_IOFFSETS_LEN 4
610 #define INITIAL_IFACES_LEN 4
612 static _Jv_IDispatchTable null_idt
= {SHRT_MAX
, 0, {}};
614 // Generate tables for constant-time assignment testing and interface
615 // method lookup. This implements the technique described by Per Bothner
616 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
617 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
619 _Jv_Linker::prepare_constant_time_tables (jclass klass
)
621 if (klass
->isPrimitive () || klass
->isInterface ())
624 // Short-circuit in case we've been called already.
625 if ((klass
->idt
!= NULL
) || klass
->depth
!= 0)
628 // Calculate the class depth and ancestor table. The depth of a class
629 // is how many "extends" it is removed from Object. Thus the depth of
630 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
631 // is 2. Depth is defined for all regular and array classes, but not
632 // interfaces or primitive types.
634 jclass klass0
= klass
;
635 jboolean has_interfaces
= 0;
636 while (klass0
!= &java::lang::Object::class$
)
638 has_interfaces
+= klass0
->interface_count
;
639 klass0
= klass0
->superclass
;
643 // We do class member testing in constant time by using a small table
644 // of all the ancestor classes within each class. The first element is
645 // a pointer to the current class, and the rest are pointers to the
646 // classes ancestors, ordered from the current class down by decreasing
647 // depth. We do not include java.lang.Object in the table of ancestors,
648 // since it is redundant. Note that the classes pointed to by
649 // 'ancestors' will always be reachable by other paths.
651 klass
->ancestors
= (jclass
*) _Jv_AllocBytes (klass
->depth
654 for (int index
= 0; index
< klass
->depth
; index
++)
656 klass
->ancestors
[index
] = klass0
;
657 klass0
= klass0
->superclass
;
660 if ((klass
->accflags
& java::lang::reflect::Modifier::ABSTRACT
) != 0)
663 // Optimization: If class implements no interfaces, use a common
664 // predefined interface table.
667 klass
->idt
= &null_idt
;
673 ifaces
.len
= INITIAL_IFACES_LEN
;
674 ifaces
.list
= (jclass
*) _Jv_Malloc (ifaces
.len
* sizeof (jclass
*));
676 int itable_size
= get_interfaces (klass
, &ifaces
);
678 if (ifaces
.count
> 0)
680 // The classes pointed to by the itable will always be reachable
682 int idt_bytes
= sizeof (_Jv_IDispatchTable
) + (itable_size
684 klass
->idt
= (_Jv_IDispatchTable
*) _Jv_AllocBytes (idt_bytes
);
685 klass
->idt
->itable_length
= itable_size
;
687 jshort
*itable_offsets
=
688 (jshort
*) _Jv_Malloc (ifaces
.count
* sizeof (jshort
));
690 generate_itable (klass
, &ifaces
, itable_offsets
);
692 jshort cls_iindex
= find_iindex (ifaces
.list
, itable_offsets
,
695 for (int i
= 0; i
< ifaces
.count
; i
++)
697 ifaces
.list
[i
]->ioffsets
[cls_iindex
] = itable_offsets
[i
];
700 klass
->idt
->iindex
= cls_iindex
;
702 _Jv_Free (ifaces
.list
);
703 _Jv_Free (itable_offsets
);
707 klass
->idt
->iindex
= SHRT_MAX
;
711 // Return index of item in list, or -1 if item is not present.
713 _Jv_Linker::indexof (void *item
, void **list
, jshort list_len
)
715 for (int i
=0; i
< list_len
; i
++)
723 // Find all unique interfaces directly or indirectly implemented by klass.
724 // Returns the size of the interface dispatch table (itable) for klass, which
725 // is the number of unique interfaces plus the total number of methods that
726 // those interfaces declare. May extend ifaces if required.
728 _Jv_Linker::get_interfaces (jclass klass
, _Jv_ifaces
*ifaces
)
732 for (int i
= 0; i
< klass
->interface_count
; i
++)
734 jclass iface
= klass
->interfaces
[i
];
736 /* Make sure interface is linked. */
737 wait_for_state(iface
, JV_STATE_LINKED
);
739 if (indexof (iface
, (void **) ifaces
->list
, ifaces
->count
) == -1)
741 if (ifaces
->count
+ 1 >= ifaces
->len
)
743 /* Resize ifaces list */
744 ifaces
->len
= ifaces
->len
* 2;
746 = (jclass
*) _Jv_Realloc (ifaces
->list
,
747 ifaces
->len
* sizeof(jclass
));
749 ifaces
->list
[ifaces
->count
] = iface
;
752 result
+= get_interfaces (klass
->interfaces
[i
], ifaces
);
756 if (klass
->isInterface())
758 // We want to add 1 plus the number of interface methods here.
759 // But, we take special care to skip <clinit>.
761 for (int i
= 0; i
< klass
->method_count
; ++i
)
763 if (klass
->methods
[i
].name
->first() != '<')
767 else if (klass
->superclass
)
768 result
+= get_interfaces (klass
->superclass
, ifaces
);
772 // Fill out itable in klass, resolving method declarations in each ifaces.
773 // itable_offsets is filled out with the position of each iface in itable,
774 // such that itable[itable_offsets[n]] == ifaces.list[n].
776 _Jv_Linker::generate_itable (jclass klass
, _Jv_ifaces
*ifaces
,
777 jshort
*itable_offsets
)
779 void **itable
= klass
->idt
->itable
;
780 jshort itable_pos
= 0;
782 for (int i
= 0; i
< ifaces
->count
; i
++)
784 jclass iface
= ifaces
->list
[i
];
785 itable_offsets
[i
] = itable_pos
;
786 itable_pos
= append_partial_itable (klass
, iface
, itable
, itable_pos
);
788 /* Create ioffsets table for iface */
789 if (iface
->ioffsets
== NULL
)
791 // The first element of ioffsets is its length (itself included).
792 jshort
*ioffsets
= (jshort
*) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
794 ioffsets
[0] = INITIAL_IOFFSETS_LEN
;
795 for (int i
= 1; i
< INITIAL_IOFFSETS_LEN
; i
++)
798 iface
->ioffsets
= ioffsets
;
803 // Format method name for use in error messages.
805 _Jv_GetMethodString (jclass klass
, _Jv_Method
*meth
,
808 using namespace java::lang
;
809 StringBuffer
*buf
= new StringBuffer (klass
->name
->toString());
810 buf
->append (jchar ('.'));
811 buf
->append (meth
->name
->toString());
812 buf
->append ((jchar
) ' ');
813 buf
->append (meth
->signature
->toString());
816 buf
->append(JvNewStringLatin1(" in "));
817 buf
->append(derived
->name
->toString());
819 return buf
->toString();
823 _Jv_ThrowNoSuchMethodError ()
825 throw new java::lang::NoSuchMethodError
;
828 #if defined USE_LIBFFI && FFI_CLOSURES
829 // A function whose invocation is prepared using libffi. It gets called
830 // whenever a static method of a missing class is invoked. The data argument
831 // holds a reference to a String denoting the missing class.
832 // The prepared function call is stored in a class' atable.
834 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif
*,
839 throw new java::lang::NoClassDefFoundError(
840 _Jv_NewStringUtf8Const((_Jv_Utf8Const
*) data
));
843 // A variant of the NoClassDefFoundError throwing method that can
844 // be used without libffi.
846 _Jv_ThrowNoClassDefFoundError()
848 throw new java::lang::NoClassDefFoundError();
852 // Throw a NoSuchFieldError. Called by compiler-generated code when
853 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
854 // otable that refers to the missing field. This index may be used to
855 // print diagnostic information about the field.
857 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
859 throw new java::lang::NoSuchFieldError
;
862 // This is put in empty vtable slots.
864 _Jv_ThrowAbstractMethodError ()
866 throw new java::lang::AbstractMethodError();
869 // Each superinterface of a class (i.e. each interface that the class
870 // directly or indirectly implements) has a corresponding "Partial
871 // Interface Dispatch Table" whose size is (number of methods + 1) words.
872 // The first word is a pointer to the interface (i.e. the java.lang.Class
873 // instance for that interface). The remaining words are pointers to the
874 // actual methods that implement the methods declared in the interface,
875 // in order of declaration.
877 // Append partial interface dispatch table for "iface" to "itable", at
878 // position itable_pos.
879 // Returns the offset at which the next partial ITable should be appended.
881 _Jv_Linker::append_partial_itable (jclass klass
, jclass iface
,
882 void **itable
, jshort pos
)
884 using namespace java::lang::reflect
;
886 itable
[pos
++] = (void *) iface
;
889 for (int j
=0; j
< iface
->method_count
; j
++)
891 // Skip '<clinit>' here.
892 if (iface
->methods
[j
].name
->first() == '<')
896 for (jclass cl
= klass
; cl
; cl
= cl
->getSuperclass())
898 meth
= _Jv_GetMethodLocal (cl
, iface
->methods
[j
].name
,
899 iface
->methods
[j
].signature
);
907 if ((meth
->accflags
& Modifier::STATIC
) != 0)
908 throw new java::lang::IncompatibleClassChangeError
909 (_Jv_GetMethodString (klass
, meth
));
910 if ((meth
->accflags
& Modifier::PUBLIC
) == 0)
911 throw new java::lang::IllegalAccessError
912 (_Jv_GetMethodString (klass
, meth
));
914 if ((meth
->accflags
& Modifier::ABSTRACT
) != 0)
915 itable
[pos
] = (void *) &_Jv_ThrowAbstractMethodError
;
917 itable
[pos
] = meth
->ncode
;
921 // The method doesn't exist in klass. Binary compatibility rules
922 // permit this, so we delay the error until runtime using a pointer
923 // to a method which throws an exception.
924 itable
[pos
] = (void *) _Jv_ThrowNoSuchMethodError
;
932 static _Jv_Mutex_t iindex_mutex
;
933 static bool iindex_mutex_initialized
= false;
935 // We need to find the correct offset in the Class Interface Dispatch
936 // Table for a given interface. Once we have that, invoking an interface
937 // method just requires combining the Method's index in the interface
938 // (known at compile time) to get the correct method. Doing a type test
939 // (cast or instanceof) is the same problem: Once we have a possible Partial
940 // Interface Dispatch Table, we just compare the first element to see if it
941 // matches the desired interface. So how can we find the correct offset?
942 // Our solution is to keep a vector of candiate offsets in each interface
943 // (ioffsets), and in each class we have an index (idt->iindex) used to
944 // select the correct offset from ioffsets.
946 // Calculate and return iindex for a new class.
947 // ifaces is a vector of num interfaces that the class implements.
948 // offsets[j] is the offset in the interface dispatch table for the
949 // interface corresponding to ifaces[j].
950 // May extend the interface ioffsets if required.
952 _Jv_Linker::find_iindex (jclass
*ifaces
, jshort
*offsets
, jshort num
)
957 // Acquire a global lock to prevent itable corruption in case of multiple
958 // classes that implement an intersecting set of interfaces being linked
959 // simultaneously. We can assume that the mutex will be initialized
961 if (! iindex_mutex_initialized
)
963 _Jv_MutexInit (&iindex_mutex
);
964 iindex_mutex_initialized
= true;
967 _Jv_MutexLock (&iindex_mutex
);
969 for (i
=1;; i
++) /* each potential position in ioffsets */
971 for (j
=0;; j
++) /* each iface */
975 if (i
>= ifaces
[j
]->ioffsets
[0])
977 int ioffset
= ifaces
[j
]->ioffsets
[i
];
978 /* We can potentially share this position with another class. */
979 if (ioffset
>= 0 && ioffset
!= offsets
[j
])
980 break; /* Nope. Try next i. */
984 for (j
= 0; j
< num
; j
++)
986 int len
= ifaces
[j
]->ioffsets
[0];
990 int newlen
= 2 * len
;
994 jshort
*old_ioffsets
= ifaces
[j
]->ioffsets
;
995 jshort
*new_ioffsets
= (jshort
*) _Jv_AllocBytes (newlen
997 memcpy (&new_ioffsets
[1], &old_ioffsets
[1],
998 (len
- 1) * sizeof (jshort
));
999 new_ioffsets
[0] = newlen
;
1001 while (len
< newlen
)
1002 new_ioffsets
[len
++] = -1;
1004 ifaces
[j
]->ioffsets
= new_ioffsets
;
1006 ifaces
[j
]->ioffsets
[i
] = offsets
[j
];
1009 _Jv_MutexUnlock (&iindex_mutex
);
1014 #if defined USE_LIBFFI && FFI_CLOSURES
1015 // We use a structure of this type to store the closure that
1016 // represents a missing method.
1017 struct method_closure
1019 // This field must come first, since the address of this field will
1020 // be the same as the address of the overall structure. This is due
1021 // to disabling interior pointers in the GC.
1022 ffi_closure closure
;
1024 ffi_type
*arg_types
[1];
1028 _Jv_Linker::create_error_method (_Jv_Utf8Const
*class_name
)
1030 method_closure
*closure
1031 = (method_closure
*) _Jv_AllocBytes(sizeof (method_closure
));
1033 closure
->arg_types
[0] = &ffi_type_void
;
1035 // Initializes the cif and the closure. If that worked the closure
1036 // is returned and can be used as a function pointer in a class'
1038 if ( ffi_prep_cif (&closure
->cif
,
1042 closure
->arg_types
) == FFI_OK
1043 && ffi_prep_closure (&closure
->closure
,
1045 _Jv_ThrowNoClassDefFoundErrorTrampoline
,
1046 class_name
) == FFI_OK
)
1047 return &closure
->closure
;
1050 java::lang::StringBuffer
*buffer
= new java::lang::StringBuffer();
1051 buffer
->append(JvNewStringLatin1("Error setting up FFI closure"
1052 " for static method of"
1053 " missing class: "));
1054 buffer
->append (_Jv_NewStringUtf8Const(class_name
));
1055 throw new java::lang::InternalError(buffer
->toString());
1060 _Jv_Linker::create_error_method (_Jv_Utf8Const
*)
1062 // Codepath for platforms which do not support (or want) libffi.
1063 // You have to accept that it is impossible to provide the name
1064 // of the missing class then.
1065 return (void *) _Jv_ThrowNoClassDefFoundError
;
1067 #endif // USE_LIBFFI && FFI_CLOSURES
1069 // Functions for indirect dispatch (symbolic virtual binding) support.
1071 // There are three tables, atable otable and itable. atable is an
1072 // array of addresses, and otable is an array of offsets, and these
1073 // are used for static and virtual members respectively. itable is an
1074 // array of pairs {address, index} where each address is a pointer to
1077 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1078 // symbol is a tuple of {classname, member name, signature}.
1080 // Set this to true to enable debugging of indirect dispatch tables/linking.
1081 static bool debug_link
= false;
1083 // link_symbol_table() scans these two arrays and fills in the
1084 // corresponding atable and otable with the addresses of static
1085 // members and the offsets of virtual members.
1087 // The offset (in bytes) for each resolved method or field is placed
1088 // at the corresponding position in the virtual method offset table
1091 // The same otable and atable may be shared by many classes.
1093 // This must be called while holding the class lock.
1096 _Jv_Linker::link_symbol_table (jclass klass
)
1099 _Jv_MethodSymbol sym
;
1100 if (klass
->otable
== NULL
1101 || klass
->otable
->state
!= 0)
1104 klass
->otable
->state
= 1;
1107 fprintf (stderr
, "Fixing up otable in %s:\n", klass
->name
->chars());
1109 (sym
= klass
->otable_syms
[index
]).class_name
!= NULL
;
1112 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1113 _Jv_Method
*meth
= NULL
;
1115 _Jv_Utf8Const
*signature
= sym
.signature
;
1117 maybe_adjust_signature (signature
, special
);
1119 if (target_class
== NULL
)
1120 throw new java::lang::NoClassDefFoundError
1121 (_Jv_NewStringUTF (sym
.class_name
->chars()));
1123 // We're looking for a field or a method, and we can tell
1124 // which is needed by looking at the signature.
1125 if (signature
->first() == '(' && signature
->len() >= 2)
1127 // Looks like someone is trying to invoke an interface method
1128 if (target_class
->isInterface())
1130 using namespace java::lang
;
1131 StringBuffer
*sb
= new StringBuffer();
1132 sb
->append(JvNewStringLatin1("found interface "));
1133 sb
->append(target_class
->getName());
1134 sb
->append(JvNewStringLatin1(" when searching for a class"));
1135 throw new VerifyError(sb
->toString());
1138 // If the target class does not have a vtable_method_count yet,
1139 // then we can't tell the offsets for its methods, so we must lay
1141 wait_for_state(target_class
, JV_STATE_PREPARED
);
1145 meth
= (search_method_in_superclasses
1146 (target_class
, klass
, sym
.name
, signature
,
1147 NULL
, special
== 0));
1149 catch (::java::lang::IllegalAccessError
*e
)
1153 // Every class has a throwNoSuchMethodErrorIndex method that
1154 // it inherits from java.lang.Object. Find its vtable
1156 static int throwNoSuchMethodErrorIndex
;
1157 if (throwNoSuchMethodErrorIndex
== 0)
1160 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1161 strlen ("throwNoSuchMethodError"));
1163 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$
,
1164 name
, gcj::void_signature
);
1165 throwNoSuchMethodErrorIndex
1166 = _Jv_VTable::idx_to_offset (meth
->index
);
1169 // If we don't find a nonstatic method, insert the
1170 // vtable index of Object.throwNoSuchMethodError().
1171 // This defers the missing method error until an attempt
1172 // is made to execute it.
1177 offset
= _Jv_VTable::idx_to_offset (meth
->index
);
1179 offset
= throwNoSuchMethodErrorIndex
;
1182 JvFail ("Bad method index");
1183 JvAssert (meth
->index
< target_class
->vtable_method_count
);
1185 klass
->otable
->offsets
[index
] = offset
;
1189 fprintf (stderr
, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1191 (int)klass
->otable
->offsets
[index
],
1192 (const char*)target_class
->name
->chars(),
1194 (const char*)sym
.name
->chars(),
1195 (const char*)signature
->chars());
1201 wait_for_state(target_class
, JV_STATE_PREPARED
);
1203 _Jv_Field
*the_field
= NULL
;
1206 the_field
= find_field (klass
, target_class
, &found_class
,
1207 sym
.name
, signature
);
1208 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1209 throw new java::lang::IncompatibleClassChangeError
;
1211 klass
->otable
->offsets
[index
] = the_field
->u
.boffset
;
1213 catch (java::lang::NoSuchFieldError
*err
)
1215 klass
->otable
->offsets
[index
] = 0;
1221 if (klass
->atable
== NULL
|| klass
->atable
->state
!= 0)
1224 klass
->atable
->state
= 1;
1227 (sym
= klass
->atable_syms
[index
]).class_name
!= NULL
;
1230 jclass target_class
=
1231 _Jv_FindClassNoException (sym
.class_name
, klass
->loader
);
1233 _Jv_Method
*meth
= NULL
;
1235 _Jv_Utf8Const
*signature
= sym
.signature
;
1237 maybe_adjust_signature (signature
, special
);
1239 // ??? Setting this pointer to null will at least get us a
1240 // NullPointerException
1241 klass
->atable
->addresses
[index
] = NULL
;
1243 // If the target class is missing we prepare a function call
1244 // that throws a NoClassDefFoundError and store the address of
1245 // that newly prepared method in the atable. The user can run
1246 // code in classes where the missing class is part of the
1247 // execution environment as long as it is never referenced.
1248 if (target_class
== NULL
)
1249 klass
->atable
->addresses
[index
] = create_error_method(sym
.class_name
);
1250 // We're looking for a static field or a static method, and we
1251 // can tell which is needed by looking at the signature.
1252 else if (signature
->first() == '(' && signature
->len() >= 2)
1254 // If the target class does not have a vtable_method_count yet,
1255 // then we can't tell the offsets for its methods, so we must lay
1257 wait_for_state (target_class
, JV_STATE_PREPARED
);
1259 // Interface methods cannot have bodies.
1260 if (target_class
->isInterface())
1262 using namespace java::lang
;
1263 StringBuffer
*sb
= new StringBuffer();
1264 sb
->append(JvNewStringLatin1("class "));
1265 sb
->append(target_class
->getName());
1266 sb
->append(JvNewStringLatin1(" is an interface: "
1268 throw new VerifyError(sb
->toString());
1273 meth
= (search_method_in_superclasses
1274 (target_class
, klass
, sym
.name
, signature
,
1275 NULL
, special
== 0));
1277 catch (::java::lang::IllegalAccessError
*e
)
1283 if (meth
->ncode
) // Maybe abstract?
1285 klass
->atable
->addresses
[index
] = meth
->ncode
;
1287 fprintf (stderr
, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1289 &klass
->atable
->addresses
[index
],
1290 (const char*)target_class
->name
->chars(),
1292 (const char*)sym
.name
->chars(),
1293 (const char*)signature
->chars());
1297 klass
->atable
->addresses
[index
]
1298 = create_error_method(sym
.class_name
);
1303 // Try fields only if the target class exists.
1304 if (target_class
!= NULL
)
1306 wait_for_state(target_class
, JV_STATE_PREPARED
);
1308 _Jv_Field
*the_field
= find_field (klass
, target_class
, &found_class
,
1309 sym
.name
, signature
);
1310 if ((the_field
->flags
& java::lang::reflect::Modifier::STATIC
))
1311 klass
->atable
->addresses
[index
] = the_field
->u
.addr
;
1313 throw new java::lang::IncompatibleClassChangeError
;
1318 if (klass
->itable
== NULL
1319 || klass
->itable
->state
!= 0)
1322 klass
->itable
->state
= 1;
1325 (sym
= klass
->itable_syms
[index
]).class_name
!= NULL
;
1328 jclass target_class
= _Jv_FindClass (sym
.class_name
, klass
->loader
);
1330 _Jv_Utf8Const
*signature
= sym
.signature
;
1332 maybe_adjust_signature (signature
, special
);
1337 wait_for_state(target_class
, JV_STATE_LOADED
);
1338 bool found
= _Jv_getInterfaceMethod (target_class
, cls
, i
,
1339 sym
.name
, signature
);
1343 klass
->itable
->addresses
[index
* 2] = cls
;
1344 klass
->itable
->addresses
[index
* 2 + 1] = (void *)(unsigned long) i
;
1347 fprintf (stderr
, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1349 klass
->itable
->addresses
[index
* 2],
1350 (const char*)cls
->name
->chars(),
1352 (const char*)sym
.name
->chars(),
1353 (const char*)signature
->chars());
1354 fprintf (stderr
, " [%d] = offset %d\n",
1356 (int)(unsigned long)klass
->itable
->addresses
[index
* 2 + 1]);
1361 throw new java::lang::IncompatibleClassChangeError
;
1366 // For each catch_record in the list of caught classes, fill in the
1369 _Jv_Linker::link_exception_table (jclass self
)
1371 struct _Jv_CatchClass
*catch_record
= self
->catch_classes
;
1372 if (!catch_record
|| catch_record
->classname
)
1375 while (catch_record
->classname
)
1380 = _Jv_FindClass (catch_record
->classname
,
1381 self
->getClassLoaderInternal ());
1382 *catch_record
->address
= target_class
;
1384 catch (::java::lang::Throwable
*t
)
1386 // FIXME: We need to do something better here.
1387 *catch_record
->address
= 0;
1391 self
->catch_classes
->classname
= (_Jv_Utf8Const
*)-1;
1394 // Set itable method indexes for members of interface IFACE.
1396 _Jv_Linker::layout_interface_methods (jclass iface
)
1398 if (! iface
->isInterface())
1401 // itable indexes start at 1.
1402 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1403 // itable so they are also assigned an index here.
1404 for (int i
= 0; i
< iface
->method_count
; i
++)
1405 iface
->methods
[i
].index
= i
+ 1;
1408 // Prepare virtual method declarations in KLASS, and any superclasses
1409 // as required, by determining their vtable index, setting
1410 // method->index, and finally setting the class's vtable_method_count.
1411 // Must be called with the lock for KLASS held.
1413 _Jv_Linker::layout_vtable_methods (jclass klass
)
1415 if (klass
->vtable
!= NULL
|| klass
->isInterface()
1416 || klass
->vtable_method_count
!= -1)
1419 jclass superclass
= klass
->getSuperclass();
1421 if (superclass
!= NULL
&& superclass
->vtable_method_count
== -1)
1423 JvSynchronize
sync (superclass
);
1424 layout_vtable_methods (superclass
);
1427 int index
= (superclass
== NULL
? 0 : superclass
->vtable_method_count
);
1429 for (int i
= 0; i
< klass
->method_count
; ++i
)
1431 _Jv_Method
*meth
= &klass
->methods
[i
];
1432 _Jv_Method
*super_meth
= NULL
;
1434 if (! _Jv_isVirtualMethod (meth
))
1437 if (superclass
!= NULL
)
1440 super_meth
= _Jv_LookupDeclaredMethod (superclass
, meth
->name
,
1441 meth
->signature
, &declarer
);
1442 // See if this method actually overrides the other method
1446 if (! _Jv_isVirtualMethod (super_meth
)
1447 || ! _Jv_CheckAccess (klass
, declarer
,
1448 super_meth
->accflags
))
1450 else if ((super_meth
->accflags
1451 & java::lang::reflect::Modifier::FINAL
) != 0)
1453 using namespace java::lang
;
1454 StringBuffer
*sb
= new StringBuffer();
1455 sb
->append(JvNewStringLatin1("method "));
1456 sb
->append(_Jv_GetMethodString(klass
, meth
));
1457 sb
->append(JvNewStringLatin1(" overrides final method "));
1458 sb
->append(_Jv_GetMethodString(declarer
, super_meth
));
1459 throw new VerifyError(sb
->toString());
1465 meth
->index
= super_meth
->index
;
1467 meth
->index
= index
++;
1470 klass
->vtable_method_count
= index
;
1473 // Set entries in VTABLE for virtual methods declared in KLASS.
1475 _Jv_Linker::set_vtable_entries (jclass klass
, _Jv_VTable
*vtable
)
1477 for (int i
= klass
->method_count
- 1; i
>= 0; i
--)
1479 using namespace java::lang::reflect
;
1481 _Jv_Method
*meth
= &klass
->methods
[i
];
1482 if (meth
->index
== (_Jv_ushort
) -1)
1484 if ((meth
->accflags
& Modifier::ABSTRACT
))
1485 // FIXME: it might be nice to have a libffi trampoline here,
1486 // so we could pass in the method name and other information.
1487 vtable
->set_method(meth
->index
,
1488 (void *) &_Jv_ThrowAbstractMethodError
);
1490 vtable
->set_method(meth
->index
, meth
->ncode
);
1494 // Allocate and lay out the virtual method table for KLASS. This will
1495 // also cause vtables to be generated for any non-abstract
1496 // superclasses, and virtual method layout to occur for any abstract
1497 // superclasses. Must be called with monitor lock for KLASS held.
1499 _Jv_Linker::make_vtable (jclass klass
)
1501 using namespace java::lang::reflect
;
1503 // If the vtable exists, or for interface classes, do nothing. All
1504 // other classes, including abstract classes, need a vtable.
1505 if (klass
->vtable
!= NULL
|| klass
->isInterface())
1508 // Ensure all the `ncode' entries are set.
1509 klass
->engine
->create_ncode(klass
);
1511 // Class must be laid out before we can create a vtable.
1512 if (klass
->vtable_method_count
== -1)
1513 layout_vtable_methods (klass
);
1515 // Allocate the new vtable.
1516 _Jv_VTable
*vtable
= _Jv_VTable::new_vtable (klass
->vtable_method_count
);
1517 klass
->vtable
= vtable
;
1519 // Copy the vtable of the closest superclass.
1520 jclass superclass
= klass
->superclass
;
1522 JvSynchronize
sync (superclass
);
1523 make_vtable (superclass
);
1525 for (int i
= 0; i
< superclass
->vtable_method_count
; ++i
)
1526 vtable
->set_method (i
, superclass
->vtable
->get_method (i
));
1528 // Set the class pointer and GC descriptor.
1529 vtable
->clas
= klass
;
1530 vtable
->gc_descr
= _Jv_BuildGCDescr (klass
);
1532 // For each virtual declared in klass, set new vtable entry or
1533 // override an old one.
1534 set_vtable_entries (klass
, vtable
);
1536 // Note that we don't check for abstract methods here. We used to,
1537 // but there is a JVMS clarification that indicates that a check
1538 // here would be too eager. And, a simple test case confirms this.
1541 // Lay out the class, allocating space for static fields and computing
1542 // offsets of instance fields. The class lock must be held by the
1545 _Jv_Linker::ensure_fields_laid_out (jclass klass
)
1547 if (klass
->size_in_bytes
!= -1)
1550 // Compute the alignment for this type by searching through the
1551 // superclasses and finding the maximum required alignment. We
1552 // could consider caching this in the Class.
1553 int max_align
= __alignof__ (java::lang::Object
);
1554 jclass super
= klass
->getSuperclass();
1555 while (super
!= NULL
)
1557 // Ensure that our super has its super installed before
1559 wait_for_state(super
, JV_STATE_LOADING
);
1560 ensure_fields_laid_out(super
);
1561 int num
= JvNumInstanceFields (super
);
1562 _Jv_Field
*field
= JvGetFirstInstanceField (super
);
1565 int field_align
= get_alignment_from_class (field
->type
);
1566 if (field_align
> max_align
)
1567 max_align
= field_align
;
1571 super
= super
->getSuperclass();
1575 // This is the size of the 'static' non-reference fields.
1576 int non_reference_size
= 0;
1577 // This is the size of the 'static' reference fields. We count
1578 // these separately to make it simpler for the GC to scan them.
1579 int reference_size
= 0;
1581 // Although java.lang.Object is never interpreted, an interface can
1582 // have a null superclass. Note that we have to lay out an
1583 // interface because it might have static fields.
1584 if (klass
->superclass
)
1585 instance_size
= klass
->superclass
->size();
1587 instance_size
= java::lang::Object::class$
.size();
1589 klass
->engine
->allocate_field_initializers (klass
);
1591 for (int i
= 0; i
< klass
->field_count
; i
++)
1596 _Jv_Field
*field
= &klass
->fields
[i
];
1598 if (! field
->isRef ())
1600 // It is safe to resolve the field here, since it's a
1601 // primitive class, which does not cause loading to happen.
1602 resolve_field (field
, klass
->loader
);
1603 field_size
= field
->type
->size ();
1604 field_align
= get_alignment_from_class (field
->type
);
1608 field_size
= sizeof (jobject
);
1609 field_align
= __alignof__ (jobject
);
1612 field
->bsize
= field_size
;
1614 if ((field
->flags
& java::lang::reflect::Modifier::STATIC
))
1616 if (field
->u
.addr
== NULL
)
1618 // This computes an offset into a region we'll allocate
1619 // shortly, and then adds this offset to the start
1623 reference_size
= ROUND (reference_size
, field_align
);
1624 field
->u
.boffset
= reference_size
;
1625 reference_size
+= field_size
;
1629 non_reference_size
= ROUND (non_reference_size
, field_align
);
1630 field
->u
.boffset
= non_reference_size
;
1631 non_reference_size
+= field_size
;
1637 instance_size
= ROUND (instance_size
, field_align
);
1638 field
->u
.boffset
= instance_size
;
1639 instance_size
+= field_size
;
1640 if (field_align
> max_align
)
1641 max_align
= field_align
;
1645 if (reference_size
!= 0 || non_reference_size
!= 0)
1646 klass
->engine
->allocate_static_fields (klass
, reference_size
,
1647 non_reference_size
);
1649 // Set the instance size for the class. Note that first we round it
1650 // to the alignment required for this object; this keeps us in sync
1651 // with our current ABI.
1652 instance_size
= ROUND (instance_size
, max_align
);
1653 klass
->size_in_bytes
= instance_size
;
1656 // This takes the class to state JV_STATE_LINKED. The class lock must
1657 // be held when calling this.
1659 _Jv_Linker::ensure_class_linked (jclass klass
)
1661 if (klass
->state
>= JV_STATE_LINKED
)
1664 int state
= klass
->state
;
1667 // Short-circuit, so that mutually dependent classes are ok.
1668 klass
->state
= JV_STATE_LINKED
;
1670 _Jv_Constants
*pool
= &klass
->constants
;
1672 // Compiled classes require that their class constants be
1673 // resolved here. However, interpreted classes need their
1674 // constants to be resolved lazily. If we resolve an
1675 // interpreted class' constants eagerly, we can end up with
1676 // spurious IllegalAccessErrors when the constant pool contains
1677 // a reference to a class we can't access. This can validly
1678 // occur in an obscure case involving the InnerClasses
1680 if (! _Jv_IsInterpretedClass (klass
))
1682 // Resolve class constants first, since other constant pool
1683 // entries may rely on these.
1684 for (int index
= 1; index
< pool
->size
; ++index
)
1686 if (pool
->tags
[index
] == JV_CONSTANT_Class
)
1687 // Lazily resolve the entries.
1688 resolve_pool_entry (klass
, index
, true);
1692 // Resolve the remaining constant pool entries.
1693 for (int index
= 1; index
< pool
->size
; ++index
)
1695 if (pool
->tags
[index
] == JV_CONSTANT_String
)
1699 str
= _Jv_NewStringUtf8Const (pool
->data
[index
].utf8
);
1700 pool
->data
[index
].o
= str
;
1701 pool
->tags
[index
] |= JV_CONSTANT_ResolvedFlag
;
1705 if (klass
->engine
->need_resolve_string_fields())
1707 jfieldID f
= JvGetFirstStaticField (klass
);
1708 for (int n
= JvNumStaticFields (klass
); n
> 0; --n
)
1710 int mod
= f
->getModifiers ();
1711 // If we have a static String field with a non-null initial
1712 // value, we know it points to a Utf8Const.
1714 // Finds out whether we have to initialize a String without the
1715 // need to resolve the field.
1716 if ((f
->isResolved()
1717 ? (f
->type
== &java::lang::String::class$
)
1718 : _Jv_equalUtf8Classnames((_Jv_Utf8Const
*) f
->type
,
1719 java::lang::String::class$
.name
))
1720 && (mod
& java::lang::reflect::Modifier::STATIC
) != 0)
1722 jstring
*strp
= (jstring
*) f
->u
.addr
;
1724 *strp
= _Jv_NewStringUtf8Const ((_Jv_Utf8Const
*) *strp
);
1726 f
= f
->getNextField ();
1730 klass
->notifyAll ();
1732 _Jv_PushClass (klass
);
1734 catch (java::lang::Throwable
*t
)
1736 klass
->state
= state
;
1741 // This ensures that symbolic superclass and superinterface references
1742 // are resolved for the indicated class. This must be called with the
1745 _Jv_Linker::ensure_supers_installed (jclass klass
)
1747 resolve_class_ref (klass
, &klass
->superclass
);
1748 // An interface won't have a superclass.
1749 if (klass
->superclass
)
1750 wait_for_state (klass
->superclass
, JV_STATE_LOADING
);
1752 for (int i
= 0; i
< klass
->interface_count
; ++i
)
1754 resolve_class_ref (klass
, &klass
->interfaces
[i
]);
1755 wait_for_state (klass
->interfaces
[i
], JV_STATE_LOADING
);
1759 // This adds missing `Miranda methods' to a class.
1761 _Jv_Linker::add_miranda_methods (jclass base
, jclass iface_class
)
1763 // Note that at this point, all our supers, and the supers of all
1764 // our superclasses and superinterfaces, will have been installed.
1766 for (int i
= 0; i
< iface_class
->interface_count
; ++i
)
1768 jclass interface
= iface_class
->interfaces
[i
];
1770 for (int j
= 0; j
< interface
->method_count
; ++j
)
1772 _Jv_Method
*meth
= &interface
->methods
[j
];
1773 // Don't bother with <clinit>.
1774 if (meth
->name
->first() == '<')
1776 _Jv_Method
*new_meth
= _Jv_LookupDeclaredMethod (base
, meth
->name
,
1780 // We assume that such methods are very unlikely, so we
1781 // just reallocate the method array each time one is
1782 // found. This greatly simplifies the searching --
1783 // otherwise we have to make sure that each such method
1784 // found is really unique among all superinterfaces.
1785 int new_count
= base
->method_count
+ 1;
1787 = (_Jv_Method
*) _Jv_AllocRawObj (sizeof (_Jv_Method
)
1789 memcpy (new_m
, base
->methods
,
1790 sizeof (_Jv_Method
) * base
->method_count
);
1793 new_m
[base
->method_count
] = *meth
;
1794 new_m
[base
->method_count
].index
= (_Jv_ushort
) -1;
1795 new_m
[base
->method_count
].accflags
1796 |= java::lang::reflect::Modifier::INVISIBLE
;
1798 base
->methods
= new_m
;
1799 base
->method_count
= new_count
;
1803 wait_for_state (interface
, JV_STATE_LOADED
);
1804 add_miranda_methods (base
, interface
);
1808 // This ensures that the class' method table is "complete". This must
1809 // be called with the class lock held.
1811 _Jv_Linker::ensure_method_table_complete (jclass klass
)
1813 if (klass
->vtable
!= NULL
)
1816 // We need our superclass to have its own Miranda methods installed.
1817 if (! klass
->isInterface())
1818 wait_for_state (klass
->getSuperclass (), JV_STATE_LOADED
);
1820 // A class might have so-called "Miranda methods". This is a method
1821 // that is declared in an interface and not re-declared in an
1822 // abstract class. Some compilers don't emit declarations for such
1823 // methods in the class; this will give us problems since we expect
1824 // a declaration for any method requiring a vtable entry. We handle
1825 // this here by searching for such methods and constructing new
1826 // internal declarations for them. Note that we do this
1827 // unconditionally, and not just for abstract classes, to correctly
1828 // account for cases where a class is modified to be concrete and
1829 // still incorrectly inherits an abstract method.
1830 int pre_count
= klass
->method_count
;
1831 add_miranda_methods (klass
, klass
);
1833 // Let the execution engine know that we've added methods.
1834 if (klass
->method_count
!= pre_count
)
1835 klass
->engine
->post_miranda_hook(klass
);
1838 // Verify a class. Must be called with class lock held.
1840 _Jv_Linker::verify_class (jclass klass
)
1842 klass
->engine
->verify(klass
);
1845 // Check the assertions contained in the type assertion table for KLASS.
1846 // This is the equivilent of bytecode verification for native, BC-ABI code.
1848 _Jv_Linker::verify_type_assertions (jclass klass
)
1851 fprintf (stderr
, "Evaluating type assertions for %s:\n",
1852 klass
->name
->chars());
1854 if (klass
->assertion_table
== NULL
)
1857 for (int i
= 0;; i
++)
1859 int assertion_code
= klass
->assertion_table
[i
].assertion_code
;
1860 _Jv_Utf8Const
*op1
= klass
->assertion_table
[i
].op1
;
1861 _Jv_Utf8Const
*op2
= klass
->assertion_table
[i
].op2
;
1863 if (assertion_code
== JV_ASSERT_END_OF_TABLE
)
1865 else if (assertion_code
== JV_ASSERT_TYPES_COMPATIBLE
)
1869 fprintf (stderr
, " code=%i, operand A=%s B=%s\n",
1870 assertion_code
, op1
->chars(), op2
->chars());
1873 // The operands are class signatures. op1 is the source,
1874 // op2 is the target.
1875 jclass cl1
= _Jv_FindClassFromSignature (op1
->chars(),
1876 klass
->getClassLoaderInternal());
1877 jclass cl2
= _Jv_FindClassFromSignature (op2
->chars(),
1878 klass
->getClassLoaderInternal());
1880 // If the class doesn't exist, ignore the assertion. An exception
1881 // will be thrown later if an attempt is made to actually
1882 // instantiate the class.
1883 if (cl1
== NULL
|| cl2
== NULL
)
1886 if (! _Jv_IsAssignableFromSlow (cl1
, cl2
))
1888 jstring s
= JvNewStringUTF ("Incompatible types: In class ");
1889 s
= s
->concat (klass
->getName());
1890 s
= s
->concat (JvNewStringUTF (": "));
1891 s
= s
->concat (cl1
->getName());
1892 s
= s
->concat (JvNewStringUTF (" is not assignable to "));
1893 s
= s
->concat (cl2
->getName());
1894 throw new java::lang::VerifyError (s
);
1897 else if (assertion_code
== JV_ASSERT_IS_INSTANTIABLE
)
1899 // TODO: Implement this.
1901 // Unknown assertion codes are ignored, for forwards-compatibility.
1906 _Jv_Linker::print_class_loaded (jclass klass
)
1908 char *codesource
= NULL
;
1909 if (klass
->protectionDomain
!= NULL
)
1911 java::security::CodeSource
*cs
1912 = klass
->protectionDomain
->getCodeSource();
1915 jstring css
= cs
->toString();
1916 int len
= JvGetStringUTFLength(css
);
1917 codesource
= (char *) _Jv_AllocBytes(len
+ 1);
1918 JvGetStringUTFRegion(css
, 0, css
->length(), codesource
);
1919 codesource
[len
] = '\0';
1922 if (codesource
== NULL
)
1923 codesource
= (char *) "<no code source>";
1926 if (_Jv_IsInterpretedClass (klass
))
1928 else if (_Jv_IsBinaryCompatibilityABI (klass
))
1929 abi
= "BC-compiled";
1931 abi
= "pre-compiled";
1933 fprintf (stderr
, "[Loaded (%s) %s from %s]\n", abi
, klass
->name
->chars(),
1937 // FIXME: mention invariants and stuff.
1939 _Jv_Linker::wait_for_state (jclass klass
, int state
)
1941 if (klass
->state
>= state
)
1944 JvSynchronize
sync (klass
);
1946 // This is similar to the strategy for class initialization. If we
1947 // already hold the lock, just leave.
1948 java::lang::Thread
*self
= java::lang::Thread::currentThread();
1949 while (klass
->state
<= state
1951 && klass
->thread
!= self
)
1954 java::lang::Thread
*save
= klass
->thread
;
1955 klass
->thread
= self
;
1957 // Allocate memory for static fields and constants.
1958 if (GC_base (klass
) && klass
->fields
&& ! GC_base (klass
->fields
))
1960 jsize count
= klass
->field_count
;
1964 = (_Jv_Field
*) _Jv_AllocRawObj (count
* sizeof (_Jv_Field
));
1965 memcpy ((void*)fields
,
1966 (void*)klass
->fields
,
1967 count
* sizeof (_Jv_Field
));
1968 klass
->fields
= fields
;
1972 // Print some debugging info if requested. Interpreted classes are
1973 // handled in defineclass, so we only need to handle the two
1974 // pre-compiled cases here.
1975 if ((klass
->state
== JV_STATE_COMPILED
1976 || klass
->state
== JV_STATE_PRELOADING
)
1977 && ! _Jv_IsInterpretedClass (klass
))
1979 if (gcj::verbose_class_flag
)
1980 print_class_loaded (klass
);
1981 ++gcj::loadedClasses
;
1986 if (state
>= JV_STATE_LOADING
&& klass
->state
< JV_STATE_LOADING
)
1988 ensure_supers_installed (klass
);
1989 klass
->set_state(JV_STATE_LOADING
);
1992 if (state
>= JV_STATE_LOADED
&& klass
->state
< JV_STATE_LOADED
)
1994 ensure_method_table_complete (klass
);
1995 klass
->set_state(JV_STATE_LOADED
);
1998 if (state
>= JV_STATE_PREPARED
&& klass
->state
< JV_STATE_PREPARED
)
2000 ensure_fields_laid_out (klass
);
2001 make_vtable (klass
);
2002 layout_interface_methods (klass
);
2003 prepare_constant_time_tables (klass
);
2004 klass
->set_state(JV_STATE_PREPARED
);
2007 if (state
>= JV_STATE_LINKED
&& klass
->state
< JV_STATE_LINKED
)
2009 if (gcj::verifyClasses
)
2010 verify_class (klass
);
2012 ensure_class_linked (klass
);
2013 link_exception_table (klass
);
2014 link_symbol_table (klass
);
2015 klass
->set_state(JV_STATE_LINKED
);
2018 catch (java::lang::Throwable
*exc
)
2020 klass
->thread
= save
;
2021 klass
->set_state(JV_STATE_ERROR
);
2025 klass
->thread
= save
;
2027 if (klass
->state
== JV_STATE_ERROR
)
2028 throw new java::lang::LinkageError
;