re PR target/34981 (Lazily-bound function called twice)
[official-gcc.git] / libjava / link.cc
blobd6fd2ddafbda745544a4573f0a0a768b63583885
1 // link.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4 Free Software Foundation
6 This file is part of libgcj.
8 This software is copyrighted work licensed under the terms of the
9 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
10 details. */
12 /* Author: Kresten Krab Thorup <krab@gnu.org> */
14 #include <config.h>
15 #include <platform.h>
17 #include <stdio.h>
19 #ifdef USE_LIBFFI
20 #include <ffi.h>
21 #endif
23 #include <java-interp.h>
25 // Set GC_DEBUG before including gc.h!
26 #ifdef LIBGCJ_GC_DEBUG
27 # define GC_DEBUG
28 #endif
29 #include <gc.h>
31 #include <jvm.h>
32 #include <gcj/cni.h>
33 #include <string.h>
34 #include <limits.h>
35 #include <java-cpool.h>
36 #include <execution.h>
37 #ifdef INTERPRETER
38 #include <jvmti.h>
39 #include "jvmti-int.h"
40 #endif
41 #include <java/lang/Class.h>
42 #include <java/lang/String.h>
43 #include <java/lang/StringBuffer.h>
44 #include <java/lang/Thread.h>
45 #include <java/lang/InternalError.h>
46 #include <java/lang/VirtualMachineError.h>
47 #include <java/lang/VerifyError.h>
48 #include <java/lang/NoSuchFieldError.h>
49 #include <java/lang/NoSuchMethodError.h>
50 #include <java/lang/ClassFormatError.h>
51 #include <java/lang/IllegalAccessError.h>
52 #include <java/lang/InternalError.h>
53 #include <java/lang/AbstractMethodError.h>
54 #include <java/lang/NoClassDefFoundError.h>
55 #include <java/lang/IncompatibleClassChangeError.h>
56 #include <java/lang/VerifyError.h>
57 #include <java/lang/VMClassLoader.h>
58 #include <java/lang/reflect/Modifier.h>
59 #include <java/security/CodeSource.h>
61 using namespace gcj;
63 template<typename T>
64 struct aligner
66 char c;
67 T field;
70 #define ALIGNOF(TYPE) (offsetof (aligner<TYPE>, field))
72 // This returns the alignment of a type as it would appear in a
73 // structure. This can be different from the alignment of the type
74 // itself. For instance on x86 double is 8-aligned but struct{double}
75 // is 4-aligned.
76 int
77 _Jv_Linker::get_alignment_from_class (jclass klass)
79 if (klass == JvPrimClass (byte))
80 return ALIGNOF (jbyte);
81 else if (klass == JvPrimClass (short))
82 return ALIGNOF (jshort);
83 else if (klass == JvPrimClass (int))
84 return ALIGNOF (jint);
85 else if (klass == JvPrimClass (long))
86 return ALIGNOF (jlong);
87 else if (klass == JvPrimClass (boolean))
88 return ALIGNOF (jboolean);
89 else if (klass == JvPrimClass (char))
90 return ALIGNOF (jchar);
91 else if (klass == JvPrimClass (float))
92 return ALIGNOF (jfloat);
93 else if (klass == JvPrimClass (double))
94 return ALIGNOF (jdouble);
95 else
96 return ALIGNOF (jobject);
99 void
100 _Jv_Linker::resolve_field (_Jv_Field *field, java::lang::ClassLoader *loader)
102 if (! field->isResolved ())
104 _Jv_Utf8Const *sig = (_Jv_Utf8Const *) field->type;
105 jclass type = _Jv_FindClassFromSignature (sig->chars(), loader);
106 if (type == NULL)
107 throw new java::lang::NoClassDefFoundError(field->name->toString());
108 field->type = type;
109 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
113 // A helper for find_field that knows how to recursively search
114 // superclasses and interfaces.
115 _Jv_Field *
116 _Jv_Linker::find_field_helper (jclass search, _Jv_Utf8Const *name,
117 _Jv_Utf8Const *type_name, jclass type,
118 jclass *declarer)
120 while (search)
122 // From 5.4.3.2. First search class itself.
123 for (int i = 0; i < search->field_count; ++i)
125 _Jv_Field *field = &search->fields[i];
126 if (! _Jv_equalUtf8Consts (field->name, name))
127 continue;
129 // Checks for the odd situation where we were able to retrieve the
130 // field's class from signature but the resolution of the field itself
131 // failed which means a different class was resolved.
132 if (type != NULL)
136 resolve_field (field, search->loader);
138 catch (java::lang::Throwable *exc)
140 java::lang::LinkageError *le = new java::lang::LinkageError
141 (JvNewStringLatin1
142 ("field type mismatch with different loaders"));
144 le->initCause(exc);
146 throw le;
150 // Note that we compare type names and not types. This is
151 // bizarre, but we do it because we want to find a field
152 // (and terminate the search) if it has the correct
153 // descriptor -- but then later reject it if the class
154 // loader check results in different classes. We can't just
155 // pass in the descriptor and check that way, because when
156 // the field is already resolved there is no easy way to
157 // find its descriptor again.
158 if ((field->isResolved ()
159 ? _Jv_equalUtf8Classnames (type_name, field->type->name)
160 : _Jv_equalUtf8Classnames (type_name,
161 (_Jv_Utf8Const *) field->type)))
163 *declarer = search;
164 return field;
168 // Next search direct interfaces.
169 for (int i = 0; i < search->interface_count; ++i)
171 _Jv_Field *result = find_field_helper (search->interfaces[i], name,
172 type_name, type, declarer);
173 if (result)
174 return result;
177 // Now search superclass.
178 search = search->superclass;
181 return NULL;
184 bool
185 _Jv_Linker::has_field_p (jclass search, _Jv_Utf8Const *field_name)
187 for (int i = 0; i < search->field_count; ++i)
189 _Jv_Field *field = &search->fields[i];
190 if (_Jv_equalUtf8Consts (field->name, field_name))
191 return true;
193 return false;
196 // Find a field.
197 // KLASS is the class that is requesting the field.
198 // OWNER is the class in which the field should be found.
199 // FIELD_TYPE_NAME is the type descriptor for the field.
200 // Fill FOUND_CLASS with the address of the class in which the field
201 // is actually declared.
202 // This function does the class loader type checks, and
203 // also access checks. Returns the field, or throws an
204 // exception on error.
205 _Jv_Field *
206 _Jv_Linker::find_field (jclass klass, jclass owner,
207 jclass *found_class,
208 _Jv_Utf8Const *field_name,
209 _Jv_Utf8Const *field_type_name)
211 // FIXME: this allocates a _Jv_Utf8Const each time. We should make
212 // it cheaper.
213 // Note: This call will resolve the primitive type names ("Z", "B", ...) to
214 // their Java counterparts ("boolean", "byte", ...) if accessed via
215 // field_type->name later. Using these variants of the type name is in turn
216 // important for the find_field_helper function. However if the class
217 // resolution failed then we can only use the already given type name.
218 jclass field_type
219 = _Jv_FindClassFromSignatureNoException (field_type_name->chars(),
220 klass->loader);
222 _Jv_Field *the_field
223 = find_field_helper (owner, field_name,
224 (field_type
225 ? field_type->name :
226 field_type_name ),
227 field_type, found_class);
229 if (the_field == 0)
231 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
232 sb->append(JvNewStringLatin1("field "));
233 sb->append(owner->getName());
234 sb->append(JvNewStringLatin1("."));
235 sb->append(_Jv_NewStringUTF(field_name->chars()));
236 sb->append(JvNewStringLatin1(" was not found."));
237 throw new java::lang::NoSuchFieldError (sb->toString());
240 // Accept it when the field's class could not be resolved.
241 if (field_type == NULL)
242 // Silently ignore that we were not able to retrieve the type to make it
243 // possible to run code which does not access this field.
244 return the_field;
246 if (_Jv_CheckAccess (klass, *found_class, the_field->flags))
248 // Note that the field returned by find_field_helper is always
249 // resolved. There's no point checking class loaders here,
250 // since we already did the work to look up all the types.
251 // FIXME: being lazy here would be nice.
252 if (the_field->type != field_type)
253 throw new java::lang::LinkageError
254 (JvNewStringLatin1
255 ("field type mismatch with different loaders"));
257 else
259 java::lang::StringBuffer *sb
260 = new java::lang::StringBuffer ();
261 sb->append(klass->getName());
262 sb->append(JvNewStringLatin1(": "));
263 sb->append((*found_class)->getName());
264 sb->append(JvNewStringLatin1("."));
265 sb->append(_Jv_NewStringUtf8Const (field_name));
266 throw new java::lang::IllegalAccessError(sb->toString());
269 return the_field;
272 _Jv_Method *
273 _Jv_Linker::resolve_method_entry (jclass klass, jclass &found_class,
274 int class_index, int name_and_type_index,
275 bool init, bool is_iface)
277 _Jv_Constants *pool = &klass->constants;
278 jclass owner = resolve_pool_entry (klass, class_index).clazz;
280 if (init && owner != klass)
281 _Jv_InitClass (owner);
283 _Jv_ushort name_index, type_index;
284 _Jv_loadIndexes (&pool->data[name_and_type_index],
285 name_index,
286 type_index);
288 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
289 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
291 _Jv_Method *the_method = 0;
292 found_class = 0;
294 // We're going to cache a pointer to the _Jv_Method object
295 // when we find it. So, to ensure this doesn't get moved from
296 // beneath us, we first put all the needed Miranda methods
297 // into the target class.
298 wait_for_state (klass, JV_STATE_LOADED);
300 // First search the class itself.
301 the_method = search_method_in_class (owner, klass,
302 method_name, method_signature);
304 if (the_method != 0)
306 found_class = owner;
307 goto end_of_method_search;
310 // If we are resolving an interface method, search the
311 // interface's superinterfaces (A superinterface is not an
312 // interface's superclass - a superinterface is implemented by
313 // the interface).
314 if (is_iface)
316 _Jv_ifaces ifaces;
317 ifaces.count = 0;
318 ifaces.len = 4;
319 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
320 * sizeof (jclass *));
322 get_interfaces (owner, &ifaces);
324 for (int i = 0; i < ifaces.count; i++)
326 jclass cls = ifaces.list[i];
327 the_method = search_method_in_class (cls, klass, method_name,
328 method_signature);
329 if (the_method != 0)
331 found_class = cls;
332 break;
336 _Jv_Free (ifaces.list);
338 if (the_method != 0)
339 goto end_of_method_search;
342 // Finally, search superclasses.
343 the_method = (search_method_in_superclasses
344 (owner->getSuperclass (), klass, method_name,
345 method_signature, &found_class));
348 end_of_method_search:
349 if (the_method == 0)
351 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
352 sb->append(JvNewStringLatin1("method "));
353 sb->append(owner->getName());
354 sb->append(JvNewStringLatin1("."));
355 sb->append(_Jv_NewStringUTF(method_name->chars()));
356 sb->append(JvNewStringLatin1(" with signature "));
357 sb->append(_Jv_NewStringUTF(method_signature->chars()));
358 sb->append(JvNewStringLatin1(" was not found."));
359 throw new java::lang::NoSuchMethodError (sb->toString());
362 // if (found_class->loader != klass->loader), then we
363 // must actually check that the types of arguments
364 // correspond. That is, for each argument type, and
365 // the return type, doing _Jv_FindClassFromSignature
366 // with either loader should produce the same result,
367 // i.e., exactly the same jclass object. JVMS 5.4.3.3
368 if (found_class->loader != klass->loader)
370 JArray<jclass> *found_args, *klass_args;
371 jclass found_return, klass_return;
373 _Jv_GetTypesFromSignature (the_method,
374 found_class,
375 &found_args,
376 &found_return);
377 _Jv_GetTypesFromSignature (the_method,
378 klass,
379 &klass_args,
380 &klass_return);
382 jclass *found_arg = elements (found_args);
383 jclass *klass_arg = elements (klass_args);
385 for (int i = 0; i < found_args->length; i++)
387 if (*(found_arg++) != *(klass_arg++))
388 throw new java::lang::LinkageError (JvNewStringLatin1
389 ("argument type mismatch with different loaders"));
391 if (found_return != klass_return)
392 throw new java::lang::LinkageError (JvNewStringLatin1
393 ("return type mismatch with different loaders"));
396 return the_method;
399 _Jv_word
400 _Jv_Linker::resolve_pool_entry (jclass klass, int index, bool lazy)
402 using namespace java::lang::reflect;
404 if (GC_base (klass) && klass->constants.data
405 && ! GC_base (klass->constants.data))
407 jsize count = klass->constants.size;
408 if (count)
410 _Jv_word* constants
411 = (_Jv_word*) _Jv_AllocRawObj (count * sizeof (_Jv_word));
412 memcpy ((void*)constants,
413 (void*)klass->constants.data,
414 count * sizeof (_Jv_word));
415 klass->constants.data = constants;
419 _Jv_Constants *pool = &klass->constants;
421 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
422 return pool->data[index];
424 switch (pool->tags[index] & ~JV_CONSTANT_LazyFlag)
426 case JV_CONSTANT_Class:
428 _Jv_Utf8Const *name = pool->data[index].utf8;
430 jclass found;
431 if (name->first() == '[')
432 found = _Jv_FindClassFromSignatureNoException (name->chars(),
433 klass->loader);
434 else
435 found = _Jv_FindClassNoException (name, klass->loader);
437 // If the class could not be loaded a phantom class is created. Any
438 // function that deals with such a class but cannot do something useful
439 // with it should just throw a NoClassDefFoundError with the class'
440 // name.
441 if (! found)
443 if (lazy)
445 found = _Jv_NewClass(name, NULL, NULL);
446 found->state = JV_STATE_PHANTOM;
447 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
448 pool->data[index].clazz = found;
449 break;
451 else
452 throw new java::lang::NoClassDefFoundError (name->toString());
455 // Check accessibility, but first strip array types as
456 // _Jv_ClassNameSamePackage can't handle arrays.
457 jclass check;
458 for (check = found;
459 check && check->isArray();
460 check = check->getComponentType())
462 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
463 || (_Jv_ClassNameSamePackage (check->name,
464 klass->name)))
466 pool->data[index].clazz = found;
467 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
469 else
471 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
472 sb->append(klass->getName());
473 sb->append(JvNewStringLatin1(" can't access class "));
474 sb->append(found->getName());
475 throw new java::lang::IllegalAccessError(sb->toString());
478 break;
480 case JV_CONSTANT_String:
482 jstring str;
483 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
484 pool->data[index].o = str;
485 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
487 break;
489 case JV_CONSTANT_Fieldref:
491 _Jv_ushort class_index, name_and_type_index;
492 _Jv_loadIndexes (&pool->data[index],
493 class_index,
494 name_and_type_index);
495 jclass owner = (resolve_pool_entry (klass, class_index, true)).clazz;
497 // If a phantom class was resolved our field reference is
498 // unusable because of the missing class.
499 if (owner->state == JV_STATE_PHANTOM)
500 throw new java::lang::NoClassDefFoundError(owner->getName());
502 // We don't initialize 'owner', but we do make sure that its
503 // fields exist.
504 wait_for_state (owner, JV_STATE_PREPARED);
506 _Jv_ushort name_index, type_index;
507 _Jv_loadIndexes (&pool->data[name_and_type_index],
508 name_index,
509 type_index);
511 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
512 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
514 jclass found_class = 0;
515 _Jv_Field *the_field = find_field (klass, owner,
516 &found_class,
517 field_name,
518 field_type_name);
519 // Initialize the field's declaring class, not its qualifying
520 // class.
521 _Jv_InitClass (found_class);
522 pool->data[index].field = the_field;
523 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
525 break;
527 case JV_CONSTANT_Methodref:
528 case JV_CONSTANT_InterfaceMethodref:
530 _Jv_ushort class_index, name_and_type_index;
531 _Jv_loadIndexes (&pool->data[index],
532 class_index,
533 name_and_type_index);
535 _Jv_Method *the_method;
536 jclass found_class;
537 the_method = resolve_method_entry (klass, found_class,
538 class_index, name_and_type_index,
539 true,
540 pool->tags[index] == JV_CONSTANT_InterfaceMethodref);
542 pool->data[index].rmethod
543 = klass->engine->resolve_method(the_method,
544 found_class,
545 ((the_method->accflags
546 & Modifier::STATIC) != 0));
547 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
549 break;
551 return pool->data[index];
554 // This function is used to lazily locate superclasses and
555 // superinterfaces. This must be called with the class lock held.
556 void
557 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
559 jclass ret = *classref;
561 // If superclass looks like a constant pool entry, resolve it now.
562 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
564 if (klass->state < JV_STATE_LINKED)
566 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
567 ret = _Jv_FindClass (name, klass->loader);
568 if (! ret)
570 throw new java::lang::NoClassDefFoundError (name->toString());
573 else
574 ret = klass->constants.data[(uaddr) classref].clazz;
575 *classref = ret;
579 // Find a method declared in the cls that is referenced from klass and
580 // perform access checks if CHECK_PERMS is true.
581 _Jv_Method *
582 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
583 _Jv_Utf8Const *method_name,
584 _Jv_Utf8Const *method_signature,
585 bool check_perms)
587 using namespace java::lang::reflect;
589 for (int i = 0; i < cls->method_count; i++)
591 _Jv_Method *method = &cls->methods[i];
592 if ( (!_Jv_equalUtf8Consts (method->name,
593 method_name))
594 || (!_Jv_equalUtf8Consts (method->signature,
595 method_signature)))
596 continue;
598 if (!check_perms || _Jv_CheckAccess (klass, cls, method->accflags))
599 return method;
600 else
602 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
603 sb->append(klass->getName());
604 sb->append(JvNewStringLatin1(": "));
605 sb->append(cls->getName());
606 sb->append(JvNewStringLatin1("."));
607 sb->append(_Jv_NewStringUTF(method_name->chars()));
608 sb->append(_Jv_NewStringUTF(method_signature->chars()));
609 throw new java::lang::IllegalAccessError (sb->toString());
612 return 0;
615 // Like search_method_in_class, but work our way up the superclass
616 // chain.
617 _Jv_Method *
618 _Jv_Linker::search_method_in_superclasses (jclass cls, jclass klass,
619 _Jv_Utf8Const *method_name,
620 _Jv_Utf8Const *method_signature,
621 jclass *found_class, bool check_perms)
623 _Jv_Method *the_method = NULL;
625 for ( ; cls != 0; cls = cls->getSuperclass ())
627 the_method = search_method_in_class (cls, klass, method_name,
628 method_signature, check_perms);
629 if (the_method != 0)
631 if (found_class)
632 *found_class = cls;
633 break;
637 return the_method;
640 #define INITIAL_IOFFSETS_LEN 4
641 #define INITIAL_IFACES_LEN 4
643 static _Jv_IDispatchTable null_idt = {SHRT_MAX, 0, {}};
645 // Generate tables for constant-time assignment testing and interface
646 // method lookup. This implements the technique described by Per Bothner
647 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
648 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
649 void
650 _Jv_Linker::prepare_constant_time_tables (jclass klass)
652 if (klass->isPrimitive () || klass->isInterface ())
653 return;
655 // Short-circuit in case we've been called already.
656 if ((klass->idt != NULL) || klass->depth != 0)
657 return;
659 // Calculate the class depth and ancestor table. The depth of a class
660 // is how many "extends" it is removed from Object. Thus the depth of
661 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
662 // is 2. Depth is defined for all regular and array classes, but not
663 // interfaces or primitive types.
665 jclass klass0 = klass;
666 jboolean has_interfaces = false;
667 while (klass0 != &java::lang::Object::class$)
669 if (klass0->interface_count)
670 has_interfaces = true;
671 klass0 = klass0->superclass;
672 klass->depth++;
675 // We do class member testing in constant time by using a small table
676 // of all the ancestor classes within each class. The first element is
677 // a pointer to the current class, and the rest are pointers to the
678 // classes ancestors, ordered from the current class down by decreasing
679 // depth. We do not include java.lang.Object in the table of ancestors,
680 // since it is redundant. Note that the classes pointed to by
681 // 'ancestors' will always be reachable by other paths.
683 klass->ancestors = (jclass *) _Jv_AllocBytes (klass->depth
684 * sizeof (jclass));
685 klass0 = klass;
686 for (int index = 0; index < klass->depth; index++)
688 klass->ancestors[index] = klass0;
689 klass0 = klass0->superclass;
692 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
693 return;
695 // Optimization: If class implements no interfaces, use a common
696 // predefined interface table.
697 if (!has_interfaces)
699 klass->idt = &null_idt;
700 return;
703 _Jv_ifaces ifaces;
704 ifaces.count = 0;
705 ifaces.len = INITIAL_IFACES_LEN;
706 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
708 int itable_size = get_interfaces (klass, &ifaces);
710 if (ifaces.count > 0)
712 // The classes pointed to by the itable will always be reachable
713 // via other paths.
714 int idt_bytes = sizeof (_Jv_IDispatchTable) + (itable_size
715 * sizeof (void *));
716 klass->idt = (_Jv_IDispatchTable *) _Jv_AllocBytes (idt_bytes);
717 klass->idt->itable_length = itable_size;
719 jshort *itable_offsets =
720 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
722 generate_itable (klass, &ifaces, itable_offsets);
724 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
725 ifaces.count);
727 for (int i = 0; i < ifaces.count; i++)
729 ifaces.list[i]->ioffsets[cls_iindex] = itable_offsets[i];
732 klass->idt->iindex = cls_iindex;
734 _Jv_Free (ifaces.list);
735 _Jv_Free (itable_offsets);
737 else
739 klass->idt->iindex = SHRT_MAX;
743 // Return index of item in list, or -1 if item is not present.
744 inline jshort
745 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
747 for (int i=0; i < list_len; i++)
749 if (list[i] == item)
750 return i;
752 return -1;
755 // Find all unique interfaces directly or indirectly implemented by klass.
756 // Returns the size of the interface dispatch table (itable) for klass, which
757 // is the number of unique interfaces plus the total number of methods that
758 // those interfaces declare. May extend ifaces if required.
759 jshort
760 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
762 jshort result = 0;
764 for (int i = 0; i < klass->interface_count; i++)
766 jclass iface = klass->interfaces[i];
768 /* Make sure interface is linked. */
769 wait_for_state(iface, JV_STATE_LINKED);
771 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
773 if (ifaces->count + 1 >= ifaces->len)
775 /* Resize ifaces list */
776 ifaces->len = ifaces->len * 2;
777 ifaces->list
778 = (jclass *) _Jv_Realloc (ifaces->list,
779 ifaces->len * sizeof(jclass));
781 ifaces->list[ifaces->count] = iface;
782 ifaces->count++;
784 result += get_interfaces (klass->interfaces[i], ifaces);
788 if (klass->isInterface())
790 // We want to add 1 plus the number of interface methods here.
791 // But, we take special care to skip <clinit>.
792 ++result;
793 for (int i = 0; i < klass->method_count; ++i)
795 if (klass->methods[i].name->first() != '<')
796 ++result;
799 else if (klass->superclass)
800 result += get_interfaces (klass->superclass, ifaces);
801 return result;
804 // Fill out itable in klass, resolving method declarations in each ifaces.
805 // itable_offsets is filled out with the position of each iface in itable,
806 // such that itable[itable_offsets[n]] == ifaces.list[n].
807 void
808 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
809 jshort *itable_offsets)
811 void **itable = klass->idt->itable;
812 jshort itable_pos = 0;
814 for (int i = 0; i < ifaces->count; i++)
816 jclass iface = ifaces->list[i];
817 itable_offsets[i] = itable_pos;
818 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
820 /* Create ioffsets table for iface */
821 if (iface->ioffsets == NULL)
823 // The first element of ioffsets is its length (itself included).
824 jshort *ioffsets = (jshort *) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
825 * sizeof (jshort));
826 ioffsets[0] = INITIAL_IOFFSETS_LEN;
827 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
828 ioffsets[i] = -1;
830 iface->ioffsets = ioffsets;
835 // Format method name for use in error messages.
836 jstring
837 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
838 jclass derived)
840 using namespace java::lang;
841 StringBuffer *buf = new StringBuffer (klass->name->toString());
842 buf->append (jchar ('.'));
843 buf->append (meth->name->toString());
844 buf->append ((jchar) ' ');
845 buf->append (meth->signature->toString());
846 if (derived)
848 buf->append(JvNewStringLatin1(" in "));
849 buf->append(derived->name->toString());
851 return buf->toString();
854 void
855 _Jv_ThrowNoSuchMethodError ()
857 throw new java::lang::NoSuchMethodError;
860 #if defined USE_LIBFFI && FFI_CLOSURES && defined(INTERPRETER)
861 // A function whose invocation is prepared using libffi. It gets called
862 // whenever a static method of a missing class is invoked. The data argument
863 // holds a reference to a String denoting the missing class.
864 // The prepared function call is stored in a class' atable.
865 void
866 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif *,
867 void *,
868 void **,
869 void *data)
871 throw new java::lang::NoClassDefFoundError(
872 _Jv_NewStringUtf8Const((_Jv_Utf8Const *) data));
874 #else
875 // A variant of the NoClassDefFoundError throwing method that can
876 // be used without libffi.
877 void
878 _Jv_ThrowNoClassDefFoundError()
880 throw new java::lang::NoClassDefFoundError();
882 #endif
884 // Throw a NoSuchFieldError. Called by compiler-generated code when
885 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
886 // otable that refers to the missing field. This index may be used to
887 // print diagnostic information about the field.
888 void
889 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
891 throw new java::lang::NoSuchFieldError;
894 // This is put in empty vtable slots.
895 void
896 _Jv_ThrowAbstractMethodError ()
898 throw new java::lang::AbstractMethodError();
901 // Each superinterface of a class (i.e. each interface that the class
902 // directly or indirectly implements) has a corresponding "Partial
903 // Interface Dispatch Table" whose size is (number of methods + 1) words.
904 // The first word is a pointer to the interface (i.e. the java.lang.Class
905 // instance for that interface). The remaining words are pointers to the
906 // actual methods that implement the methods declared in the interface,
907 // in order of declaration.
909 // Append partial interface dispatch table for "iface" to "itable", at
910 // position itable_pos.
911 // Returns the offset at which the next partial ITable should be appended.
912 jshort
913 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
914 void **itable, jshort pos)
916 using namespace java::lang::reflect;
918 itable[pos++] = (void *) iface;
919 _Jv_Method *meth;
921 for (int j=0; j < iface->method_count; j++)
923 // Skip '<clinit>' here.
924 if (iface->methods[j].name->first() == '<')
925 continue;
927 meth = NULL;
928 for (jclass cl = klass; cl; cl = cl->getSuperclass())
930 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
931 iface->methods[j].signature);
933 if (meth)
934 break;
937 if (meth)
939 if ((meth->accflags & Modifier::STATIC) != 0)
940 throw new java::lang::IncompatibleClassChangeError
941 (_Jv_GetMethodString (klass, meth));
942 if ((meth->accflags & Modifier::PUBLIC) == 0)
943 throw new java::lang::IllegalAccessError
944 (_Jv_GetMethodString (klass, meth));
946 if ((meth->accflags & Modifier::ABSTRACT) != 0)
947 itable[pos] = (void *) &_Jv_ThrowAbstractMethodError;
948 else
949 itable[pos] = meth->ncode;
951 else
953 // The method doesn't exist in klass. Binary compatibility rules
954 // permit this, so we delay the error until runtime using a pointer
955 // to a method which throws an exception.
956 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
958 pos++;
961 return pos;
964 static _Jv_Mutex_t iindex_mutex;
965 static bool iindex_mutex_initialized = false;
967 // We need to find the correct offset in the Class Interface Dispatch
968 // Table for a given interface. Once we have that, invoking an interface
969 // method just requires combining the Method's index in the interface
970 // (known at compile time) to get the correct method. Doing a type test
971 // (cast or instanceof) is the same problem: Once we have a possible Partial
972 // Interface Dispatch Table, we just compare the first element to see if it
973 // matches the desired interface. So how can we find the correct offset?
974 // Our solution is to keep a vector of candiate offsets in each interface
975 // (ioffsets), and in each class we have an index (idt->iindex) used to
976 // select the correct offset from ioffsets.
978 // Calculate and return iindex for a new class.
979 // ifaces is a vector of num interfaces that the class implements.
980 // offsets[j] is the offset in the interface dispatch table for the
981 // interface corresponding to ifaces[j].
982 // May extend the interface ioffsets if required.
983 jshort
984 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
986 int i;
987 int j;
989 // Acquire a global lock to prevent itable corruption in case of multiple
990 // classes that implement an intersecting set of interfaces being linked
991 // simultaneously. We can assume that the mutex will be initialized
992 // single-threaded.
993 if (! iindex_mutex_initialized)
995 _Jv_MutexInit (&iindex_mutex);
996 iindex_mutex_initialized = true;
999 _Jv_MutexLock (&iindex_mutex);
1001 for (i=1;; i++) /* each potential position in ioffsets */
1003 for (j=0;; j++) /* each iface */
1005 if (j >= num)
1006 goto found;
1007 if (i >= ifaces[j]->ioffsets[0])
1008 continue;
1009 int ioffset = ifaces[j]->ioffsets[i];
1010 /* We can potentially share this position with another class. */
1011 if (ioffset >= 0 && ioffset != offsets[j])
1012 break; /* Nope. Try next i. */
1015 found:
1016 for (j = 0; j < num; j++)
1018 int len = ifaces[j]->ioffsets[0];
1019 if (i >= len)
1021 // Resize ioffsets.
1022 int newlen = 2 * len;
1023 if (i >= newlen)
1024 newlen = i + 3;
1026 jshort *old_ioffsets = ifaces[j]->ioffsets;
1027 jshort *new_ioffsets = (jshort *) _Jv_AllocBytes (newlen
1028 * sizeof(jshort));
1029 memcpy (&new_ioffsets[1], &old_ioffsets[1],
1030 (len - 1) * sizeof (jshort));
1031 new_ioffsets[0] = newlen;
1033 while (len < newlen)
1034 new_ioffsets[len++] = -1;
1036 ifaces[j]->ioffsets = new_ioffsets;
1038 ifaces[j]->ioffsets[i] = offsets[j];
1041 _Jv_MutexUnlock (&iindex_mutex);
1043 return i;
1046 #if defined USE_LIBFFI && FFI_CLOSURES && defined(INTERPRETER)
1047 // We use a structure of this type to store the closure that
1048 // represents a missing method.
1049 struct method_closure
1051 // This field must come first, since the address of this field will
1052 // be the same as the address of the overall structure. This is due
1053 // to disabling interior pointers in the GC.
1054 ffi_closure closure;
1055 _Jv_ClosureList list;
1056 ffi_cif cif;
1057 ffi_type *arg_types[1];
1060 void *
1061 _Jv_Linker::create_error_method (_Jv_Utf8Const *class_name, jclass klass)
1063 void *code;
1064 method_closure *closure
1065 = (method_closure *)ffi_closure_alloc (sizeof (method_closure), &code);
1067 closure->arg_types[0] = &ffi_type_void;
1069 // Initializes the cif and the closure. If that worked the closure
1070 // is returned and can be used as a function pointer in a class'
1071 // atable.
1072 if ( ffi_prep_cif (&closure->cif,
1073 FFI_DEFAULT_ABI,
1075 &ffi_type_void,
1076 closure->arg_types) == FFI_OK
1077 && ffi_prep_closure_loc (&closure->closure,
1078 &closure->cif,
1079 _Jv_ThrowNoClassDefFoundErrorTrampoline,
1080 class_name,
1081 code) == FFI_OK)
1083 closure->list.registerClosure (klass, closure);
1084 return code;
1086 else
1088 ffi_closure_free (closure);
1089 java::lang::StringBuffer *buffer = new java::lang::StringBuffer();
1090 buffer->append(JvNewStringLatin1("Error setting up FFI closure"
1091 " for static method of"
1092 " missing class: "));
1093 buffer->append (_Jv_NewStringUtf8Const(class_name));
1094 throw new java::lang::InternalError(buffer->toString());
1097 #else
1098 void *
1099 _Jv_Linker::create_error_method (_Jv_Utf8Const *, jclass)
1101 // Codepath for platforms which do not support (or want) libffi.
1102 // You have to accept that it is impossible to provide the name
1103 // of the missing class then.
1104 return (void *) _Jv_ThrowNoClassDefFoundError;
1106 #endif // USE_LIBFFI && FFI_CLOSURES
1108 // Functions for indirect dispatch (symbolic virtual binding) support.
1110 // There are three tables, atable otable and itable. atable is an
1111 // array of addresses, and otable is an array of offsets, and these
1112 // are used for static and virtual members respectively. itable is an
1113 // array of pairs {address, index} where each address is a pointer to
1114 // an interface.
1116 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1117 // symbol is a tuple of {classname, member name, signature}.
1119 // Set this to true to enable debugging of indirect dispatch tables/linking.
1120 static bool debug_link = false;
1122 // link_symbol_table() scans these two arrays and fills in the
1123 // corresponding atable and otable with the addresses of static
1124 // members and the offsets of virtual members.
1126 // The offset (in bytes) for each resolved method or field is placed
1127 // at the corresponding position in the virtual method offset table
1128 // (klass->otable).
1130 // This must be called while holding the class lock.
1132 void
1133 _Jv_Linker::link_symbol_table (jclass klass)
1135 int index = 0;
1136 _Jv_MethodSymbol sym;
1137 if (klass->otable == NULL
1138 || klass->otable->state != 0)
1139 goto atable;
1141 klass->otable->state = 1;
1143 if (debug_link)
1144 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
1145 for (index = 0;
1146 (sym = klass->otable_syms[index]).class_name != NULL;
1147 ++index)
1149 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1150 _Jv_Method *meth = NULL;
1152 _Jv_Utf8Const *signature = sym.signature;
1153 uaddr special;
1154 maybe_adjust_signature (signature, special);
1156 if (target_class == NULL)
1157 throw new java::lang::NoClassDefFoundError
1158 (_Jv_NewStringUTF (sym.class_name->chars()));
1160 // We're looking for a field or a method, and we can tell
1161 // which is needed by looking at the signature.
1162 if (signature->first() == '(' && signature->len() >= 2)
1164 // Looks like someone is trying to invoke an interface method
1165 if (target_class->isInterface())
1167 using namespace java::lang;
1168 StringBuffer *sb = new StringBuffer();
1169 sb->append(JvNewStringLatin1("found interface "));
1170 sb->append(target_class->getName());
1171 sb->append(JvNewStringLatin1(" when searching for a class"));
1172 throw new VerifyError(sb->toString());
1175 // If the target class does not have a vtable_method_count yet,
1176 // then we can't tell the offsets for its methods, so we must lay
1177 // it out now.
1178 wait_for_state(target_class, JV_STATE_PREPARED);
1182 meth = (search_method_in_superclasses
1183 (target_class, klass, sym.name, signature,
1184 NULL, special == 0));
1186 catch (::java::lang::IllegalAccessError *e)
1190 // Every class has a throwNoSuchMethodErrorIndex method that
1191 // it inherits from java.lang.Object. Find its vtable
1192 // offset.
1193 static int throwNoSuchMethodErrorIndex;
1194 if (throwNoSuchMethodErrorIndex == 0)
1196 Utf8Const* name
1197 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1198 strlen ("throwNoSuchMethodError"));
1199 _Jv_Method* meth
1200 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$,
1201 name, gcj::void_signature);
1202 throwNoSuchMethodErrorIndex
1203 = _Jv_VTable::idx_to_offset (meth->index);
1206 // If we don't find a nonstatic method, insert the
1207 // vtable index of Object.throwNoSuchMethodError().
1208 // This defers the missing method error until an attempt
1209 // is made to execute it.
1211 int offset;
1213 if (meth != NULL)
1214 offset = _Jv_VTable::idx_to_offset (meth->index);
1215 else
1216 offset = throwNoSuchMethodErrorIndex;
1218 if (offset == -1)
1219 JvFail ("Bad method index");
1220 JvAssert (meth->index < target_class->vtable_method_count);
1222 klass->otable->offsets[index] = offset;
1225 if (debug_link)
1226 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1227 (int)index,
1228 (int)klass->otable->offsets[index],
1229 (const char*)target_class->name->chars(),
1230 target_class,
1231 (const char*)sym.name->chars(),
1232 (const char*)signature->chars());
1233 continue;
1236 // Try fields.
1238 wait_for_state(target_class, JV_STATE_PREPARED);
1239 jclass found_class;
1240 _Jv_Field *the_field = NULL;
1243 the_field = find_field (klass, target_class, &found_class,
1244 sym.name, signature);
1245 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1246 throw new java::lang::IncompatibleClassChangeError;
1247 else
1248 klass->otable->offsets[index] = the_field->u.boffset;
1250 catch (java::lang::NoSuchFieldError *err)
1252 klass->otable->offsets[index] = 0;
1257 atable:
1258 if (klass->atable == NULL || klass->atable->state != 0)
1259 goto itable;
1261 klass->atable->state = 1;
1263 for (index = 0;
1264 (sym = klass->atable_syms[index]).class_name != NULL;
1265 ++index)
1267 jclass target_class =
1268 _Jv_FindClassNoException (sym.class_name, klass->loader);
1270 _Jv_Method *meth = NULL;
1272 _Jv_Utf8Const *signature = sym.signature;
1273 uaddr special;
1274 maybe_adjust_signature (signature, special);
1276 // ??? Setting this pointer to null will at least get us a
1277 // NullPointerException
1278 klass->atable->addresses[index] = NULL;
1280 bool use_error_method = false;
1282 // If the target class is missing we prepare a function call
1283 // that throws a NoClassDefFoundError and store the address of
1284 // that newly prepared method in the atable. The user can run
1285 // code in classes where the missing class is part of the
1286 // execution environment as long as it is never referenced.
1287 if (target_class == NULL)
1288 use_error_method = true;
1289 // We're looking for a static field or a static method, and we
1290 // can tell which is needed by looking at the signature.
1291 else if (signature->first() == '(' && signature->len() >= 2)
1293 // If the target class does not have a vtable_method_count yet,
1294 // then we can't tell the offsets for its methods, so we must lay
1295 // it out now.
1296 wait_for_state (target_class, JV_STATE_PREPARED);
1298 // Interface methods cannot have bodies.
1299 if (target_class->isInterface())
1301 using namespace java::lang;
1302 StringBuffer *sb = new StringBuffer();
1303 sb->append(JvNewStringLatin1("class "));
1304 sb->append(target_class->getName());
1305 sb->append(JvNewStringLatin1(" is an interface: "
1306 "class expected"));
1307 throw new VerifyError(sb->toString());
1312 meth = (search_method_in_superclasses
1313 (target_class, klass, sym.name, signature,
1314 NULL, special == 0));
1316 catch (::java::lang::IllegalAccessError *e)
1320 if (meth != NULL)
1322 if (meth->ncode) // Maybe abstract?
1324 klass->atable->addresses[index] = meth->ncode;
1325 if (debug_link)
1326 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1327 index,
1328 &klass->atable->addresses[index],
1329 (const char*)target_class->name->chars(),
1330 klass,
1331 (const char*)sym.name->chars(),
1332 (const char*)signature->chars());
1335 else
1336 use_error_method = true;
1338 if (use_error_method)
1339 klass->atable->addresses[index]
1340 = create_error_method(sym.class_name, klass);
1342 continue;
1346 // Try fields only if the target class exists.
1347 if (target_class != NULL)
1349 wait_for_state(target_class, JV_STATE_PREPARED);
1350 jclass found_class;
1351 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
1352 sym.name, signature);
1353 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1354 klass->atable->addresses[index] = the_field->u.addr;
1355 else
1356 throw new java::lang::IncompatibleClassChangeError;
1360 itable:
1361 if (klass->itable == NULL
1362 || klass->itable->state != 0)
1363 return;
1365 klass->itable->state = 1;
1367 for (index = 0;
1368 (sym = klass->itable_syms[index]).class_name != NULL;
1369 ++index)
1371 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1373 _Jv_Utf8Const *signature = sym.signature;
1374 uaddr special;
1375 maybe_adjust_signature (signature, special);
1377 jclass cls;
1378 int i;
1380 wait_for_state(target_class, JV_STATE_LOADED);
1381 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1382 sym.name, signature);
1384 if (found)
1386 klass->itable->addresses[index * 2] = cls;
1387 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1388 if (debug_link)
1390 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1391 index,
1392 klass->itable->addresses[index * 2],
1393 (const char*)cls->name->chars(),
1394 cls,
1395 (const char*)sym.name->chars(),
1396 (const char*)signature->chars());
1397 fprintf (stderr, " [%d] = offset %d\n",
1398 index + 1,
1399 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1403 else
1404 throw new java::lang::IncompatibleClassChangeError;
1409 // For each catch_record in the list of caught classes, fill in the
1410 // address field.
1411 void
1412 _Jv_Linker::link_exception_table (jclass self)
1414 struct _Jv_CatchClass *catch_record = self->catch_classes;
1415 if (!catch_record || catch_record->classname)
1416 return;
1417 catch_record++;
1418 while (catch_record->classname)
1422 jclass target_class
1423 = _Jv_FindClass (catch_record->classname,
1424 self->getClassLoaderInternal ());
1425 *catch_record->address = target_class;
1427 catch (::java::lang::Throwable *t)
1429 // FIXME: We need to do something better here.
1430 *catch_record->address = 0;
1432 catch_record++;
1434 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1437 // Set itable method indexes for members of interface IFACE.
1438 void
1439 _Jv_Linker::layout_interface_methods (jclass iface)
1441 if (! iface->isInterface())
1442 return;
1444 // itable indexes start at 1.
1445 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1446 // itable so they are also assigned an index here.
1447 for (int i = 0; i < iface->method_count; i++)
1448 iface->methods[i].index = i + 1;
1451 // Prepare virtual method declarations in KLASS, and any superclasses
1452 // as required, by determining their vtable index, setting
1453 // method->index, and finally setting the class's vtable_method_count.
1454 // Must be called with the lock for KLASS held.
1455 void
1456 _Jv_Linker::layout_vtable_methods (jclass klass)
1458 if (klass->vtable != NULL || klass->isInterface()
1459 || klass->vtable_method_count != -1)
1460 return;
1462 jclass superclass = klass->getSuperclass();
1464 if (superclass != NULL && superclass->vtable_method_count == -1)
1466 JvSynchronize sync (superclass);
1467 layout_vtable_methods (superclass);
1470 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1472 for (int i = 0; i < klass->method_count; ++i)
1474 _Jv_Method *meth = &klass->methods[i];
1475 _Jv_Method *super_meth = NULL;
1477 if (! _Jv_isVirtualMethod (meth))
1478 continue;
1480 if (superclass != NULL)
1482 jclass declarer;
1483 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1484 meth->signature, &declarer);
1485 // See if this method actually overrides the other method
1486 // we've found.
1487 if (super_meth)
1489 if (! _Jv_isVirtualMethod (super_meth)
1490 || ! _Jv_CheckAccess (klass, declarer,
1491 super_meth->accflags))
1492 super_meth = NULL;
1493 else if ((super_meth->accflags
1494 & java::lang::reflect::Modifier::FINAL) != 0)
1496 using namespace java::lang;
1497 StringBuffer *sb = new StringBuffer();
1498 sb->append(JvNewStringLatin1("method "));
1499 sb->append(_Jv_GetMethodString(klass, meth));
1500 sb->append(JvNewStringLatin1(" overrides final method "));
1501 sb->append(_Jv_GetMethodString(declarer, super_meth));
1502 throw new VerifyError(sb->toString());
1507 if (super_meth)
1508 meth->index = super_meth->index;
1509 else
1510 meth->index = index++;
1513 klass->vtable_method_count = index;
1516 // Set entries in VTABLE for virtual methods declared in KLASS.
1517 void
1518 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1520 for (int i = klass->method_count - 1; i >= 0; i--)
1522 using namespace java::lang::reflect;
1524 _Jv_Method *meth = &klass->methods[i];
1525 if (meth->index == (_Jv_ushort) -1)
1526 continue;
1527 if ((meth->accflags & Modifier::ABSTRACT))
1528 // FIXME: it might be nice to have a libffi trampoline here,
1529 // so we could pass in the method name and other information.
1530 vtable->set_method(meth->index,
1531 (void *) &_Jv_ThrowAbstractMethodError);
1532 else
1533 vtable->set_method(meth->index, meth->ncode);
1537 // Allocate and lay out the virtual method table for KLASS. This will
1538 // also cause vtables to be generated for any non-abstract
1539 // superclasses, and virtual method layout to occur for any abstract
1540 // superclasses. Must be called with monitor lock for KLASS held.
1541 void
1542 _Jv_Linker::make_vtable (jclass klass)
1544 using namespace java::lang::reflect;
1546 // If the vtable exists, or for interface classes, do nothing. All
1547 // other classes, including abstract classes, need a vtable.
1548 if (klass->vtable != NULL || klass->isInterface())
1549 return;
1551 // Ensure all the `ncode' entries are set.
1552 klass->engine->create_ncode(klass);
1554 // Class must be laid out before we can create a vtable.
1555 if (klass->vtable_method_count == -1)
1556 layout_vtable_methods (klass);
1558 // Allocate the new vtable.
1559 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1560 klass->vtable = vtable;
1562 // Copy the vtable of the closest superclass.
1563 jclass superclass = klass->superclass;
1565 JvSynchronize sync (superclass);
1566 make_vtable (superclass);
1568 for (int i = 0; i < superclass->vtable_method_count; ++i)
1569 vtable->set_method (i, superclass->vtable->get_method (i));
1571 // Set the class pointer and GC descriptor.
1572 vtable->clas = klass;
1573 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1575 // For each virtual declared in klass, set new vtable entry or
1576 // override an old one.
1577 set_vtable_entries (klass, vtable);
1579 // Note that we don't check for abstract methods here. We used to,
1580 // but there is a JVMS clarification that indicates that a check
1581 // here would be too eager. And, a simple test case confirms this.
1584 // Lay out the class, allocating space for static fields and computing
1585 // offsets of instance fields. The class lock must be held by the
1586 // caller.
1587 void
1588 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1590 if (klass->size_in_bytes != -1)
1591 return;
1593 // Compute the alignment for this type by searching through the
1594 // superclasses and finding the maximum required alignment. We
1595 // could consider caching this in the Class.
1596 int max_align = __alignof__ (java::lang::Object);
1597 jclass super = klass->getSuperclass();
1598 while (super != NULL)
1600 // Ensure that our super has its super installed before
1601 // recursing.
1602 wait_for_state(super, JV_STATE_LOADING);
1603 ensure_fields_laid_out(super);
1604 int num = JvNumInstanceFields (super);
1605 _Jv_Field *field = JvGetFirstInstanceField (super);
1606 while (num > 0)
1608 int field_align = get_alignment_from_class (field->type);
1609 if (field_align > max_align)
1610 max_align = field_align;
1611 ++field;
1612 --num;
1614 super = super->getSuperclass();
1617 int instance_size;
1618 // This is the size of the 'static' non-reference fields.
1619 int non_reference_size = 0;
1620 // This is the size of the 'static' reference fields. We count
1621 // these separately to make it simpler for the GC to scan them.
1622 int reference_size = 0;
1624 // Although java.lang.Object is never interpreted, an interface can
1625 // have a null superclass. Note that we have to lay out an
1626 // interface because it might have static fields.
1627 if (klass->superclass)
1628 instance_size = klass->superclass->size();
1629 else
1630 instance_size = java::lang::Object::class$.size();
1632 klass->engine->allocate_field_initializers (klass);
1634 for (int i = 0; i < klass->field_count; i++)
1636 int field_size;
1637 int field_align;
1639 _Jv_Field *field = &klass->fields[i];
1641 if (! field->isRef ())
1643 // It is safe to resolve the field here, since it's a
1644 // primitive class, which does not cause loading to happen.
1645 resolve_field (field, klass->loader);
1646 field_size = field->type->size ();
1647 field_align = get_alignment_from_class (field->type);
1649 else
1651 field_size = sizeof (jobject);
1652 field_align = __alignof__ (jobject);
1655 field->bsize = field_size;
1657 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1659 if (field->u.addr == NULL)
1661 // This computes an offset into a region we'll allocate
1662 // shortly, and then adds this offset to the start
1663 // address.
1664 if (field->isRef())
1666 reference_size = ROUND (reference_size, field_align);
1667 field->u.boffset = reference_size;
1668 reference_size += field_size;
1670 else
1672 non_reference_size = ROUND (non_reference_size, field_align);
1673 field->u.boffset = non_reference_size;
1674 non_reference_size += field_size;
1678 else
1680 instance_size = ROUND (instance_size, field_align);
1681 field->u.boffset = instance_size;
1682 instance_size += field_size;
1683 if (field_align > max_align)
1684 max_align = field_align;
1688 if (reference_size != 0 || non_reference_size != 0)
1689 klass->engine->allocate_static_fields (klass, reference_size,
1690 non_reference_size);
1692 // Set the instance size for the class. Note that first we round it
1693 // to the alignment required for this object; this keeps us in sync
1694 // with our current ABI.
1695 instance_size = ROUND (instance_size, max_align);
1696 klass->size_in_bytes = instance_size;
1699 // This takes the class to state JV_STATE_LINKED. The class lock must
1700 // be held when calling this.
1701 void
1702 _Jv_Linker::ensure_class_linked (jclass klass)
1704 if (klass->state >= JV_STATE_LINKED)
1705 return;
1707 int state = klass->state;
1710 // Short-circuit, so that mutually dependent classes are ok.
1711 klass->state = JV_STATE_LINKED;
1713 _Jv_Constants *pool = &klass->constants;
1715 // Compiled classes require that their class constants be
1716 // resolved here. However, interpreted classes need their
1717 // constants to be resolved lazily. If we resolve an
1718 // interpreted class' constants eagerly, we can end up with
1719 // spurious IllegalAccessErrors when the constant pool contains
1720 // a reference to a class we can't access. This can validly
1721 // occur in an obscure case involving the InnerClasses
1722 // attribute.
1723 if (! _Jv_IsInterpretedClass (klass))
1725 // Resolve class constants first, since other constant pool
1726 // entries may rely on these.
1727 for (int index = 1; index < pool->size; ++index)
1729 if (pool->tags[index] == JV_CONSTANT_Class)
1730 // Lazily resolve the entries.
1731 resolve_pool_entry (klass, index, true);
1735 // Resolve the remaining constant pool entries.
1736 for (int index = 1; index < pool->size; ++index)
1738 if (pool->tags[index] == JV_CONSTANT_String)
1740 jstring str;
1742 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1743 pool->data[index].o = str;
1744 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1748 if (klass->engine->need_resolve_string_fields())
1750 jfieldID f = JvGetFirstStaticField (klass);
1751 for (int n = JvNumStaticFields (klass); n > 0; --n)
1753 int mod = f->getModifiers ();
1754 // If we have a static String field with a non-null initial
1755 // value, we know it points to a Utf8Const.
1757 // Finds out whether we have to initialize a String without the
1758 // need to resolve the field.
1759 if ((f->isResolved()
1760 ? (f->type == &java::lang::String::class$)
1761 : _Jv_equalUtf8Classnames((_Jv_Utf8Const *) f->type,
1762 java::lang::String::class$.name))
1763 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1765 jstring *strp = (jstring *) f->u.addr;
1766 if (*strp)
1767 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1769 f = f->getNextField ();
1773 klass->notifyAll ();
1775 _Jv_PushClass (klass);
1777 catch (java::lang::Throwable *t)
1779 klass->state = state;
1780 throw t;
1784 // This ensures that symbolic superclass and superinterface references
1785 // are resolved for the indicated class. This must be called with the
1786 // class lock held.
1787 void
1788 _Jv_Linker::ensure_supers_installed (jclass klass)
1790 resolve_class_ref (klass, &klass->superclass);
1791 // An interface won't have a superclass.
1792 if (klass->superclass)
1793 wait_for_state (klass->superclass, JV_STATE_LOADING);
1795 for (int i = 0; i < klass->interface_count; ++i)
1797 resolve_class_ref (klass, &klass->interfaces[i]);
1798 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1802 // This adds missing `Miranda methods' to a class.
1803 void
1804 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1806 // Note that at this point, all our supers, and the supers of all
1807 // our superclasses and superinterfaces, will have been installed.
1809 for (int i = 0; i < iface_class->interface_count; ++i)
1811 jclass interface = iface_class->interfaces[i];
1813 for (int j = 0; j < interface->method_count; ++j)
1815 _Jv_Method *meth = &interface->methods[j];
1816 // Don't bother with <clinit>.
1817 if (meth->name->first() == '<')
1818 continue;
1819 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1820 meth->signature);
1821 if (! new_meth)
1823 // We assume that such methods are very unlikely, so we
1824 // just reallocate the method array each time one is
1825 // found. This greatly simplifies the searching --
1826 // otherwise we have to make sure that each such method
1827 // found is really unique among all superinterfaces.
1828 int new_count = base->method_count + 1;
1829 _Jv_Method *new_m
1830 = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method)
1831 * new_count);
1832 memcpy (new_m, base->methods,
1833 sizeof (_Jv_Method) * base->method_count);
1835 // Add new method.
1836 new_m[base->method_count] = *meth;
1837 new_m[base->method_count].index = (_Jv_ushort) -1;
1838 new_m[base->method_count].accflags
1839 |= java::lang::reflect::Modifier::INVISIBLE;
1841 base->methods = new_m;
1842 base->method_count = new_count;
1846 wait_for_state (interface, JV_STATE_LOADED);
1847 add_miranda_methods (base, interface);
1851 // This ensures that the class' method table is "complete". This must
1852 // be called with the class lock held.
1853 void
1854 _Jv_Linker::ensure_method_table_complete (jclass klass)
1856 if (klass->vtable != NULL)
1857 return;
1859 // We need our superclass to have its own Miranda methods installed.
1860 if (! klass->isInterface())
1861 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1863 // A class might have so-called "Miranda methods". This is a method
1864 // that is declared in an interface and not re-declared in an
1865 // abstract class. Some compilers don't emit declarations for such
1866 // methods in the class; this will give us problems since we expect
1867 // a declaration for any method requiring a vtable entry. We handle
1868 // this here by searching for such methods and constructing new
1869 // internal declarations for them. Note that we do this
1870 // unconditionally, and not just for abstract classes, to correctly
1871 // account for cases where a class is modified to be concrete and
1872 // still incorrectly inherits an abstract method.
1873 int pre_count = klass->method_count;
1874 add_miranda_methods (klass, klass);
1876 // Let the execution engine know that we've added methods.
1877 if (klass->method_count != pre_count)
1878 klass->engine->post_miranda_hook(klass);
1881 // Verify a class. Must be called with class lock held.
1882 void
1883 _Jv_Linker::verify_class (jclass klass)
1885 klass->engine->verify(klass);
1888 // Check the assertions contained in the type assertion table for KLASS.
1889 // This is the equivilent of bytecode verification for native, BC-ABI code.
1890 void
1891 _Jv_Linker::verify_type_assertions (jclass klass)
1893 if (debug_link)
1894 fprintf (stderr, "Evaluating type assertions for %s:\n",
1895 klass->name->chars());
1897 if (klass->assertion_table == NULL)
1898 return;
1900 for (int i = 0;; i++)
1902 int assertion_code = klass->assertion_table[i].assertion_code;
1903 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1904 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1906 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1907 return;
1908 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1910 if (debug_link)
1912 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1913 assertion_code, op1->chars(), op2->chars());
1916 // The operands are class signatures. op1 is the source,
1917 // op2 is the target.
1918 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1919 klass->getClassLoaderInternal());
1920 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1921 klass->getClassLoaderInternal());
1923 // If the class doesn't exist, ignore the assertion. An exception
1924 // will be thrown later if an attempt is made to actually
1925 // instantiate the class.
1926 if (cl1 == NULL || cl2 == NULL)
1927 continue;
1929 if (! _Jv_IsAssignableFromSlow (cl1, cl2))
1931 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1932 s = s->concat (klass->getName());
1933 s = s->concat (JvNewStringUTF (": "));
1934 s = s->concat (cl1->getName());
1935 s = s->concat (JvNewStringUTF (" is not assignable to "));
1936 s = s->concat (cl2->getName());
1937 throw new java::lang::VerifyError (s);
1940 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1942 // TODO: Implement this.
1944 // Unknown assertion codes are ignored, for forwards-compatibility.
1948 void
1949 _Jv_Linker::print_class_loaded (jclass klass)
1951 char *codesource = NULL;
1952 if (klass->protectionDomain != NULL)
1954 java::security::CodeSource *cs
1955 = klass->protectionDomain->getCodeSource();
1956 if (cs != NULL)
1958 jstring css = cs->toString();
1959 int len = JvGetStringUTFLength(css);
1960 codesource = (char *) _Jv_AllocBytes(len + 1);
1961 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1962 codesource[len] = '\0';
1965 if (codesource == NULL)
1966 codesource = (char *) "<no code source>";
1968 const char *abi;
1969 if (_Jv_IsInterpretedClass (klass))
1970 abi = "bytecode";
1971 else if (_Jv_IsBinaryCompatibilityABI (klass))
1972 abi = "BC-compiled";
1973 else
1974 abi = "pre-compiled";
1976 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1977 codesource);
1980 // FIXME: mention invariants and stuff.
1981 void
1982 _Jv_Linker::wait_for_state (jclass klass, int state)
1984 if (klass->state >= state)
1985 return;
1987 java::lang::Thread *self = java::lang::Thread::currentThread();
1990 JvSynchronize sync (klass);
1992 // This is similar to the strategy for class initialization. If we
1993 // already hold the lock, just leave.
1994 while (klass->state <= state
1995 && klass->thread
1996 && klass->thread != self)
1997 klass->wait ();
1999 java::lang::Thread *save = klass->thread;
2000 klass->thread = self;
2002 // Allocate memory for static fields and constants.
2003 if (GC_base (klass) && klass->fields && ! GC_base (klass->fields))
2005 jsize count = klass->field_count;
2006 if (count)
2008 _Jv_Field* fields
2009 = (_Jv_Field*) _Jv_AllocRawObj (count * sizeof (_Jv_Field));
2010 memcpy ((void*)fields,
2011 (void*)klass->fields,
2012 count * sizeof (_Jv_Field));
2013 klass->fields = fields;
2017 // Print some debugging info if requested. Interpreted classes are
2018 // handled in defineclass, so we only need to handle the two
2019 // pre-compiled cases here.
2020 if ((klass->state == JV_STATE_COMPILED
2021 || klass->state == JV_STATE_PRELOADING)
2022 && ! _Jv_IsInterpretedClass (klass))
2024 if (gcj::verbose_class_flag)
2025 print_class_loaded (klass);
2026 ++gcj::loadedClasses;
2031 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
2033 ensure_supers_installed (klass);
2034 klass->set_state(JV_STATE_LOADING);
2037 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
2039 ensure_method_table_complete (klass);
2040 klass->set_state(JV_STATE_LOADED);
2043 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
2045 ensure_fields_laid_out (klass);
2046 make_vtable (klass);
2047 layout_interface_methods (klass);
2048 prepare_constant_time_tables (klass);
2049 klass->set_state(JV_STATE_PREPARED);
2052 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
2054 if (gcj::verifyClasses)
2055 verify_class (klass);
2057 ensure_class_linked (klass);
2058 link_exception_table (klass);
2059 link_symbol_table (klass);
2060 klass->set_state(JV_STATE_LINKED);
2063 catch (java::lang::Throwable *exc)
2065 klass->thread = save;
2066 klass->set_state(JV_STATE_ERROR);
2067 throw exc;
2070 klass->thread = save;
2072 if (klass->state == JV_STATE_ERROR)
2073 throw new java::lang::LinkageError;
2076 #ifdef INTERPRETER
2077 if (__builtin_expect (klass->state == JV_STATE_LINKED, false)
2078 && state >= JV_STATE_LINKED
2079 && JVMTI_REQUESTED_EVENT (ClassPrepare))
2081 JNIEnv *jni_env = _Jv_GetCurrentJNIEnv ();
2082 _Jv_JVMTI_PostEvent (JVMTI_EVENT_CLASS_PREPARE, self, jni_env,
2083 klass);
2085 #endif