objc.exp (objc_libgcc_s_path): Set objc_libgcc_s_path instead of appending to it.
[official-gcc.git] / libjava / link.cc
blob3b4f37d1d3c43abd17c5aa035c8c1942948fdc88
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
9 details. */
11 /* Author: Kresten Krab Thorup <krab@gnu.org> */
13 #include <config.h>
14 #include <platform.h>
16 #include <stdio.h>
18 #ifdef USE_LIBFFI
19 #include <ffi.h>
20 #endif
22 #include <java-interp.h>
24 // Set GC_DEBUG before including gc.h!
25 #ifdef LIBGCJ_GC_DEBUG
26 # define GC_DEBUG
27 #endif
28 #include <gc.h>
30 #include <jvm.h>
31 #include <gcj/cni.h>
32 #include <string.h>
33 #include <limits.h>
34 #include <java-cpool.h>
35 #include <execution.h>
36 #ifdef INTERPRETER
37 #include <jvmti.h>
38 #include "jvmti-int.h"
39 #endif
40 #include <java/lang/Class.h>
41 #include <java/lang/String.h>
42 #include <java/lang/StringBuffer.h>
43 #include <java/lang/Thread.h>
44 #include <java/lang/InternalError.h>
45 #include <java/lang/VirtualMachineError.h>
46 #include <java/lang/VerifyError.h>
47 #include <java/lang/NoSuchFieldError.h>
48 #include <java/lang/NoSuchMethodError.h>
49 #include <java/lang/ClassFormatError.h>
50 #include <java/lang/IllegalAccessError.h>
51 #include <java/lang/InternalError.h>
52 #include <java/lang/AbstractMethodError.h>
53 #include <java/lang/NoClassDefFoundError.h>
54 #include <java/lang/IncompatibleClassChangeError.h>
55 #include <java/lang/VerifyError.h>
56 #include <java/lang/VMClassLoader.h>
57 #include <java/lang/reflect/Modifier.h>
58 #include <java/security/CodeSource.h>
60 using namespace gcj;
62 template<typename T>
63 struct aligner
65 char c;
66 T field;
69 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
71 // This returns the alignment of a type as it would appear in a
72 // structure. This can be different from the alignment of the type
73 // itself. For instance on x86 double is 8-aligned but struct{double}
74 // is 4-aligned.
75 int
76 _Jv_Linker::get_alignment_from_class (jclass klass)
78 if (klass == JvPrimClass (byte))
79 return ALIGNOF (jbyte);
80 else if (klass == JvPrimClass (short))
81 return ALIGNOF (jshort);
82 else if (klass == JvPrimClass (int))
83 return ALIGNOF (jint);
84 else if (klass == JvPrimClass (long))
85 return ALIGNOF (jlong);
86 else if (klass == JvPrimClass (boolean))
87 return ALIGNOF (jboolean);
88 else if (klass == JvPrimClass (char))
89 return ALIGNOF (jchar);
90 else if (klass == JvPrimClass (float))
91 return ALIGNOF (jfloat);
92 else if (klass == JvPrimClass (double))
93 return ALIGNOF (jdouble);
94 else
95 return ALIGNOF (jobject);
98 void
99 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
101 if (! field->isResolved ())
103 _Jv_Utf8Const *sig = (_Jv_Utf8Const *) field->type;
104 jclass type = _Jv_FindClassFromSignature (sig->chars(), loader);
105 if (type == NULL)
106 throw new java::lang::NoClassDefFoundError(field->name->toString());
107 field->type = type;
108 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
112 // A helper for find_field that knows how to recursively search
113 // superclasses and interfaces.
114 _Jv_Field *
115 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
116 _Jv_Utf8Const *type_name, jclass type,
117 jclass *declarer)
119 while (search)
121 // From 5.4.3.2. First search class itself.
122 for (int i = 0; i < search->field_count; ++i)
124 _Jv_Field *field = &search->fields[i];
125 if (! _Jv_equalUtf8Consts (field->name, name))
126 continue;
128 // Checks for the odd situation where we were able to retrieve the
129 // field's class from signature but the resolution of the field itself
130 // failed which means a different class was resolved.
131 if (type != NULL)
135 resolve_field (field, search->loader);
137 catch (java::lang::Throwable *exc)
139 java::lang::LinkageError *le = new java::lang::LinkageError
140 (JvNewStringLatin1
141 ("field type mismatch with different loaders"));
143 le->initCause(exc);
145 throw le;
149 // Note that we compare type names and not types. This is
150 // bizarre, but we do it because we want to find a field
151 // (and terminate the search) if it has the correct
152 // descriptor -- but then later reject it if the class
153 // loader check results in different classes. We can't just
154 // pass in the descriptor and check that way, because when
155 // the field is already resolved there is no easy way to
156 // find its descriptor again.
157 if ((field->isResolved ()
158 ? _Jv_equalUtf8Classnames (type_name, field->type->name)
159 : _Jv_equalUtf8Classnames (type_name,
160 (_Jv_Utf8Const *) field->type)))
162 *declarer = search;
163 return field;
167 // Next search direct interfaces.
168 for (int i = 0; i < search->interface_count; ++i)
170 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
171 type_name, type, declarer);
172 if (result)
173 return result;
176 // Now search superclass.
177 search = search->superclass;
180 return NULL;
183 bool
184 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
186 for (int i = 0; i < search->field_count; ++i)
188 _Jv_Field *field = &search->fields[i];
189 if (_Jv_equalUtf8Consts (field->name, field_name))
190 return true;
192 return false;
195 // Find a field.
196 // KLASS is the class that is requesting the field.
197 // OWNER is the class in which the field should be found.
198 // FIELD_TYPE_NAME is the type descriptor for the field.
199 // Fill FOUND_CLASS with the address of the class in which the field
200 // is actually declared.
201 // This function does the class loader type checks, and
202 // also access checks. Returns the field, or throws an
203 // exception on error.
204 _Jv_Field *
205 _Jv_Linker::find_field (jclass klass, jclass owner,
206 jclass *found_class,
207 _Jv_Utf8Const *field_name,
208 _Jv_Utf8Const *field_type_name)
210 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
211 // it cheaper.
212 // Note: This call will resolve the primitive type names ("Z", "B", ...) to
213 // their Java counterparts ("boolean", "byte", ...) if accessed via
214 // field_type->name later. Using these variants of the type name is in turn
215 // important for the find_field_helper function. However if the class
216 // resolution failed then we can only use the already given type name.
217 jclass field_type
218 = _Jv_FindClassFromSignatureNoException (field_type_name->chars(),
219 klass->loader);
221 _Jv_Field *the_field
222 = find_field_helper (owner, field_name,
223 (field_type
224 ? field_type->name :
225 field_type_name ),
226 field_type, found_class);
228 if (the_field == 0)
230 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
231 sb->append(JvNewStringLatin1("field "));
232 sb->append(owner->getName());
233 sb->append(JvNewStringLatin1("."));
234 sb->append(_Jv_NewStringUTF(field_name->chars()));
235 sb->append(JvNewStringLatin1(" was not found."));
236 throw new java::lang::NoSuchFieldError (sb->toString());
239 // Accept it when the field's class could not be resolved.
240 if (field_type == NULL)
241 // Silently ignore that we were not able to retrieve the type to make it
242 // possible to run code which does not access this field.
243 return the_field;
245 if (_Jv_CheckAccess (klass, *found_class, the_field->flags))
247 // Note that the field returned by find_field_helper is always
248 // resolved. There's no point checking class loaders here,
249 // since we already did the work to look up all the types.
250 // FIXME: being lazy here would be nice.
251 if (the_field->type != field_type)
252 throw new java::lang::LinkageError
253 (JvNewStringLatin1
254 ("field type mismatch with different loaders"));
256 else
258 java::lang::StringBuffer *sb
259 = new java::lang::StringBuffer ();
260 sb->append(klass->getName());
261 sb->append(JvNewStringLatin1(": "));
262 sb->append((*found_class)->getName());
263 sb->append(JvNewStringLatin1("."));
264 sb->append(_Jv_NewStringUtf8Const (field_name));
265 throw new java::lang::IllegalAccessError(sb->toString());
268 return the_field;
271 _Jv_Method *
272 _Jv_Linker::resolve_method_entry (jclass klass, jclass &found_class,
273 int class_index, int name_and_type_index,
274 bool init, bool is_iface)
276 _Jv_Constants *pool = &klass->constants;
277 jclass owner = resolve_pool_entry (klass, class_index).clazz;
279 if (init && owner != klass)
280 _Jv_InitClass (owner);
282 _Jv_ushort name_index, type_index;
283 _Jv_loadIndexes (&pool->data[name_and_type_index],
284 name_index,
285 type_index);
287 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
288 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
290 _Jv_Method *the_method = 0;
291 found_class = 0;
293 // We're going to cache a pointer to the _Jv_Method object
294 // when we find it. So, to ensure this doesn't get moved from
295 // beneath us, we first put all the needed Miranda methods
296 // into the target class.
297 wait_for_state (klass, JV_STATE_LOADED);
299 // First search the class itself.
300 the_method = search_method_in_class (owner, klass,
301 method_name, method_signature);
303 if (the_method != 0)
305 found_class = owner;
306 goto end_of_method_search;
309 // If we are resolving an interface method, search the
310 // interface's superinterfaces (A superinterface is not an
311 // interface's superclass - a superinterface is implemented by
312 // the interface).
313 if (is_iface)
315 _Jv_ifaces ifaces;
316 ifaces.count = 0;
317 ifaces.len = 4;
318 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
319 * sizeof (jclass *));
321 get_interfaces (owner, &ifaces);
323 for (int i = 0; i < ifaces.count; i++)
325 jclass cls = ifaces.list[i];
326 the_method = search_method_in_class (cls, klass, method_name,
327 method_signature);
328 if (the_method != 0)
330 found_class = cls;
331 break;
335 _Jv_Free (ifaces.list);
337 if (the_method != 0)
338 goto end_of_method_search;
341 // Finally, search superclasses.
342 the_method = (search_method_in_superclasses
343 (owner->getSuperclass (), klass, method_name,
344 method_signature, &found_class));
347 end_of_method_search:
348 if (the_method == 0)
350 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
351 sb->append(JvNewStringLatin1("method "));
352 sb->append(owner->getName());
353 sb->append(JvNewStringLatin1("."));
354 sb->append(_Jv_NewStringUTF(method_name->chars()));
355 sb->append(JvNewStringLatin1(" with signature "));
356 sb->append(_Jv_NewStringUTF(method_signature->chars()));
357 sb->append(JvNewStringLatin1(" was not found."));
358 throw new java::lang::NoSuchMethodError (sb->toString());
361 // if (found_class->loader != klass->loader), then we
362 // must actually check that the types of arguments
363 // correspond. That is, for each argument type, and
364 // the return type, doing _Jv_FindClassFromSignature
365 // with either loader should produce the same result,
366 // i.e., exactly the same jclass object. JVMS 5.4.3.3
367 if (found_class->loader != klass->loader)
369 JArray<jclass> *found_args, *klass_args;
370 jclass found_return, klass_return;
372 _Jv_GetTypesFromSignature (the_method,
373 found_class,
374 &found_args,
375 &found_return);
376 _Jv_GetTypesFromSignature (the_method,
377 klass,
378 &klass_args,
379 &klass_return);
381 jclass *found_arg = elements (found_args);
382 jclass *klass_arg = elements (klass_args);
384 for (int i = 0; i < found_args->length; i++)
386 if (*(found_arg++) != *(klass_arg++))
387 throw new java::lang::LinkageError (JvNewStringLatin1
388 ("argument type mismatch with different loaders"));
390 if (found_return != klass_return)
391 throw new java::lang::LinkageError (JvNewStringLatin1
392 ("return type mismatch with different loaders"));
395 return the_method;
398 _Jv_word
399 _Jv_Linker::resolve_pool_entry (jclass klass, int index, bool lazy)
401 using namespace java::lang::reflect;
403 if (GC_base (klass) && klass->constants.data
404 && ! GC_base (klass->constants.data))
406 jsize count = klass->constants.size;
407 if (count)
409 _Jv_word* constants
410 = (_Jv_word*) _Jv_AllocRawObj (count * sizeof (_Jv_word));
411 memcpy ((void*)constants,
412 (void*)klass->constants.data,
413 count * sizeof (_Jv_word));
414 klass->constants.data = constants;
418 _Jv_Constants *pool = &klass->constants;
420 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
421 return pool->data[index];
423 switch (pool->tags[index] & ~JV_CONSTANT_LazyFlag)
425 case JV_CONSTANT_Class:
427 _Jv_Utf8Const *name = pool->data[index].utf8;
429 jclass found;
430 if (name->first() == '[')
431 found = _Jv_FindClassFromSignatureNoException (name->chars(),
432 klass->loader);
433 else
434 found = _Jv_FindClassNoException (name, klass->loader);
436 // If the class could not be loaded a phantom class is created. Any
437 // function that deals with such a class but cannot do something useful
438 // with it should just throw a NoClassDefFoundError with the class'
439 // name.
440 if (! found)
442 if (lazy)
444 found = _Jv_NewClass(name, NULL, NULL);
445 found->state = JV_STATE_PHANTOM;
446 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
447 pool->data[index].clazz = found;
448 break;
450 else
451 throw new java::lang::NoClassDefFoundError (name->toString());
454 // Check accessibility, but first strip array types as
455 // _Jv_ClassNameSamePackage can't handle arrays.
456 jclass check;
457 for (check = found;
458 check && check->isArray();
459 check = check->getComponentType())
461 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
462 || (_Jv_ClassNameSamePackage (check->name,
463 klass->name)))
465 pool->data[index].clazz = found;
466 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
468 else
470 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
471 sb->append(klass->getName());
472 sb->append(JvNewStringLatin1(" can't access class "));
473 sb->append(found->getName());
474 throw new java::lang::IllegalAccessError(sb->toString());
477 break;
479 case JV_CONSTANT_String:
481 jstring str;
482 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
483 pool->data[index].o = str;
484 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
486 break;
488 case JV_CONSTANT_Fieldref:
490 _Jv_ushort class_index, name_and_type_index;
491 _Jv_loadIndexes (&pool->data[index],
492 class_index,
493 name_and_type_index);
494 jclass owner = (resolve_pool_entry (klass, class_index, true)).clazz;
496 // If a phantom class was resolved our field reference is
497 // unusable because of the missing class.
498 if (owner->state == JV_STATE_PHANTOM)
499 throw new java::lang::NoClassDefFoundError(owner->getName());
501 // We don't initialize 'owner', but we do make sure that its
502 // fields exist.
503 wait_for_state (owner, JV_STATE_PREPARED);
505 _Jv_ushort name_index, type_index;
506 _Jv_loadIndexes (&pool->data[name_and_type_index],
507 name_index,
508 type_index);
510 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
511 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
513 jclass found_class = 0;
514 _Jv_Field *the_field = find_field (klass, owner,
515 &found_class,
516 field_name,
517 field_type_name);
518 // Initialize the field's declaring class, not its qualifying
519 // class.
520 _Jv_InitClass (found_class);
521 pool->data[index].field = the_field;
522 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
524 break;
526 case JV_CONSTANT_Methodref:
527 case JV_CONSTANT_InterfaceMethodref:
529 _Jv_ushort class_index, name_and_type_index;
530 _Jv_loadIndexes (&pool->data[index],
531 class_index,
532 name_and_type_index);
534 _Jv_Method *the_method;
535 jclass found_class;
536 the_method = resolve_method_entry (klass, found_class,
537 class_index, name_and_type_index,
538 true,
539 pool->tags[index] == JV_CONSTANT_InterfaceMethodref);
541 pool->data[index].rmethod
542 = klass->engine->resolve_method(the_method,
543 found_class,
544 ((the_method->accflags
545 & Modifier::STATIC) != 0));
546 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
548 break;
550 return pool->data[index];
553 // This function is used to lazily locate superclasses and
554 // superinterfaces. This must be called with the class lock held.
555 void
556 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
558 jclass ret = *classref;
560 // If superclass looks like a constant pool entry, resolve it now.
561 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
563 if (klass->state < JV_STATE_LINKED)
565 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
566 ret = _Jv_FindClass (name, klass->loader);
567 if (! ret)
569 throw new java::lang::NoClassDefFoundError (name->toString());
572 else
573 ret = klass->constants.data[(uaddr) classref].clazz;
574 *classref = ret;
578 // Find a method declared in the cls that is referenced from klass and
579 // perform access checks if CHECK_PERMS is true.
580 _Jv_Method *
581 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
582 _Jv_Utf8Const *method_name,
583 _Jv_Utf8Const *method_signature,
584 bool check_perms)
586 using namespace java::lang::reflect;
588 for (int i = 0; i < cls->method_count; i++)
590 _Jv_Method *method = &cls->methods[i];
591 if ( (!_Jv_equalUtf8Consts (method->name,
592 method_name))
593 || (!_Jv_equalUtf8Consts (method->signature,
594 method_signature)))
595 continue;
597 if (!check_perms || _Jv_CheckAccess (klass, cls, method->accflags))
598 return method;
599 else
601 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
602 sb->append(klass->getName());
603 sb->append(JvNewStringLatin1(": "));
604 sb->append(cls->getName());
605 sb->append(JvNewStringLatin1("."));
606 sb->append(_Jv_NewStringUTF(method_name->chars()));
607 sb->append(_Jv_NewStringUTF(method_signature->chars()));
608 throw new java::lang::IllegalAccessError (sb->toString());
611 return 0;
614 // Like search_method_in_class, but work our way up the superclass
615 // chain.
616 _Jv_Method *
617 _Jv_Linker::search_method_in_superclasses (jclass cls, jclass klass,
618 _Jv_Utf8Const *method_name,
619 _Jv_Utf8Const *method_signature,
620 jclass *found_class, bool check_perms)
622 _Jv_Method *the_method = NULL;
624 for ( ; cls != 0; cls = cls->getSuperclass ())
626 the_method = search_method_in_class (cls, klass, method_name,
627 method_signature, check_perms);
628 if (the_method != 0)
630 if (found_class)
631 *found_class = cls;
632 break;
636 return the_method;
639 #define INITIAL_IOFFSETS_LEN 4
640 #define INITIAL_IFACES_LEN 4
642 static _Jv_IDispatchTable null_idt = {SHRT_MAX, 0, {}};
644 // Generate tables for constant-time assignment testing and interface
645 // method lookup. This implements the technique described by Per Bothner
646 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
647 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
648 void
649 _Jv_Linker::prepare_constant_time_tables (jclass klass)
651 if (klass->isPrimitive () || klass->isInterface ())
652 return;
654 // Short-circuit in case we've been called already.
655 if ((klass->idt != NULL) || klass->depth != 0)
656 return;
658 // Calculate the class depth and ancestor table. The depth of a class
659 // is how many "extends" it is removed from Object. Thus the depth of
660 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
661 // is 2. Depth is defined for all regular and array classes, but not
662 // interfaces or primitive types.
664 jclass klass0 = klass;
665 jboolean has_interfaces = 0;
666 while (klass0 != &java::lang::Object::class$)
668 has_interfaces += klass0->interface_count;
669 klass0 = klass0->superclass;
670 klass->depth++;
673 // We do class member testing in constant time by using a small table
674 // of all the ancestor classes within each class. The first element is
675 // a pointer to the current class, and the rest are pointers to the
676 // classes ancestors, ordered from the current class down by decreasing
677 // depth. We do not include java.lang.Object in the table of ancestors,
678 // since it is redundant. Note that the classes pointed to by
679 // 'ancestors' will always be reachable by other paths.
681 klass->ancestors = (jclass *) _Jv_AllocBytes (klass->depth
682 * sizeof (jclass));
683 klass0 = klass;
684 for (int index = 0; index < klass->depth; index++)
686 klass->ancestors[index] = klass0;
687 klass0 = klass0->superclass;
690 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
691 return;
693 // Optimization: If class implements no interfaces, use a common
694 // predefined interface table.
695 if (!has_interfaces)
697 klass->idt = &null_idt;
698 return;
701 _Jv_ifaces ifaces;
702 ifaces.count = 0;
703 ifaces.len = INITIAL_IFACES_LEN;
704 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
706 int itable_size = get_interfaces (klass, &ifaces);
708 if (ifaces.count > 0)
710 // The classes pointed to by the itable will always be reachable
711 // via other paths.
712 int idt_bytes = sizeof (_Jv_IDispatchTable) + (itable_size
713 * sizeof (void *));
714 klass->idt = (_Jv_IDispatchTable *) _Jv_AllocBytes (idt_bytes);
715 klass->idt->itable_length = itable_size;
717 jshort *itable_offsets =
718 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
720 generate_itable (klass, &ifaces, itable_offsets);
722 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
723 ifaces.count);
725 for (int i = 0; i < ifaces.count; i++)
727 ifaces.list[i]->ioffsets[cls_iindex] = itable_offsets[i];
730 klass->idt->iindex = cls_iindex;
732 _Jv_Free (ifaces.list);
733 _Jv_Free (itable_offsets);
735 else
737 klass->idt->iindex = SHRT_MAX;
741 // Return index of item in list, or -1 if item is not present.
742 inline jshort
743 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
745 for (int i=0; i < list_len; i++)
747 if (list[i] == item)
748 return i;
750 return -1;
753 // Find all unique interfaces directly or indirectly implemented by klass.
754 // Returns the size of the interface dispatch table (itable) for klass, which
755 // is the number of unique interfaces plus the total number of methods that
756 // those interfaces declare. May extend ifaces if required.
757 jshort
758 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
760 jshort result = 0;
762 for (int i = 0; i < klass->interface_count; i++)
764 jclass iface = klass->interfaces[i];
766 /* Make sure interface is linked. */
767 wait_for_state(iface, JV_STATE_LINKED);
769 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
771 if (ifaces->count + 1 >= ifaces->len)
773 /* Resize ifaces list */
774 ifaces->len = ifaces->len * 2;
775 ifaces->list
776 = (jclass *) _Jv_Realloc (ifaces->list,
777 ifaces->len * sizeof(jclass));
779 ifaces->list[ifaces->count] = iface;
780 ifaces->count++;
782 result += get_interfaces (klass->interfaces[i], ifaces);
786 if (klass->isInterface())
788 // We want to add 1 plus the number of interface methods here.
789 // But, we take special care to skip <clinit>.
790 ++result;
791 for (int i = 0; i < klass->method_count; ++i)
793 if (klass->methods[i].name->first() != '<')
794 ++result;
797 else if (klass->superclass)
798 result += get_interfaces (klass->superclass, ifaces);
799 return result;
802 // Fill out itable in klass, resolving method declarations in each ifaces.
803 // itable_offsets is filled out with the position of each iface in itable,
804 // such that itable[itable_offsets[n]] == ifaces.list[n].
805 void
806 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
807 jshort *itable_offsets)
809 void **itable = klass->idt->itable;
810 jshort itable_pos = 0;
812 for (int i = 0; i < ifaces->count; i++)
814 jclass iface = ifaces->list[i];
815 itable_offsets[i] = itable_pos;
816 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
818 /* Create ioffsets table for iface */
819 if (iface->ioffsets == NULL)
821 // The first element of ioffsets is its length (itself included).
822 jshort *ioffsets = (jshort *) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
823 * sizeof (jshort));
824 ioffsets[0] = INITIAL_IOFFSETS_LEN;
825 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
826 ioffsets[i] = -1;
828 iface->ioffsets = ioffsets;
833 // Format method name for use in error messages.
834 jstring
835 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
836 jclass derived)
838 using namespace java::lang;
839 StringBuffer *buf = new StringBuffer (klass->name->toString());
840 buf->append (jchar ('.'));
841 buf->append (meth->name->toString());
842 buf->append ((jchar) ' ');
843 buf->append (meth->signature->toString());
844 if (derived)
846 buf->append(JvNewStringLatin1(" in "));
847 buf->append(derived->name->toString());
849 return buf->toString();
852 void
853 _Jv_ThrowNoSuchMethodError ()
855 throw new java::lang::NoSuchMethodError;
858 #if defined USE_LIBFFI && FFI_CLOSURES && defined(INTERPRETER)
859 // A function whose invocation is prepared using libffi. It gets called
860 // whenever a static method of a missing class is invoked. The data argument
861 // holds a reference to a String denoting the missing class.
862 // The prepared function call is stored in a class' atable.
863 void
864 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif *,
865 void *,
866 void **,
867 void *data)
869 throw new java::lang::NoClassDefFoundError(
870 _Jv_NewStringUtf8Const((_Jv_Utf8Const *) data));
872 #else
873 // A variant of the NoClassDefFoundError throwing method that can
874 // be used without libffi.
875 void
876 _Jv_ThrowNoClassDefFoundError()
878 throw new java::lang::NoClassDefFoundError();
880 #endif
882 // Throw a NoSuchFieldError. Called by compiler-generated code when
883 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
884 // otable that refers to the missing field. This index may be used to
885 // print diagnostic information about the field.
886 void
887 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
889 throw new java::lang::NoSuchFieldError;
892 // This is put in empty vtable slots.
893 void
894 _Jv_ThrowAbstractMethodError ()
896 throw new java::lang::AbstractMethodError();
899 // Each superinterface of a class (i.e. each interface that the class
900 // directly or indirectly implements) has a corresponding "Partial
901 // Interface Dispatch Table" whose size is (number of methods + 1) words.
902 // The first word is a pointer to the interface (i.e. the java.lang.Class
903 // instance for that interface). The remaining words are pointers to the
904 // actual methods that implement the methods declared in the interface,
905 // in order of declaration.
907 // Append partial interface dispatch table for "iface" to "itable", at
908 // position itable_pos.
909 // Returns the offset at which the next partial ITable should be appended.
910 jshort
911 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
912 void **itable, jshort pos)
914 using namespace java::lang::reflect;
916 itable[pos++] = (void *) iface;
917 _Jv_Method *meth;
919 for (int j=0; j < iface->method_count; j++)
921 // Skip '<clinit>' here.
922 if (iface->methods[j].name->first() == '<')
923 continue;
925 meth = NULL;
926 for (jclass cl = klass; cl; cl = cl->getSuperclass())
928 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
929 iface->methods[j].signature);
931 if (meth)
932 break;
935 if (meth)
937 if ((meth->accflags & Modifier::STATIC) != 0)
938 throw new java::lang::IncompatibleClassChangeError
939 (_Jv_GetMethodString (klass, meth));
940 if ((meth->accflags & Modifier::PUBLIC) == 0)
941 throw new java::lang::IllegalAccessError
942 (_Jv_GetMethodString (klass, meth));
944 if ((meth->accflags & Modifier::ABSTRACT) != 0)
945 itable[pos] = (void *) &_Jv_ThrowAbstractMethodError;
946 else
947 itable[pos] = meth->ncode;
949 else
951 // The method doesn't exist in klass. Binary compatibility rules
952 // permit this, so we delay the error until runtime using a pointer
953 // to a method which throws an exception.
954 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
956 pos++;
959 return pos;
962 static _Jv_Mutex_t iindex_mutex;
963 static bool iindex_mutex_initialized = false;
965 // We need to find the correct offset in the Class Interface Dispatch
966 // Table for a given interface. Once we have that, invoking an interface
967 // method just requires combining the Method's index in the interface
968 // (known at compile time) to get the correct method. Doing a type test
969 // (cast or instanceof) is the same problem: Once we have a possible Partial
970 // Interface Dispatch Table, we just compare the first element to see if it
971 // matches the desired interface. So how can we find the correct offset?
972 // Our solution is to keep a vector of candiate offsets in each interface
973 // (ioffsets), and in each class we have an index (idt->iindex) used to
974 // select the correct offset from ioffsets.
976 // Calculate and return iindex for a new class.
977 // ifaces is a vector of num interfaces that the class implements.
978 // offsets[j] is the offset in the interface dispatch table for the
979 // interface corresponding to ifaces[j].
980 // May extend the interface ioffsets if required.
981 jshort
982 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
984 int i;
985 int j;
987 // Acquire a global lock to prevent itable corruption in case of multiple
988 // classes that implement an intersecting set of interfaces being linked
989 // simultaneously. We can assume that the mutex will be initialized
990 // single-threaded.
991 if (! iindex_mutex_initialized)
993 _Jv_MutexInit (&iindex_mutex);
994 iindex_mutex_initialized = true;
997 _Jv_MutexLock (&iindex_mutex);
999 for (i=1;; i++) /* each potential position in ioffsets */
1001 for (j=0;; j++) /* each iface */
1003 if (j >= num)
1004 goto found;
1005 if (i >= ifaces[j]->ioffsets[0])
1006 continue;
1007 int ioffset = ifaces[j]->ioffsets[i];
1008 /* We can potentially share this position with another class. */
1009 if (ioffset >= 0 && ioffset != offsets[j])
1010 break; /* Nope. Try next i. */
1013 found:
1014 for (j = 0; j < num; j++)
1016 int len = ifaces[j]->ioffsets[0];
1017 if (i >= len)
1019 // Resize ioffsets.
1020 int newlen = 2 * len;
1021 if (i >= newlen)
1022 newlen = i + 3;
1024 jshort *old_ioffsets = ifaces[j]->ioffsets;
1025 jshort *new_ioffsets = (jshort *) _Jv_AllocBytes (newlen
1026 * sizeof(jshort));
1027 memcpy (&new_ioffsets[1], &old_ioffsets[1],
1028 (len - 1) * sizeof (jshort));
1029 new_ioffsets[0] = newlen;
1031 while (len < newlen)
1032 new_ioffsets[len++] = -1;
1034 ifaces[j]->ioffsets = new_ioffsets;
1036 ifaces[j]->ioffsets[i] = offsets[j];
1039 _Jv_MutexUnlock (&iindex_mutex);
1041 return i;
1044 #if defined USE_LIBFFI && FFI_CLOSURES && defined(INTERPRETER)
1045 // We use a structure of this type to store the closure that
1046 // represents a missing method.
1047 struct method_closure
1049 // This field must come first, since the address of this field will
1050 // be the same as the address of the overall structure. This is due
1051 // to disabling interior pointers in the GC.
1052 ffi_closure closure;
1053 _Jv_ClosureList list;
1054 ffi_cif cif;
1055 ffi_type *arg_types[1];
1058 void *
1059 _Jv_Linker::create_error_method (_Jv_Utf8Const *class_name, jclass klass)
1061 void *code;
1062 method_closure *closure
1063 = (method_closure *)ffi_closure_alloc (sizeof (method_closure), &code);
1065 closure->arg_types[0] = &ffi_type_void;
1067 // Initializes the cif and the closure. If that worked the closure
1068 // is returned and can be used as a function pointer in a class'
1069 // atable.
1070 if ( ffi_prep_cif (&closure->cif,
1071 FFI_DEFAULT_ABI,
1073 &ffi_type_void,
1074 closure->arg_types) == FFI_OK
1075 && ffi_prep_closure_loc (&closure->closure,
1076 &closure->cif,
1077 _Jv_ThrowNoClassDefFoundErrorTrampoline,
1078 class_name,
1079 code) == FFI_OK)
1081 closure->list.registerClosure (klass, closure);
1082 return code;
1084 else
1086 ffi_closure_free (closure);
1087 java::lang::StringBuffer *buffer = new java::lang::StringBuffer();
1088 buffer->append(JvNewStringLatin1("Error setting up FFI closure"
1089 " for static method of"
1090 " missing class: "));
1091 buffer->append (_Jv_NewStringUtf8Const(class_name));
1092 throw new java::lang::InternalError(buffer->toString());
1095 #else
1096 void *
1097 _Jv_Linker::create_error_method (_Jv_Utf8Const *, jclass)
1099 // Codepath for platforms which do not support (or want) libffi.
1100 // You have to accept that it is impossible to provide the name
1101 // of the missing class then.
1102 return (void *) _Jv_ThrowNoClassDefFoundError;
1104 #endif // USE_LIBFFI && FFI_CLOSURES
1106 // Functions for indirect dispatch (symbolic virtual binding) support.
1108 // There are three tables, atable otable and itable. atable is an
1109 // array of addresses, and otable is an array of offsets, and these
1110 // are used for static and virtual members respectively. itable is an
1111 // array of pairs {address, index} where each address is a pointer to
1112 // an interface.
1114 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1115 // symbol is a tuple of {classname, member name, signature}.
1117 // Set this to true to enable debugging of indirect dispatch tables/linking.
1118 static bool debug_link = false;
1120 // link_symbol_table() scans these two arrays and fills in the
1121 // corresponding atable and otable with the addresses of static
1122 // members and the offsets of virtual members.
1124 // The offset (in bytes) for each resolved method or field is placed
1125 // at the corresponding position in the virtual method offset table
1126 // (klass->otable).
1128 // This must be called while holding the class lock.
1130 void
1131 _Jv_Linker::link_symbol_table (jclass klass)
1133 int index = 0;
1134 _Jv_MethodSymbol sym;
1135 if (klass->otable == NULL
1136 || klass->otable->state != 0)
1137 goto atable;
1139 klass->otable->state = 1;
1141 if (debug_link)
1142 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
1143 for (index = 0;
1144 (sym = klass->otable_syms[index]).class_name != NULL;
1145 ++index)
1147 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1148 _Jv_Method *meth = NULL;
1150 _Jv_Utf8Const *signature = sym.signature;
1151 uaddr special;
1152 maybe_adjust_signature (signature, special);
1154 if (target_class == NULL)
1155 throw new java::lang::NoClassDefFoundError
1156 (_Jv_NewStringUTF (sym.class_name->chars()));
1158 // We're looking for a field or a method, and we can tell
1159 // which is needed by looking at the signature.
1160 if (signature->first() == '(' && signature->len() >= 2)
1162 // Looks like someone is trying to invoke an interface method
1163 if (target_class->isInterface())
1165 using namespace java::lang;
1166 StringBuffer *sb = new StringBuffer();
1167 sb->append(JvNewStringLatin1("found interface "));
1168 sb->append(target_class->getName());
1169 sb->append(JvNewStringLatin1(" when searching for a class"));
1170 throw new VerifyError(sb->toString());
1173 // If the target class does not have a vtable_method_count yet,
1174 // then we can't tell the offsets for its methods, so we must lay
1175 // it out now.
1176 wait_for_state(target_class, JV_STATE_PREPARED);
1180 meth = (search_method_in_superclasses
1181 (target_class, klass, sym.name, signature,
1182 NULL, special == 0));
1184 catch (::java::lang::IllegalAccessError *e)
1188 // Every class has a throwNoSuchMethodErrorIndex method that
1189 // it inherits from java.lang.Object. Find its vtable
1190 // offset.
1191 static int throwNoSuchMethodErrorIndex;
1192 if (throwNoSuchMethodErrorIndex == 0)
1194 Utf8Const* name
1195 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1196 strlen ("throwNoSuchMethodError"));
1197 _Jv_Method* meth
1198 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$,
1199 name, gcj::void_signature);
1200 throwNoSuchMethodErrorIndex
1201 = _Jv_VTable::idx_to_offset (meth->index);
1204 // If we don't find a nonstatic method, insert the
1205 // vtable index of Object.throwNoSuchMethodError().
1206 // This defers the missing method error until an attempt
1207 // is made to execute it.
1209 int offset;
1211 if (meth != NULL)
1212 offset = _Jv_VTable::idx_to_offset (meth->index);
1213 else
1214 offset = throwNoSuchMethodErrorIndex;
1216 if (offset == -1)
1217 JvFail ("Bad method index");
1218 JvAssert (meth->index < target_class->vtable_method_count);
1220 klass->otable->offsets[index] = offset;
1223 if (debug_link)
1224 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1225 (int)index,
1226 (int)klass->otable->offsets[index],
1227 (const char*)target_class->name->chars(),
1228 target_class,
1229 (const char*)sym.name->chars(),
1230 (const char*)signature->chars());
1231 continue;
1234 // Try fields.
1236 wait_for_state(target_class, JV_STATE_PREPARED);
1237 jclass found_class;
1238 _Jv_Field *the_field = NULL;
1241 the_field = find_field (klass, target_class, &found_class,
1242 sym.name, signature);
1243 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1244 throw new java::lang::IncompatibleClassChangeError;
1245 else
1246 klass->otable->offsets[index] = the_field->u.boffset;
1248 catch (java::lang::NoSuchFieldError *err)
1250 klass->otable->offsets[index] = 0;
1255 atable:
1256 if (klass->atable == NULL || klass->atable->state != 0)
1257 goto itable;
1259 klass->atable->state = 1;
1261 for (index = 0;
1262 (sym = klass->atable_syms[index]).class_name != NULL;
1263 ++index)
1265 jclass target_class =
1266 _Jv_FindClassNoException (sym.class_name, klass->loader);
1268 _Jv_Method *meth = NULL;
1270 _Jv_Utf8Const *signature = sym.signature;
1271 uaddr special;
1272 maybe_adjust_signature (signature, special);
1274 // ??? Setting this pointer to null will at least get us a
1275 // NullPointerException
1276 klass->atable->addresses[index] = NULL;
1278 bool use_error_method = false;
1280 // If the target class is missing we prepare a function call
1281 // that throws a NoClassDefFoundError and store the address of
1282 // that newly prepared method in the atable. The user can run
1283 // code in classes where the missing class is part of the
1284 // execution environment as long as it is never referenced.
1285 if (target_class == NULL)
1286 use_error_method = true;
1287 // We're looking for a static field or a static method, and we
1288 // can tell which is needed by looking at the signature.
1289 else if (signature->first() == '(' && signature->len() >= 2)
1291 // If the target class does not have a vtable_method_count yet,
1292 // then we can't tell the offsets for its methods, so we must lay
1293 // it out now.
1294 wait_for_state (target_class, JV_STATE_PREPARED);
1296 // Interface methods cannot have bodies.
1297 if (target_class->isInterface())
1299 using namespace java::lang;
1300 StringBuffer *sb = new StringBuffer();
1301 sb->append(JvNewStringLatin1("class "));
1302 sb->append(target_class->getName());
1303 sb->append(JvNewStringLatin1(" is an interface: "
1304 "class expected"));
1305 throw new VerifyError(sb->toString());
1310 meth = (search_method_in_superclasses
1311 (target_class, klass, sym.name, signature,
1312 NULL, special == 0));
1314 catch (::java::lang::IllegalAccessError *e)
1318 if (meth != NULL)
1320 if (meth->ncode) // Maybe abstract?
1322 klass->atable->addresses[index] = meth->ncode;
1323 if (debug_link)
1324 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1325 index,
1326 &klass->atable->addresses[index],
1327 (const char*)target_class->name->chars(),
1328 klass,
1329 (const char*)sym.name->chars(),
1330 (const char*)signature->chars());
1333 else
1334 use_error_method = true;
1336 if (use_error_method)
1337 klass->atable->addresses[index]
1338 = create_error_method(sym.class_name, klass);
1340 continue;
1344 // Try fields only if the target class exists.
1345 if (target_class != NULL)
1347 wait_for_state(target_class, JV_STATE_PREPARED);
1348 jclass found_class;
1349 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
1350 sym.name, signature);
1351 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1352 klass->atable->addresses[index] = the_field->u.addr;
1353 else
1354 throw new java::lang::IncompatibleClassChangeError;
1358 itable:
1359 if (klass->itable == NULL
1360 || klass->itable->state != 0)
1361 return;
1363 klass->itable->state = 1;
1365 for (index = 0;
1366 (sym = klass->itable_syms[index]).class_name != NULL;
1367 ++index)
1369 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1371 _Jv_Utf8Const *signature = sym.signature;
1372 uaddr special;
1373 maybe_adjust_signature (signature, special);
1375 jclass cls;
1376 int i;
1378 wait_for_state(target_class, JV_STATE_LOADED);
1379 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1380 sym.name, signature);
1382 if (found)
1384 klass->itable->addresses[index * 2] = cls;
1385 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1386 if (debug_link)
1388 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1389 index,
1390 klass->itable->addresses[index * 2],
1391 (const char*)cls->name->chars(),
1392 cls,
1393 (const char*)sym.name->chars(),
1394 (const char*)signature->chars());
1395 fprintf (stderr, " [%d] = offset %d\n",
1396 index + 1,
1397 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1401 else
1402 throw new java::lang::IncompatibleClassChangeError;
1407 // For each catch_record in the list of caught classes, fill in the
1408 // address field.
1409 void
1410 _Jv_Linker::link_exception_table (jclass self)
1412 struct _Jv_CatchClass *catch_record = self->catch_classes;
1413 if (!catch_record || catch_record->classname)
1414 return;
1415 catch_record++;
1416 while (catch_record->classname)
1420 jclass target_class
1421 = _Jv_FindClass (catch_record->classname,
1422 self->getClassLoaderInternal ());
1423 *catch_record->address = target_class;
1425 catch (::java::lang::Throwable *t)
1427 // FIXME: We need to do something better here.
1428 *catch_record->address = 0;
1430 catch_record++;
1432 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1435 // Set itable method indexes for members of interface IFACE.
1436 void
1437 _Jv_Linker::layout_interface_methods (jclass iface)
1439 if (! iface->isInterface())
1440 return;
1442 // itable indexes start at 1.
1443 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1444 // itable so they are also assigned an index here.
1445 for (int i = 0; i < iface->method_count; i++)
1446 iface->methods[i].index = i + 1;
1449 // Prepare virtual method declarations in KLASS, and any superclasses
1450 // as required, by determining their vtable index, setting
1451 // method->index, and finally setting the class's vtable_method_count.
1452 // Must be called with the lock for KLASS held.
1453 void
1454 _Jv_Linker::layout_vtable_methods (jclass klass)
1456 if (klass->vtable != NULL || klass->isInterface()
1457 || klass->vtable_method_count != -1)
1458 return;
1460 jclass superclass = klass->getSuperclass();
1462 if (superclass != NULL && superclass->vtable_method_count == -1)
1464 JvSynchronize sync (superclass);
1465 layout_vtable_methods (superclass);
1468 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1470 for (int i = 0; i < klass->method_count; ++i)
1472 _Jv_Method *meth = &klass->methods[i];
1473 _Jv_Method *super_meth = NULL;
1475 if (! _Jv_isVirtualMethod (meth))
1476 continue;
1478 if (superclass != NULL)
1480 jclass declarer;
1481 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1482 meth->signature, &declarer);
1483 // See if this method actually overrides the other method
1484 // we've found.
1485 if (super_meth)
1487 if (! _Jv_isVirtualMethod (super_meth)
1488 || ! _Jv_CheckAccess (klass, declarer,
1489 super_meth->accflags))
1490 super_meth = NULL;
1491 else if ((super_meth->accflags
1492 & java::lang::reflect::Modifier::FINAL) != 0)
1494 using namespace java::lang;
1495 StringBuffer *sb = new StringBuffer();
1496 sb->append(JvNewStringLatin1("method "));
1497 sb->append(_Jv_GetMethodString(klass, meth));
1498 sb->append(JvNewStringLatin1(" overrides final method "));
1499 sb->append(_Jv_GetMethodString(declarer, super_meth));
1500 throw new VerifyError(sb->toString());
1505 if (super_meth)
1506 meth->index = super_meth->index;
1507 else
1508 meth->index = index++;
1511 klass->vtable_method_count = index;
1514 // Set entries in VTABLE for virtual methods declared in KLASS.
1515 void
1516 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1518 for (int i = klass->method_count - 1; i >= 0; i--)
1520 using namespace java::lang::reflect;
1522 _Jv_Method *meth = &klass->methods[i];
1523 if (meth->index == (_Jv_ushort) -1)
1524 continue;
1525 if ((meth->accflags & Modifier::ABSTRACT))
1526 // FIXME: it might be nice to have a libffi trampoline here,
1527 // so we could pass in the method name and other information.
1528 vtable->set_method(meth->index,
1529 (void *) &_Jv_ThrowAbstractMethodError);
1530 else
1531 vtable->set_method(meth->index, meth->ncode);
1535 // Allocate and lay out the virtual method table for KLASS. This will
1536 // also cause vtables to be generated for any non-abstract
1537 // superclasses, and virtual method layout to occur for any abstract
1538 // superclasses. Must be called with monitor lock for KLASS held.
1539 void
1540 _Jv_Linker::make_vtable (jclass klass)
1542 using namespace java::lang::reflect;
1544 // If the vtable exists, or for interface classes, do nothing. All
1545 // other classes, including abstract classes, need a vtable.
1546 if (klass->vtable != NULL || klass->isInterface())
1547 return;
1549 // Ensure all the `ncode' entries are set.
1550 klass->engine->create_ncode(klass);
1552 // Class must be laid out before we can create a vtable.
1553 if (klass->vtable_method_count == -1)
1554 layout_vtable_methods (klass);
1556 // Allocate the new vtable.
1557 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1558 klass->vtable = vtable;
1560 // Copy the vtable of the closest superclass.
1561 jclass superclass = klass->superclass;
1563 JvSynchronize sync (superclass);
1564 make_vtable (superclass);
1566 for (int i = 0; i < superclass->vtable_method_count; ++i)
1567 vtable->set_method (i, superclass->vtable->get_method (i));
1569 // Set the class pointer and GC descriptor.
1570 vtable->clas = klass;
1571 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1573 // For each virtual declared in klass, set new vtable entry or
1574 // override an old one.
1575 set_vtable_entries (klass, vtable);
1577 // Note that we don't check for abstract methods here. We used to,
1578 // but there is a JVMS clarification that indicates that a check
1579 // here would be too eager. And, a simple test case confirms this.
1582 // Lay out the class, allocating space for static fields and computing
1583 // offsets of instance fields. The class lock must be held by the
1584 // caller.
1585 void
1586 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1588 if (klass->size_in_bytes != -1)
1589 return;
1591 // Compute the alignment for this type by searching through the
1592 // superclasses and finding the maximum required alignment. We
1593 // could consider caching this in the Class.
1594 int max_align = __alignof__ (java::lang::Object);
1595 jclass super = klass->getSuperclass();
1596 while (super != NULL)
1598 // Ensure that our super has its super installed before
1599 // recursing.
1600 wait_for_state(super, JV_STATE_LOADING);
1601 ensure_fields_laid_out(super);
1602 int num = JvNumInstanceFields (super);
1603 _Jv_Field *field = JvGetFirstInstanceField (super);
1604 while (num > 0)
1606 int field_align = get_alignment_from_class (field->type);
1607 if (field_align > max_align)
1608 max_align = field_align;
1609 ++field;
1610 --num;
1612 super = super->getSuperclass();
1615 int instance_size;
1616 // This is the size of the 'static' non-reference fields.
1617 int non_reference_size = 0;
1618 // This is the size of the 'static' reference fields. We count
1619 // these separately to make it simpler for the GC to scan them.
1620 int reference_size = 0;
1622 // Although java.lang.Object is never interpreted, an interface can
1623 // have a null superclass. Note that we have to lay out an
1624 // interface because it might have static fields.
1625 if (klass->superclass)
1626 instance_size = klass->superclass->size();
1627 else
1628 instance_size = java::lang::Object::class$.size();
1630 klass->engine->allocate_field_initializers (klass);
1632 for (int i = 0; i < klass->field_count; i++)
1634 int field_size;
1635 int field_align;
1637 _Jv_Field *field = &klass->fields[i];
1639 if (! field->isRef ())
1641 // It is safe to resolve the field here, since it's a
1642 // primitive class, which does not cause loading to happen.
1643 resolve_field (field, klass->loader);
1644 field_size = field->type->size ();
1645 field_align = get_alignment_from_class (field->type);
1647 else
1649 field_size = sizeof (jobject);
1650 field_align = __alignof__ (jobject);
1653 field->bsize = field_size;
1655 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1657 if (field->u.addr == NULL)
1659 // This computes an offset into a region we'll allocate
1660 // shortly, and then adds this offset to the start
1661 // address.
1662 if (field->isRef())
1664 reference_size = ROUND (reference_size, field_align);
1665 field->u.boffset = reference_size;
1666 reference_size += field_size;
1668 else
1670 non_reference_size = ROUND (non_reference_size, field_align);
1671 field->u.boffset = non_reference_size;
1672 non_reference_size += field_size;
1676 else
1678 instance_size = ROUND (instance_size, field_align);
1679 field->u.boffset = instance_size;
1680 instance_size += field_size;
1681 if (field_align > max_align)
1682 max_align = field_align;
1686 if (reference_size != 0 || non_reference_size != 0)
1687 klass->engine->allocate_static_fields (klass, reference_size,
1688 non_reference_size);
1690 // Set the instance size for the class. Note that first we round it
1691 // to the alignment required for this object; this keeps us in sync
1692 // with our current ABI.
1693 instance_size = ROUND (instance_size, max_align);
1694 klass->size_in_bytes = instance_size;
1697 // This takes the class to state JV_STATE_LINKED. The class lock must
1698 // be held when calling this.
1699 void
1700 _Jv_Linker::ensure_class_linked (jclass klass)
1702 if (klass->state >= JV_STATE_LINKED)
1703 return;
1705 int state = klass->state;
1708 // Short-circuit, so that mutually dependent classes are ok.
1709 klass->state = JV_STATE_LINKED;
1711 _Jv_Constants *pool = &klass->constants;
1713 // Compiled classes require that their class constants be
1714 // resolved here. However, interpreted classes need their
1715 // constants to be resolved lazily. If we resolve an
1716 // interpreted class' constants eagerly, we can end up with
1717 // spurious IllegalAccessErrors when the constant pool contains
1718 // a reference to a class we can't access. This can validly
1719 // occur in an obscure case involving the InnerClasses
1720 // attribute.
1721 if (! _Jv_IsInterpretedClass (klass))
1723 // Resolve class constants first, since other constant pool
1724 // entries may rely on these.
1725 for (int index = 1; index < pool->size; ++index)
1727 if (pool->tags[index] == JV_CONSTANT_Class)
1728 // Lazily resolve the entries.
1729 resolve_pool_entry (klass, index, true);
1733 // Resolve the remaining constant pool entries.
1734 for (int index = 1; index < pool->size; ++index)
1736 if (pool->tags[index] == JV_CONSTANT_String)
1738 jstring str;
1740 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1741 pool->data[index].o = str;
1742 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1746 if (klass->engine->need_resolve_string_fields())
1748 jfieldID f = JvGetFirstStaticField (klass);
1749 for (int n = JvNumStaticFields (klass); n > 0; --n)
1751 int mod = f->getModifiers ();
1752 // If we have a static String field with a non-null initial
1753 // value, we know it points to a Utf8Const.
1755 // Finds out whether we have to initialize a String without the
1756 // need to resolve the field.
1757 if ((f->isResolved()
1758 ? (f->type == &java::lang::String::class$)
1759 : _Jv_equalUtf8Classnames((_Jv_Utf8Const *) f->type,
1760 java::lang::String::class$.name))
1761 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1763 jstring *strp = (jstring *) f->u.addr;
1764 if (*strp)
1765 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1767 f = f->getNextField ();
1771 klass->notifyAll ();
1773 _Jv_PushClass (klass);
1775 catch (java::lang::Throwable *t)
1777 klass->state = state;
1778 throw t;
1782 // This ensures that symbolic superclass and superinterface references
1783 // are resolved for the indicated class. This must be called with the
1784 // class lock held.
1785 void
1786 _Jv_Linker::ensure_supers_installed (jclass klass)
1788 resolve_class_ref (klass, &klass->superclass);
1789 // An interface won't have a superclass.
1790 if (klass->superclass)
1791 wait_for_state (klass->superclass, JV_STATE_LOADING);
1793 for (int i = 0; i < klass->interface_count; ++i)
1795 resolve_class_ref (klass, &klass->interfaces[i]);
1796 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1800 // This adds missing `Miranda methods' to a class.
1801 void
1802 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1804 // Note that at this point, all our supers, and the supers of all
1805 // our superclasses and superinterfaces, will have been installed.
1807 for (int i = 0; i < iface_class->interface_count; ++i)
1809 jclass interface = iface_class->interfaces[i];
1811 for (int j = 0; j < interface->method_count; ++j)
1813 _Jv_Method *meth = &interface->methods[j];
1814 // Don't bother with <clinit>.
1815 if (meth->name->first() == '<')
1816 continue;
1817 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1818 meth->signature);
1819 if (! new_meth)
1821 // We assume that such methods are very unlikely, so we
1822 // just reallocate the method array each time one is
1823 // found. This greatly simplifies the searching --
1824 // otherwise we have to make sure that each such method
1825 // found is really unique among all superinterfaces.
1826 int new_count = base->method_count + 1;
1827 _Jv_Method *new_m
1828 = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method)
1829 * new_count);
1830 memcpy (new_m, base->methods,
1831 sizeof (_Jv_Method) * base->method_count);
1833 // Add new method.
1834 new_m[base->method_count] = *meth;
1835 new_m[base->method_count].index = (_Jv_ushort) -1;
1836 new_m[base->method_count].accflags
1837 |= java::lang::reflect::Modifier::INVISIBLE;
1839 base->methods = new_m;
1840 base->method_count = new_count;
1844 wait_for_state (interface, JV_STATE_LOADED);
1845 add_miranda_methods (base, interface);
1849 // This ensures that the class' method table is "complete". This must
1850 // be called with the class lock held.
1851 void
1852 _Jv_Linker::ensure_method_table_complete (jclass klass)
1854 if (klass->vtable != NULL)
1855 return;
1857 // We need our superclass to have its own Miranda methods installed.
1858 if (! klass->isInterface())
1859 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1861 // A class might have so-called "Miranda methods". This is a method
1862 // that is declared in an interface and not re-declared in an
1863 // abstract class. Some compilers don't emit declarations for such
1864 // methods in the class; this will give us problems since we expect
1865 // a declaration for any method requiring a vtable entry. We handle
1866 // this here by searching for such methods and constructing new
1867 // internal declarations for them. Note that we do this
1868 // unconditionally, and not just for abstract classes, to correctly
1869 // account for cases where a class is modified to be concrete and
1870 // still incorrectly inherits an abstract method.
1871 int pre_count = klass->method_count;
1872 add_miranda_methods (klass, klass);
1874 // Let the execution engine know that we've added methods.
1875 if (klass->method_count != pre_count)
1876 klass->engine->post_miranda_hook(klass);
1879 // Verify a class. Must be called with class lock held.
1880 void
1881 _Jv_Linker::verify_class (jclass klass)
1883 klass->engine->verify(klass);
1886 // Check the assertions contained in the type assertion table for KLASS.
1887 // This is the equivilent of bytecode verification for native, BC-ABI code.
1888 void
1889 _Jv_Linker::verify_type_assertions (jclass klass)
1891 if (debug_link)
1892 fprintf (stderr, "Evaluating type assertions for %s:\n",
1893 klass->name->chars());
1895 if (klass->assertion_table == NULL)
1896 return;
1898 for (int i = 0;; i++)
1900 int assertion_code = klass->assertion_table[i].assertion_code;
1901 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1902 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1904 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1905 return;
1906 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1908 if (debug_link)
1910 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1911 assertion_code, op1->chars(), op2->chars());
1914 // The operands are class signatures. op1 is the source,
1915 // op2 is the target.
1916 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1917 klass->getClassLoaderInternal());
1918 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1919 klass->getClassLoaderInternal());
1921 // If the class doesn't exist, ignore the assertion. An exception
1922 // will be thrown later if an attempt is made to actually
1923 // instantiate the class.
1924 if (cl1 == NULL || cl2 == NULL)
1925 continue;
1927 if (! _Jv_IsAssignableFromSlow (cl1, cl2))
1929 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1930 s = s->concat (klass->getName());
1931 s = s->concat (JvNewStringUTF (": "));
1932 s = s->concat (cl1->getName());
1933 s = s->concat (JvNewStringUTF (" is not assignable to "));
1934 s = s->concat (cl2->getName());
1935 throw new java::lang::VerifyError (s);
1938 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1940 // TODO: Implement this.
1942 // Unknown assertion codes are ignored, for forwards-compatibility.
1946 void
1947 _Jv_Linker::print_class_loaded (jclass klass)
1949 char *codesource = NULL;
1950 if (klass->protectionDomain != NULL)
1952 java::security::CodeSource *cs
1953 = klass->protectionDomain->getCodeSource();
1954 if (cs != NULL)
1956 jstring css = cs->toString();
1957 int len = JvGetStringUTFLength(css);
1958 codesource = (char *) _Jv_AllocBytes(len + 1);
1959 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1960 codesource[len] = '\0';
1963 if (codesource == NULL)
1964 codesource = (char *) "<no code source>";
1966 const char *abi;
1967 if (_Jv_IsInterpretedClass (klass))
1968 abi = "bytecode";
1969 else if (_Jv_IsBinaryCompatibilityABI (klass))
1970 abi = "BC-compiled";
1971 else
1972 abi = "pre-compiled";
1974 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1975 codesource);
1978 // FIXME: mention invariants and stuff.
1979 void
1980 _Jv_Linker::wait_for_state (jclass klass, int state)
1982 if (klass->state >= state)
1983 return;
1985 java::lang::Thread *self = java::lang::Thread::currentThread();
1988 JvSynchronize sync (klass);
1990 // This is similar to the strategy for class initialization. If we
1991 // already hold the lock, just leave.
1992 while (klass->state <= state
1993 && klass->thread
1994 && klass->thread != self)
1995 klass->wait ();
1997 java::lang::Thread *save = klass->thread;
1998 klass->thread = self;
2000 // Allocate memory for static fields and constants.
2001 if (GC_base (klass) && klass->fields && ! GC_base (klass->fields))
2003 jsize count = klass->field_count;
2004 if (count)
2006 _Jv_Field* fields
2007 = (_Jv_Field*) _Jv_AllocRawObj (count * sizeof (_Jv_Field));
2008 memcpy ((void*)fields,
2009 (void*)klass->fields,
2010 count * sizeof (_Jv_Field));
2011 klass->fields = fields;
2015 // Print some debugging info if requested. Interpreted classes are
2016 // handled in defineclass, so we only need to handle the two
2017 // pre-compiled cases here.
2018 if ((klass->state == JV_STATE_COMPILED
2019 || klass->state == JV_STATE_PRELOADING)
2020 && ! _Jv_IsInterpretedClass (klass))
2022 if (gcj::verbose_class_flag)
2023 print_class_loaded (klass);
2024 ++gcj::loadedClasses;
2029 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
2031 ensure_supers_installed (klass);
2032 klass->set_state(JV_STATE_LOADING);
2035 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
2037 ensure_method_table_complete (klass);
2038 klass->set_state(JV_STATE_LOADED);
2041 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
2043 ensure_fields_laid_out (klass);
2044 make_vtable (klass);
2045 layout_interface_methods (klass);
2046 prepare_constant_time_tables (klass);
2047 klass->set_state(JV_STATE_PREPARED);
2050 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
2052 if (gcj::verifyClasses)
2053 verify_class (klass);
2055 ensure_class_linked (klass);
2056 link_exception_table (klass);
2057 link_symbol_table (klass);
2058 klass->set_state(JV_STATE_LINKED);
2061 catch (java::lang::Throwable *exc)
2063 klass->thread = save;
2064 klass->set_state(JV_STATE_ERROR);
2065 throw exc;
2068 klass->thread = save;
2070 if (klass->state == JV_STATE_ERROR)
2071 throw new java::lang::LinkageError;
2074 #ifdef INTERPRETER
2075 if (__builtin_expect (klass->state == JV_STATE_LINKED, false)
2076 && state >= JV_STATE_LINKED
2077 && JVMTI_REQUESTED_EVENT (ClassPrepare))
2079 JNIEnv *jni_env = _Jv_GetCurrentJNIEnv ();
2080 _Jv_JVMTI_PostEvent (JVMTI_EVENT_CLASS_PREPARE, self, jni_env,
2081 klass);
2083 #endif