Check in tree-dce enh to trunk
[official-gcc.git] / libjava / link.cc
blobf995531e813ecf73ac16e600107307bb87fd37fb
1 // link.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4 Free Software Foundation
6 This file is part of libgcj.
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
10 details. */
12 /* Author: Kresten Krab Thorup <krab@gnu.org> */
14 #include <config.h>
15 #include <platform.h>
17 #include <stdio.h>
19 #ifdef USE_LIBFFI
20 #include <ffi.h>
21 #endif
23 #include <java-interp.h>
25 // Set GC_DEBUG before including gc.h!
26 #ifdef LIBGCJ_GC_DEBUG
27 # define GC_DEBUG
28 #endif
29 #include <gc.h>
31 #include <jvm.h>
32 #include <gcj/cni.h>
33 #include <string.h>
34 #include <limits.h>
35 #include <java-cpool.h>
36 #include <execution.h>
37 #ifdef INTERPRETER
38 #include <jvmti.h>
39 #include "jvmti-int.h"
40 #endif
41 #include <java/lang/Class.h>
42 #include <java/lang/String.h>
43 #include <java/lang/StringBuffer.h>
44 #include <java/lang/Thread.h>
45 #include <java/lang/InternalError.h>
46 #include <java/lang/VirtualMachineError.h>
47 #include <java/lang/VerifyError.h>
48 #include <java/lang/NoSuchFieldError.h>
49 #include <java/lang/NoSuchMethodError.h>
50 #include <java/lang/ClassFormatError.h>
51 #include <java/lang/IllegalAccessError.h>
52 #include <java/lang/InternalError.h>
53 #include <java/lang/AbstractMethodError.h>
54 #include <java/lang/NoClassDefFoundError.h>
55 #include <java/lang/IncompatibleClassChangeError.h>
56 #include <java/lang/VerifyError.h>
57 #include <java/lang/VMClassLoader.h>
58 #include <java/lang/reflect/Modifier.h>
59 #include <java/security/CodeSource.h>
61 using namespace gcj;
63 template<typename T>
64 struct aligner
66 char c;
67 T field;
70 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
72 // This returns the alignment of a type as it would appear in a
73 // structure. This can be different from the alignment of the type
74 // itself. For instance on x86 double is 8-aligned but struct{double}
75 // is 4-aligned.
76 int
77 _Jv_Linker::get_alignment_from_class (jclass klass)
79 if (klass == JvPrimClass (byte))
80 return ALIGNOF (jbyte);
81 else if (klass == JvPrimClass (short))
82 return ALIGNOF (jshort);
83 else if (klass == JvPrimClass (int))
84 return ALIGNOF (jint);
85 else if (klass == JvPrimClass (long))
86 return ALIGNOF (jlong);
87 else if (klass == JvPrimClass (boolean))
88 return ALIGNOF (jboolean);
89 else if (klass == JvPrimClass (char))
90 return ALIGNOF (jchar);
91 else if (klass == JvPrimClass (float))
92 return ALIGNOF (jfloat);
93 else if (klass == JvPrimClass (double))
94 return ALIGNOF (jdouble);
95 else
96 return ALIGNOF (jobject);
99 void
100 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
102 if (! field->isResolved ())
104 _Jv_Utf8Const *sig = (_Jv_Utf8Const *) field->type;
105 jclass type = _Jv_FindClassFromSignature (sig->chars(), loader);
106 if (type == NULL)
107 throw new java::lang::NoClassDefFoundError(field->name->toString());
108 field->type = type;
109 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
113 // A helper for find_field that knows how to recursively search
114 // superclasses and interfaces.
115 _Jv_Field *
116 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
117 _Jv_Utf8Const *type_name, jclass type,
118 jclass *declarer)
120 while (search)
122 // From 5.4.3.2. First search class itself.
123 for (int i = 0; i < search->field_count; ++i)
125 _Jv_Field *field = &search->fields[i];
126 if (! _Jv_equalUtf8Consts (field->name, name))
127 continue;
129 // Checks for the odd situation where we were able to retrieve the
130 // field's class from signature but the resolution of the field itself
131 // failed which means a different class was resolved.
132 if (type != NULL)
136 resolve_field (field, search->loader);
138 catch (java::lang::Throwable *exc)
140 java::lang::LinkageError *le = new java::lang::LinkageError
141 (JvNewStringLatin1
142 ("field type mismatch with different loaders"));
144 le->initCause(exc);
146 throw le;
150 // Note that we compare type names and not types. This is
151 // bizarre, but we do it because we want to find a field
152 // (and terminate the search) if it has the correct
153 // descriptor -- but then later reject it if the class
154 // loader check results in different classes. We can't just
155 // pass in the descriptor and check that way, because when
156 // the field is already resolved there is no easy way to
157 // find its descriptor again.
158 if ((field->isResolved ()
159 ? _Jv_equalUtf8Classnames (type_name, field->type->name)
160 : _Jv_equalUtf8Classnames (type_name,
161 (_Jv_Utf8Const *) field->type)))
163 *declarer = search;
164 return field;
168 // Next search direct interfaces.
169 for (int i = 0; i < search->interface_count; ++i)
171 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
172 type_name, type, declarer);
173 if (result)
174 return result;
177 // Now search superclass.
178 search = search->superclass;
181 return NULL;
184 bool
185 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
187 for (int i = 0; i < search->field_count; ++i)
189 _Jv_Field *field = &search->fields[i];
190 if (_Jv_equalUtf8Consts (field->name, field_name))
191 return true;
193 return false;
196 // Find a field.
197 // KLASS is the class that is requesting the field.
198 // OWNER is the class in which the field should be found.
199 // FIELD_TYPE_NAME is the type descriptor for the field.
200 // Fill FOUND_CLASS with the address of the class in which the field
201 // is actually declared.
202 // This function does the class loader type checks, and
203 // also access checks. Returns the field, or throws an
204 // exception on error.
205 _Jv_Field *
206 _Jv_Linker::find_field (jclass klass, jclass owner,
207 jclass *found_class,
208 _Jv_Utf8Const *field_name,
209 _Jv_Utf8Const *field_type_name)
211 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
212 // it cheaper.
213 // Note: This call will resolve the primitive type names ("Z", "B", ...) to
214 // their Java counterparts ("boolean", "byte", ...) if accessed via
215 // field_type->name later. Using these variants of the type name is in turn
216 // important for the find_field_helper function. However if the class
217 // resolution failed then we can only use the already given type name.
218 jclass field_type
219 = _Jv_FindClassFromSignatureNoException (field_type_name->chars(),
220 klass->loader);
222 _Jv_Field *the_field
223 = find_field_helper (owner, field_name,
224 (field_type
225 ? field_type->name :
226 field_type_name ),
227 field_type, found_class);
229 if (the_field == 0)
231 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
232 sb->append(JvNewStringLatin1("field "));
233 sb->append(owner->getName());
234 sb->append(JvNewStringLatin1("."));
235 sb->append(_Jv_NewStringUTF(field_name->chars()));
236 sb->append(JvNewStringLatin1(" was not found."));
237 throw new java::lang::NoSuchFieldError (sb->toString());
240 // Accept it when the field's class could not be resolved.
241 if (field_type == NULL)
242 // Silently ignore that we were not able to retrieve the type to make it
243 // possible to run code which does not access this field.
244 return the_field;
246 if (_Jv_CheckAccess (klass, *found_class, the_field->flags))
248 // Note that the field returned by find_field_helper is always
249 // resolved. However, we still use the constraint mechanism
250 // because this may affect other lookups.
251 _Jv_CheckOrCreateLoadingConstraint (klass, (*found_class)->loader);
253 else
255 java::lang::StringBuffer *sb
256 = new java::lang::StringBuffer ();
257 sb->append(klass->getName());
258 sb->append(JvNewStringLatin1(": "));
259 sb->append((*found_class)->getName());
260 sb->append(JvNewStringLatin1("."));
261 sb->append(_Jv_NewStringUtf8Const (field_name));
262 throw new java::lang::IllegalAccessError(sb->toString());
265 return the_field;
268 // Check loading constraints for method.
269 void
270 _Jv_Linker::check_loading_constraints (_Jv_Method *method, jclass self_class,
271 jclass other_class)
273 JArray<jclass> *klass_args;
274 jclass klass_return;
276 _Jv_GetTypesFromSignature (method, self_class, &klass_args, &klass_return);
277 jclass *klass_arg = elements (klass_args);
278 java::lang::ClassLoader *found_loader = other_class->loader;
280 _Jv_CheckOrCreateLoadingConstraint (klass_return, found_loader);
281 for (int i = 0; i < klass_args->length; i++)
282 _Jv_CheckOrCreateLoadingConstraint (*(klass_arg++), found_loader);
285 _Jv_Method *
286 _Jv_Linker::resolve_method_entry (jclass klass, jclass &found_class,
287 int class_index, int name_and_type_index,
288 bool init, bool is_iface)
290 _Jv_Constants *pool = &klass->constants;
291 jclass owner = resolve_pool_entry (klass, class_index).clazz;
293 if (init && owner != klass)
294 _Jv_InitClass (owner);
296 _Jv_ushort name_index, type_index;
297 _Jv_loadIndexes (&pool->data[name_and_type_index],
298 name_index,
299 type_index);
301 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
302 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
304 _Jv_Method *the_method = 0;
305 found_class = 0;
307 // We're going to cache a pointer to the _Jv_Method object
308 // when we find it. So, to ensure this doesn't get moved from
309 // beneath us, we first put all the needed Miranda methods
310 // into the target class.
311 wait_for_state (klass, JV_STATE_LOADED);
313 // First search the class itself.
314 the_method = search_method_in_class (owner, klass,
315 method_name, method_signature);
317 if (the_method != 0)
319 found_class = owner;
320 goto end_of_method_search;
323 // If we are resolving an interface method, search the
324 // interface's superinterfaces (A superinterface is not an
325 // interface's superclass - a superinterface is implemented by
326 // the interface).
327 if (is_iface)
329 _Jv_ifaces ifaces;
330 ifaces.count = 0;
331 ifaces.len = 4;
332 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
333 * sizeof (jclass *));
335 get_interfaces (owner, &ifaces);
337 for (int i = 0; i < ifaces.count; i++)
339 jclass cls = ifaces.list[i];
340 the_method = search_method_in_class (cls, klass, method_name,
341 method_signature);
342 if (the_method != 0)
344 found_class = cls;
345 break;
349 _Jv_Free (ifaces.list);
351 if (the_method != 0)
352 goto end_of_method_search;
355 // Finally, search superclasses.
356 the_method = (search_method_in_superclasses
357 (owner->getSuperclass (), klass, method_name,
358 method_signature, &found_class));
361 end_of_method_search:
362 if (the_method == 0)
364 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
365 sb->append(JvNewStringLatin1("method "));
366 sb->append(owner->getName());
367 sb->append(JvNewStringLatin1("."));
368 sb->append(_Jv_NewStringUTF(method_name->chars()));
369 sb->append(JvNewStringLatin1(" with signature "));
370 sb->append(_Jv_NewStringUTF(method_signature->chars()));
371 sb->append(JvNewStringLatin1(" was not found."));
372 throw new java::lang::NoSuchMethodError (sb->toString());
375 // if (found_class->loader != klass->loader), then we must actually
376 // check that the types of arguments correspond. JVMS 5.4.3.3.
377 if (found_class->loader != klass->loader)
378 check_loading_constraints (the_method, klass, found_class);
380 return the_method;
383 _Jv_word
384 _Jv_Linker::resolve_pool_entry (jclass klass, int index, bool lazy)
386 using namespace java::lang::reflect;
388 if (GC_base (klass) && klass->constants.data
389 && ! GC_base (klass->constants.data))
391 jsize count = klass->constants.size;
392 if (count)
394 _Jv_word* constants
395 = (_Jv_word*) _Jv_AllocRawObj (count * sizeof (_Jv_word));
396 memcpy ((void*)constants,
397 (void*)klass->constants.data,
398 count * sizeof (_Jv_word));
399 klass->constants.data = constants;
403 _Jv_Constants *pool = &klass->constants;
405 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
406 return pool->data[index];
408 switch (pool->tags[index] & ~JV_CONSTANT_LazyFlag)
410 case JV_CONSTANT_Class:
412 _Jv_Utf8Const *name = pool->data[index].utf8;
414 jclass found;
415 if (name->first() == '[')
416 found = _Jv_FindClassFromSignatureNoException (name->chars(),
417 klass->loader);
418 else
419 found = _Jv_FindClassNoException (name, klass->loader);
421 // If the class could not be loaded a phantom class is created. Any
422 // function that deals with such a class but cannot do something useful
423 // with it should just throw a NoClassDefFoundError with the class'
424 // name.
425 if (! found)
427 if (lazy)
429 found = _Jv_NewClass(name, NULL, NULL);
430 found->state = JV_STATE_PHANTOM;
431 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
432 pool->data[index].clazz = found;
433 break;
435 else
436 throw new java::lang::NoClassDefFoundError (name->toString());
439 // Check accessibility, but first strip array types as
440 // _Jv_ClassNameSamePackage can't handle arrays.
441 jclass check;
442 for (check = found;
443 check && check->isArray();
444 check = check->getComponentType())
446 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
447 || (_Jv_ClassNameSamePackage (check->name,
448 klass->name)))
450 pool->data[index].clazz = found;
451 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
453 else
455 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
456 sb->append(klass->getName());
457 sb->append(JvNewStringLatin1(" can't access class "));
458 sb->append(found->getName());
459 throw new java::lang::IllegalAccessError(sb->toString());
462 break;
464 case JV_CONSTANT_String:
466 jstring str;
467 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
468 pool->data[index].o = str;
469 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
471 break;
473 case JV_CONSTANT_Fieldref:
475 _Jv_ushort class_index, name_and_type_index;
476 _Jv_loadIndexes (&pool->data[index],
477 class_index,
478 name_and_type_index);
479 jclass owner = (resolve_pool_entry (klass, class_index, true)).clazz;
481 // If a phantom class was resolved our field reference is
482 // unusable because of the missing class.
483 if (owner->state == JV_STATE_PHANTOM)
484 throw new java::lang::NoClassDefFoundError(owner->getName());
486 // We don't initialize 'owner', but we do make sure that its
487 // fields exist.
488 wait_for_state (owner, JV_STATE_PREPARED);
490 _Jv_ushort name_index, type_index;
491 _Jv_loadIndexes (&pool->data[name_and_type_index],
492 name_index,
493 type_index);
495 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
496 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
498 jclass found_class = 0;
499 _Jv_Field *the_field = find_field (klass, owner,
500 &found_class,
501 field_name,
502 field_type_name);
503 // Initialize the field's declaring class, not its qualifying
504 // class.
505 _Jv_InitClass (found_class);
506 pool->data[index].field = the_field;
507 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
509 break;
511 case JV_CONSTANT_Methodref:
512 case JV_CONSTANT_InterfaceMethodref:
514 _Jv_ushort class_index, name_and_type_index;
515 _Jv_loadIndexes (&pool->data[index],
516 class_index,
517 name_and_type_index);
519 _Jv_Method *the_method;
520 jclass found_class;
521 the_method = resolve_method_entry (klass, found_class,
522 class_index, name_and_type_index,
523 true,
524 pool->tags[index] == JV_CONSTANT_InterfaceMethodref);
526 pool->data[index].rmethod
527 = klass->engine->resolve_method(the_method,
528 found_class,
529 ((the_method->accflags
530 & Modifier::STATIC) != 0));
531 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
533 break;
535 return pool->data[index];
538 // This function is used to lazily locate superclasses and
539 // superinterfaces. This must be called with the class lock held.
540 void
541 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
543 jclass ret = *classref;
545 // If superclass looks like a constant pool entry, resolve it now.
546 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
548 if (klass->state < JV_STATE_LINKED)
550 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
551 ret = _Jv_FindClass (name, klass->loader);
552 if (! ret)
554 throw new java::lang::NoClassDefFoundError (name->toString());
557 else
558 ret = klass->constants.data[(uaddr) classref].clazz;
559 *classref = ret;
563 // Find a method declared in the cls that is referenced from klass and
564 // perform access checks if CHECK_PERMS is true.
565 _Jv_Method *
566 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
567 _Jv_Utf8Const *method_name,
568 _Jv_Utf8Const *method_signature,
569 bool check_perms)
571 using namespace java::lang::reflect;
573 for (int i = 0; i < cls->method_count; i++)
575 _Jv_Method *method = &cls->methods[i];
576 if ( (!_Jv_equalUtf8Consts (method->name,
577 method_name))
578 || (!_Jv_equalUtf8Consts (method->signature,
579 method_signature)))
580 continue;
582 if (!check_perms || _Jv_CheckAccess (klass, cls, method->accflags))
583 return method;
584 else
586 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
587 sb->append(klass->getName());
588 sb->append(JvNewStringLatin1(": "));
589 sb->append(cls->getName());
590 sb->append(JvNewStringLatin1("."));
591 sb->append(_Jv_NewStringUTF(method_name->chars()));
592 sb->append(_Jv_NewStringUTF(method_signature->chars()));
593 throw new java::lang::IllegalAccessError (sb->toString());
596 return 0;
599 // Like search_method_in_class, but work our way up the superclass
600 // chain.
601 _Jv_Method *
602 _Jv_Linker::search_method_in_superclasses (jclass cls, jclass klass,
603 _Jv_Utf8Const *method_name,
604 _Jv_Utf8Const *method_signature,
605 jclass *found_class, bool check_perms)
607 _Jv_Method *the_method = NULL;
609 for ( ; cls != 0; cls = cls->getSuperclass ())
611 the_method = search_method_in_class (cls, klass, method_name,
612 method_signature, check_perms);
613 if (the_method != 0)
615 if (found_class)
616 *found_class = cls;
617 break;
621 return the_method;
624 #define INITIAL_IOFFSETS_LEN 4
625 #define INITIAL_IFACES_LEN 4
627 static _Jv_IDispatchTable null_idt = {SHRT_MAX, 0, {}};
629 // Generate tables for constant-time assignment testing and interface
630 // method lookup. This implements the technique described by Per Bothner
631 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
632 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
633 void
634 _Jv_Linker::prepare_constant_time_tables (jclass klass)
636 if (klass->isPrimitive () || klass->isInterface ())
637 return;
639 // Short-circuit in case we've been called already.
640 if ((klass->idt != NULL) || klass->depth != 0)
641 return;
643 // Calculate the class depth and ancestor table. The depth of a class
644 // is how many "extends" it is removed from Object. Thus the depth of
645 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
646 // is 2. Depth is defined for all regular and array classes, but not
647 // interfaces or primitive types.
649 jclass klass0 = klass;
650 jboolean has_interfaces = false;
651 while (klass0 != &java::lang::Object::class$)
653 if (klass0->interface_count)
654 has_interfaces = true;
655 klass0 = klass0->superclass;
656 klass->depth++;
659 // We do class member testing in constant time by using a small table
660 // of all the ancestor classes within each class. The first element is
661 // a pointer to the current class, and the rest are pointers to the
662 // classes ancestors, ordered from the current class down by decreasing
663 // depth. We do not include java.lang.Object in the table of ancestors,
664 // since it is redundant. Note that the classes pointed to by
665 // 'ancestors' will always be reachable by other paths.
667 klass->ancestors = (jclass *) _Jv_AllocBytes (klass->depth
668 * sizeof (jclass));
669 klass0 = klass;
670 for (int index = 0; index < klass->depth; index++)
672 klass->ancestors[index] = klass0;
673 klass0 = klass0->superclass;
676 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
677 return;
679 // Optimization: If class implements no interfaces, use a common
680 // predefined interface table.
681 if (!has_interfaces)
683 klass->idt = &null_idt;
684 return;
687 _Jv_ifaces ifaces;
688 ifaces.count = 0;
689 ifaces.len = INITIAL_IFACES_LEN;
690 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
692 int itable_size = get_interfaces (klass, &ifaces);
694 if (ifaces.count > 0)
696 // The classes pointed to by the itable will always be reachable
697 // via other paths.
698 int idt_bytes = sizeof (_Jv_IDispatchTable) + (itable_size
699 * sizeof (void *));
700 klass->idt = (_Jv_IDispatchTable *) _Jv_AllocBytes (idt_bytes);
701 klass->idt->itable_length = itable_size;
703 jshort *itable_offsets =
704 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
706 generate_itable (klass, &ifaces, itable_offsets);
708 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
709 ifaces.count);
711 for (int i = 0; i < ifaces.count; i++)
713 ifaces.list[i]->ioffsets[cls_iindex] = itable_offsets[i];
716 klass->idt->iindex = cls_iindex;
718 _Jv_Free (ifaces.list);
719 _Jv_Free (itable_offsets);
721 else
723 klass->idt->iindex = SHRT_MAX;
727 // Return index of item in list, or -1 if item is not present.
728 inline jshort
729 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
731 for (int i=0; i < list_len; i++)
733 if (list[i] == item)
734 return i;
736 return -1;
739 // Find all unique interfaces directly or indirectly implemented by klass.
740 // Returns the size of the interface dispatch table (itable) for klass, which
741 // is the number of unique interfaces plus the total number of methods that
742 // those interfaces declare. May extend ifaces if required.
743 jshort
744 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
746 jshort result = 0;
748 for (int i = 0; i < klass->interface_count; i++)
750 jclass iface = klass->interfaces[i];
752 /* Make sure interface is linked. */
753 wait_for_state(iface, JV_STATE_LINKED);
755 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
757 if (ifaces->count + 1 >= ifaces->len)
759 /* Resize ifaces list */
760 ifaces->len = ifaces->len * 2;
761 ifaces->list
762 = (jclass *) _Jv_Realloc (ifaces->list,
763 ifaces->len * sizeof(jclass));
765 ifaces->list[ifaces->count] = iface;
766 ifaces->count++;
768 result += get_interfaces (klass->interfaces[i], ifaces);
772 if (klass->isInterface())
774 // We want to add 1 plus the number of interface methods here.
775 // But, we take special care to skip <clinit>.
776 ++result;
777 for (int i = 0; i < klass->method_count; ++i)
779 if (klass->methods[i].name->first() != '<')
780 ++result;
783 else if (klass->superclass)
784 result += get_interfaces (klass->superclass, ifaces);
785 return result;
788 // Fill out itable in klass, resolving method declarations in each ifaces.
789 // itable_offsets is filled out with the position of each iface in itable,
790 // such that itable[itable_offsets[n]] == ifaces.list[n].
791 void
792 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
793 jshort *itable_offsets)
795 void **itable = klass->idt->itable;
796 jshort itable_pos = 0;
798 for (int i = 0; i < ifaces->count; i++)
800 jclass iface = ifaces->list[i];
801 itable_offsets[i] = itable_pos;
802 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
804 /* Create ioffsets table for iface */
805 if (iface->ioffsets == NULL)
807 // The first element of ioffsets is its length (itself included).
808 jshort *ioffsets = (jshort *) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
809 * sizeof (jshort));
810 ioffsets[0] = INITIAL_IOFFSETS_LEN;
811 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
812 ioffsets[i] = -1;
814 iface->ioffsets = ioffsets;
819 // Format method name for use in error messages.
820 jstring
821 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
822 jclass derived)
824 using namespace java::lang;
825 StringBuffer *buf = new StringBuffer (klass->name->toString());
826 buf->append (jchar ('.'));
827 buf->append (meth->name->toString());
828 buf->append ((jchar) ' ');
829 buf->append (meth->signature->toString());
830 if (derived)
832 buf->append(JvNewStringLatin1(" in "));
833 buf->append(derived->name->toString());
835 return buf->toString();
838 void
839 _Jv_ThrowNoSuchMethodError ()
841 throw new java::lang::NoSuchMethodError;
844 #if defined USE_LIBFFI && FFI_CLOSURES && defined(INTERPRETER)
845 // A function whose invocation is prepared using libffi. It gets called
846 // whenever a static method of a missing class is invoked. The data argument
847 // holds a reference to a String denoting the missing class.
848 // The prepared function call is stored in a class' atable.
849 void
850 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif *,
851 void *,
852 void **,
853 void *data)
855 throw new java::lang::NoClassDefFoundError(
856 _Jv_NewStringUtf8Const((_Jv_Utf8Const *) data));
858 #else
859 // A variant of the NoClassDefFoundError throwing method that can
860 // be used without libffi.
861 void
862 _Jv_ThrowNoClassDefFoundError()
864 throw new java::lang::NoClassDefFoundError();
866 #endif
868 // Throw a NoSuchFieldError. Called by compiler-generated code when
869 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
870 // otable that refers to the missing field. This index may be used to
871 // print diagnostic information about the field.
872 void
873 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
875 throw new java::lang::NoSuchFieldError;
878 // This is put in empty vtable slots.
879 void
880 _Jv_ThrowAbstractMethodError ()
882 throw new java::lang::AbstractMethodError();
885 // Each superinterface of a class (i.e. each interface that the class
886 // directly or indirectly implements) has a corresponding "Partial
887 // Interface Dispatch Table" whose size is (number of methods + 1) words.
888 // The first word is a pointer to the interface (i.e. the java.lang.Class
889 // instance for that interface). The remaining words are pointers to the
890 // actual methods that implement the methods declared in the interface,
891 // in order of declaration.
893 // Append partial interface dispatch table for "iface" to "itable", at
894 // position itable_pos.
895 // Returns the offset at which the next partial ITable should be appended.
896 jshort
897 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
898 void **itable, jshort pos)
900 using namespace java::lang::reflect;
902 itable[pos++] = (void *) iface;
903 _Jv_Method *meth;
905 for (int j=0; j < iface->method_count; j++)
907 // Skip '<clinit>' here.
908 if (iface->methods[j].name->first() == '<')
909 continue;
911 meth = NULL;
912 jclass cl;
913 for (cl = klass; cl; cl = cl->getSuperclass())
915 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
916 iface->methods[j].signature);
918 if (meth)
919 break;
922 if (meth)
924 if ((meth->accflags & Modifier::STATIC) != 0)
925 throw new java::lang::IncompatibleClassChangeError
926 (_Jv_GetMethodString (klass, meth));
927 if ((meth->accflags & Modifier::PUBLIC) == 0)
928 throw new java::lang::IllegalAccessError
929 (_Jv_GetMethodString (klass, meth));
931 if ((meth->accflags & Modifier::ABSTRACT) != 0)
932 itable[pos] = (void *) &_Jv_ThrowAbstractMethodError;
933 else
934 itable[pos] = meth->ncode;
936 if (cl->loader != iface->loader)
937 check_loading_constraints (meth, cl, iface);
939 else
941 // The method doesn't exist in klass. Binary compatibility rules
942 // permit this, so we delay the error until runtime using a pointer
943 // to a method which throws an exception.
944 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
946 pos++;
949 return pos;
952 static _Jv_Mutex_t iindex_mutex;
953 static bool iindex_mutex_initialized = false;
955 // We need to find the correct offset in the Class Interface Dispatch
956 // Table for a given interface. Once we have that, invoking an interface
957 // method just requires combining the Method's index in the interface
958 // (known at compile time) to get the correct method. Doing a type test
959 // (cast or instanceof) is the same problem: Once we have a possible Partial
960 // Interface Dispatch Table, we just compare the first element to see if it
961 // matches the desired interface. So how can we find the correct offset?
962 // Our solution is to keep a vector of candiate offsets in each interface
963 // (ioffsets), and in each class we have an index (idt->iindex) used to
964 // select the correct offset from ioffsets.
966 // Calculate and return iindex for a new class.
967 // ifaces is a vector of num interfaces that the class implements.
968 // offsets[j] is the offset in the interface dispatch table for the
969 // interface corresponding to ifaces[j].
970 // May extend the interface ioffsets if required.
971 jshort
972 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
974 int i;
975 int j;
977 // Acquire a global lock to prevent itable corruption in case of multiple
978 // classes that implement an intersecting set of interfaces being linked
979 // simultaneously. We can assume that the mutex will be initialized
980 // single-threaded.
981 if (! iindex_mutex_initialized)
983 _Jv_MutexInit (&iindex_mutex);
984 iindex_mutex_initialized = true;
987 _Jv_MutexLock (&iindex_mutex);
989 for (i=1;; i++) /* each potential position in ioffsets */
991 for (j=0;; j++) /* each iface */
993 if (j >= num)
994 goto found;
995 if (i >= ifaces[j]->ioffsets[0])
996 continue;
997 int ioffset = ifaces[j]->ioffsets[i];
998 /* We can potentially share this position with another class. */
999 if (ioffset >= 0 && ioffset != offsets[j])
1000 break; /* Nope. Try next i. */
1003 found:
1004 for (j = 0; j < num; j++)
1006 int len = ifaces[j]->ioffsets[0];
1007 if (i >= len)
1009 // Resize ioffsets.
1010 int newlen = 2 * len;
1011 if (i >= newlen)
1012 newlen = i + 3;
1014 jshort *old_ioffsets = ifaces[j]->ioffsets;
1015 jshort *new_ioffsets = (jshort *) _Jv_AllocBytes (newlen
1016 * sizeof(jshort));
1017 memcpy (&new_ioffsets[1], &old_ioffsets[1],
1018 (len - 1) * sizeof (jshort));
1019 new_ioffsets[0] = newlen;
1021 while (len < newlen)
1022 new_ioffsets[len++] = -1;
1024 ifaces[j]->ioffsets = new_ioffsets;
1026 ifaces[j]->ioffsets[i] = offsets[j];
1029 _Jv_MutexUnlock (&iindex_mutex);
1031 return i;
1034 #if defined USE_LIBFFI && FFI_CLOSURES && defined(INTERPRETER)
1035 // We use a structure of this type to store the closure that
1036 // represents a missing method.
1037 struct method_closure
1039 // This field must come first, since the address of this field will
1040 // be the same as the address of the overall structure. This is due
1041 // to disabling interior pointers in the GC.
1042 ffi_closure closure;
1043 _Jv_ClosureList list;
1044 ffi_cif cif;
1045 ffi_type *arg_types[1];
1048 void *
1049 _Jv_Linker::create_error_method (_Jv_Utf8Const *class_name, jclass klass)
1051 void *code;
1052 method_closure *closure
1053 = (method_closure *)ffi_closure_alloc (sizeof (method_closure), &code);
1055 closure->arg_types[0] = &ffi_type_void;
1057 // Initializes the cif and the closure. If that worked the closure
1058 // is returned and can be used as a function pointer in a class'
1059 // atable.
1060 if ( ffi_prep_cif (&closure->cif,
1061 FFI_DEFAULT_ABI,
1063 &ffi_type_void,
1064 closure->arg_types) == FFI_OK
1065 && ffi_prep_closure_loc (&closure->closure,
1066 &closure->cif,
1067 _Jv_ThrowNoClassDefFoundErrorTrampoline,
1068 class_name,
1069 code) == FFI_OK)
1071 closure->list.registerClosure (klass, closure);
1072 return code;
1074 else
1076 ffi_closure_free (closure);
1077 java::lang::StringBuffer *buffer = new java::lang::StringBuffer();
1078 buffer->append(JvNewStringLatin1("Error setting up FFI closure"
1079 " for static method of"
1080 " missing class: "));
1081 buffer->append (_Jv_NewStringUtf8Const(class_name));
1082 throw new java::lang::InternalError(buffer->toString());
1085 #else
1086 void *
1087 _Jv_Linker::create_error_method (_Jv_Utf8Const *, jclass)
1089 // Codepath for platforms which do not support (or want) libffi.
1090 // You have to accept that it is impossible to provide the name
1091 // of the missing class then.
1092 return (void *) _Jv_ThrowNoClassDefFoundError;
1094 #endif // USE_LIBFFI && FFI_CLOSURES
1096 // Functions for indirect dispatch (symbolic virtual binding) support.
1098 // There are three tables, atable otable and itable. atable is an
1099 // array of addresses, and otable is an array of offsets, and these
1100 // are used for static and virtual members respectively. itable is an
1101 // array of pairs {address, index} where each address is a pointer to
1102 // an interface.
1104 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1105 // symbol is a tuple of {classname, member name, signature}.
1107 // Set this to true to enable debugging of indirect dispatch tables/linking.
1108 static bool debug_link = false;
1110 // link_symbol_table() scans these two arrays and fills in the
1111 // corresponding atable and otable with the addresses of static
1112 // members and the offsets of virtual members.
1114 // The offset (in bytes) for each resolved method or field is placed
1115 // at the corresponding position in the virtual method offset table
1116 // (klass->otable).
1118 // This must be called while holding the class lock.
1120 void
1121 _Jv_Linker::link_symbol_table (jclass klass)
1123 int index = 0;
1124 _Jv_MethodSymbol sym;
1125 if (klass->otable == NULL
1126 || klass->otable->state != 0)
1127 goto atable;
1129 klass->otable->state = 1;
1131 if (debug_link)
1132 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
1133 for (index = 0;
1134 (sym = klass->otable_syms[index]).class_name != NULL;
1135 ++index)
1137 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1138 _Jv_Method *meth = NULL;
1140 _Jv_Utf8Const *signature = sym.signature;
1141 uaddr special;
1142 maybe_adjust_signature (signature, special);
1144 if (target_class == NULL)
1145 throw new java::lang::NoClassDefFoundError
1146 (_Jv_NewStringUTF (sym.class_name->chars()));
1148 // We're looking for a field or a method, and we can tell
1149 // which is needed by looking at the signature.
1150 if (signature->first() == '(' && signature->len() >= 2)
1152 // Looks like someone is trying to invoke an interface method
1153 if (target_class->isInterface())
1155 using namespace java::lang;
1156 StringBuffer *sb = new StringBuffer();
1157 sb->append(JvNewStringLatin1("found interface "));
1158 sb->append(target_class->getName());
1159 sb->append(JvNewStringLatin1(" when searching for a class"));
1160 throw new VerifyError(sb->toString());
1163 // If the target class does not have a vtable_method_count yet,
1164 // then we can't tell the offsets for its methods, so we must lay
1165 // it out now.
1166 wait_for_state(target_class, JV_STATE_PREPARED);
1170 meth = (search_method_in_superclasses
1171 (target_class, klass, sym.name, signature,
1172 NULL, special == 0));
1174 catch (::java::lang::IllegalAccessError *e)
1178 // Every class has a throwNoSuchMethodErrorIndex method that
1179 // it inherits from java.lang.Object. Find its vtable
1180 // offset.
1181 static int throwNoSuchMethodErrorIndex;
1182 if (throwNoSuchMethodErrorIndex == 0)
1184 Utf8Const* name
1185 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1186 strlen ("throwNoSuchMethodError"));
1187 _Jv_Method* meth
1188 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$,
1189 name, gcj::void_signature);
1190 throwNoSuchMethodErrorIndex
1191 = _Jv_VTable::idx_to_offset (meth->index);
1194 // If we don't find a nonstatic method, insert the
1195 // vtable index of Object.throwNoSuchMethodError().
1196 // This defers the missing method error until an attempt
1197 // is made to execute it.
1199 int offset;
1201 if (meth != NULL)
1202 offset = _Jv_VTable::idx_to_offset (meth->index);
1203 else
1204 offset = throwNoSuchMethodErrorIndex;
1206 if (offset == -1)
1207 JvFail ("Bad method index");
1208 JvAssert (meth->index < target_class->vtable_method_count);
1210 klass->otable->offsets[index] = offset;
1213 if (debug_link)
1214 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1215 (int)index,
1216 (int)klass->otable->offsets[index],
1217 (const char*)target_class->name->chars(),
1218 target_class,
1219 (const char*)sym.name->chars(),
1220 (const char*)signature->chars());
1221 continue;
1224 // Try fields.
1226 wait_for_state(target_class, JV_STATE_PREPARED);
1227 jclass found_class;
1228 _Jv_Field *the_field = NULL;
1231 the_field = find_field (klass, target_class, &found_class,
1232 sym.name, signature);
1233 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1234 throw new java::lang::IncompatibleClassChangeError;
1235 else
1236 klass->otable->offsets[index] = the_field->u.boffset;
1238 catch (java::lang::NoSuchFieldError *err)
1240 klass->otable->offsets[index] = 0;
1245 atable:
1246 if (klass->atable == NULL || klass->atable->state != 0)
1247 goto itable;
1249 klass->atable->state = 1;
1251 for (index = 0;
1252 (sym = klass->atable_syms[index]).class_name != NULL;
1253 ++index)
1255 jclass target_class =
1256 _Jv_FindClassNoException (sym.class_name, klass->loader);
1258 _Jv_Method *meth = NULL;
1260 _Jv_Utf8Const *signature = sym.signature;
1261 uaddr special;
1262 maybe_adjust_signature (signature, special);
1264 // ??? Setting this pointer to null will at least get us a
1265 // NullPointerException
1266 klass->atable->addresses[index] = NULL;
1268 bool use_error_method = false;
1270 // If the target class is missing we prepare a function call
1271 // that throws a NoClassDefFoundError and store the address of
1272 // that newly prepared method in the atable. The user can run
1273 // code in classes where the missing class is part of the
1274 // execution environment as long as it is never referenced.
1275 if (target_class == NULL)
1276 use_error_method = true;
1277 // We're looking for a static field or a static method, and we
1278 // can tell which is needed by looking at the signature.
1279 else if (signature->first() == '(' && signature->len() >= 2)
1281 // If the target class does not have a vtable_method_count yet,
1282 // then we can't tell the offsets for its methods, so we must lay
1283 // it out now.
1284 wait_for_state (target_class, JV_STATE_PREPARED);
1286 // Interface methods cannot have bodies.
1287 if (target_class->isInterface())
1289 using namespace java::lang;
1290 StringBuffer *sb = new StringBuffer();
1291 sb->append(JvNewStringLatin1("class "));
1292 sb->append(target_class->getName());
1293 sb->append(JvNewStringLatin1(" is an interface: "
1294 "class expected"));
1295 throw new VerifyError(sb->toString());
1300 meth = (search_method_in_superclasses
1301 (target_class, klass, sym.name, signature,
1302 NULL, special == 0));
1304 catch (::java::lang::IllegalAccessError *e)
1308 if (meth != NULL)
1310 if (meth->ncode) // Maybe abstract?
1312 klass->atable->addresses[index] = meth->ncode;
1313 if (debug_link)
1314 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1315 index,
1316 &klass->atable->addresses[index],
1317 (const char*)target_class->name->chars(),
1318 klass,
1319 (const char*)sym.name->chars(),
1320 (const char*)signature->chars());
1323 else
1324 use_error_method = true;
1326 if (use_error_method)
1327 klass->atable->addresses[index]
1328 = create_error_method(sym.class_name, klass);
1330 continue;
1334 // Try fields only if the target class exists.
1335 if (target_class != NULL)
1337 wait_for_state(target_class, JV_STATE_PREPARED);
1338 jclass found_class;
1339 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
1340 sym.name, signature);
1341 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1342 klass->atable->addresses[index] = the_field->u.addr;
1343 else
1344 throw new java::lang::IncompatibleClassChangeError;
1348 itable:
1349 if (klass->itable == NULL
1350 || klass->itable->state != 0)
1351 return;
1353 klass->itable->state = 1;
1355 for (index = 0;
1356 (sym = klass->itable_syms[index]).class_name != NULL;
1357 ++index)
1359 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1361 _Jv_Utf8Const *signature = sym.signature;
1362 uaddr special;
1363 maybe_adjust_signature (signature, special);
1365 jclass cls;
1366 int i;
1368 wait_for_state(target_class, JV_STATE_LOADED);
1369 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1370 sym.name, signature);
1372 if (found)
1374 klass->itable->addresses[index * 2] = cls;
1375 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1376 if (debug_link)
1378 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1379 index,
1380 klass->itable->addresses[index * 2],
1381 (const char*)cls->name->chars(),
1382 cls,
1383 (const char*)sym.name->chars(),
1384 (const char*)signature->chars());
1385 fprintf (stderr, " [%d] = offset %d\n",
1386 index + 1,
1387 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1391 else
1392 throw new java::lang::IncompatibleClassChangeError;
1397 // For each catch_record in the list of caught classes, fill in the
1398 // address field.
1399 void
1400 _Jv_Linker::link_exception_table (jclass self)
1402 struct _Jv_CatchClass *catch_record = self->catch_classes;
1403 if (!catch_record || catch_record->classname)
1404 return;
1405 catch_record++;
1406 while (catch_record->classname)
1410 jclass target_class
1411 = _Jv_FindClass (catch_record->classname,
1412 self->getClassLoaderInternal ());
1413 *catch_record->address = target_class;
1415 catch (::java::lang::Throwable *t)
1417 // FIXME: We need to do something better here.
1418 *catch_record->address = 0;
1420 catch_record++;
1422 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1425 // Set itable method indexes for members of interface IFACE.
1426 void
1427 _Jv_Linker::layout_interface_methods (jclass iface)
1429 if (! iface->isInterface())
1430 return;
1432 // itable indexes start at 1.
1433 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1434 // itable so they are also assigned an index here.
1435 for (int i = 0; i < iface->method_count; i++)
1436 iface->methods[i].index = i + 1;
1439 // Prepare virtual method declarations in KLASS, and any superclasses
1440 // as required, by determining their vtable index, setting
1441 // method->index, and finally setting the class's vtable_method_count.
1442 // Must be called with the lock for KLASS held.
1443 void
1444 _Jv_Linker::layout_vtable_methods (jclass klass)
1446 if (klass->vtable != NULL || klass->isInterface()
1447 || klass->vtable_method_count != -1)
1448 return;
1450 jclass superclass = klass->getSuperclass();
1452 if (superclass != NULL && superclass->vtable_method_count == -1)
1454 JvSynchronize sync (superclass);
1455 layout_vtable_methods (superclass);
1458 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1460 for (int i = 0; i < klass->method_count; ++i)
1462 _Jv_Method *meth = &klass->methods[i];
1463 _Jv_Method *super_meth = NULL;
1465 if (! _Jv_isVirtualMethod (meth))
1466 continue;
1468 if (superclass != NULL)
1470 jclass declarer;
1471 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1472 meth->signature, &declarer);
1473 // See if this method actually overrides the other method
1474 // we've found.
1475 if (super_meth)
1477 if (! _Jv_isVirtualMethod (super_meth)
1478 || ! _Jv_CheckAccess (klass, declarer,
1479 super_meth->accflags))
1480 super_meth = NULL;
1481 else if ((super_meth->accflags
1482 & java::lang::reflect::Modifier::FINAL) != 0)
1484 using namespace java::lang;
1485 StringBuffer *sb = new StringBuffer();
1486 sb->append(JvNewStringLatin1("method "));
1487 sb->append(_Jv_GetMethodString(klass, meth));
1488 sb->append(JvNewStringLatin1(" overrides final method "));
1489 sb->append(_Jv_GetMethodString(declarer, super_meth));
1490 throw new VerifyError(sb->toString());
1492 else if (declarer->loader != klass->loader)
1494 // JVMS 5.4.2.
1495 check_loading_constraints (meth, klass, declarer);
1500 if (super_meth)
1501 meth->index = super_meth->index;
1502 else
1503 meth->index = index++;
1506 klass->vtable_method_count = index;
1509 // Set entries in VTABLE for virtual methods declared in KLASS.
1510 void
1511 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1513 for (int i = klass->method_count - 1; i >= 0; i--)
1515 using namespace java::lang::reflect;
1517 _Jv_Method *meth = &klass->methods[i];
1518 if (meth->index == (_Jv_ushort) -1)
1519 continue;
1520 if ((meth->accflags & Modifier::ABSTRACT))
1521 // FIXME: it might be nice to have a libffi trampoline here,
1522 // so we could pass in the method name and other information.
1523 vtable->set_method(meth->index,
1524 (void *) &_Jv_ThrowAbstractMethodError);
1525 else
1526 vtable->set_method(meth->index, meth->ncode);
1530 // Allocate and lay out the virtual method table for KLASS. This will
1531 // also cause vtables to be generated for any non-abstract
1532 // superclasses, and virtual method layout to occur for any abstract
1533 // superclasses. Must be called with monitor lock for KLASS held.
1534 void
1535 _Jv_Linker::make_vtable (jclass klass)
1537 using namespace java::lang::reflect;
1539 // If the vtable exists, or for interface classes, do nothing. All
1540 // other classes, including abstract classes, need a vtable.
1541 if (klass->vtable != NULL || klass->isInterface())
1542 return;
1544 // Ensure all the `ncode' entries are set.
1545 klass->engine->create_ncode(klass);
1547 // Class must be laid out before we can create a vtable.
1548 if (klass->vtable_method_count == -1)
1549 layout_vtable_methods (klass);
1551 // Allocate the new vtable.
1552 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1553 klass->vtable = vtable;
1555 // Copy the vtable of the closest superclass.
1556 jclass superclass = klass->superclass;
1558 JvSynchronize sync (superclass);
1559 make_vtable (superclass);
1561 for (int i = 0; i < superclass->vtable_method_count; ++i)
1562 vtable->set_method (i, superclass->vtable->get_method (i));
1564 // Set the class pointer and GC descriptor.
1565 vtable->clas = klass;
1566 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1568 // For each virtual declared in klass, set new vtable entry or
1569 // override an old one.
1570 set_vtable_entries (klass, vtable);
1572 // Note that we don't check for abstract methods here. We used to,
1573 // but there is a JVMS clarification that indicates that a check
1574 // here would be too eager. And, a simple test case confirms this.
1577 // Lay out the class, allocating space for static fields and computing
1578 // offsets of instance fields. The class lock must be held by the
1579 // caller.
1580 void
1581 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1583 if (klass->size_in_bytes != -1)
1584 return;
1586 // Compute the alignment for this type by searching through the
1587 // superclasses and finding the maximum required alignment. We
1588 // could consider caching this in the Class.
1589 int max_align = __alignof__ (java::lang::Object);
1590 jclass super = klass->getSuperclass();
1591 while (super != NULL)
1593 // Ensure that our super has its super installed before
1594 // recursing.
1595 wait_for_state(super, JV_STATE_LOADING);
1596 ensure_fields_laid_out(super);
1597 int num = JvNumInstanceFields (super);
1598 _Jv_Field *field = JvGetFirstInstanceField (super);
1599 while (num > 0)
1601 int field_align = get_alignment_from_class (field->type);
1602 if (field_align > max_align)
1603 max_align = field_align;
1604 ++field;
1605 --num;
1607 super = super->getSuperclass();
1610 int instance_size;
1611 // This is the size of the 'static' non-reference fields.
1612 int non_reference_size = 0;
1613 // This is the size of the 'static' reference fields. We count
1614 // these separately to make it simpler for the GC to scan them.
1615 int reference_size = 0;
1617 // Although java.lang.Object is never interpreted, an interface can
1618 // have a null superclass. Note that we have to lay out an
1619 // interface because it might have static fields.
1620 if (klass->superclass)
1621 instance_size = klass->superclass->size();
1622 else
1623 instance_size = java::lang::Object::class$.size();
1625 klass->engine->allocate_field_initializers (klass);
1627 for (int i = 0; i < klass->field_count; i++)
1629 int field_size;
1630 int field_align;
1632 _Jv_Field *field = &klass->fields[i];
1634 if (! field->isRef ())
1636 // It is safe to resolve the field here, since it's a
1637 // primitive class, which does not cause loading to happen.
1638 resolve_field (field, klass->loader);
1639 field_size = field->type->size ();
1640 field_align = get_alignment_from_class (field->type);
1642 else
1644 field_size = sizeof (jobject);
1645 field_align = __alignof__ (jobject);
1648 field->bsize = field_size;
1650 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1652 if (field->u.addr == NULL)
1654 // This computes an offset into a region we'll allocate
1655 // shortly, and then adds this offset to the start
1656 // address.
1657 if (field->isRef())
1659 reference_size = ROUND (reference_size, field_align);
1660 field->u.boffset = reference_size;
1661 reference_size += field_size;
1663 else
1665 non_reference_size = ROUND (non_reference_size, field_align);
1666 field->u.boffset = non_reference_size;
1667 non_reference_size += field_size;
1671 else
1673 instance_size = ROUND (instance_size, field_align);
1674 field->u.boffset = instance_size;
1675 instance_size += field_size;
1676 if (field_align > max_align)
1677 max_align = field_align;
1681 if (reference_size != 0 || non_reference_size != 0)
1682 klass->engine->allocate_static_fields (klass, reference_size,
1683 non_reference_size);
1685 // Set the instance size for the class. Note that first we round it
1686 // to the alignment required for this object; this keeps us in sync
1687 // with our current ABI.
1688 instance_size = ROUND (instance_size, max_align);
1689 klass->size_in_bytes = instance_size;
1692 // This takes the class to state JV_STATE_LINKED. The class lock must
1693 // be held when calling this.
1694 void
1695 _Jv_Linker::ensure_class_linked (jclass klass)
1697 if (klass->state >= JV_STATE_LINKED)
1698 return;
1700 int state = klass->state;
1703 // Short-circuit, so that mutually dependent classes are ok.
1704 klass->state = JV_STATE_LINKED;
1706 _Jv_Constants *pool = &klass->constants;
1708 // Compiled classes require that their class constants be
1709 // resolved here. However, interpreted classes need their
1710 // constants to be resolved lazily. If we resolve an
1711 // interpreted class' constants eagerly, we can end up with
1712 // spurious IllegalAccessErrors when the constant pool contains
1713 // a reference to a class we can't access. This can validly
1714 // occur in an obscure case involving the InnerClasses
1715 // attribute.
1716 if (! _Jv_IsInterpretedClass (klass))
1718 // Resolve class constants first, since other constant pool
1719 // entries may rely on these.
1720 for (int index = 1; index < pool->size; ++index)
1722 if (pool->tags[index] == JV_CONSTANT_Class)
1723 // Lazily resolve the entries.
1724 resolve_pool_entry (klass, index, true);
1728 // Resolve the remaining constant pool entries.
1729 for (int index = 1; index < pool->size; ++index)
1731 if (pool->tags[index] == JV_CONSTANT_String)
1733 jstring str;
1735 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1736 pool->data[index].o = str;
1737 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1741 if (klass->engine->need_resolve_string_fields())
1743 jfieldID f = JvGetFirstStaticField (klass);
1744 for (int n = JvNumStaticFields (klass); n > 0; --n)
1746 int mod = f->getModifiers ();
1747 // If we have a static String field with a non-null initial
1748 // value, we know it points to a Utf8Const.
1750 // Finds out whether we have to initialize a String without the
1751 // need to resolve the field.
1752 if ((f->isResolved()
1753 ? (f->type == &java::lang::String::class$)
1754 : _Jv_equalUtf8Classnames((_Jv_Utf8Const *) f->type,
1755 java::lang::String::class$.name))
1756 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1758 jstring *strp = (jstring *) f->u.addr;
1759 if (*strp)
1760 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1762 f = f->getNextField ();
1766 klass->notifyAll ();
1768 _Jv_PushClass (klass);
1770 catch (java::lang::Throwable *t)
1772 klass->state = state;
1773 throw t;
1777 // This ensures that symbolic superclass and superinterface references
1778 // are resolved for the indicated class. This must be called with the
1779 // class lock held.
1780 void
1781 _Jv_Linker::ensure_supers_installed (jclass klass)
1783 resolve_class_ref (klass, &klass->superclass);
1784 // An interface won't have a superclass.
1785 if (klass->superclass)
1786 wait_for_state (klass->superclass, JV_STATE_LOADING);
1788 for (int i = 0; i < klass->interface_count; ++i)
1790 resolve_class_ref (klass, &klass->interfaces[i]);
1791 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1795 // This adds missing `Miranda methods' to a class.
1796 void
1797 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1799 // Note that at this point, all our supers, and the supers of all
1800 // our superclasses and superinterfaces, will have been installed.
1802 for (int i = 0; i < iface_class->interface_count; ++i)
1804 jclass interface = iface_class->interfaces[i];
1806 for (int j = 0; j < interface->method_count; ++j)
1808 _Jv_Method *meth = &interface->methods[j];
1809 // Don't bother with <clinit>.
1810 if (meth->name->first() == '<')
1811 continue;
1812 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1813 meth->signature);
1814 if (! new_meth)
1816 // We assume that such methods are very unlikely, so we
1817 // just reallocate the method array each time one is
1818 // found. This greatly simplifies the searching --
1819 // otherwise we have to make sure that each such method
1820 // found is really unique among all superinterfaces.
1821 int new_count = base->method_count + 1;
1822 _Jv_Method *new_m
1823 = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method)
1824 * new_count);
1825 memcpy (new_m, base->methods,
1826 sizeof (_Jv_Method) * base->method_count);
1828 // Add new method.
1829 new_m[base->method_count] = *meth;
1830 new_m[base->method_count].index = (_Jv_ushort) -1;
1831 new_m[base->method_count].accflags
1832 |= java::lang::reflect::Modifier::INVISIBLE;
1834 base->methods = new_m;
1835 base->method_count = new_count;
1839 wait_for_state (interface, JV_STATE_LOADED);
1840 add_miranda_methods (base, interface);
1844 // This ensures that the class' method table is "complete". This must
1845 // be called with the class lock held.
1846 void
1847 _Jv_Linker::ensure_method_table_complete (jclass klass)
1849 if (klass->vtable != NULL)
1850 return;
1852 // We need our superclass to have its own Miranda methods installed.
1853 if (! klass->isInterface())
1854 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1856 // A class might have so-called "Miranda methods". This is a method
1857 // that is declared in an interface and not re-declared in an
1858 // abstract class. Some compilers don't emit declarations for such
1859 // methods in the class; this will give us problems since we expect
1860 // a declaration for any method requiring a vtable entry. We handle
1861 // this here by searching for such methods and constructing new
1862 // internal declarations for them. Note that we do this
1863 // unconditionally, and not just for abstract classes, to correctly
1864 // account for cases where a class is modified to be concrete and
1865 // still incorrectly inherits an abstract method.
1866 int pre_count = klass->method_count;
1867 add_miranda_methods (klass, klass);
1869 // Let the execution engine know that we've added methods.
1870 if (klass->method_count != pre_count)
1871 klass->engine->post_miranda_hook(klass);
1874 // Verify a class. Must be called with class lock held.
1875 void
1876 _Jv_Linker::verify_class (jclass klass)
1878 klass->engine->verify(klass);
1881 // Check the assertions contained in the type assertion table for KLASS.
1882 // This is the equivilent of bytecode verification for native, BC-ABI code.
1883 void
1884 _Jv_Linker::verify_type_assertions (jclass klass)
1886 if (debug_link)
1887 fprintf (stderr, "Evaluating type assertions for %s:\n",
1888 klass->name->chars());
1890 if (klass->assertion_table == NULL)
1891 return;
1893 for (int i = 0;; i++)
1895 int assertion_code = klass->assertion_table[i].assertion_code;
1896 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1897 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1899 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1900 return;
1901 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1903 if (debug_link)
1905 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1906 assertion_code, op1->chars(), op2->chars());
1909 // The operands are class signatures. op1 is the source,
1910 // op2 is the target.
1911 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1912 klass->getClassLoaderInternal());
1913 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1914 klass->getClassLoaderInternal());
1916 // If the class doesn't exist, ignore the assertion. An exception
1917 // will be thrown later if an attempt is made to actually
1918 // instantiate the class.
1919 if (cl1 == NULL || cl2 == NULL)
1920 continue;
1922 if (! _Jv_IsAssignableFromSlow (cl1, cl2))
1924 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1925 s = s->concat (klass->getName());
1926 s = s->concat (JvNewStringUTF (": "));
1927 s = s->concat (cl1->getName());
1928 s = s->concat (JvNewStringUTF (" is not assignable to "));
1929 s = s->concat (cl2->getName());
1930 throw new java::lang::VerifyError (s);
1933 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1935 // TODO: Implement this.
1937 // Unknown assertion codes are ignored, for forwards-compatibility.
1941 void
1942 _Jv_Linker::print_class_loaded (jclass klass)
1944 char *codesource = NULL;
1945 if (klass->protectionDomain != NULL)
1947 java::security::CodeSource *cs
1948 = klass->protectionDomain->getCodeSource();
1949 if (cs != NULL)
1951 jstring css = cs->toString();
1952 int len = JvGetStringUTFLength(css);
1953 codesource = (char *) _Jv_AllocBytes(len + 1);
1954 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1955 codesource[len] = '\0';
1958 if (codesource == NULL)
1959 codesource = (char *) "<no code source>";
1961 const char *abi;
1962 if (_Jv_IsInterpretedClass (klass))
1963 abi = "bytecode";
1964 else if (_Jv_IsBinaryCompatibilityABI (klass))
1965 abi = "BC-compiled";
1966 else
1967 abi = "pre-compiled";
1969 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1970 codesource);
1973 // FIXME: mention invariants and stuff.
1974 void
1975 _Jv_Linker::wait_for_state (jclass klass, int state)
1977 if (klass->state >= state)
1978 return;
1980 java::lang::Thread *self = java::lang::Thread::currentThread();
1983 JvSynchronize sync (klass);
1985 // This is similar to the strategy for class initialization. If we
1986 // already hold the lock, just leave.
1987 while (klass->state <= state
1988 && klass->thread
1989 && klass->thread != self)
1990 klass->wait ();
1992 java::lang::Thread *save = klass->thread;
1993 klass->thread = self;
1995 // Allocate memory for static fields and constants.
1996 if (GC_base (klass) && klass->fields && ! GC_base (klass->fields))
1998 jsize count = klass->field_count;
1999 if (count)
2001 _Jv_Field* fields
2002 = (_Jv_Field*) _Jv_AllocRawObj (count * sizeof (_Jv_Field));
2003 memcpy ((void*)fields,
2004 (void*)klass->fields,
2005 count * sizeof (_Jv_Field));
2006 klass->fields = fields;
2010 // Print some debugging info if requested. Interpreted classes are
2011 // handled in defineclass, so we only need to handle the two
2012 // pre-compiled cases here.
2013 if ((klass->state == JV_STATE_COMPILED
2014 || klass->state == JV_STATE_PRELOADING)
2015 && ! _Jv_IsInterpretedClass (klass))
2017 if (gcj::verbose_class_flag)
2018 print_class_loaded (klass);
2019 ++gcj::loadedClasses;
2024 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
2026 ensure_supers_installed (klass);
2027 klass->set_state(JV_STATE_LOADING);
2030 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
2032 ensure_method_table_complete (klass);
2033 klass->set_state(JV_STATE_LOADED);
2036 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
2038 ensure_fields_laid_out (klass);
2039 make_vtable (klass);
2040 layout_interface_methods (klass);
2041 prepare_constant_time_tables (klass);
2042 klass->set_state(JV_STATE_PREPARED);
2045 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
2047 if (gcj::verifyClasses)
2048 verify_class (klass);
2050 ensure_class_linked (klass);
2051 link_exception_table (klass);
2052 link_symbol_table (klass);
2053 klass->set_state(JV_STATE_LINKED);
2056 catch (java::lang::Throwable *exc)
2058 klass->thread = save;
2059 klass->set_state(JV_STATE_ERROR);
2060 throw exc;
2063 klass->thread = save;
2065 if (klass->state == JV_STATE_ERROR)
2066 throw new java::lang::LinkageError;
2069 #ifdef INTERPRETER
2070 if (__builtin_expect (klass->state == JV_STATE_LINKED, false)
2071 && state >= JV_STATE_LINKED
2072 && JVMTI_REQUESTED_EVENT (ClassPrepare))
2074 JNIEnv *jni_env = _Jv_GetCurrentJNIEnv ();
2075 _Jv_JVMTI_PostEvent (JVMTI_EVENT_CLASS_PREPARE, self, jni_env,
2076 klass);
2078 #endif