1 // resolve.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001 , 2002 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
11 /* Author: Kresten Krab Thorup <krab@gnu.org> */
15 #include <java-interp.h>
20 #include <java-cpool.h>
21 #include <java/lang/Class.h>
22 #include <java/lang/String.h>
23 #include <java/lang/StringBuffer.h>
24 #include <java/lang/Thread.h>
25 #include <java/lang/InternalError.h>
26 #include <java/lang/VirtualMachineError.h>
27 #include <java/lang/NoSuchFieldError.h>
28 #include <java/lang/NoSuchMethodError.h>
29 #include <java/lang/ClassFormatError.h>
30 #include <java/lang/IllegalAccessError.h>
31 #include <java/lang/AbstractMethodError.h>
32 #include <java/lang/NoClassDefFoundError.h>
33 #include <java/lang/IncompatibleClassChangeError.h>
34 #include <java/lang/reflect/Modifier.h>
39 _Jv_ResolveField (_Jv_Field *field, java::lang::ClassLoader *loader)
41 if (! field->isResolved ())
43 _Jv_Utf8Const *sig = (_Jv_Utf8Const*)field->type;
44 field->type = _Jv_FindClassFromSignature (sig->data, loader);
45 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
51 static void throw_internal_error (char *msg)
52 __attribute__ ((__noreturn__));
53 static void throw_class_format_error (jstring msg)
54 __attribute__ ((__noreturn__));
55 static void throw_class_format_error (char *msg)
56 __attribute__ ((__noreturn__));
58 static int get_alignment_from_class (jclass);
60 static _Jv_ResolvedMethod*
61 _Jv_BuildResolvedMethod (_Jv_Method*,
67 static void throw_incompatible_class_change_error (jstring msg)
69 throw new java::lang::IncompatibleClassChangeError (msg);
73 _Jv_ResolvePoolEntry (jclass klass, int index)
75 using namespace java::lang::reflect;
77 _Jv_Constants *pool = &klass->constants;
79 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
80 return pool->data[index];
82 switch (pool->tags[index]) {
83 case JV_CONSTANT_Class:
85 _Jv_Utf8Const *name = pool->data[index].utf8;
88 if (name->data[0] == '[')
89 found = _Jv_FindClassFromSignature (&name->data[0],
92 found = _Jv_FindClass (name, klass->loader);
96 jstring str = _Jv_NewStringUTF (name->data);
97 // This exception is specified in JLS 2nd Ed, section 5.1.
98 throw new java::lang::NoClassDefFoundError (str);
101 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
102 || (_Jv_ClassNameSamePackage (found->name,
105 pool->data[index].clazz = found;
106 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
110 throw new java::lang::IllegalAccessError (found->getName());
115 case JV_CONSTANT_String:
118 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
119 pool->data[index].o = str;
120 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
125 case JV_CONSTANT_Fieldref:
127 _Jv_ushort class_index, name_and_type_index;
128 _Jv_loadIndexes (&pool->data[index],
130 name_and_type_index);
131 jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
134 _Jv_InitClass (owner);
136 _Jv_ushort name_index, type_index;
137 _Jv_loadIndexes (&pool->data[name_and_type_index],
141 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
142 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
144 // FIXME: The implementation of this function
145 // (_Jv_FindClassFromSignature) will generate an instance of
146 // _Jv_Utf8Const for each call if the field type is a class name
147 // (Lxx.yy.Z;). This may be too expensive to do for each and
148 // every fieldref being resolved. For now, we fix the problem by
149 // only doing it when we have a loader different from the class
150 // declaring the field.
152 jclass field_type = 0;
154 if (owner->loader != klass->loader)
155 field_type = _Jv_FindClassFromSignature (field_type_name->data,
158 _Jv_Field* the_field = 0;
160 for (jclass cls = owner; cls != 0; cls = cls->getSuperclass ())
162 for (int i = 0; i < cls->field_count; i++)
164 _Jv_Field *field = &cls->fields[i];
165 if (! _Jv_equalUtf8Consts (field->name, field_name))
168 // now, check field access.
171 || ((field->flags & Modifier::PUBLIC) != 0)
172 || (((field->flags & Modifier::PROTECTED) != 0)
173 && cls->isAssignableFrom (klass))
174 || (((field->flags & Modifier::PRIVATE) == 0)
175 && _Jv_ClassNameSamePackage (cls->name,
178 /* resove the field using the class' own loader
181 if (!field->isResolved ())
182 _Jv_ResolveField (field, cls->loader);
184 if (field_type != 0 && field->type != field_type)
185 throw new java::lang::LinkageError
187 ("field type mismatch with different loaders"));
190 goto end_of_field_search;
194 throw new java::lang::IllegalAccessError;
202 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
203 sb->append(JvNewStringLatin1("field "));
204 sb->append(owner->getName());
205 sb->append(JvNewStringLatin1("."));
206 sb->append(_Jv_NewStringUTF(field_name->data));
207 sb->append(JvNewStringLatin1(" was not found."));
208 throw_incompatible_class_change_error(sb->toString());
211 pool->data[index].field = the_field;
212 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
216 case JV_CONSTANT_Methodref:
217 case JV_CONSTANT_InterfaceMethodref:
219 _Jv_ushort class_index, name_and_type_index;
220 _Jv_loadIndexes (&pool->data[index],
222 name_and_type_index);
223 jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
226 _Jv_InitClass (owner);
228 _Jv_ushort name_index, type_index;
229 _Jv_loadIndexes (&pool->data[name_and_type_index],
233 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
234 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
236 _Jv_Method *the_method = 0;
237 jclass found_class = 0;
239 // First search the class itself.
240 the_method = _Jv_SearchMethodInClass (owner, klass,
241 method_name, method_signature);
246 goto end_of_method_search;
249 // If we are resolving an interface method, search the interface's
250 // superinterfaces (A superinterface is not an interface's superclass -
251 // a superinterface is implemented by the interface).
252 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
257 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
259 _Jv_GetInterfaces (owner, &ifaces);
261 for (int i=0; i < ifaces.count; i++)
263 jclass cls = ifaces.list[i];
264 the_method = _Jv_SearchMethodInClass (cls, klass, method_name,
273 _Jv_Free (ifaces.list);
276 goto end_of_method_search;
279 // Finally, search superclasses.
280 for (jclass cls = owner->getSuperclass (); cls != 0;
281 cls = cls->getSuperclass ())
283 the_method = _Jv_SearchMethodInClass (cls, klass,
284 method_name, method_signature);
292 end_of_method_search:
294 // FIXME: if (cls->loader != klass->loader), then we
295 // must actually check that the types of arguments
296 // correspond. That is, for each argument type, and
297 // the return type, doing _Jv_FindClassFromSignature
298 // with either loader should produce the same result,
299 // i.e., exactly the same jclass object. JVMS 5.4.3.3
303 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
304 sb->append(JvNewStringLatin1("method "));
305 sb->append(owner->getName());
306 sb->append(JvNewStringLatin1("."));
307 sb->append(_Jv_NewStringUTF(method_name->data));
308 sb->append(JvNewStringLatin1(" was not found."));
309 throw new java::lang::NoSuchMethodError (sb->toString());
312 int vtable_index = -1;
313 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
314 vtable_index = (jshort)the_method->index;
316 pool->data[index].rmethod =
317 _Jv_BuildResolvedMethod(the_method,
319 (the_method->accflags & Modifier::STATIC) != 0,
321 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
327 return pool->data[index];
330 // Find a method declared in the cls that is referenced from klass and
331 // perform access checks.
333 _Jv_SearchMethodInClass (jclass cls, jclass klass,
334 _Jv_Utf8Const *method_name,
335 _Jv_Utf8Const *method_signature)
337 using namespace java::lang::reflect;
339 for (int i = 0; i < cls->method_count; i++)
341 _Jv_Method *method = &cls->methods[i];
342 if ( (!_Jv_equalUtf8Consts (method->name,
344 || (!_Jv_equalUtf8Consts (method->signature,
349 || ((method->accflags & Modifier::PUBLIC) != 0)
350 || (((method->accflags & Modifier::PROTECTED) != 0)
351 && cls->isAssignableFrom (klass))
352 || (((method->accflags & Modifier::PRIVATE) == 0)
353 && _Jv_ClassNameSamePackage (cls->name,
360 throw new java::lang::IllegalAccessError;
367 _Jv_PrepareClass(jclass klass)
369 using namespace java::lang::reflect;
372 * The job of this function is to: 1) assign storage to fields, and 2)
373 * build the vtable. static fields are assigned real memory, instance
374 * fields are assigned offsets.
376 * NOTE: we have a contract with the garbage collector here. Static
377 * reference fields must not be resolved, until after they have storage
378 * assigned which is the check used by the collector to see if it
379 * should indirect the static field reference and mark the object
382 * Most fields are resolved lazily (i.e. have their class-type
383 * assigned) when they are accessed the first time by calling as part
384 * of _Jv_ResolveField, which is allways called after _Jv_PrepareClass.
385 * Static fields with initializers are resolved as part of this
386 * function, as are fields with primitive types.
389 if (! _Jv_IsInterpretedClass (klass))
392 if (klass->state >= JV_STATE_PREPARED)
395 // Make sure super-class is linked. This involves taking a lock on
396 // the super class, so we use the Java method resolveClass, which
397 // will unlock it properly, should an exception happen. If there's
398 // no superclass, do nothing -- Object will already have been
401 if (klass->superclass)
402 java::lang::ClassLoader::resolveClass0 (klass->superclass);
404 _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
406 /************ PART ONE: OBJECT LAYOUT ***************/
411 // Although java.lang.Object is never interpreted, an interface can
412 // have a null superclass.
414 instance_size = clz->superclass->size();
416 instance_size = java::lang::Object::class$.size();
419 for (int i = 0; i < clz->field_count; i++)
424 _Jv_Field *field = &clz->fields[i];
426 if (! field->isRef ())
428 // it's safe to resolve the field here, since it's
429 // a primitive class, which does not cause loading to happen.
430 _Jv_ResolveField (field, clz->loader);
432 field_size = field->type->size ();
433 field_align = get_alignment_from_class (field->type);
437 field_size = sizeof (jobject);
438 field_align = __alignof__ (jobject);
441 #ifndef COMPACT_FIELDS
442 field->bsize = field_size;
445 if (field->flags & Modifier::STATIC)
447 /* this computes an offset into a region we'll allocate
448 shortly, and then add this offset to the start address */
450 static_size = ROUND (static_size, field_align);
451 field->u.boffset = static_size;
452 static_size += field_size;
456 instance_size = ROUND (instance_size, field_align);
457 field->u.boffset = instance_size;
458 instance_size += field_size;
462 // set the instance size for the class
463 clz->size_in_bytes = instance_size;
465 // allocate static memory
466 if (static_size != 0)
468 char *static_data = (char*)_Jv_AllocBytes (static_size);
470 memset (static_data, 0, static_size);
472 for (int i = 0; i < clz->field_count; i++)
474 _Jv_Field *field = &clz->fields[i];
476 if ((field->flags & Modifier::STATIC) != 0)
478 field->u.addr = static_data + field->u.boffset;
480 if (clz->field_initializers[i] != 0)
482 _Jv_ResolveField (field, clz->loader);
483 _Jv_InitField (0, clz, i);
488 // now we don't need the field_initializers anymore, so let the
489 // collector get rid of it!
491 clz->field_initializers = 0;
494 /************ PART TWO: VTABLE LAYOUT ***************/
496 /* preparation: build the vtable stubs (even interfaces can)
497 have code -- for static constructors. */
498 for (int i = 0; i < clz->method_count; i++)
500 _Jv_MethodBase *imeth = clz->interpreted_methods[i];
502 if ((clz->methods[i].accflags & Modifier::NATIVE) != 0)
504 // You might think we could use a virtual `ncode' method in
505 // the _Jv_MethodBase and unify the native and non-native
506 // cases. Well, we can't, because we don't allocate these
507 // objects using `new', and thus they don't get a vtable.
508 _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
509 clz->methods[i].ncode = jnim->ncode ();
511 else if (imeth != 0) // it could be abstract
513 _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
514 _Jv_VerifyMethod (im);
515 clz->methods[i].ncode = im->ncode ();
519 if (clz->accflags & Modifier::INTERFACE)
521 clz->state = JV_STATE_PREPARED;
526 clz->vtable_method_count = -1;
527 _Jv_MakeVTable (clz);
529 /* wooha! we're done. */
530 clz->state = JV_STATE_PREPARED;
534 /** Do static initialization for fields with a constant initializer */
536 _Jv_InitField (jobject obj, jclass klass, int index)
538 using namespace java::lang::reflect;
540 if (obj != 0 && klass == 0)
541 klass = obj->getClass ();
543 if (!_Jv_IsInterpretedClass (klass))
546 _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
548 _Jv_Field * field = (&clz->fields[0]) + index;
550 if (index > clz->field_count)
551 throw_internal_error ("field out of range");
553 int init = clz->field_initializers[index];
557 _Jv_Constants *pool = &clz->constants;
558 int tag = pool->tags[init];
560 if (! field->isResolved ())
561 throw_internal_error ("initializing unresolved field");
563 if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
564 throw_internal_error ("initializing non-static field with no object");
568 if ((field->flags & Modifier::STATIC) != 0)
569 addr = (void*) field->u.addr;
571 addr = (void*) (((char*)obj) + field->u.boffset);
575 case JV_CONSTANT_String:
577 _Jv_MonitorEnter (clz);
579 str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
580 pool->data[init].string = str;
581 pool->tags[init] = JV_CONSTANT_ResolvedString;
582 _Jv_MonitorExit (clz);
586 case JV_CONSTANT_ResolvedString:
587 if (! (field->type == &StringClass
588 || field->type == &java::lang::Class::class$))
589 throw_class_format_error ("string initialiser to non-string field");
591 *(jstring*)addr = pool->data[init].string;
594 case JV_CONSTANT_Integer:
596 int value = pool->data[init].i;
598 if (field->type == JvPrimClass (boolean))
599 *(jboolean*)addr = (jboolean)value;
601 else if (field->type == JvPrimClass (byte))
602 *(jbyte*)addr = (jbyte)value;
604 else if (field->type == JvPrimClass (char))
605 *(jchar*)addr = (jchar)value;
607 else if (field->type == JvPrimClass (short))
608 *(jshort*)addr = (jshort)value;
610 else if (field->type == JvPrimClass (int))
611 *(jint*)addr = (jint)value;
614 throw_class_format_error ("erroneous field initializer");
618 case JV_CONSTANT_Long:
619 if (field->type != JvPrimClass (long))
620 throw_class_format_error ("erroneous field initializer");
622 *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
625 case JV_CONSTANT_Float:
626 if (field->type != JvPrimClass (float))
627 throw_class_format_error ("erroneous field initializer");
629 *(jfloat*)addr = pool->data[init].f;
632 case JV_CONSTANT_Double:
633 if (field->type != JvPrimClass (double))
634 throw_class_format_error ("erroneous field initializer");
636 *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
640 throw_class_format_error ("erroneous field initializer");
645 get_alignment_from_class (jclass klass)
647 if (klass == JvPrimClass (byte))
648 return __alignof__ (jbyte);
649 else if (klass == JvPrimClass (short))
650 return __alignof__ (jshort);
651 else if (klass == JvPrimClass (int))
652 return __alignof__ (jint);
653 else if (klass == JvPrimClass (long))
654 return __alignof__ (jlong);
655 else if (klass == JvPrimClass (boolean))
656 return __alignof__ (jboolean);
657 else if (klass == JvPrimClass (char))
658 return __alignof__ (jchar);
659 else if (klass == JvPrimClass (float))
660 return __alignof__ (jfloat);
661 else if (klass == JvPrimClass (double))
662 return __alignof__ (jdouble);
664 return __alignof__ (jobject);
668 inline static unsigned char*
669 skip_one_type (unsigned char* ptr)
680 do { ch = *ptr++; } while (ch != ';');
687 get_ffi_type_from_signature (unsigned char* ptr)
693 return &ffi_type_pointer;
697 // On some platforms a bool is a byte, on others an int.
698 if (sizeof (jboolean) == sizeof (jbyte))
699 return &ffi_type_sint8;
702 JvAssert (sizeof (jbyte) == sizeof (jint));
703 return &ffi_type_sint32;
708 return &ffi_type_sint8;
712 return &ffi_type_uint16;
716 return &ffi_type_sint16;
720 return &ffi_type_sint32;
724 return &ffi_type_sint64;
728 return &ffi_type_float;
732 return &ffi_type_double;
736 return &ffi_type_void;
740 throw_internal_error ("unknown type in signature");
743 /* this function yields the number of actual arguments, that is, if the
744 * function is non-static, then one is added to the number of elements
745 * found in the signature */
748 _Jv_count_arguments (_Jv_Utf8Const *signature,
751 unsigned char *ptr = (unsigned char*) signature->data;
752 int arg_count = staticp ? 0 : 1;
754 /* first, count number of arguments */
762 ptr = skip_one_type (ptr);
769 /* This beast will build a cif, given the signature. Memory for
770 * the cif itself and for the argument types must be allocated by the
775 init_cif (_Jv_Utf8Const* signature,
779 ffi_type **arg_types,
782 unsigned char *ptr = (unsigned char*) signature->data;
784 int arg_index = 0; // arg number
785 int item_count = 0; // stack-item count
790 arg_types[arg_index++] = &ffi_type_pointer;
800 arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
802 if (*ptr == 'J' || *ptr == 'D')
807 ptr = skip_one_type (ptr);
812 ffi_type *rtype = get_ffi_type_from_signature (ptr);
814 ptr = skip_one_type (ptr);
815 if (ptr != (unsigned char*)signature->data + signature->length)
816 throw_internal_error ("did not find end of signature");
818 if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
819 arg_count, rtype, arg_types) != FFI_OK)
820 throw_internal_error ("ffi_prep_cif failed");
828 #if FFI_NATIVE_RAW_API
829 # define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure
830 # define FFI_RAW_SIZE ffi_raw_size
832 # define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure
833 # define FFI_RAW_SIZE ffi_java_raw_size
836 /* we put this one here, and not in interpret.cc because it
837 * calls the utility routines _Jv_count_arguments
838 * which are static to this module. The following struct defines the
839 * layout we use for the stubs, it's only used in the ncode method. */
842 ffi_raw_closure closure;
844 ffi_type *arg_types[0];
847 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
850 _Jv_InterpMethod::ncode ()
852 using namespace java::lang::reflect;
854 if (self->ncode != 0)
857 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
858 int arg_count = _Jv_count_arguments (self->signature, staticp);
860 ncode_closure *closure =
861 (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
862 + arg_count * sizeof (ffi_type*));
864 init_cif (self->signature,
868 &closure->arg_types[0],
873 args_raw_size = FFI_RAW_SIZE (&closure->cif);
875 JvAssert ((self->accflags & Modifier::NATIVE) == 0);
877 if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
880 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
882 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object;
886 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
889 FFI_PREP_RAW_CLOSURE (&closure->closure,
894 self->ncode = (void*)closure;
900 _Jv_JNIMethod::ncode ()
902 using namespace java::lang::reflect;
904 if (self->ncode != 0)
907 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
908 int arg_count = _Jv_count_arguments (self->signature, staticp);
910 ncode_closure *closure =
911 (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
912 + arg_count * sizeof (ffi_type*));
915 init_cif (self->signature,
919 &closure->arg_types[0],
924 args_raw_size = FFI_RAW_SIZE (&closure->cif);
926 // Initialize the argument types and CIF that represent the actual
927 // underlying JNI function.
929 if ((self->accflags & Modifier::STATIC))
931 jni_arg_types = (ffi_type **) _Jv_Malloc ((extra_args + arg_count)
932 * sizeof (ffi_type *));
934 jni_arg_types[offset++] = &ffi_type_pointer;
935 if ((self->accflags & Modifier::STATIC))
936 jni_arg_types[offset++] = &ffi_type_pointer;
937 memcpy (&jni_arg_types[offset], &closure->arg_types[0],
938 arg_count * sizeof (ffi_type *));
940 if (ffi_prep_cif (&jni_cif, FFI_DEFAULT_ABI,
941 extra_args + arg_count, rtype,
942 jni_arg_types) != FFI_OK)
943 throw_internal_error ("ffi_prep_cif failed for JNI function");
945 JvAssert ((self->accflags & Modifier::NATIVE) != 0);
947 // FIXME: for now we assume that all native methods for
948 // interpreted code use JNI.
949 fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
951 FFI_PREP_RAW_CLOSURE (&closure->closure,
956 self->ncode = (void *) closure;
961 /* A _Jv_ResolvedMethod is what is put in the constant pool for a
962 * MethodRef or InterfacemethodRef. */
963 static _Jv_ResolvedMethod*
964 _Jv_BuildResolvedMethod (_Jv_Method* method,
969 int arg_count = _Jv_count_arguments (method->signature, staticp);
971 _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
972 _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
973 + arg_count*sizeof (ffi_type*));
975 result->stack_item_count
976 = init_cif (method->signature,
980 &result->arg_types[0],
983 result->vtable_index = vtable_index;
984 result->method = method;
985 result->klass = klass;
992 throw_class_format_error (jstring msg)
995 ? new java::lang::ClassFormatError (msg)
996 : new java::lang::ClassFormatError);
1000 throw_class_format_error (char *msg)
1002 throw_class_format_error (JvNewStringLatin1 (msg));
1006 throw_internal_error (char *msg)
1008 throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1012 #endif /* INTERPRETER */