* error.c (show_locus): Remove always-false test.
[official-gcc.git] / libjava / link.cc
blob1d873acf288cdcecdb88fe647e311b5627b9b415
1 // link.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 /* Author: Kresten Krab Thorup <krab@gnu.org> */
13 #include <config.h>
14 #include <platform.h>
16 #include <stdio.h>
18 #ifdef USE_LIBFFI
19 #include <ffi.h>
20 #endif
22 #include <java-interp.h>
24 // Set GC_DEBUG before including gc.h!
25 #ifdef LIBGCJ_GC_DEBUG
26 # define GC_DEBUG
27 #endif
28 #include <gc.h>
30 #include <jvm.h>
31 #include <gcj/cni.h>
32 #include <string.h>
33 #include <limits.h>
34 #include <java-cpool.h>
35 #include <execution.h>
36 #include <jvmti.h>
37 #include "jvmti-int.h"
38 #include <java/lang/Class.h>
39 #include <java/lang/String.h>
40 #include <java/lang/StringBuffer.h>
41 #include <java/lang/Thread.h>
42 #include <java/lang/InternalError.h>
43 #include <java/lang/VirtualMachineError.h>
44 #include <java/lang/VerifyError.h>
45 #include <java/lang/NoSuchFieldError.h>
46 #include <java/lang/NoSuchMethodError.h>
47 #include <java/lang/ClassFormatError.h>
48 #include <java/lang/IllegalAccessError.h>
49 #include <java/lang/InternalError.h>
50 #include <java/lang/AbstractMethodError.h>
51 #include <java/lang/NoClassDefFoundError.h>
52 #include <java/lang/IncompatibleClassChangeError.h>
53 #include <java/lang/VerifyError.h>
54 #include <java/lang/VMClassLoader.h>
55 #include <java/lang/reflect/Modifier.h>
56 #include <java/security/CodeSource.h>
58 using namespace gcj;
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_Method *
270 _Jv_Linker::resolve_method_entry (jclass klass, jclass &found_class,
271 int class_index, int name_and_type_index,
272 bool init, bool is_iface)
274 _Jv_Constants *pool = &klass->constants;
275 jclass owner = resolve_pool_entry (klass, class_index).clazz;
277 if (init && owner != klass)
278 _Jv_InitClass (owner);
280 _Jv_ushort name_index, type_index;
281 _Jv_loadIndexes (&pool->data[name_and_type_index],
282 name_index,
283 type_index);
285 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
286 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
288 _Jv_Method *the_method = 0;
289 found_class = 0;
291 // We're going to cache a pointer to the _Jv_Method object
292 // when we find it. So, to ensure this doesn't get moved from
293 // beneath us, we first put all the needed Miranda methods
294 // into the target class.
295 wait_for_state (klass, JV_STATE_LOADED);
297 // First search the class itself.
298 the_method = search_method_in_class (owner, klass,
299 method_name, method_signature);
301 if (the_method != 0)
303 found_class = owner;
304 goto end_of_method_search;
307 // If we are resolving an interface method, search the
308 // interface's superinterfaces (A superinterface is not an
309 // interface's superclass - a superinterface is implemented by
310 // the interface).
311 if (is_iface)
313 _Jv_ifaces ifaces;
314 ifaces.count = 0;
315 ifaces.len = 4;
316 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len
317 * sizeof (jclass *));
319 get_interfaces (owner, &ifaces);
321 for (int i = 0; i < ifaces.count; i++)
323 jclass cls = ifaces.list[i];
324 the_method = search_method_in_class (cls, klass, method_name,
325 method_signature);
326 if (the_method != 0)
328 found_class = cls;
329 break;
333 _Jv_Free (ifaces.list);
335 if (the_method != 0)
336 goto end_of_method_search;
339 // Finally, search superclasses.
340 the_method = (search_method_in_superclasses
341 (owner->getSuperclass (), klass, method_name,
342 method_signature, &found_class));
345 end_of_method_search:
346 if (the_method == 0)
348 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
349 sb->append(JvNewStringLatin1("method "));
350 sb->append(owner->getName());
351 sb->append(JvNewStringLatin1("."));
352 sb->append(_Jv_NewStringUTF(method_name->chars()));
353 sb->append(JvNewStringLatin1(" with signature "));
354 sb->append(_Jv_NewStringUTF(method_signature->chars()));
355 sb->append(JvNewStringLatin1(" was not found."));
356 throw new java::lang::NoSuchMethodError (sb->toString());
359 // if (found_class->loader != klass->loader), then we
360 // must actually check that the types of arguments
361 // correspond. That is, for each argument type, and
362 // the return type, doing _Jv_FindClassFromSignature
363 // with either loader should produce the same result,
364 // i.e., exactly the same jclass object. JVMS 5.4.3.3
365 if (found_class->loader != klass->loader)
367 JArray<jclass> *found_args, *klass_args;
368 jclass found_return, klass_return;
370 _Jv_GetTypesFromSignature (the_method,
371 found_class,
372 &found_args,
373 &found_return);
374 _Jv_GetTypesFromSignature (the_method,
375 klass,
376 &klass_args,
377 &klass_return);
379 jclass *found_arg = elements (found_args);
380 jclass *klass_arg = elements (klass_args);
382 for (int i = 0; i < found_args->length; i++)
384 if (*(found_arg++) != *(klass_arg++))
385 throw new java::lang::LinkageError (JvNewStringLatin1
386 ("argument type mismatch with different loaders"));
388 if (found_return != klass_return)
389 throw new java::lang::LinkageError (JvNewStringLatin1
390 ("return type mismatch with different loaders"));
393 return the_method;
396 _Jv_word
397 _Jv_Linker::resolve_pool_entry (jclass klass, int index, bool lazy)
399 using namespace java::lang::reflect;
401 if (GC_base (klass) && klass->constants.data
402 && ! GC_base (klass->constants.data))
404 jsize count = klass->constants.size;
405 if (count)
407 _Jv_word* constants
408 = (_Jv_word*) _Jv_AllocRawObj (count * sizeof (_Jv_word));
409 memcpy ((void*)constants,
410 (void*)klass->constants.data,
411 count * sizeof (_Jv_word));
412 klass->constants.data = constants;
416 _Jv_Constants *pool = &klass->constants;
418 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
419 return pool->data[index];
421 switch (pool->tags[index] & ~JV_CONSTANT_LazyFlag)
423 case JV_CONSTANT_Class:
425 _Jv_Utf8Const *name = pool->data[index].utf8;
427 jclass found;
428 if (name->first() == '[')
429 found = _Jv_FindClassFromSignatureNoException (name->chars(),
430 klass->loader);
431 else
432 found = _Jv_FindClassNoException (name, klass->loader);
434 // If the class could not be loaded a phantom class is created. Any
435 // function that deals with such a class but cannot do something useful
436 // with it should just throw a NoClassDefFoundError with the class'
437 // name.
438 if (! found)
440 if (lazy)
442 found = _Jv_NewClass(name, NULL, NULL);
443 found->state = JV_STATE_PHANTOM;
444 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
445 pool->data[index].clazz = found;
446 break;
448 else
449 throw new java::lang::NoClassDefFoundError (name->toString());
452 // Check accessibility, but first strip array types as
453 // _Jv_ClassNameSamePackage can't handle arrays.
454 jclass check;
455 for (check = found;
456 check && check->isArray();
457 check = check->getComponentType())
459 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
460 || (_Jv_ClassNameSamePackage (check->name,
461 klass->name)))
463 pool->data[index].clazz = found;
464 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
466 else
468 java::lang::StringBuffer *sb = new java::lang::StringBuffer ();
469 sb->append(klass->getName());
470 sb->append(JvNewStringLatin1(" can't access class "));
471 sb->append(found->getName());
472 throw new java::lang::IllegalAccessError(sb->toString());
475 break;
477 case JV_CONSTANT_String:
479 jstring str;
480 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
481 pool->data[index].o = str;
482 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
484 break;
486 case JV_CONSTANT_Fieldref:
488 _Jv_ushort class_index, name_and_type_index;
489 _Jv_loadIndexes (&pool->data[index],
490 class_index,
491 name_and_type_index);
492 jclass owner = (resolve_pool_entry (klass, class_index, true)).clazz;
494 // If a phantom class was resolved our field reference is
495 // unusable because of the missing class.
496 if (owner->state == JV_STATE_PHANTOM)
497 throw new java::lang::NoClassDefFoundError(owner->getName());
499 // We don't initialize 'owner', but we do make sure that its
500 // fields exist.
501 wait_for_state (owner, JV_STATE_PREPARED);
503 _Jv_ushort name_index, type_index;
504 _Jv_loadIndexes (&pool->data[name_and_type_index],
505 name_index,
506 type_index);
508 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
509 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
511 jclass found_class = 0;
512 _Jv_Field *the_field = find_field (klass, owner,
513 &found_class,
514 field_name,
515 field_type_name);
516 // Initialize the field's declaring class, not its qualifying
517 // class.
518 _Jv_InitClass (found_class);
519 pool->data[index].field = the_field;
520 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
522 break;
524 case JV_CONSTANT_Methodref:
525 case JV_CONSTANT_InterfaceMethodref:
527 _Jv_ushort class_index, name_and_type_index;
528 _Jv_loadIndexes (&pool->data[index],
529 class_index,
530 name_and_type_index);
532 _Jv_Method *the_method;
533 jclass found_class;
534 the_method = resolve_method_entry (klass, found_class,
535 class_index, name_and_type_index,
536 true,
537 pool->tags[index] == JV_CONSTANT_InterfaceMethodref);
539 pool->data[index].rmethod
540 = klass->engine->resolve_method(the_method,
541 found_class,
542 ((the_method->accflags
543 & Modifier::STATIC) != 0));
544 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
546 break;
548 return pool->data[index];
551 // This function is used to lazily locate superclasses and
552 // superinterfaces. This must be called with the class lock held.
553 void
554 _Jv_Linker::resolve_class_ref (jclass klass, jclass *classref)
556 jclass ret = *classref;
558 // If superclass looks like a constant pool entry, resolve it now.
559 if (ret && (uaddr) ret < (uaddr) klass->constants.size)
561 if (klass->state < JV_STATE_LINKED)
563 _Jv_Utf8Const *name = klass->constants.data[(uaddr) *classref].utf8;
564 ret = _Jv_FindClass (name, klass->loader);
565 if (! ret)
567 throw new java::lang::NoClassDefFoundError (name->toString());
570 else
571 ret = klass->constants.data[(uaddr) classref].clazz;
572 *classref = ret;
576 // Find a method declared in the cls that is referenced from klass and
577 // perform access checks if CHECK_PERMS is true.
578 _Jv_Method *
579 _Jv_Linker::search_method_in_class (jclass cls, jclass klass,
580 _Jv_Utf8Const *method_name,
581 _Jv_Utf8Const *method_signature,
582 bool check_perms)
584 using namespace java::lang::reflect;
586 for (int i = 0; i < cls->method_count; i++)
588 _Jv_Method *method = &cls->methods[i];
589 if ( (!_Jv_equalUtf8Consts (method->name,
590 method_name))
591 || (!_Jv_equalUtf8Consts (method->signature,
592 method_signature)))
593 continue;
595 if (!check_perms || _Jv_CheckAccess (klass, cls, method->accflags))
596 return method;
597 else
599 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
600 sb->append(klass->getName());
601 sb->append(JvNewStringLatin1(": "));
602 sb->append(cls->getName());
603 sb->append(JvNewStringLatin1("."));
604 sb->append(_Jv_NewStringUTF(method_name->chars()));
605 sb->append(_Jv_NewStringUTF(method_signature->chars()));
606 throw new java::lang::IllegalAccessError (sb->toString());
609 return 0;
612 // Like search_method_in_class, but work our way up the superclass
613 // chain.
614 _Jv_Method *
615 _Jv_Linker::search_method_in_superclasses (jclass cls, jclass klass,
616 _Jv_Utf8Const *method_name,
617 _Jv_Utf8Const *method_signature,
618 jclass *found_class, bool check_perms)
620 _Jv_Method *the_method = NULL;
622 for ( ; cls != 0; cls = cls->getSuperclass ())
624 the_method = search_method_in_class (cls, klass, method_name,
625 method_signature, check_perms);
626 if (the_method != 0)
628 if (found_class)
629 *found_class = cls;
630 break;
634 return the_method;
637 #define INITIAL_IOFFSETS_LEN 4
638 #define INITIAL_IFACES_LEN 4
640 static _Jv_IDispatchTable null_idt = {SHRT_MAX, 0, {}};
642 // Generate tables for constant-time assignment testing and interface
643 // method lookup. This implements the technique described by Per Bothner
644 // <per@bothner.com> on the java-discuss mailing list on 1999-09-02:
645 // http://gcc.gnu.org/ml/java/1999-q3/msg00377.html
646 void
647 _Jv_Linker::prepare_constant_time_tables (jclass klass)
649 if (klass->isPrimitive () || klass->isInterface ())
650 return;
652 // Short-circuit in case we've been called already.
653 if ((klass->idt != NULL) || klass->depth != 0)
654 return;
656 // Calculate the class depth and ancestor table. The depth of a class
657 // is how many "extends" it is removed from Object. Thus the depth of
658 // java.lang.Object is 0, but the depth of java.io.FilterOutputStream
659 // is 2. Depth is defined for all regular and array classes, but not
660 // interfaces or primitive types.
662 jclass klass0 = klass;
663 jboolean has_interfaces = 0;
664 while (klass0 != &java::lang::Object::class$)
666 has_interfaces += klass0->interface_count;
667 klass0 = klass0->superclass;
668 klass->depth++;
671 // We do class member testing in constant time by using a small table
672 // of all the ancestor classes within each class. The first element is
673 // a pointer to the current class, and the rest are pointers to the
674 // classes ancestors, ordered from the current class down by decreasing
675 // depth. We do not include java.lang.Object in the table of ancestors,
676 // since it is redundant. Note that the classes pointed to by
677 // 'ancestors' will always be reachable by other paths.
679 klass->ancestors = (jclass *) _Jv_AllocBytes (klass->depth
680 * sizeof (jclass));
681 klass0 = klass;
682 for (int index = 0; index < klass->depth; index++)
684 klass->ancestors[index] = klass0;
685 klass0 = klass0->superclass;
688 if ((klass->accflags & java::lang::reflect::Modifier::ABSTRACT) != 0)
689 return;
691 // Optimization: If class implements no interfaces, use a common
692 // predefined interface table.
693 if (!has_interfaces)
695 klass->idt = &null_idt;
696 return;
699 _Jv_ifaces ifaces;
700 ifaces.count = 0;
701 ifaces.len = INITIAL_IFACES_LEN;
702 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
704 int itable_size = get_interfaces (klass, &ifaces);
706 if (ifaces.count > 0)
708 // The classes pointed to by the itable will always be reachable
709 // via other paths.
710 int idt_bytes = sizeof (_Jv_IDispatchTable) + (itable_size
711 * sizeof (void *));
712 klass->idt = (_Jv_IDispatchTable *) _Jv_AllocBytes (idt_bytes);
713 klass->idt->itable_length = itable_size;
715 jshort *itable_offsets =
716 (jshort *) _Jv_Malloc (ifaces.count * sizeof (jshort));
718 generate_itable (klass, &ifaces, itable_offsets);
720 jshort cls_iindex = find_iindex (ifaces.list, itable_offsets,
721 ifaces.count);
723 for (int i = 0; i < ifaces.count; i++)
725 ifaces.list[i]->ioffsets[cls_iindex] = itable_offsets[i];
728 klass->idt->iindex = cls_iindex;
730 _Jv_Free (ifaces.list);
731 _Jv_Free (itable_offsets);
733 else
735 klass->idt->iindex = SHRT_MAX;
739 // Return index of item in list, or -1 if item is not present.
740 inline jshort
741 _Jv_Linker::indexof (void *item, void **list, jshort list_len)
743 for (int i=0; i < list_len; i++)
745 if (list[i] == item)
746 return i;
748 return -1;
751 // Find all unique interfaces directly or indirectly implemented by klass.
752 // Returns the size of the interface dispatch table (itable) for klass, which
753 // is the number of unique interfaces plus the total number of methods that
754 // those interfaces declare. May extend ifaces if required.
755 jshort
756 _Jv_Linker::get_interfaces (jclass klass, _Jv_ifaces *ifaces)
758 jshort result = 0;
760 for (int i = 0; i < klass->interface_count; i++)
762 jclass iface = klass->interfaces[i];
764 /* Make sure interface is linked. */
765 wait_for_state(iface, JV_STATE_LINKED);
767 if (indexof (iface, (void **) ifaces->list, ifaces->count) == -1)
769 if (ifaces->count + 1 >= ifaces->len)
771 /* Resize ifaces list */
772 ifaces->len = ifaces->len * 2;
773 ifaces->list
774 = (jclass *) _Jv_Realloc (ifaces->list,
775 ifaces->len * sizeof(jclass));
777 ifaces->list[ifaces->count] = iface;
778 ifaces->count++;
780 result += get_interfaces (klass->interfaces[i], ifaces);
784 if (klass->isInterface())
786 // We want to add 1 plus the number of interface methods here.
787 // But, we take special care to skip <clinit>.
788 ++result;
789 for (int i = 0; i < klass->method_count; ++i)
791 if (klass->methods[i].name->first() != '<')
792 ++result;
795 else if (klass->superclass)
796 result += get_interfaces (klass->superclass, ifaces);
797 return result;
800 // Fill out itable in klass, resolving method declarations in each ifaces.
801 // itable_offsets is filled out with the position of each iface in itable,
802 // such that itable[itable_offsets[n]] == ifaces.list[n].
803 void
804 _Jv_Linker::generate_itable (jclass klass, _Jv_ifaces *ifaces,
805 jshort *itable_offsets)
807 void **itable = klass->idt->itable;
808 jshort itable_pos = 0;
810 for (int i = 0; i < ifaces->count; i++)
812 jclass iface = ifaces->list[i];
813 itable_offsets[i] = itable_pos;
814 itable_pos = append_partial_itable (klass, iface, itable, itable_pos);
816 /* Create ioffsets table for iface */
817 if (iface->ioffsets == NULL)
819 // The first element of ioffsets is its length (itself included).
820 jshort *ioffsets = (jshort *) _Jv_AllocBytes (INITIAL_IOFFSETS_LEN
821 * sizeof (jshort));
822 ioffsets[0] = INITIAL_IOFFSETS_LEN;
823 for (int i = 1; i < INITIAL_IOFFSETS_LEN; i++)
824 ioffsets[i] = -1;
826 iface->ioffsets = ioffsets;
831 // Format method name for use in error messages.
832 jstring
833 _Jv_GetMethodString (jclass klass, _Jv_Method *meth,
834 jclass derived)
836 using namespace java::lang;
837 StringBuffer *buf = new StringBuffer (klass->name->toString());
838 buf->append (jchar ('.'));
839 buf->append (meth->name->toString());
840 buf->append ((jchar) ' ');
841 buf->append (meth->signature->toString());
842 if (derived)
844 buf->append(JvNewStringLatin1(" in "));
845 buf->append(derived->name->toString());
847 return buf->toString();
850 void
851 _Jv_ThrowNoSuchMethodError ()
853 throw new java::lang::NoSuchMethodError;
856 #if defined USE_LIBFFI && FFI_CLOSURES
857 // A function whose invocation is prepared using libffi. It gets called
858 // whenever a static method of a missing class is invoked. The data argument
859 // holds a reference to a String denoting the missing class.
860 // The prepared function call is stored in a class' atable.
861 void
862 _Jv_ThrowNoClassDefFoundErrorTrampoline(ffi_cif *,
863 void *,
864 void **,
865 void *data)
867 throw new java::lang::NoClassDefFoundError(
868 _Jv_NewStringUtf8Const((_Jv_Utf8Const *) data));
870 #else
871 // A variant of the NoClassDefFoundError throwing method that can
872 // be used without libffi.
873 void
874 _Jv_ThrowNoClassDefFoundError()
876 throw new java::lang::NoClassDefFoundError();
878 #endif
880 // Throw a NoSuchFieldError. Called by compiler-generated code when
881 // an otable entry is zero. OTABLE_INDEX is the index in the caller's
882 // otable that refers to the missing field. This index may be used to
883 // print diagnostic information about the field.
884 void
885 _Jv_ThrowNoSuchFieldError (int /* otable_index */)
887 throw new java::lang::NoSuchFieldError;
890 // This is put in empty vtable slots.
891 void
892 _Jv_ThrowAbstractMethodError ()
894 throw new java::lang::AbstractMethodError();
897 // Each superinterface of a class (i.e. each interface that the class
898 // directly or indirectly implements) has a corresponding "Partial
899 // Interface Dispatch Table" whose size is (number of methods + 1) words.
900 // The first word is a pointer to the interface (i.e. the java.lang.Class
901 // instance for that interface). The remaining words are pointers to the
902 // actual methods that implement the methods declared in the interface,
903 // in order of declaration.
905 // Append partial interface dispatch table for "iface" to "itable", at
906 // position itable_pos.
907 // Returns the offset at which the next partial ITable should be appended.
908 jshort
909 _Jv_Linker::append_partial_itable (jclass klass, jclass iface,
910 void **itable, jshort pos)
912 using namespace java::lang::reflect;
914 itable[pos++] = (void *) iface;
915 _Jv_Method *meth;
917 for (int j=0; j < iface->method_count; j++)
919 // Skip '<clinit>' here.
920 if (iface->methods[j].name->first() == '<')
921 continue;
923 meth = NULL;
924 for (jclass cl = klass; cl; cl = cl->getSuperclass())
926 meth = _Jv_GetMethodLocal (cl, iface->methods[j].name,
927 iface->methods[j].signature);
929 if (meth)
930 break;
933 if (meth)
935 if ((meth->accflags & Modifier::STATIC) != 0)
936 throw new java::lang::IncompatibleClassChangeError
937 (_Jv_GetMethodString (klass, meth));
938 if ((meth->accflags & Modifier::PUBLIC) == 0)
939 throw new java::lang::IllegalAccessError
940 (_Jv_GetMethodString (klass, meth));
942 if ((meth->accflags & Modifier::ABSTRACT) != 0)
943 itable[pos] = (void *) &_Jv_ThrowAbstractMethodError;
944 else
945 itable[pos] = meth->ncode;
947 else
949 // The method doesn't exist in klass. Binary compatibility rules
950 // permit this, so we delay the error until runtime using a pointer
951 // to a method which throws an exception.
952 itable[pos] = (void *) _Jv_ThrowNoSuchMethodError;
954 pos++;
957 return pos;
960 static _Jv_Mutex_t iindex_mutex;
961 static bool iindex_mutex_initialized = false;
963 // We need to find the correct offset in the Class Interface Dispatch
964 // Table for a given interface. Once we have that, invoking an interface
965 // method just requires combining the Method's index in the interface
966 // (known at compile time) to get the correct method. Doing a type test
967 // (cast or instanceof) is the same problem: Once we have a possible Partial
968 // Interface Dispatch Table, we just compare the first element to see if it
969 // matches the desired interface. So how can we find the correct offset?
970 // Our solution is to keep a vector of candiate offsets in each interface
971 // (ioffsets), and in each class we have an index (idt->iindex) used to
972 // select the correct offset from ioffsets.
974 // Calculate and return iindex for a new class.
975 // ifaces is a vector of num interfaces that the class implements.
976 // offsets[j] is the offset in the interface dispatch table for the
977 // interface corresponding to ifaces[j].
978 // May extend the interface ioffsets if required.
979 jshort
980 _Jv_Linker::find_iindex (jclass *ifaces, jshort *offsets, jshort num)
982 int i;
983 int j;
985 // Acquire a global lock to prevent itable corruption in case of multiple
986 // classes that implement an intersecting set of interfaces being linked
987 // simultaneously. We can assume that the mutex will be initialized
988 // single-threaded.
989 if (! iindex_mutex_initialized)
991 _Jv_MutexInit (&iindex_mutex);
992 iindex_mutex_initialized = true;
995 _Jv_MutexLock (&iindex_mutex);
997 for (i=1;; i++) /* each potential position in ioffsets */
999 for (j=0;; j++) /* each iface */
1001 if (j >= num)
1002 goto found;
1003 if (i >= ifaces[j]->ioffsets[0])
1004 continue;
1005 int ioffset = ifaces[j]->ioffsets[i];
1006 /* We can potentially share this position with another class. */
1007 if (ioffset >= 0 && ioffset != offsets[j])
1008 break; /* Nope. Try next i. */
1011 found:
1012 for (j = 0; j < num; j++)
1014 int len = ifaces[j]->ioffsets[0];
1015 if (i >= len)
1017 // Resize ioffsets.
1018 int newlen = 2 * len;
1019 if (i >= newlen)
1020 newlen = i + 3;
1022 jshort *old_ioffsets = ifaces[j]->ioffsets;
1023 jshort *new_ioffsets = (jshort *) _Jv_AllocBytes (newlen
1024 * sizeof(jshort));
1025 memcpy (&new_ioffsets[1], &old_ioffsets[1],
1026 (len - 1) * sizeof (jshort));
1027 new_ioffsets[0] = newlen;
1029 while (len < newlen)
1030 new_ioffsets[len++] = -1;
1032 ifaces[j]->ioffsets = new_ioffsets;
1034 ifaces[j]->ioffsets[i] = offsets[j];
1037 _Jv_MutexUnlock (&iindex_mutex);
1039 return i;
1042 #if defined USE_LIBFFI && FFI_CLOSURES
1043 // We use a structure of this type to store the closure that
1044 // represents a missing method.
1045 struct method_closure
1047 // This field must come first, since the address of this field will
1048 // be the same as the address of the overall structure. This is due
1049 // to disabling interior pointers in the GC.
1050 ffi_closure closure;
1051 _Jv_ClosureList list;
1052 ffi_cif cif;
1053 ffi_type *arg_types[1];
1056 void *
1057 _Jv_Linker::create_error_method (_Jv_Utf8Const *class_name, jclass klass)
1059 void *code;
1060 method_closure *closure
1061 = (method_closure *)ffi_closure_alloc (sizeof (method_closure), &code);
1063 closure->arg_types[0] = &ffi_type_void;
1065 // Initializes the cif and the closure. If that worked the closure
1066 // is returned and can be used as a function pointer in a class'
1067 // atable.
1068 if ( ffi_prep_cif (&closure->cif,
1069 FFI_DEFAULT_ABI,
1071 &ffi_type_void,
1072 closure->arg_types) == FFI_OK
1073 && ffi_prep_closure_loc (&closure->closure,
1074 &closure->cif,
1075 _Jv_ThrowNoClassDefFoundErrorTrampoline,
1076 class_name,
1077 code) == FFI_OK)
1079 closure->list.registerClosure (klass, closure);
1080 return code;
1082 else
1084 ffi_closure_free (closure);
1085 java::lang::StringBuffer *buffer = new java::lang::StringBuffer();
1086 buffer->append(JvNewStringLatin1("Error setting up FFI closure"
1087 " for static method of"
1088 " missing class: "));
1089 buffer->append (_Jv_NewStringUtf8Const(class_name));
1090 throw new java::lang::InternalError(buffer->toString());
1093 #else
1094 void *
1095 _Jv_Linker::create_error_method (_Jv_Utf8Const *, jclass)
1097 // Codepath for platforms which do not support (or want) libffi.
1098 // You have to accept that it is impossible to provide the name
1099 // of the missing class then.
1100 return (void *) _Jv_ThrowNoClassDefFoundError;
1102 #endif // USE_LIBFFI && FFI_CLOSURES
1104 // Functions for indirect dispatch (symbolic virtual binding) support.
1106 // There are three tables, atable otable and itable. atable is an
1107 // array of addresses, and otable is an array of offsets, and these
1108 // are used for static and virtual members respectively. itable is an
1109 // array of pairs {address, index} where each address is a pointer to
1110 // an interface.
1112 // {a,o,i}table_syms is an array of _Jv_MethodSymbols. Each such
1113 // symbol is a tuple of {classname, member name, signature}.
1115 // Set this to true to enable debugging of indirect dispatch tables/linking.
1116 static bool debug_link = false;
1118 // link_symbol_table() scans these two arrays and fills in the
1119 // corresponding atable and otable with the addresses of static
1120 // members and the offsets of virtual members.
1122 // The offset (in bytes) for each resolved method or field is placed
1123 // at the corresponding position in the virtual method offset table
1124 // (klass->otable).
1126 // This must be called while holding the class lock.
1128 void
1129 _Jv_Linker::link_symbol_table (jclass klass)
1131 int index = 0;
1132 _Jv_MethodSymbol sym;
1133 if (klass->otable == NULL
1134 || klass->otable->state != 0)
1135 goto atable;
1137 klass->otable->state = 1;
1139 if (debug_link)
1140 fprintf (stderr, "Fixing up otable in %s:\n", klass->name->chars());
1141 for (index = 0;
1142 (sym = klass->otable_syms[index]).class_name != NULL;
1143 ++index)
1145 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1146 _Jv_Method *meth = NULL;
1148 _Jv_Utf8Const *signature = sym.signature;
1149 uaddr special;
1150 maybe_adjust_signature (signature, special);
1152 if (target_class == NULL)
1153 throw new java::lang::NoClassDefFoundError
1154 (_Jv_NewStringUTF (sym.class_name->chars()));
1156 // We're looking for a field or a method, and we can tell
1157 // which is needed by looking at the signature.
1158 if (signature->first() == '(' && signature->len() >= 2)
1160 // Looks like someone is trying to invoke an interface method
1161 if (target_class->isInterface())
1163 using namespace java::lang;
1164 StringBuffer *sb = new StringBuffer();
1165 sb->append(JvNewStringLatin1("found interface "));
1166 sb->append(target_class->getName());
1167 sb->append(JvNewStringLatin1(" when searching for a class"));
1168 throw new VerifyError(sb->toString());
1171 // If the target class does not have a vtable_method_count yet,
1172 // then we can't tell the offsets for its methods, so we must lay
1173 // it out now.
1174 wait_for_state(target_class, JV_STATE_PREPARED);
1178 meth = (search_method_in_superclasses
1179 (target_class, klass, sym.name, signature,
1180 NULL, special == 0));
1182 catch (::java::lang::IllegalAccessError *e)
1186 // Every class has a throwNoSuchMethodErrorIndex method that
1187 // it inherits from java.lang.Object. Find its vtable
1188 // offset.
1189 static int throwNoSuchMethodErrorIndex;
1190 if (throwNoSuchMethodErrorIndex == 0)
1192 Utf8Const* name
1193 = _Jv_makeUtf8Const ("throwNoSuchMethodError",
1194 strlen ("throwNoSuchMethodError"));
1195 _Jv_Method* meth
1196 = _Jv_LookupDeclaredMethod (&java::lang::Object::class$,
1197 name, gcj::void_signature);
1198 throwNoSuchMethodErrorIndex
1199 = _Jv_VTable::idx_to_offset (meth->index);
1202 // If we don't find a nonstatic method, insert the
1203 // vtable index of Object.throwNoSuchMethodError().
1204 // This defers the missing method error until an attempt
1205 // is made to execute it.
1207 int offset;
1209 if (meth != NULL)
1210 offset = _Jv_VTable::idx_to_offset (meth->index);
1211 else
1212 offset = throwNoSuchMethodErrorIndex;
1214 if (offset == -1)
1215 JvFail ("Bad method index");
1216 JvAssert (meth->index < target_class->vtable_method_count);
1218 klass->otable->offsets[index] = offset;
1221 if (debug_link)
1222 fprintf (stderr, " offsets[%d] = %d (class %s@%p : %s(%s))\n",
1223 (int)index,
1224 (int)klass->otable->offsets[index],
1225 (const char*)target_class->name->chars(),
1226 target_class,
1227 (const char*)sym.name->chars(),
1228 (const char*)signature->chars());
1229 continue;
1232 // Try fields.
1234 wait_for_state(target_class, JV_STATE_PREPARED);
1235 jclass found_class;
1236 _Jv_Field *the_field = NULL;
1239 the_field = find_field (klass, target_class, &found_class,
1240 sym.name, signature);
1241 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1242 throw new java::lang::IncompatibleClassChangeError;
1243 else
1244 klass->otable->offsets[index] = the_field->u.boffset;
1246 catch (java::lang::NoSuchFieldError *err)
1248 klass->otable->offsets[index] = 0;
1253 atable:
1254 if (klass->atable == NULL || klass->atable->state != 0)
1255 goto itable;
1257 klass->atable->state = 1;
1259 for (index = 0;
1260 (sym = klass->atable_syms[index]).class_name != NULL;
1261 ++index)
1263 jclass target_class =
1264 _Jv_FindClassNoException (sym.class_name, klass->loader);
1266 _Jv_Method *meth = NULL;
1268 _Jv_Utf8Const *signature = sym.signature;
1269 uaddr special;
1270 maybe_adjust_signature (signature, special);
1272 // ??? Setting this pointer to null will at least get us a
1273 // NullPointerException
1274 klass->atable->addresses[index] = NULL;
1276 bool use_error_method = false;
1278 // If the target class is missing we prepare a function call
1279 // that throws a NoClassDefFoundError and store the address of
1280 // that newly prepared method in the atable. The user can run
1281 // code in classes where the missing class is part of the
1282 // execution environment as long as it is never referenced.
1283 if (target_class == NULL)
1284 use_error_method = true;
1285 // We're looking for a static field or a static method, and we
1286 // can tell which is needed by looking at the signature.
1287 else if (signature->first() == '(' && signature->len() >= 2)
1289 // If the target class does not have a vtable_method_count yet,
1290 // then we can't tell the offsets for its methods, so we must lay
1291 // it out now.
1292 wait_for_state (target_class, JV_STATE_PREPARED);
1294 // Interface methods cannot have bodies.
1295 if (target_class->isInterface())
1297 using namespace java::lang;
1298 StringBuffer *sb = new StringBuffer();
1299 sb->append(JvNewStringLatin1("class "));
1300 sb->append(target_class->getName());
1301 sb->append(JvNewStringLatin1(" is an interface: "
1302 "class expected"));
1303 throw new VerifyError(sb->toString());
1308 meth = (search_method_in_superclasses
1309 (target_class, klass, sym.name, signature,
1310 NULL, special == 0));
1312 catch (::java::lang::IllegalAccessError *e)
1316 if (meth != NULL)
1318 if (meth->ncode) // Maybe abstract?
1320 klass->atable->addresses[index] = meth->ncode;
1321 if (debug_link)
1322 fprintf (stderr, " addresses[%d] = %p (class %s@%p : %s(%s))\n",
1323 index,
1324 &klass->atable->addresses[index],
1325 (const char*)target_class->name->chars(),
1326 klass,
1327 (const char*)sym.name->chars(),
1328 (const char*)signature->chars());
1331 else
1332 use_error_method = true;
1334 if (use_error_method)
1335 klass->atable->addresses[index]
1336 = create_error_method(sym.class_name, klass);
1338 continue;
1342 // Try fields only if the target class exists.
1343 if (target_class != NULL)
1345 wait_for_state(target_class, JV_STATE_PREPARED);
1346 jclass found_class;
1347 _Jv_Field *the_field = find_field (klass, target_class, &found_class,
1348 sym.name, signature);
1349 if ((the_field->flags & java::lang::reflect::Modifier::STATIC))
1350 klass->atable->addresses[index] = the_field->u.addr;
1351 else
1352 throw new java::lang::IncompatibleClassChangeError;
1356 itable:
1357 if (klass->itable == NULL
1358 || klass->itable->state != 0)
1359 return;
1361 klass->itable->state = 1;
1363 for (index = 0;
1364 (sym = klass->itable_syms[index]).class_name != NULL;
1365 ++index)
1367 jclass target_class = _Jv_FindClass (sym.class_name, klass->loader);
1369 _Jv_Utf8Const *signature = sym.signature;
1370 uaddr special;
1371 maybe_adjust_signature (signature, special);
1373 jclass cls;
1374 int i;
1376 wait_for_state(target_class, JV_STATE_LOADED);
1377 bool found = _Jv_getInterfaceMethod (target_class, cls, i,
1378 sym.name, signature);
1380 if (found)
1382 klass->itable->addresses[index * 2] = cls;
1383 klass->itable->addresses[index * 2 + 1] = (void *)(unsigned long) i;
1384 if (debug_link)
1386 fprintf (stderr, " interfaces[%d] = %p (interface %s@%p : %s(%s))\n",
1387 index,
1388 klass->itable->addresses[index * 2],
1389 (const char*)cls->name->chars(),
1390 cls,
1391 (const char*)sym.name->chars(),
1392 (const char*)signature->chars());
1393 fprintf (stderr, " [%d] = offset %d\n",
1394 index + 1,
1395 (int)(unsigned long)klass->itable->addresses[index * 2 + 1]);
1399 else
1400 throw new java::lang::IncompatibleClassChangeError;
1405 // For each catch_record in the list of caught classes, fill in the
1406 // address field.
1407 void
1408 _Jv_Linker::link_exception_table (jclass self)
1410 struct _Jv_CatchClass *catch_record = self->catch_classes;
1411 if (!catch_record || catch_record->classname)
1412 return;
1413 catch_record++;
1414 while (catch_record->classname)
1418 jclass target_class
1419 = _Jv_FindClass (catch_record->classname,
1420 self->getClassLoaderInternal ());
1421 *catch_record->address = target_class;
1423 catch (::java::lang::Throwable *t)
1425 // FIXME: We need to do something better here.
1426 *catch_record->address = 0;
1428 catch_record++;
1430 self->catch_classes->classname = (_Jv_Utf8Const *)-1;
1433 // Set itable method indexes for members of interface IFACE.
1434 void
1435 _Jv_Linker::layout_interface_methods (jclass iface)
1437 if (! iface->isInterface())
1438 return;
1440 // itable indexes start at 1.
1441 // FIXME: Static initalizers currently get a NULL placeholder entry in the
1442 // itable so they are also assigned an index here.
1443 for (int i = 0; i < iface->method_count; i++)
1444 iface->methods[i].index = i + 1;
1447 // Prepare virtual method declarations in KLASS, and any superclasses
1448 // as required, by determining their vtable index, setting
1449 // method->index, and finally setting the class's vtable_method_count.
1450 // Must be called with the lock for KLASS held.
1451 void
1452 _Jv_Linker::layout_vtable_methods (jclass klass)
1454 if (klass->vtable != NULL || klass->isInterface()
1455 || klass->vtable_method_count != -1)
1456 return;
1458 jclass superclass = klass->getSuperclass();
1460 if (superclass != NULL && superclass->vtable_method_count == -1)
1462 JvSynchronize sync (superclass);
1463 layout_vtable_methods (superclass);
1466 int index = (superclass == NULL ? 0 : superclass->vtable_method_count);
1468 for (int i = 0; i < klass->method_count; ++i)
1470 _Jv_Method *meth = &klass->methods[i];
1471 _Jv_Method *super_meth = NULL;
1473 if (! _Jv_isVirtualMethod (meth))
1474 continue;
1476 if (superclass != NULL)
1478 jclass declarer;
1479 super_meth = _Jv_LookupDeclaredMethod (superclass, meth->name,
1480 meth->signature, &declarer);
1481 // See if this method actually overrides the other method
1482 // we've found.
1483 if (super_meth)
1485 if (! _Jv_isVirtualMethod (super_meth)
1486 || ! _Jv_CheckAccess (klass, declarer,
1487 super_meth->accflags))
1488 super_meth = NULL;
1489 else if ((super_meth->accflags
1490 & java::lang::reflect::Modifier::FINAL) != 0)
1492 using namespace java::lang;
1493 StringBuffer *sb = new StringBuffer();
1494 sb->append(JvNewStringLatin1("method "));
1495 sb->append(_Jv_GetMethodString(klass, meth));
1496 sb->append(JvNewStringLatin1(" overrides final method "));
1497 sb->append(_Jv_GetMethodString(declarer, super_meth));
1498 throw new VerifyError(sb->toString());
1503 if (super_meth)
1504 meth->index = super_meth->index;
1505 else
1506 meth->index = index++;
1509 klass->vtable_method_count = index;
1512 // Set entries in VTABLE for virtual methods declared in KLASS.
1513 void
1514 _Jv_Linker::set_vtable_entries (jclass klass, _Jv_VTable *vtable)
1516 for (int i = klass->method_count - 1; i >= 0; i--)
1518 using namespace java::lang::reflect;
1520 _Jv_Method *meth = &klass->methods[i];
1521 if (meth->index == (_Jv_ushort) -1)
1522 continue;
1523 if ((meth->accflags & Modifier::ABSTRACT))
1524 // FIXME: it might be nice to have a libffi trampoline here,
1525 // so we could pass in the method name and other information.
1526 vtable->set_method(meth->index,
1527 (void *) &_Jv_ThrowAbstractMethodError);
1528 else
1529 vtable->set_method(meth->index, meth->ncode);
1533 // Allocate and lay out the virtual method table for KLASS. This will
1534 // also cause vtables to be generated for any non-abstract
1535 // superclasses, and virtual method layout to occur for any abstract
1536 // superclasses. Must be called with monitor lock for KLASS held.
1537 void
1538 _Jv_Linker::make_vtable (jclass klass)
1540 using namespace java::lang::reflect;
1542 // If the vtable exists, or for interface classes, do nothing. All
1543 // other classes, including abstract classes, need a vtable.
1544 if (klass->vtable != NULL || klass->isInterface())
1545 return;
1547 // Ensure all the `ncode' entries are set.
1548 klass->engine->create_ncode(klass);
1550 // Class must be laid out before we can create a vtable.
1551 if (klass->vtable_method_count == -1)
1552 layout_vtable_methods (klass);
1554 // Allocate the new vtable.
1555 _Jv_VTable *vtable = _Jv_VTable::new_vtable (klass->vtable_method_count);
1556 klass->vtable = vtable;
1558 // Copy the vtable of the closest superclass.
1559 jclass superclass = klass->superclass;
1561 JvSynchronize sync (superclass);
1562 make_vtable (superclass);
1564 for (int i = 0; i < superclass->vtable_method_count; ++i)
1565 vtable->set_method (i, superclass->vtable->get_method (i));
1567 // Set the class pointer and GC descriptor.
1568 vtable->clas = klass;
1569 vtable->gc_descr = _Jv_BuildGCDescr (klass);
1571 // For each virtual declared in klass, set new vtable entry or
1572 // override an old one.
1573 set_vtable_entries (klass, vtable);
1575 // Note that we don't check for abstract methods here. We used to,
1576 // but there is a JVMS clarification that indicates that a check
1577 // here would be too eager. And, a simple test case confirms this.
1580 // Lay out the class, allocating space for static fields and computing
1581 // offsets of instance fields. The class lock must be held by the
1582 // caller.
1583 void
1584 _Jv_Linker::ensure_fields_laid_out (jclass klass)
1586 if (klass->size_in_bytes != -1)
1587 return;
1589 // Compute the alignment for this type by searching through the
1590 // superclasses and finding the maximum required alignment. We
1591 // could consider caching this in the Class.
1592 int max_align = __alignof__ (java::lang::Object);
1593 jclass super = klass->getSuperclass();
1594 while (super != NULL)
1596 // Ensure that our super has its super installed before
1597 // recursing.
1598 wait_for_state(super, JV_STATE_LOADING);
1599 ensure_fields_laid_out(super);
1600 int num = JvNumInstanceFields (super);
1601 _Jv_Field *field = JvGetFirstInstanceField (super);
1602 while (num > 0)
1604 int field_align = get_alignment_from_class (field->type);
1605 if (field_align > max_align)
1606 max_align = field_align;
1607 ++field;
1608 --num;
1610 super = super->getSuperclass();
1613 int instance_size;
1614 // This is the size of the 'static' non-reference fields.
1615 int non_reference_size = 0;
1616 // This is the size of the 'static' reference fields. We count
1617 // these separately to make it simpler for the GC to scan them.
1618 int reference_size = 0;
1620 // Although java.lang.Object is never interpreted, an interface can
1621 // have a null superclass. Note that we have to lay out an
1622 // interface because it might have static fields.
1623 if (klass->superclass)
1624 instance_size = klass->superclass->size();
1625 else
1626 instance_size = java::lang::Object::class$.size();
1628 klass->engine->allocate_field_initializers (klass);
1630 for (int i = 0; i < klass->field_count; i++)
1632 int field_size;
1633 int field_align;
1635 _Jv_Field *field = &klass->fields[i];
1637 if (! field->isRef ())
1639 // It is safe to resolve the field here, since it's a
1640 // primitive class, which does not cause loading to happen.
1641 resolve_field (field, klass->loader);
1642 field_size = field->type->size ();
1643 field_align = get_alignment_from_class (field->type);
1645 else
1647 field_size = sizeof (jobject);
1648 field_align = __alignof__ (jobject);
1651 field->bsize = field_size;
1653 if ((field->flags & java::lang::reflect::Modifier::STATIC))
1655 if (field->u.addr == NULL)
1657 // This computes an offset into a region we'll allocate
1658 // shortly, and then adds this offset to the start
1659 // address.
1660 if (field->isRef())
1662 reference_size = ROUND (reference_size, field_align);
1663 field->u.boffset = reference_size;
1664 reference_size += field_size;
1666 else
1668 non_reference_size = ROUND (non_reference_size, field_align);
1669 field->u.boffset = non_reference_size;
1670 non_reference_size += field_size;
1674 else
1676 instance_size = ROUND (instance_size, field_align);
1677 field->u.boffset = instance_size;
1678 instance_size += field_size;
1679 if (field_align > max_align)
1680 max_align = field_align;
1684 if (reference_size != 0 || non_reference_size != 0)
1685 klass->engine->allocate_static_fields (klass, reference_size,
1686 non_reference_size);
1688 // Set the instance size for the class. Note that first we round it
1689 // to the alignment required for this object; this keeps us in sync
1690 // with our current ABI.
1691 instance_size = ROUND (instance_size, max_align);
1692 klass->size_in_bytes = instance_size;
1695 // This takes the class to state JV_STATE_LINKED. The class lock must
1696 // be held when calling this.
1697 void
1698 _Jv_Linker::ensure_class_linked (jclass klass)
1700 if (klass->state >= JV_STATE_LINKED)
1701 return;
1703 int state = klass->state;
1706 // Short-circuit, so that mutually dependent classes are ok.
1707 klass->state = JV_STATE_LINKED;
1709 _Jv_Constants *pool = &klass->constants;
1711 // Compiled classes require that their class constants be
1712 // resolved here. However, interpreted classes need their
1713 // constants to be resolved lazily. If we resolve an
1714 // interpreted class' constants eagerly, we can end up with
1715 // spurious IllegalAccessErrors when the constant pool contains
1716 // a reference to a class we can't access. This can validly
1717 // occur in an obscure case involving the InnerClasses
1718 // attribute.
1719 if (! _Jv_IsInterpretedClass (klass))
1721 // Resolve class constants first, since other constant pool
1722 // entries may rely on these.
1723 for (int index = 1; index < pool->size; ++index)
1725 if (pool->tags[index] == JV_CONSTANT_Class)
1726 // Lazily resolve the entries.
1727 resolve_pool_entry (klass, index, true);
1731 // Resolve the remaining constant pool entries.
1732 for (int index = 1; index < pool->size; ++index)
1734 if (pool->tags[index] == JV_CONSTANT_String)
1736 jstring str;
1738 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
1739 pool->data[index].o = str;
1740 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
1744 if (klass->engine->need_resolve_string_fields())
1746 jfieldID f = JvGetFirstStaticField (klass);
1747 for (int n = JvNumStaticFields (klass); n > 0; --n)
1749 int mod = f->getModifiers ();
1750 // If we have a static String field with a non-null initial
1751 // value, we know it points to a Utf8Const.
1753 // Finds out whether we have to initialize a String without the
1754 // need to resolve the field.
1755 if ((f->isResolved()
1756 ? (f->type == &java::lang::String::class$)
1757 : _Jv_equalUtf8Classnames((_Jv_Utf8Const *) f->type,
1758 java::lang::String::class$.name))
1759 && (mod & java::lang::reflect::Modifier::STATIC) != 0)
1761 jstring *strp = (jstring *) f->u.addr;
1762 if (*strp)
1763 *strp = _Jv_NewStringUtf8Const ((_Jv_Utf8Const *) *strp);
1765 f = f->getNextField ();
1769 klass->notifyAll ();
1771 _Jv_PushClass (klass);
1773 catch (java::lang::Throwable *t)
1775 klass->state = state;
1776 throw t;
1780 // This ensures that symbolic superclass and superinterface references
1781 // are resolved for the indicated class. This must be called with the
1782 // class lock held.
1783 void
1784 _Jv_Linker::ensure_supers_installed (jclass klass)
1786 resolve_class_ref (klass, &klass->superclass);
1787 // An interface won't have a superclass.
1788 if (klass->superclass)
1789 wait_for_state (klass->superclass, JV_STATE_LOADING);
1791 for (int i = 0; i < klass->interface_count; ++i)
1793 resolve_class_ref (klass, &klass->interfaces[i]);
1794 wait_for_state (klass->interfaces[i], JV_STATE_LOADING);
1798 // This adds missing `Miranda methods' to a class.
1799 void
1800 _Jv_Linker::add_miranda_methods (jclass base, jclass iface_class)
1802 // Note that at this point, all our supers, and the supers of all
1803 // our superclasses and superinterfaces, will have been installed.
1805 for (int i = 0; i < iface_class->interface_count; ++i)
1807 jclass interface = iface_class->interfaces[i];
1809 for (int j = 0; j < interface->method_count; ++j)
1811 _Jv_Method *meth = &interface->methods[j];
1812 // Don't bother with <clinit>.
1813 if (meth->name->first() == '<')
1814 continue;
1815 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
1816 meth->signature);
1817 if (! new_meth)
1819 // We assume that such methods are very unlikely, so we
1820 // just reallocate the method array each time one is
1821 // found. This greatly simplifies the searching --
1822 // otherwise we have to make sure that each such method
1823 // found is really unique among all superinterfaces.
1824 int new_count = base->method_count + 1;
1825 _Jv_Method *new_m
1826 = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method)
1827 * new_count);
1828 memcpy (new_m, base->methods,
1829 sizeof (_Jv_Method) * base->method_count);
1831 // Add new method.
1832 new_m[base->method_count] = *meth;
1833 new_m[base->method_count].index = (_Jv_ushort) -1;
1834 new_m[base->method_count].accflags
1835 |= java::lang::reflect::Modifier::INVISIBLE;
1837 base->methods = new_m;
1838 base->method_count = new_count;
1842 wait_for_state (interface, JV_STATE_LOADED);
1843 add_miranda_methods (base, interface);
1847 // This ensures that the class' method table is "complete". This must
1848 // be called with the class lock held.
1849 void
1850 _Jv_Linker::ensure_method_table_complete (jclass klass)
1852 if (klass->vtable != NULL)
1853 return;
1855 // We need our superclass to have its own Miranda methods installed.
1856 if (! klass->isInterface())
1857 wait_for_state (klass->getSuperclass (), JV_STATE_LOADED);
1859 // A class might have so-called "Miranda methods". This is a method
1860 // that is declared in an interface and not re-declared in an
1861 // abstract class. Some compilers don't emit declarations for such
1862 // methods in the class; this will give us problems since we expect
1863 // a declaration for any method requiring a vtable entry. We handle
1864 // this here by searching for such methods and constructing new
1865 // internal declarations for them. Note that we do this
1866 // unconditionally, and not just for abstract classes, to correctly
1867 // account for cases where a class is modified to be concrete and
1868 // still incorrectly inherits an abstract method.
1869 int pre_count = klass->method_count;
1870 add_miranda_methods (klass, klass);
1872 // Let the execution engine know that we've added methods.
1873 if (klass->method_count != pre_count)
1874 klass->engine->post_miranda_hook(klass);
1877 // Verify a class. Must be called with class lock held.
1878 void
1879 _Jv_Linker::verify_class (jclass klass)
1881 klass->engine->verify(klass);
1884 // Check the assertions contained in the type assertion table for KLASS.
1885 // This is the equivilent of bytecode verification for native, BC-ABI code.
1886 void
1887 _Jv_Linker::verify_type_assertions (jclass klass)
1889 if (debug_link)
1890 fprintf (stderr, "Evaluating type assertions for %s:\n",
1891 klass->name->chars());
1893 if (klass->assertion_table == NULL)
1894 return;
1896 for (int i = 0;; i++)
1898 int assertion_code = klass->assertion_table[i].assertion_code;
1899 _Jv_Utf8Const *op1 = klass->assertion_table[i].op1;
1900 _Jv_Utf8Const *op2 = klass->assertion_table[i].op2;
1902 if (assertion_code == JV_ASSERT_END_OF_TABLE)
1903 return;
1904 else if (assertion_code == JV_ASSERT_TYPES_COMPATIBLE)
1906 if (debug_link)
1908 fprintf (stderr, " code=%i, operand A=%s B=%s\n",
1909 assertion_code, op1->chars(), op2->chars());
1912 // The operands are class signatures. op1 is the source,
1913 // op2 is the target.
1914 jclass cl1 = _Jv_FindClassFromSignature (op1->chars(),
1915 klass->getClassLoaderInternal());
1916 jclass cl2 = _Jv_FindClassFromSignature (op2->chars(),
1917 klass->getClassLoaderInternal());
1919 // If the class doesn't exist, ignore the assertion. An exception
1920 // will be thrown later if an attempt is made to actually
1921 // instantiate the class.
1922 if (cl1 == NULL || cl2 == NULL)
1923 continue;
1925 if (! _Jv_IsAssignableFromSlow (cl1, cl2))
1927 jstring s = JvNewStringUTF ("Incompatible types: In class ");
1928 s = s->concat (klass->getName());
1929 s = s->concat (JvNewStringUTF (": "));
1930 s = s->concat (cl1->getName());
1931 s = s->concat (JvNewStringUTF (" is not assignable to "));
1932 s = s->concat (cl2->getName());
1933 throw new java::lang::VerifyError (s);
1936 else if (assertion_code == JV_ASSERT_IS_INSTANTIABLE)
1938 // TODO: Implement this.
1940 // Unknown assertion codes are ignored, for forwards-compatibility.
1944 void
1945 _Jv_Linker::print_class_loaded (jclass klass)
1947 char *codesource = NULL;
1948 if (klass->protectionDomain != NULL)
1950 java::security::CodeSource *cs
1951 = klass->protectionDomain->getCodeSource();
1952 if (cs != NULL)
1954 jstring css = cs->toString();
1955 int len = JvGetStringUTFLength(css);
1956 codesource = (char *) _Jv_AllocBytes(len + 1);
1957 JvGetStringUTFRegion(css, 0, css->length(), codesource);
1958 codesource[len] = '\0';
1961 if (codesource == NULL)
1962 codesource = (char *) "<no code source>";
1964 const char *abi;
1965 if (_Jv_IsInterpretedClass (klass))
1966 abi = "bytecode";
1967 else if (_Jv_IsBinaryCompatibilityABI (klass))
1968 abi = "BC-compiled";
1969 else
1970 abi = "pre-compiled";
1972 fprintf (stderr, "[Loaded (%s) %s from %s]\n", abi, klass->name->chars(),
1973 codesource);
1976 // FIXME: mention invariants and stuff.
1977 void
1978 _Jv_Linker::wait_for_state (jclass klass, int state)
1980 if (klass->state >= state)
1981 return;
1983 java::lang::Thread *self = java::lang::Thread::currentThread();
1986 JvSynchronize sync (klass);
1988 // This is similar to the strategy for class initialization. If we
1989 // already hold the lock, just leave.
1990 while (klass->state <= state
1991 && klass->thread
1992 && klass->thread != self)
1993 klass->wait ();
1995 java::lang::Thread *save = klass->thread;
1996 klass->thread = self;
1998 // Allocate memory for static fields and constants.
1999 if (GC_base (klass) && klass->fields && ! GC_base (klass->fields))
2001 jsize count = klass->field_count;
2002 if (count)
2004 _Jv_Field* fields
2005 = (_Jv_Field*) _Jv_AllocRawObj (count * sizeof (_Jv_Field));
2006 memcpy ((void*)fields,
2007 (void*)klass->fields,
2008 count * sizeof (_Jv_Field));
2009 klass->fields = fields;
2013 // Print some debugging info if requested. Interpreted classes are
2014 // handled in defineclass, so we only need to handle the two
2015 // pre-compiled cases here.
2016 if ((klass->state == JV_STATE_COMPILED
2017 || klass->state == JV_STATE_PRELOADING)
2018 && ! _Jv_IsInterpretedClass (klass))
2020 if (gcj::verbose_class_flag)
2021 print_class_loaded (klass);
2022 ++gcj::loadedClasses;
2027 if (state >= JV_STATE_LOADING && klass->state < JV_STATE_LOADING)
2029 ensure_supers_installed (klass);
2030 klass->set_state(JV_STATE_LOADING);
2033 if (state >= JV_STATE_LOADED && klass->state < JV_STATE_LOADED)
2035 ensure_method_table_complete (klass);
2036 klass->set_state(JV_STATE_LOADED);
2039 if (state >= JV_STATE_PREPARED && klass->state < JV_STATE_PREPARED)
2041 ensure_fields_laid_out (klass);
2042 make_vtable (klass);
2043 layout_interface_methods (klass);
2044 prepare_constant_time_tables (klass);
2045 klass->set_state(JV_STATE_PREPARED);
2048 if (state >= JV_STATE_LINKED && klass->state < JV_STATE_LINKED)
2050 if (gcj::verifyClasses)
2051 verify_class (klass);
2053 ensure_class_linked (klass);
2054 link_exception_table (klass);
2055 link_symbol_table (klass);
2056 klass->set_state(JV_STATE_LINKED);
2059 catch (java::lang::Throwable *exc)
2061 klass->thread = save;
2062 klass->set_state(JV_STATE_ERROR);
2063 throw exc;
2066 klass->thread = save;
2068 if (klass->state == JV_STATE_ERROR)
2069 throw new java::lang::LinkageError;
2072 if (__builtin_expect (klass->state == JV_STATE_LINKED, false)
2073 && state >= JV_STATE_LINKED
2074 && JVMTI_REQUESTED_EVENT (ClassPrepare))
2076 JNIEnv *jni_env = _Jv_GetCurrentJNIEnv ();
2077 _Jv_JVMTI_PostEvent (JVMTI_EVENT_CLASS_PREPARE, self, jni_env,
2078 klass);