PR target/27829
[official-gcc.git] / libjava / link.cc
blob4f01cb545640174c3e79f3c013a55605c3be116b
1 // link.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
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 #include <java/lang/Class.h>
37 #include <java/lang/String.h>
38 #include <java/lang/StringBuffer.h>
39 #include <java/lang/Thread.h>
40 #include <java/lang/InternalError.h>
41 #include <java/lang/VirtualMachineError.h>
42 #include <java/lang/VerifyError.h>
43 #include <java/lang/NoSuchFieldError.h>
44 #include <java/lang/NoSuchMethodError.h>
45 #include <java/lang/ClassFormatError.h>
46 #include <java/lang/IllegalAccessError.h>
47 #include <java/lang/InternalError.h>
48 #include <java/lang/AbstractMethodError.h>
49 #include <java/lang/NoClassDefFoundError.h>
50 #include <java/lang/IncompatibleClassChangeError.h>
51 #include <java/lang/VerifyError.h>
52 #include <java/lang/VMClassLoader.h>
53 #include <java/lang/reflect/Modifier.h>
54 #include <java/security/CodeSource.h>
56 using namespace gcj;
58 typedef unsigned int uaddr __attribute__ ((mode (pointer)));
60 template<typename T>
61 struct aligner
63 char c;
64 T field;
67 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
69 // This returns the alignment of a type as it would appear in a
70 // structure. This can be different from the alignment of the type
71 // itself. For instance on x86 double is 8-aligned but struct{double}
72 // is 4-aligned.
73 int
74 _Jv_Linker::get_alignment_from_class (jclass klass)
76 if (klass == JvPrimClass (byte))
77 return ALIGNOF (jbyte);
78 else if (klass == JvPrimClass (short))
79 return ALIGNOF (jshort);
80 else if (klass == JvPrimClass (int))
81 return ALIGNOF (jint);
82 else if (klass == JvPrimClass (long))
83 return ALIGNOF (jlong);
84 else if (klass == JvPrimClass (boolean))
85 return ALIGNOF (jboolean);
86 else if (klass == JvPrimClass (char))
87 return ALIGNOF (jchar);
88 else if (klass == JvPrimClass (float))
89 return ALIGNOF (jfloat);
90 else if (klass == JvPrimClass (double))
91 return ALIGNOF (jdouble);
92 else
93 return ALIGNOF (jobject);
96 void
97 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
99 if (! field->isResolved ())
101 _Jv_Utf8Const *sig = (_Jv_Utf8Const *) field->type;
102 jclass type = _Jv_FindClassFromSignature (sig->chars(), loader);
103 if (type == NULL)
104 throw new java::lang::NoClassDefFoundError(field->name->toString());
105 field->type = type;
106 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
110 // A helper for find_field that knows how to recursively search
111 // superclasses and interfaces.
112 _Jv_Field *
113 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
114 _Jv_Utf8Const *type_name, jclass type,
115 jclass *declarer)
117 while (search)
119 // From 5.4.3.2. First search class itself.
120 for (int i = 0; i < search->field_count; ++i)
122 _Jv_Field *field = &search->fields[i];
123 if (! _Jv_equalUtf8Consts (field->name, name))
124 continue;
126 // Checks for the odd situation where we were able to retrieve the
127 // field's class from signature but the resolution of the field itself
128 // failed which means a different class was resolved.
129 if (type != NULL)
133 resolve_field (field, search->loader);
135 catch (java::lang::Throwable *exc)
137 java::lang::LinkageError *le = new java::lang::LinkageError
138 (JvNewStringLatin1
139 ("field type mismatch with different loaders"));
141 le->initCause(exc);
143 throw le;
147 // Note that we compare type names and not types. This is
148 // bizarre, but we do it because we want to find a field
149 // (and terminate the search) if it has the correct
150 // descriptor -- but then later reject it if the class
151 // loader check results in different classes. We can't just
152 // pass in the descriptor and check that way, because when
153 // the field is already resolved there is no easy way to
154 // find its descriptor again.
155 if ((field->isResolved ()
156 ? _Jv_equalUtf8Classnames (type_name, field->type->name)
157 : _Jv_equalUtf8Classnames (type_name,
158 (_Jv_Utf8Const *) field->type)))
160 *declarer = search;
161 return field;
165 // Next search direct interfaces.
166 for (int i = 0; i < search->interface_count; ++i)
168 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
169 type_name, type, declarer);
170 if (result)
171 return result;
174 // Now search superclass.
175 search = search->superclass;
178 return NULL;
181 bool
182 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
184 for (int i = 0; i < search->field_count; ++i)
186 _Jv_Field *field = &search->fields[i];
187 if (_Jv_equalUtf8Consts (field->name, field_name))
188 return true;
190 return false;
193 // Find a field.
194 // KLASS is the class that is requesting the field.
195 // OWNER is the class in which the field should be found.
196 // FIELD_TYPE_NAME is the type descriptor for the field.
197 // Fill FOUND_CLASS with the address of the class in which the field
198 // is actually declared.
199 // This function does the class loader type checks, and
200 // also access checks. Returns the field, or throws an
201 // exception on error.
202 _Jv_Field *
203 _Jv_Linker::find_field (jclass klass, jclass owner,
204 jclass *found_class,
205 _Jv_Utf8Const *field_name,
206 _Jv_Utf8Const *field_type_name)
208 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
209 // it cheaper.
210 // Note: This call will resolve the primitive type names ("Z", "B", ...) to
211 // their Java counterparts ("boolean", "byte", ...) if accessed via
212 // field_type->name later. Using these variants of the type name is in turn
213 // important for the find_field_helper function. However if the class
214 // resolution failed then we can only use the already given type name.
215 jclass field_type
216 = _Jv_FindClassFromSignatureNoException (field_type_name->chars(),
217 klass->loader);
219 _Jv_Field *the_field
220 = find_field_helper (owner, field_name,
221 (field_type
222 ? field_type->name :
223 field_type_name ),
224 field_type, found_class);
226 if (the_field == 0)
228 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
229 sb->append(JvNewStringLatin1("field "));
230 sb->append(owner->getName());
231 sb->append(JvNewStringLatin1("."));
232 sb->append(_Jv_NewStringUTF(field_name->chars()));
233 sb->append(JvNewStringLatin1(" was not found."));
234 throw new java::lang::NoSuchFieldError (sb->toString());
237 // Accept it when the field's class could not be resolved.
238 if (field_type == NULL)
239 // Silently ignore that we were not able to retrieve the type to make it
240 // possible to run code which does not access this field.
241 return the_field;
243 if (_Jv_CheckAccess (klass, *found_class, the_field->flags))
245 // Note that the field returned by find_field_helper is always
246 // resolved. There's no point checking class loaders here,
247 // since we already did the work to look up all the types.
248 // FIXME: being lazy here would be nice.
249 if (the_field->type != field_type)
250 throw new java::lang::LinkageError
251 (JvNewStringLatin1
252 ("field type mismatch with different loaders"));
254 else
256 java::lang::StringBuffer *sb
257 = new java::lang::StringBuffer ();
258 sb->append(klass->getName());
259 sb->append(JvNewStringLatin1(": "));
260 sb->append((*found_class)->getName());
261 sb->append(JvNewStringLatin1("."));
262 sb->append(_Jv_NewStringUtf8Const (field_name));
263 throw new java::lang::IllegalAccessError(sb->toString());
266 return the_field;
269 _Jv_word
270 _Jv_Linker::resolve_pool_entry (jclass klass, int index, bool lazy)
272 using namespace java::lang::reflect;
274 if (GC_base (klass) && klass->constants.data
275 && ! GC_base (klass->constants.data))
277 jsize count = klass->constants.size;
278 if (count)
280 _Jv_word* constants
281 = (_Jv_word*) _Jv_AllocRawObj (count * sizeof (_Jv_word));
282 memcpy ((void*)constants,
283 (void*)klass->constants.data,
284 count * sizeof (_Jv_word));
285 klass->constants.data = constants;
289 _Jv_Constants *pool = &klass->constants;
291 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
292 return pool->data[index];
294 switch (pool->tags[index])
296 case JV_CONSTANT_Class:
298 _Jv_Utf8Const *name = pool->data[index].utf8;
300 jclass found;
301 if (name->first() == '[')
302 found = _Jv_FindClassFromSignatureNoException (name->chars(),
303 klass->loader);
304 else
305 found = _Jv_FindClassNoException (name, klass->loader);
307 // If the class could not be loaded a phantom class is created. Any
308 // function that deals with such a class but cannot do something useful
309 // with it should just throw a NoClassDefFoundError with the class'
310 // name.
311 if (! found)
312 if (lazy)
314 found = _Jv_NewClass(name, NULL, NULL);
315 found->state = JV_STATE_PHANTOM;
316 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
317 pool->data[index].clazz = found;
318 break;
320 else
321 throw new java::lang::NoClassDefFoundError (name->toString());
323 // Check accessibility, but first strip array types as
324 // _Jv_ClassNameSamePackage can't handle arrays.
325 jclass check;
326 for (check = found;
327 check && check->isArray();
328 check = check->getComponentType())
330 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
331 || (_Jv_ClassNameSamePackage (check->name,
332 klass->name)))
334 pool->data[index].clazz = found;
335 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
337 else
339 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
340 sb->append(klass->getName());
341 sb->append(JvNewStringLatin1(" can't access class "));
342 sb->append(found->getName());
343 throw new java::lang::IllegalAccessError(sb->toString());
346 break;
348 case JV_CONSTANT_String:
350 jstring str;
351 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
352 pool->data[index].o = str;
353 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
355 break;
357 case JV_CONSTANT_Fieldref:
359 _Jv_ushort class_index, name_and_type_index;
360 _Jv_loadIndexes (&pool->data[index],
361 class_index,
362 name_and_type_index);
363 jclass owner = (resolve_pool_entry (klass, class_index, true)).clazz;
365 // If a phantom class was resolved our field reference is
366 // unusable because of the missing class.
367 if (owner->state == JV_STATE_PHANTOM)
368 throw new java::lang::NoClassDefFoundError(owner->getName());
370 if (owner != klass)
371 _Jv_InitClass (owner);
373 _Jv_ushort name_index, type_index;
374 _Jv_loadIndexes (&pool->data[name_and_type_index],
375 name_index,
376 type_index);
378 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
379 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
381 jclass found_class = 0;
382 _Jv_Field *the_field = find_field (klass, owner,
383 &found_class,
384 field_name,
385 field_type_name);
386 if (owner != found_class)
387 _Jv_InitClass (found_class);
388 pool->data[index].field = the_field;
389 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
391 break;
393 case JV_CONSTANT_Methodref:
394 case JV_CONSTANT_InterfaceMethodref:
396 _Jv_ushort class_index, name_and_type_index;
397 _Jv_loadIndexes (&pool->data[index],
398 class_index,
399 name_and_type_index);
400 jclass owner = (resolve_pool_entry (klass, class_index)).clazz;
402 if (owner != klass)
403 _Jv_InitClass (owner);
405 _Jv_ushort name_index, type_index;
406 _Jv_loadIndexes (&pool->data[name_and_type_index],
407 name_index,
408 type_index);
410 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
411 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
413 _Jv_Method *the_method = 0;
414 jclass found_class = 0;
416 // We're going to cache a pointer to the _Jv_Method object
417 // when we find it. So, to ensure this doesn't get moved from
418 // beneath us, we first put all the needed Miranda methods
419 // into the target class.
420 wait_for_state (klass, JV_STATE_LOADED);
422 // First search the class itself.
423 the_method = search_method_in_class (owner, klass,
424 method_name, method_signature);
426 if (the_method != 0)
428 found_class = owner;
429 goto end_of_method_search;
432 // If we are resolving an interface method, search the
433 // interface's superinterfaces (A superinterface is not an
434 // interface's superclass - a superinterface is implemented by
435 // the interface).
436 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
438 _Jv_ifaces ifaces;
439 ifaces.count = 0;
440 ifaces.len = 4;
441 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
442 * sizeof (jclass *));
444 get_interfaces (owner, &ifaces);
446 for (int i = 0; i < ifaces.count; i++)
448 jclass cls = ifaces.list[i];
449 the_method = search_method_in_class (cls, klass, method_name,
450 method_signature);
451 if (the_method != 0)
453 found_class = cls;
454 break;
458 _Jv_Free (ifaces.list);
460 if (the_method != 0)
461 goto end_of_method_search;
464 // Finally, search superclasses.
465 for (jclass cls = owner->getSuperclass (); cls != 0;
466 cls = cls->getSuperclass ())
468 the_method = search_method_in_class (cls, klass, method_name,
469 method_signature);
470 if (the_method != 0)
472 found_class = cls;
473 break;
477 end_of_method_search:
479 // FIXME: if (cls->loader != klass->loader), then we
480 // must actually check that the types of arguments
481 // correspond. That is, for each argument type, and
482 // the return type, doing _Jv_FindClassFromSignature
483 // with either loader should produce the same result,
484 // i.e., exactly the same jclass object. JVMS 5.4.3.3
486 if (the_method == 0)
488 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
489 sb->append(JvNewStringLatin1("method "));
490 sb->append(owner->getName());
491 sb->append(JvNewStringLatin1("."));
492 sb->append(_Jv_NewStringUTF(method_name->chars()));
493 sb->append(JvNewStringLatin1(" with signature "));
494 sb->append(_Jv_NewStringUTF(method_signature->chars()));
495 sb->append(JvNewStringLatin1(" was not found."));
496 throw new java::lang::NoSuchMethodError (sb->toString());
499 pool->data[index].rmethod
500 = klass->engine->resolve_method(the_method,
501 found_class,
502 ((the_method->accflags
503 & Modifier::STATIC) != 0));
504 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
506 break;
508 return pool->data[index];
511 // This function is used to lazily locate superclasses and
512 // superinterfaces. This must be called with the class lock held.
513 void
514 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
516 jclass ret = *classref;
518 // If superclass looks like a constant pool entry, resolve it now.
519 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
521 if (klass->state < JV_STATE_LINKED)
523 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
524 ret = _Jv_FindClass (name, klass->loader);
525 if (! ret)
527 throw new java::lang::NoClassDefFoundError (name->toString());
530 else
531 ret = klass->constants.data[(uaddr) classref].clazz;
532 *classref = ret;
536 // Find a method declared in the cls that is referenced from klass and
537 // perform access checks.
538 _Jv_Method *
539 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
540 _Jv_Utf8Const *method_name,
541 _Jv_Utf8Const *method_signature)
543 using namespace java::lang::reflect;
545 for (int i = 0; i < cls->method_count; i++)
547 _Jv_Method *method = &cls->methods[i];
548 if ( (!_Jv_equalUtf8Consts (method->name,
549 method_name))
550 || (!_Jv_equalUtf8Consts (method->signature,
551 method_signature)))
552 continue;
554 if (_Jv_CheckAccess (klass, cls, method->accflags))
555 return method;
556 else
558 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
559 sb->append(klass->getName());
560 sb->append(JvNewStringLatin1(": "));
561 sb->append(cls->getName());
562 sb->append(JvNewStringLatin1("."));
563 sb->append(_Jv_NewStringUTF(method_name->chars()));
564 sb->append(_Jv_NewStringUTF(method_signature->chars()));
565 throw new java::lang::IllegalAccessError (sb->toString());
568 return 0;
572 #define INITIAL_IOFFSETS_LEN 4
573 #define INITIAL_IFACES_LEN 4
575 static _Jv_IDispatchTable null_idt = {SHRT_MAX, 0, {}};
577 // Generate tables for constant-time assignment testing and interface
578 // method lookup. This implements the technique described by Per Bothner
579 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
580 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
581 void
582 _Jv_Linker::prepare_constant_time_tables (jclass klass)
584 if (klass->isPrimitive () || klass->isInterface ())
585 return;
587 // Short-circuit in case we've been called already.
588 if ((klass->idt != NULL) || klass->depth != 0)
589 return;
591 // Calculate the class depth and ancestor table. The depth of a class
592 // is how many "extends" it is removed from Object. Thus the depth of
593 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
594 // is 2. Depth is defined for all regular and array classes, but not
595 // interfaces or primitive types.
597 jclass klass0 = klass;
598 jboolean has_interfaces = 0;
599 while (klass0 != &java::lang::Object::class$)
601 has_interfaces += klass0->interface_count;
602 klass0 = klass0->superclass;
603 klass->depth++;
606 // We do class member testing in constant time by using a small table
607 // of all the ancestor classes within each class. The first element is
608 // a pointer to the current class, and the rest are pointers to the
609 // classes ancestors, ordered from the current class down by decreasing
610 // depth. We do not include java.lang.Object in the table of ancestors,
611 // since it is redundant. Note that the classes pointed to by
612 // 'ancestors' will always be reachable by other paths.
614 klass->ancestors = (jclass *) _Jv_AllocBytes (klass->depth
615 * sizeof (jclass));
616 klass0 = klass;
617 for (int index = 0; index < klass->depth; index++)
619 klass->ancestors[index] = klass0;
620 klass0 = klass0->superclass;
623 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
624 return;
626 // Optimization: If class implements no interfaces, use a common
627 // predefined interface table.
628 if (!has_interfaces)
630 klass->idt = &null_idt;
631 return;
634 _Jv_ifaces ifaces;
635 ifaces.count = 0;
636 ifaces.len = INITIAL_IFACES_LEN;
637 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
639 int itable_size = get_interfaces (klass, &ifaces);
641 if (ifaces.count > 0)
643 // The classes pointed to by the itable will always be reachable
644 // via other paths.
645 int idt_bytes = sizeof (_Jv_IDispatchTable) + (itable_size
646 * sizeof (void *));
647 klass->idt = (_Jv_IDispatchTable *) _Jv_AllocBytes (idt_bytes);
648 klass->idt->itable_length = itable_size;
650 jshort *itable_offsets =
651 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
653 generate_itable (klass, &ifaces, itable_offsets);
655 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
656 ifaces.count);
658 for (int i = 0; i < ifaces.count; i++)
660 ifaces.list[i]->ioffsets[cls_iindex] = itable_offsets[i];
663 klass->idt->iindex = cls_iindex;
665 _Jv_Free (ifaces.list);
666 _Jv_Free (itable_offsets);
668 else
670 klass->idt->iindex = SHRT_MAX;
674 // Return index of item in list, or -1 if item is not present.
675 inline jshort
676 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
678 for (int i=0; i < list_len; i++)
680 if (list[i] == item)
681 return i;
683 return -1;
686 // Find all unique interfaces directly or indirectly implemented by klass.
687 // Returns the size of the interface dispatch table (itable) for klass, which
688 // is the number of unique interfaces plus the total number of methods that
689 // those interfaces declare. May extend ifaces if required.
690 jshort
691 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
693 jshort result = 0;
695 for (int i = 0; i < klass->interface_count; i++)
697 jclass iface = klass->interfaces[i];
699 /* Make sure interface is linked. */
700 wait_for_state(iface, JV_STATE_LINKED);
702 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
704 if (ifaces->count + 1 >= ifaces->len)
706 /* Resize ifaces list */
707 ifaces->len = ifaces->len * 2;
708 ifaces->list
709 = (jclass *) _Jv_Realloc (ifaces->list,
710 ifaces->len * sizeof(jclass));
712 ifaces->list[ifaces->count] = iface;
713 ifaces->count++;
715 result += get_interfaces (klass->interfaces[i], ifaces);
719 if (klass->isInterface())
721 // We want to add 1 plus the number of interface methods here.
722 // But, we take special care to skip <clinit>.
723 ++result;
724 for (int i = 0; i < klass->method_count; ++i)
726 if (klass->methods[i].name->first() != '<')
727 ++result;
730 else if (klass->superclass)
731 result += get_interfaces (klass->superclass, ifaces);
732 return result;
735 // Fill out itable in klass, resolving method declarations in each ifaces.
736 // itable_offsets is filled out with the position of each iface in itable,
737 // such that itable[itable_offsets[n]] == ifaces.list[n].
738 void
739 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
740 jshort *itable_offsets)
742 void **itable = klass->idt->itable;
743 jshort itable_pos = 0;
745 for (int i = 0; i < ifaces->count; i++)
747 jclass iface = ifaces->list[i];
748 itable_offsets[i] = itable_pos;
749 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
751 /* Create ioffsets table for iface */
752 if (iface->ioffsets == NULL)
754 // The first element of ioffsets is its length (itself included).
755 jshort *ioffsets = (jshort *) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
756 * sizeof (jshort));
757 ioffsets[0] = INITIAL_IOFFSETS_LEN;
758 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
759 ioffsets[i] = -1;
761 iface->ioffsets = ioffsets;
766 // Format method name for use in error messages.
767 jstring
768 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
769 jclass derived)
771 using namespace java::lang;
772 StringBuffer *buf = new StringBuffer (klass->name->toString());
773 buf->append (jchar ('.'));
774 buf->append (meth->name->toString());
775 buf->append ((jchar) ' ');
776 buf->append (meth->signature->toString());
777 if (derived)
779 buf->append(JvNewStringLatin1(" in "));
780 buf->append(derived->name->toString());
782 return buf->toString();
785 void
786 _Jv_ThrowNoSuchMethodError ()
788 throw new java::lang::NoSuchMethodError;
791 #ifdef USE_LIBFFI
792 // A function whose invocation is prepared using libffi. It gets called
793 // whenever a static method of a missing class is invoked. The data argument
794 // holds a reference to a String denoting the missing class.
795 // The prepared function call is stored in a class' atable.
796 void
797 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif *,
798 void *,
799 void **,
800 void *data)
802 throw new java::lang::NoClassDefFoundError(
803 _Jv_NewStringUtf8Const((_Jv_Utf8Const *) data));
805 #else
806 // A variant of the NoClassDefFoundError throwing method that can
807 // be used without libffi.
808 void
809 _Jv_ThrowNoClassDefFoundError()
811 throw new java::lang::NoClassDefFoundError();
813 #endif
815 // Throw a NoSuchFieldError. Called by compiler-generated code when
816 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
817 // otable that refers to the missing field. This index may be used to
818 // print diagnostic information about the field.
819 void
820 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
822 throw new java::lang::NoSuchFieldError;
825 // This is put in empty vtable slots.
826 void
827 _Jv_ThrowAbstractMethodError ()
829 throw new java::lang::AbstractMethodError();
832 // Each superinterface of a class (i.e. each interface that the class
833 // directly or indirectly implements) has a corresponding "Partial
834 // Interface Dispatch Table" whose size is (number of methods + 1) words.
835 // The first word is a pointer to the interface (i.e. the java.lang.Class
836 // instance for that interface). The remaining words are pointers to the
837 // actual methods that implement the methods declared in the interface,
838 // in order of declaration.
840 // Append partial interface dispatch table for "iface" to "itable", at
841 // position itable_pos.
842 // Returns the offset at which the next partial ITable should be appended.
843 jshort
844 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
845 void **itable, jshort pos)
847 using namespace java::lang::reflect;
849 itable[pos++] = (void *) iface;
850 _Jv_Method *meth;
852 for (int j=0; j < iface->method_count; j++)
854 // Skip '<clinit>' here.
855 if (iface->methods[j].name->first() == '<')
856 continue;
858 meth = NULL;
859 for (jclass cl = klass; cl; cl = cl->getSuperclass())
861 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
862 iface->methods[j].signature);
864 if (meth)
865 break;
868 if (meth)
870 if ((meth->accflags & Modifier::STATIC) != 0)
871 throw new java::lang::IncompatibleClassChangeError
872 (_Jv_GetMethodString (klass, meth));
873 if ((meth->accflags & Modifier::PUBLIC) == 0)
874 throw new java::lang::IllegalAccessError
875 (_Jv_GetMethodString (klass, meth));
877 if ((meth->accflags & Modifier::ABSTRACT) != 0)
878 itable[pos] = (void *) &_Jv_ThrowAbstractMethodError;
879 else
880 itable[pos] = meth->ncode;
882 else
884 // The method doesn't exist in klass. Binary compatibility rules
885 // permit this, so we delay the error until runtime using a pointer
886 // to a method which throws an exception.
887 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
889 pos++;
892 return pos;
895 static _Jv_Mutex_t iindex_mutex;
896 static bool iindex_mutex_initialized = false;
898 // We need to find the correct offset in the Class Interface Dispatch
899 // Table for a given interface. Once we have that, invoking an interface
900 // method just requires combining the Method's index in the interface
901 // (known at compile time) to get the correct method. Doing a type test
902 // (cast or instanceof) is the same problem: Once we have a possible Partial
903 // Interface Dispatch Table, we just compare the first element to see if it
904 // matches the desired interface. So how can we find the correct offset?
905 // Our solution is to keep a vector of candiate offsets in each interface
906 // (ioffsets), and in each class we have an index (idt->iindex) used to
907 // select the correct offset from ioffsets.
909 // Calculate and return iindex for a new class.
910 // ifaces is a vector of num interfaces that the class implements.
911 // offsets[j] is the offset in the interface dispatch table for the
912 // interface corresponding to ifaces[j].
913 // May extend the interface ioffsets if required.
914 jshort
915 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
917 int i;
918 int j;
920 // Acquire a global lock to prevent itable corruption in case of multiple
921 // classes that implement an intersecting set of interfaces being linked
922 // simultaneously. We can assume that the mutex will be initialized
923 // single-threaded.
924 if (! iindex_mutex_initialized)
926 _Jv_MutexInit (&iindex_mutex);
927 iindex_mutex_initialized = true;
930 _Jv_MutexLock (&iindex_mutex);
932 for (i=1;; i++) /* each potential position in ioffsets */
934 for (j=0;; j++) /* each iface */
936 if (j >= num)
937 goto found;
938 if (i >= ifaces[j]->ioffsets[0])
939 continue;
940 int ioffset = ifaces[j]->ioffsets[i];
941 /* We can potentially share this position with another class. */
942 if (ioffset >= 0 && ioffset != offsets[j])
943 break; /* Nope. Try next i. */
946 found:
947 for (j = 0; j < num; j++)
949 int len = ifaces[j]->ioffsets[0];
950 if (i >= len)
952 // Resize ioffsets.
953 int newlen = 2 * len;
954 if (i >= newlen)
955 newlen = i + 3;
957 jshort *old_ioffsets = ifaces[j]->ioffsets;
958 jshort *new_ioffsets = (jshort *) _Jv_AllocBytes (newlen
959 * sizeof(jshort));
960 memcpy (&new_ioffsets[1], &old_ioffsets[1],
961 (len - 1) * sizeof (jshort));
962 new_ioffsets[0] = newlen;
964 while (len < newlen)
965 new_ioffsets[len++] = -1;
967 ifaces[j]->ioffsets = new_ioffsets;
969 ifaces[j]->ioffsets[i] = offsets[j];
972 _Jv_MutexUnlock (&iindex_mutex);
974 return i;
977 #ifdef USE_LIBFFI
978 // We use a structure of this type to store the closure that
979 // represents a missing method.
980 struct method_closure
982 // This field must come first, since the address of this field will
983 // be the same as the address of the overall structure. This is due
984 // to disabling interior pointers in the GC.
985 ffi_closure closure;
986 ffi_cif cif;
987 ffi_type *arg_types[1];
990 void *
991 _Jv_Linker::create_error_method (_Jv_Utf8Const *class_name)
993 method_closure *closure
994 = (method_closure *) _Jv_AllocBytes(sizeof (method_closure));
996 closure->arg_types[0] = &ffi_type_void;
998 // Initializes the cif and the closure. If that worked the closure
999 // is returned and can be used as a function pointer in a class'
1000 // atable.
1001 if ( ffi_prep_cif (&closure->cif,
1002 FFI_DEFAULT_ABI,
1004 &ffi_type_void,
1005 closure->arg_types) == FFI_OK
1006 && ffi_prep_closure (&closure->closure,
1007 &closure->cif,
1008 _Jv_ThrowNoClassDefFoundErrorTrampoline,
1009 class_name) == FFI_OK)
1010 return &closure->closure;
1011 else
1013 java::lang::StringBuffer *buffer = new java::lang::StringBuffer();
1014 buffer->append(JvNewStringLatin1("Error setting up FFI closure"
1015 " for static method of"
1016 " missing class: "));
1017 buffer->append (_Jv_NewStringUtf8Const(class_name));
1018 throw new java::lang::InternalError(buffer->toString());
1021 #else
1022 void *
1023 _Jv_Linker::create_error_method (_Jv_Utf8Const *)
1025 // Codepath for platforms which do not support (or want) libffi.
1026 // You have to accept that it is impossible to provide the name
1027 // of the missing class then.
1028 return (void *) _Jv_ThrowNoClassDefFoundError;
1030 #endif // USE_LIBFFI
1032 // Functions for indirect dispatch (symbolic virtual binding) support.
1034 // There are three tables, atable otable and itable. atable is an
1035 // array of addresses, and otable is an array of offsets, and these
1036 // are used for static and virtual members respectively. itable is an
1037 // array of pairs {address, index} where each address is a pointer to
1038 // an interface.
1040 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1041 // symbol is a tuple of {classname, member name, signature}.
1043 // Set this to true to enable debugging of indirect dispatch tables/linking.
1044 static bool debug_link = false;
1046 // link_symbol_table() scans these two arrays and fills in the
1047 // corresponding atable and otable with the addresses of static
1048 // members and the offsets of virtual members.
1050 // The offset (in bytes) for each resolved method or field is placed
1051 // at the corresponding position in the virtual method offset table
1052 // (klass->otable).
1054 // The same otable and atable may be shared by many classes.
1056 // This must be called while holding the class lock.
1058 void
1059 _Jv_Linker::link_symbol_table (jclass klass)
1061 int index = 0;
1062 _Jv_MethodSymbol sym;
1063 if (klass->otable == NULL
1064 || klass->otable->state != 0)
1065 goto atable;
1067 klass->otable->state = 1;
1069 if (debug_link)
1070 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
1071 for (index = 0;
1072 (sym = klass->otable_syms[index]).class_name != NULL;
1073 ++index)
1075 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1076 _Jv_Method *meth = NULL;
1078 _Jv_Utf8Const *signature = sym.signature;
1080 if (target_class == NULL)
1081 throw new java::lang::NoClassDefFoundError
1082 (_Jv_NewStringUTF (sym.class_name->chars()));
1084 // We're looking for a field or a method, and we can tell
1085 // which is needed by looking at the signature.
1086 if (signature->first() == '(' && signature->len() >= 2)
1088 // Looks like someone is trying to invoke an interface method
1089 if (target_class->isInterface())
1091 using namespace java::lang;
1092 StringBuffer *sb = new StringBuffer();
1093 sb->append(JvNewStringLatin1("found interface "));
1094 sb->append(target_class->getName());
1095 sb->append(JvNewStringLatin1(" when searching for a class"));
1096 throw new VerifyError(sb->toString());
1099 // If the target class does not have a vtable_method_count yet,
1100 // then we can't tell the offsets for its methods, so we must lay
1101 // it out now.
1102 wait_for_state(target_class, JV_STATE_PREPARED);
1104 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1105 sym.signature);
1107 // Every class has a throwNoSuchMethodErrorIndex method that
1108 // it inherits from java.lang.Object. Find its vtable
1109 // offset.
1110 static int throwNoSuchMethodErrorIndex;
1111 if (throwNoSuchMethodErrorIndex == 0)
1113 Utf8Const* name
1114 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1115 strlen ("throwNoSuchMethodError"));
1116 _Jv_Method* meth
1117 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$,
1118 name, gcj::void_signature);
1119 throwNoSuchMethodErrorIndex
1120 = _Jv_VTable::idx_to_offset (meth->index);
1123 // If we don't find a nonstatic method, insert the
1124 // vtable index of Object.throwNoSuchMethodError().
1125 // This defers the missing method error until an attempt
1126 // is made to execute it.
1128 int offset;
1130 if (meth != NULL)
1131 offset = _Jv_VTable::idx_to_offset (meth->index);
1132 else
1133 offset = throwNoSuchMethodErrorIndex;
1135 if (offset == -1)
1136 JvFail ("Bad method index");
1137 JvAssert (meth->index < target_class->vtable_method_count);
1139 klass->otable->offsets[index] = offset;
1142 if (debug_link)
1143 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1144 (int)index,
1145 (int)klass->otable->offsets[index],
1146 (const char*)target_class->name->chars(),
1147 target_class,
1148 (const char*)sym.name->chars(),
1149 (const char*)signature->chars());
1150 continue;
1153 // Try fields.
1155 wait_for_state(target_class, JV_STATE_PREPARED);
1156 jclass found_class;
1157 _Jv_Field *the_field = NULL;
1160 the_field = find_field (klass, target_class, &found_class,
1161 sym.name, sym.signature);
1162 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1163 throw new java::lang::IncompatibleClassChangeError;
1164 else
1165 klass->otable->offsets[index] = the_field->u.boffset;
1167 catch (java::lang::NoSuchFieldError *err)
1169 klass->otable->offsets[index] = 0;
1174 atable:
1175 if (klass->atable == NULL || klass->atable->state != 0)
1176 goto itable;
1178 klass->atable->state = 1;
1180 for (index = 0;
1181 (sym = klass->atable_syms[index]).class_name != NULL;
1182 ++index)
1184 jclass target_class =
1185 _Jv_FindClassNoException (sym.class_name, klass->loader);
1187 _Jv_Method *meth = NULL;
1188 _Jv_Utf8Const *signature = sym.signature;
1190 // ??? Setting this pointer to null will at least get us a
1191 // NullPointerException
1192 klass->atable->addresses[index] = NULL;
1194 // If the target class is missing we prepare a function call
1195 // that throws a NoClassDefFoundError and store the address of
1196 // that newly prepare method in the atable. The user can run
1197 // code in classes where the missing class is part of the
1198 // execution environment as long as it is never referenced.
1199 if (target_class == NULL)
1200 klass->atable->addresses[index] = create_error_method(sym.class_name);
1201 // We're looking for a static field or a static method, and we
1202 // can tell which is needed by looking at the signature.
1203 else if (signature->first() == '(' && signature->len() >= 2)
1205 // If the target class does not have a vtable_method_count yet,
1206 // then we can't tell the offsets for its methods, so we must lay
1207 // it out now.
1208 wait_for_state (target_class, JV_STATE_PREPARED);
1210 // Interface methods cannot have bodies.
1211 if (target_class->isInterface())
1213 using namespace java::lang;
1214 StringBuffer *sb = new StringBuffer();
1215 sb->append(JvNewStringLatin1("class "));
1216 sb->append(target_class->getName());
1217 sb->append(JvNewStringLatin1(" is an interface: "
1218 "class expected"));
1219 throw new VerifyError(sb->toString());
1222 meth = _Jv_LookupDeclaredMethod(target_class, sym.name,
1223 sym.signature);
1225 if (meth != NULL)
1227 if (meth->ncode) // Maybe abstract?
1229 klass->atable->addresses[index] = meth->ncode;
1230 if (debug_link)
1231 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1232 index,
1233 &klass->atable->addresses[index],
1234 (const char*)target_class->name->chars(),
1235 klass,
1236 (const char*)sym.name->chars(),
1237 (const char*)signature->chars());
1240 else
1241 klass->atable->addresses[index]
1242 = create_error_method(sym.class_name);
1244 continue;
1247 // Try fields only if the target class exists.
1248 if (target_class != NULL)
1250 wait_for_state(target_class, JV_STATE_PREPARED);
1251 jclass found_class;
1252 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
1253 sym.name, sym.signature);
1254 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1255 klass->atable->addresses[index] = the_field->u.addr;
1256 else
1257 throw new java::lang::IncompatibleClassChangeError;
1261 itable:
1262 if (klass->itable == NULL
1263 || klass->itable->state != 0)
1264 return;
1266 klass->itable->state = 1;
1268 for (index = 0;
1269 (sym = klass->itable_syms[index]).class_name != NULL;
1270 ++index)
1272 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1273 _Jv_Utf8Const *signature = sym.signature;
1275 jclass cls;
1276 int i;
1278 wait_for_state(target_class, JV_STATE_LOADED);
1279 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1280 sym.name, sym.signature);
1282 if (found)
1284 klass->itable->addresses[index * 2] = cls;
1285 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1286 if (debug_link)
1288 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1289 index,
1290 klass->itable->addresses[index * 2],
1291 (const char*)cls->name->chars(),
1292 cls,
1293 (const char*)sym.name->chars(),
1294 (const char*)signature->chars());
1295 fprintf (stderr, " [%d] = offset %d\n",
1296 index + 1,
1297 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1301 else
1302 throw new java::lang::IncompatibleClassChangeError;
1307 // For each catch_record in the list of caught classes, fill in the
1308 // address field.
1309 void
1310 _Jv_Linker::link_exception_table (jclass self)
1312 struct _Jv_CatchClass *catch_record = self->catch_classes;
1313 if (!catch_record || catch_record->classname)
1314 return;
1315 catch_record++;
1316 while (catch_record->classname)
1320 jclass target_class
1321 = _Jv_FindClass (catch_record->classname,
1322 self->getClassLoaderInternal ());
1323 *catch_record->address = target_class;
1325 catch (::java::lang::Throwable *t)
1327 // FIXME: We need to do something better here.
1328 *catch_record->address = 0;
1330 catch_record++;
1332 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1335 // Set itable method indexes for members of interface IFACE.
1336 void
1337 _Jv_Linker::layout_interface_methods (jclass iface)
1339 if (! iface->isInterface())
1340 return;
1342 // itable indexes start at 1.
1343 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1344 // itable so they are also assigned an index here.
1345 for (int i = 0; i < iface->method_count; i++)
1346 iface->methods[i].index = i + 1;
1349 // Prepare virtual method declarations in KLASS, and any superclasses
1350 // as required, by determining their vtable index, setting
1351 // method->index, and finally setting the class's vtable_method_count.
1352 // Must be called with the lock for KLASS held.
1353 void
1354 _Jv_Linker::layout_vtable_methods (jclass klass)
1356 if (klass->vtable != NULL || klass->isInterface()
1357 || klass->vtable_method_count != -1)
1358 return;
1360 jclass superclass = klass->getSuperclass();
1362 if (superclass != NULL && superclass->vtable_method_count == -1)
1364 JvSynchronize sync (superclass);
1365 layout_vtable_methods (superclass);
1368 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1370 for (int i = 0; i < klass->method_count; ++i)
1372 _Jv_Method *meth = &klass->methods[i];
1373 _Jv_Method *super_meth = NULL;
1375 if (! _Jv_isVirtualMethod (meth))
1376 continue;
1378 if (superclass != NULL)
1380 jclass declarer;
1381 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1382 meth->signature, &declarer);
1383 // See if this method actually overrides the other method
1384 // we've found.
1385 if (super_meth)
1387 if (! _Jv_isVirtualMethod (super_meth)
1388 || ! _Jv_CheckAccess (klass, declarer,
1389 super_meth->accflags))
1390 super_meth = NULL;
1391 else if ((super_meth->accflags
1392 & java::lang::reflect::Modifier::FINAL) != 0)
1394 using namespace java::lang;
1395 StringBuffer *sb = new StringBuffer();
1396 sb->append(JvNewStringLatin1("method "));
1397 sb->append(_Jv_GetMethodString(klass, meth));
1398 sb->append(JvNewStringLatin1(" overrides final method "));
1399 sb->append(_Jv_GetMethodString(declarer, super_meth));
1400 throw new VerifyError(sb->toString());
1405 if (super_meth)
1406 meth->index = super_meth->index;
1407 else
1408 meth->index = index++;
1411 klass->vtable_method_count = index;
1414 // Set entries in VTABLE for virtual methods declared in KLASS.
1415 void
1416 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1418 for (int i = klass->method_count - 1; i >= 0; i--)
1420 using namespace java::lang::reflect;
1422 _Jv_Method *meth = &klass->methods[i];
1423 if (meth->index == (_Jv_ushort) -1)
1424 continue;
1425 if ((meth->accflags & Modifier::ABSTRACT))
1426 // FIXME: it might be nice to have a libffi trampoline here,
1427 // so we could pass in the method name and other information.
1428 vtable->set_method(meth->index,
1429 (void *) &_Jv_ThrowAbstractMethodError);
1430 else
1431 vtable->set_method(meth->index, meth->ncode);
1435 // Allocate and lay out the virtual method table for KLASS. This will
1436 // also cause vtables to be generated for any non-abstract
1437 // superclasses, and virtual method layout to occur for any abstract
1438 // superclasses. Must be called with monitor lock for KLASS held.
1439 void
1440 _Jv_Linker::make_vtable (jclass klass)
1442 using namespace java::lang::reflect;
1444 // If the vtable exists, or for interface classes, do nothing. All
1445 // other classes, including abstract classes, need a vtable.
1446 if (klass->vtable != NULL || klass->isInterface())
1447 return;
1449 // Ensure all the `ncode' entries are set.
1450 klass->engine->create_ncode(klass);
1452 // Class must be laid out before we can create a vtable.
1453 if (klass->vtable_method_count == -1)
1454 layout_vtable_methods (klass);
1456 // Allocate the new vtable.
1457 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1458 klass->vtable = vtable;
1460 // Copy the vtable of the closest superclass.
1461 jclass superclass = klass->superclass;
1463 JvSynchronize sync (superclass);
1464 make_vtable (superclass);
1466 for (int i = 0; i < superclass->vtable_method_count; ++i)
1467 vtable->set_method (i, superclass->vtable->get_method (i));
1469 // Set the class pointer and GC descriptor.
1470 vtable->clas = klass;
1471 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1473 // For each virtual declared in klass, set new vtable entry or
1474 // override an old one.
1475 set_vtable_entries (klass, vtable);
1477 // Note that we don't check for abstract methods here. We used to,
1478 // but there is a JVMS clarification that indicates that a check
1479 // here would be too eager. And, a simple test case confirms this.
1482 // Lay out the class, allocating space for static fields and computing
1483 // offsets of instance fields. The class lock must be held by the
1484 // caller.
1485 void
1486 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1488 if (klass->size_in_bytes != -1)
1489 return;
1491 // Compute the alignment for this type by searching through the
1492 // superclasses and finding the maximum required alignment. We
1493 // could consider caching this in the Class.
1494 int max_align = __alignof__ (java::lang::Object);
1495 jclass super = klass->getSuperclass();
1496 while (super != NULL)
1498 // Ensure that our super has its super installed before
1499 // recursing.
1500 wait_for_state(super, JV_STATE_LOADING);
1501 ensure_fields_laid_out(super);
1502 int num = JvNumInstanceFields (super);
1503 _Jv_Field *field = JvGetFirstInstanceField (super);
1504 while (num > 0)
1506 int field_align = get_alignment_from_class (field->type);
1507 if (field_align > max_align)
1508 max_align = field_align;
1509 ++field;
1510 --num;
1512 super = super->getSuperclass();
1515 int instance_size;
1516 // This is the size of the 'static' non-reference fields.
1517 int non_reference_size = 0;
1518 // This is the size of the 'static' reference fields. We count
1519 // these separately to make it simpler for the GC to scan them.
1520 int reference_size = 0;
1522 // Although java.lang.Object is never interpreted, an interface can
1523 // have a null superclass. Note that we have to lay out an
1524 // interface because it might have static fields.
1525 if (klass->superclass)
1526 instance_size = klass->superclass->size();
1527 else
1528 instance_size = java::lang::Object::class$.size();
1530 klass->engine->allocate_field_initializers (klass);
1532 for (int i = 0; i < klass->field_count; i++)
1534 int field_size;
1535 int field_align;
1537 _Jv_Field *field = &klass->fields[i];
1539 if (! field->isRef ())
1541 // It is safe to resolve the field here, since it's a
1542 // primitive class, which does not cause loading to happen.
1543 resolve_field (field, klass->loader);
1544 field_size = field->type->size ();
1545 field_align = get_alignment_from_class (field->type);
1547 else
1549 field_size = sizeof (jobject);
1550 field_align = __alignof__ (jobject);
1553 field->bsize = field_size;
1555 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1557 if (field->u.addr == NULL)
1559 // This computes an offset into a region we'll allocate
1560 // shortly, and then adds this offset to the start
1561 // address.
1562 if (field->isRef())
1564 reference_size = ROUND (reference_size, field_align);
1565 field->u.boffset = reference_size;
1566 reference_size += field_size;
1568 else
1570 non_reference_size = ROUND (non_reference_size, field_align);
1571 field->u.boffset = non_reference_size;
1572 non_reference_size += field_size;
1576 else
1578 instance_size = ROUND (instance_size, field_align);
1579 field->u.boffset = instance_size;
1580 instance_size += field_size;
1581 if (field_align > max_align)
1582 max_align = field_align;
1586 if (reference_size != 0 || non_reference_size != 0)
1587 klass->engine->allocate_static_fields (klass, reference_size,
1588 non_reference_size);
1590 // Set the instance size for the class. Note that first we round it
1591 // to the alignment required for this object; this keeps us in sync
1592 // with our current ABI.
1593 instance_size = ROUND (instance_size, max_align);
1594 klass->size_in_bytes = instance_size;
1597 // This takes the class to state JV_STATE_LINKED. The class lock must
1598 // be held when calling this.
1599 void
1600 _Jv_Linker::ensure_class_linked (jclass klass)
1602 if (klass->state >= JV_STATE_LINKED)
1603 return;
1605 int state = klass->state;
1608 // Short-circuit, so that mutually dependent classes are ok.
1609 klass->state = JV_STATE_LINKED;
1611 _Jv_Constants *pool = &klass->constants;
1613 // Compiled classes require that their class constants be
1614 // resolved here. However, interpreted classes need their
1615 // constants to be resolved lazily. If we resolve an
1616 // interpreted class' constants eagerly, we can end up with
1617 // spurious IllegalAccessErrors when the constant pool contains
1618 // a reference to a class we can't access. This can validly
1619 // occur in an obscure case involving the InnerClasses
1620 // attribute.
1621 if (! _Jv_IsInterpretedClass (klass))
1623 // Resolve class constants first, since other constant pool
1624 // entries may rely on these.
1625 for (int index = 1; index < pool->size; ++index)
1627 if (pool->tags[index] == JV_CONSTANT_Class)
1628 // Lazily resolve the entries.
1629 resolve_pool_entry (klass, index, true);
1633 // Resolve the remaining constant pool entries.
1634 for (int index = 1; index < pool->size; ++index)
1636 if (pool->tags[index] == JV_CONSTANT_String)
1638 jstring str;
1640 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1641 pool->data[index].o = str;
1642 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1646 if (klass->engine->need_resolve_string_fields())
1648 jfieldID f = JvGetFirstStaticField (klass);
1649 for (int n = JvNumStaticFields (klass); n > 0; --n)
1651 int mod = f->getModifiers ();
1652 // If we have a static String field with a non-null initial
1653 // value, we know it points to a Utf8Const.
1655 // Finds out whether we have to initialize a String without the
1656 // need to resolve the field.
1657 if ((f->isResolved()
1658 ? (f->type == &java::lang::String::class$)
1659 : _Jv_equalUtf8Classnames((_Jv_Utf8Const *) f->type,
1660 java::lang::String::class$.name))
1661 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1663 jstring *strp = (jstring *) f->u.addr;
1664 if (*strp)
1665 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1667 f = f->getNextField ();
1671 klass->notifyAll ();
1673 _Jv_PushClass (klass);
1675 catch (java::lang::Throwable *t)
1677 klass->state = state;
1678 throw t;
1682 // This ensures that symbolic superclass and superinterface references
1683 // are resolved for the indicated class. This must be called with the
1684 // class lock held.
1685 void
1686 _Jv_Linker::ensure_supers_installed (jclass klass)
1688 resolve_class_ref (klass, &klass->superclass);
1689 // An interface won't have a superclass.
1690 if (klass->superclass)
1691 wait_for_state (klass->superclass, JV_STATE_LOADING);
1693 for (int i = 0; i < klass->interface_count; ++i)
1695 resolve_class_ref (klass, &klass->interfaces[i]);
1696 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1700 // This adds missing `Miranda methods' to a class.
1701 void
1702 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1704 // Note that at this point, all our supers, and the supers of all
1705 // our superclasses and superinterfaces, will have been installed.
1707 for (int i = 0; i < iface_class->interface_count; ++i)
1709 jclass interface = iface_class->interfaces[i];
1711 for (int j = 0; j < interface->method_count; ++j)
1713 _Jv_Method *meth = &interface->methods[j];
1714 // Don't bother with <clinit>.
1715 if (meth->name->first() == '<')
1716 continue;
1717 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1718 meth->signature);
1719 if (! new_meth)
1721 // We assume that such methods are very unlikely, so we
1722 // just reallocate the method array each time one is
1723 // found. This greatly simplifies the searching --
1724 // otherwise we have to make sure that each such method
1725 // found is really unique among all superinterfaces.
1726 int new_count = base->method_count + 1;
1727 _Jv_Method *new_m
1728 = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method)
1729 * new_count);
1730 memcpy (new_m, base->methods,
1731 sizeof (_Jv_Method) * base->method_count);
1733 // Add new method.
1734 new_m[base->method_count] = *meth;
1735 new_m[base->method_count].index = (_Jv_ushort) -1;
1736 new_m[base->method_count].accflags
1737 |= java::lang::reflect::Modifier::INVISIBLE;
1739 base->methods = new_m;
1740 base->method_count = new_count;
1744 wait_for_state (interface, JV_STATE_LOADED);
1745 add_miranda_methods (base, interface);
1749 // This ensures that the class' method table is "complete". This must
1750 // be called with the class lock held.
1751 void
1752 _Jv_Linker::ensure_method_table_complete (jclass klass)
1754 if (klass->vtable != NULL)
1755 return;
1757 // We need our superclass to have its own Miranda methods installed.
1758 if (! klass->isInterface())
1759 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1761 // A class might have so-called "Miranda methods". This is a method
1762 // that is declared in an interface and not re-declared in an
1763 // abstract class. Some compilers don't emit declarations for such
1764 // methods in the class; this will give us problems since we expect
1765 // a declaration for any method requiring a vtable entry. We handle
1766 // this here by searching for such methods and constructing new
1767 // internal declarations for them. Note that we do this
1768 // unconditionally, and not just for abstract classes, to correctly
1769 // account for cases where a class is modified to be concrete and
1770 // still incorrectly inherits an abstract method.
1771 int pre_count = klass->method_count;
1772 add_miranda_methods (klass, klass);
1774 // Let the execution engine know that we've added methods.
1775 if (klass->method_count != pre_count)
1776 klass->engine->post_miranda_hook(klass);
1779 // Verify a class. Must be called with class lock held.
1780 void
1781 _Jv_Linker::verify_class (jclass klass)
1783 klass->engine->verify(klass);
1786 // Check the assertions contained in the type assertion table for KLASS.
1787 // This is the equivilent of bytecode verification for native, BC-ABI code.
1788 void
1789 _Jv_Linker::verify_type_assertions (jclass klass)
1791 if (debug_link)
1792 fprintf (stderr, "Evaluating type assertions for %s:\n",
1793 klass->name->chars());
1795 if (klass->assertion_table == NULL)
1796 return;
1798 for (int i = 0;; i++)
1800 int assertion_code = klass->assertion_table[i].assertion_code;
1801 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1802 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1804 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1805 return;
1806 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1808 if (debug_link)
1810 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1811 assertion_code, op1->chars(), op2->chars());
1814 // The operands are class signatures. op1 is the source,
1815 // op2 is the target.
1816 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1817 klass->getClassLoaderInternal());
1818 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1819 klass->getClassLoaderInternal());
1821 // If the class doesn't exist, ignore the assertion. An exception
1822 // will be thrown later if an attempt is made to actually
1823 // instantiate the class.
1824 if (cl1 == NULL || cl2 == NULL)
1825 continue;
1827 if (! _Jv_IsAssignableFromSlow (cl1, cl2))
1829 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1830 s = s->concat (klass->getName());
1831 s = s->concat (JvNewStringUTF (": "));
1832 s = s->concat (cl1->getName());
1833 s = s->concat (JvNewStringUTF (" is not assignable to "));
1834 s = s->concat (cl2->getName());
1835 throw new java::lang::VerifyError (s);
1838 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1840 // TODO: Implement this.
1842 // Unknown assertion codes are ignored, for forwards-compatibility.
1846 void
1847 _Jv_Linker::print_class_loaded (jclass klass)
1849 char *codesource = NULL;
1850 if (klass->protectionDomain != NULL)
1852 java::security::CodeSource *cs
1853 = klass->protectionDomain->getCodeSource();
1854 if (cs != NULL)
1856 jstring css = cs->toString();
1857 int len = JvGetStringUTFLength(css);
1858 codesource = (char *) _Jv_AllocBytes(len + 1);
1859 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1860 codesource[len] = '\0';
1863 if (codesource == NULL)
1864 codesource = (char *) "<no code source>";
1866 const char *abi;
1867 if (_Jv_IsInterpretedClass (klass))
1868 abi = "bytecode";
1869 else if (_Jv_IsBinaryCompatibilityABI (klass))
1870 abi = "BC-compiled";
1871 else
1872 abi = "pre-compiled";
1874 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1875 codesource);
1878 // FIXME: mention invariants and stuff.
1879 void
1880 _Jv_Linker::wait_for_state (jclass klass, int state)
1882 if (klass->state >= state)
1883 return;
1885 JvSynchronize sync (klass);
1887 // This is similar to the strategy for class initialization. If we
1888 // already hold the lock, just leave.
1889 java::lang::Thread *self = java::lang::Thread::currentThread();
1890 while (klass->state <= state
1891 && klass->thread
1892 && klass->thread != self)
1893 klass->wait ();
1895 java::lang::Thread *save = klass->thread;
1896 klass->thread = self;
1898 // Allocate memory for static fields and constants.
1899 if (GC_base (klass) && klass->fields && ! GC_base (klass->fields))
1901 jsize count = klass->field_count;
1902 if (count)
1904 _Jv_Field* fields
1905 = (_Jv_Field*) _Jv_AllocRawObj (count * sizeof (_Jv_Field));
1906 memcpy ((void*)fields,
1907 (void*)klass->fields,
1908 count * sizeof (_Jv_Field));
1909 klass->fields = fields;
1913 // Print some debugging info if requested. Interpreted classes are
1914 // handled in defineclass, so we only need to handle the two
1915 // pre-compiled cases here.
1916 if (gcj::verbose_class_flag
1917 && (klass->state == JV_STATE_COMPILED
1918 || klass->state == JV_STATE_PRELOADING)
1919 && ! _Jv_IsInterpretedClass (klass))
1920 print_class_loaded (klass);
1924 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
1926 ensure_supers_installed (klass);
1927 klass->set_state(JV_STATE_LOADING);
1930 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
1932 ensure_method_table_complete (klass);
1933 klass->set_state(JV_STATE_LOADED);
1936 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
1938 ensure_fields_laid_out (klass);
1939 make_vtable (klass);
1940 layout_interface_methods (klass);
1941 prepare_constant_time_tables (klass);
1942 klass->set_state(JV_STATE_PREPARED);
1945 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
1947 if (gcj::verifyClasses)
1948 verify_class (klass);
1950 ensure_class_linked (klass);
1951 link_exception_table (klass);
1952 link_symbol_table (klass);
1953 klass->set_state(JV_STATE_LINKED);
1956 catch (java::lang::Throwable *exc)
1958 klass->thread = save;
1959 klass->set_state(JV_STATE_ERROR);
1960 throw exc;
1963 klass->thread = save;
1965 if (klass->state == JV_STATE_ERROR)
1966 throw new java::lang::LinkageError;