Fix typo.
[official-gcc.git] / libjava / resolve.cc
blob5ebefebecef5d101b1654e6a7c1f87731de6131a
1 // resolve.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 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 <java-interp.h>
18 #include <jvm.h>
19 #include <gcj/cni.h>
20 #include <string.h>
21 #include <java-cpool.h>
22 #include <java/lang/Class.h>
23 #include <java/lang/String.h>
24 #include <java/lang/StringBuffer.h>
25 #include <java/lang/Thread.h>
26 #include <java/lang/InternalError.h>
27 #include <java/lang/VirtualMachineError.h>
28 #include <java/lang/NoSuchFieldError.h>
29 #include <java/lang/NoSuchMethodError.h>
30 #include <java/lang/ClassFormatError.h>
31 #include <java/lang/IllegalAccessError.h>
32 #include <java/lang/AbstractMethodError.h>
33 #include <java/lang/NoClassDefFoundError.h>
34 #include <java/lang/IncompatibleClassChangeError.h>
35 #include <java/lang/VMClassLoader.h>
36 #include <java/lang/reflect/Modifier.h>
38 using namespace gcj;
40 void
41 _Jv_ResolveField (_Jv_Field *field, java::lang::ClassLoader *loader)
43 if (! field->isResolved ())
45 _Jv_Utf8Const *sig = (_Jv_Utf8Const*)field->type;
46 field->type = _Jv_FindClassFromSignature (sig->chars(), loader);
47 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
51 #ifdef INTERPRETER
53 static void throw_internal_error (char *msg)
54 __attribute__ ((__noreturn__));
55 static void throw_class_format_error (jstring msg)
56 __attribute__ ((__noreturn__));
57 static void throw_class_format_error (char *msg)
58 __attribute__ ((__noreturn__));
60 static int get_alignment_from_class (jclass);
62 static _Jv_ResolvedMethod*
63 _Jv_BuildResolvedMethod (_Jv_Method*,
64 jclass,
65 jboolean,
66 jint);
69 static void throw_incompatible_class_change_error (jstring msg)
71 throw new java::lang::IncompatibleClassChangeError (msg);
74 _Jv_word
75 _Jv_ResolvePoolEntry (jclass klass, int index)
77 using namespace java::lang::reflect;
79 _Jv_Constants *pool = &klass->constants;
81 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
82 return pool->data[index];
84 switch (pool->tags[index]) {
85 case JV_CONSTANT_Class:
87 _Jv_Utf8Const *name = pool->data[index].utf8;
89 jclass found;
90 if (name->first() == '[')
91 found = _Jv_FindClassFromSignature (name->chars(),
92 klass->loader);
93 else
94 found = _Jv_FindClass (name, klass->loader);
96 if (! found)
98 jstring str = name->toString();
99 // This exception is specified in JLS 2nd Ed, section 5.1.
100 throw new java::lang::NoClassDefFoundError (str);
103 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
104 || (_Jv_ClassNameSamePackage (found->name,
105 klass->name)))
107 pool->data[index].clazz = found;
108 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
110 else
112 throw new java::lang::IllegalAccessError (found->getName());
115 break;
117 case JV_CONSTANT_String:
119 jstring str;
120 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
121 pool->data[index].o = str;
122 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
124 break;
127 case JV_CONSTANT_Fieldref:
129 _Jv_ushort class_index, name_and_type_index;
130 _Jv_loadIndexes (&pool->data[index],
131 class_index,
132 name_and_type_index);
133 jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
135 if (owner != klass)
136 _Jv_InitClass (owner);
138 _Jv_ushort name_index, type_index;
139 _Jv_loadIndexes (&pool->data[name_and_type_index],
140 name_index,
141 type_index);
143 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
144 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
146 // FIXME: The implementation of this function
147 // (_Jv_FindClassFromSignature) will generate an instance of
148 // _Jv_Utf8Const for each call if the field type is a class name
149 // (Lxx.yy.Z;). This may be too expensive to do for each and
150 // every fieldref being resolved. For now, we fix the problem by
151 // only doing it when we have a loader different from the class
152 // declaring the field.
154 jclass field_type = 0;
156 if (owner->loader != klass->loader)
157 field_type = _Jv_FindClassFromSignature (field_type_name->chars(),
158 klass->loader);
160 _Jv_Field* the_field = 0;
162 for (jclass cls = owner; cls != 0; cls = cls->getSuperclass ())
164 for (int i = 0; i < cls->field_count; i++)
166 _Jv_Field *field = &cls->fields[i];
167 if (! _Jv_equalUtf8Consts (field->name, field_name))
168 continue;
170 if (_Jv_CheckAccess (klass, cls, field->flags))
172 /* resove the field using the class' own loader
173 if necessary */
175 if (!field->isResolved ())
176 _Jv_ResolveField (field, cls->loader);
178 if (field_type != 0 && field->type != field_type)
179 throw new java::lang::LinkageError
180 (JvNewStringLatin1
181 ("field type mismatch with different loaders"));
183 the_field = field;
184 goto end_of_field_search;
186 else
188 java::lang::StringBuffer *sb
189 = new java::lang::StringBuffer ();
190 sb->append(klass->getName());
191 sb->append(JvNewStringLatin1(": "));
192 sb->append(cls->getName());
193 sb->append(JvNewStringLatin1("."));
194 sb->append(_Jv_NewStringUtf8Const (field_name));
195 throw new java::lang::IllegalAccessError(sb->toString());
200 end_of_field_search:
201 if (the_field == 0)
203 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
204 sb->append(JvNewStringLatin1("field "));
205 sb->append(owner->getName());
206 sb->append(JvNewStringLatin1("."));
207 sb->append(field_name->toString());
208 sb->append(JvNewStringLatin1(" was not found."));
209 throw_incompatible_class_change_error(sb->toString());
212 pool->data[index].field = the_field;
213 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
215 break;
217 case JV_CONSTANT_Methodref:
218 case JV_CONSTANT_InterfaceMethodref:
220 _Jv_ushort class_index, name_and_type_index;
221 _Jv_loadIndexes (&pool->data[index],
222 class_index,
223 name_and_type_index);
224 jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
226 if (owner != klass)
227 _Jv_InitClass (owner);
229 _Jv_ushort name_index, type_index;
230 _Jv_loadIndexes (&pool->data[name_and_type_index],
231 name_index,
232 type_index);
234 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
235 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
237 _Jv_Method *the_method = 0;
238 jclass found_class = 0;
240 // First search the class itself.
241 the_method = _Jv_SearchMethodInClass (owner, klass,
242 method_name, method_signature);
244 if (the_method != 0)
246 found_class = owner;
247 goto end_of_method_search;
250 // If we are resolving an interface method, search the
251 // interface's superinterfaces (A superinterface is not an
252 // interface's superclass - a superinterface is implemented by
253 // the interface).
254 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
256 _Jv_ifaces ifaces;
257 ifaces.count = 0;
258 ifaces.len = 4;
259 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
261 _Jv_GetInterfaces (owner, &ifaces);
263 for (int i = 0; i < ifaces.count; i++)
265 jclass cls = ifaces.list[i];
266 the_method = _Jv_SearchMethodInClass (cls, klass, method_name,
267 method_signature);
268 if (the_method != 0)
270 found_class = cls;
271 break;
275 _Jv_Free (ifaces.list);
277 if (the_method != 0)
278 goto end_of_method_search;
281 // Finally, search superclasses.
282 for (jclass cls = owner->getSuperclass (); cls != 0;
283 cls = cls->getSuperclass ())
285 the_method = _Jv_SearchMethodInClass (cls, klass,
286 method_name, method_signature);
287 if (the_method != 0)
289 found_class = cls;
290 break;
294 end_of_method_search:
296 // FIXME: if (cls->loader != klass->loader), then we
297 // must actually check that the types of arguments
298 // correspond. That is, for each argument type, and
299 // the return type, doing _Jv_FindClassFromSignature
300 // with either loader should produce the same result,
301 // i.e., exactly the same jclass object. JVMS 5.4.3.3
303 if (the_method == 0)
305 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
306 sb->append(JvNewStringLatin1("method "));
307 sb->append(owner->getName());
308 sb->append(JvNewStringLatin1("."));
309 sb->append(method_name->toString());
310 sb->append(JvNewStringLatin1(" was not found."));
311 throw new java::lang::NoSuchMethodError (sb->toString());
314 int vtable_index = -1;
315 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
316 vtable_index = (jshort)the_method->index;
318 pool->data[index].rmethod =
319 _Jv_BuildResolvedMethod(the_method,
320 found_class,
321 (the_method->accflags & Modifier::STATIC) != 0,
322 vtable_index);
323 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
325 break;
329 return pool->data[index];
332 // Find a method declared in the cls that is referenced from klass and
333 // perform access checks.
334 _Jv_Method *
335 _Jv_SearchMethodInClass (jclass cls, jclass klass,
336 _Jv_Utf8Const *method_name,
337 _Jv_Utf8Const *method_signature)
339 using namespace java::lang::reflect;
341 for (int i = 0; i < cls->method_count; i++)
343 _Jv_Method *method = &cls->methods[i];
344 if ( (!_Jv_equalUtf8Consts (method->name,
345 method_name))
346 || (!_Jv_equalUtf8Consts (method->signature,
347 method_signature)))
348 continue;
350 if (_Jv_CheckAccess (klass, cls, method->accflags))
351 return method;
352 else
354 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
355 sb->append(klass->getName());
356 sb->append(JvNewStringLatin1(": "));
357 sb->append(cls->getName());
358 sb->append(JvNewStringLatin1("."));
359 sb->append(method_name->toString());
360 sb->append(method_signature->toString());
361 throw new java::lang::IllegalAccessError (sb->toString());
364 return 0;
367 // A helper for _Jv_PrepareClass. This adds missing `Miranda methods'
368 // to a class.
369 void
370 _Jv_PrepareMissingMethods (jclass base, jclass iface_class)
372 _Jv_InterpClass *interp_base = (_Jv_InterpClass *) base->aux_info;
373 for (int i = 0; i < iface_class->interface_count; ++i)
375 for (int j = 0; j < iface_class->interfaces[i]->method_count; ++j)
377 _Jv_Method *meth = &iface_class->interfaces[i]->methods[j];
378 // Don't bother with <clinit>.
379 if (meth->name->first() == '<')
380 continue;
381 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
382 meth->signature);
383 if (! new_meth)
385 // We assume that such methods are very unlikely, so we
386 // just reallocate the method array each time one is
387 // found. This greatly simplifies the searching --
388 // otherwise we have to make sure that each such method
389 // found is really unique among all superinterfaces.
390 int new_count = base->method_count + 1;
391 _Jv_Method *new_m
392 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
393 * new_count);
394 memcpy (new_m, base->methods,
395 sizeof (_Jv_Method) * base->method_count);
397 // Add new method.
398 new_m[base->method_count] = *meth;
399 new_m[base->method_count].index = (_Jv_ushort) -1;
400 new_m[base->method_count].accflags
401 |= java::lang::reflect::Modifier::INVISIBLE;
403 _Jv_MethodBase **new_im
404 = (_Jv_MethodBase **) _Jv_AllocBytes (sizeof (_Jv_MethodBase *)
405 * new_count);
406 memcpy (new_im, interp_base->interpreted_methods,
407 sizeof (_Jv_MethodBase *) * base->method_count);
409 base->methods = new_m;
410 interp_base->interpreted_methods = new_im;
411 base->method_count = new_count;
415 _Jv_PrepareMissingMethods (base, iface_class->interfaces[i]);
419 void
420 _Jv_PrepareClass(jclass klass)
422 using namespace java::lang::reflect;
425 * The job of this function is to: 1) assign storage to fields, and 2)
426 * build the vtable. static fields are assigned real memory, instance
427 * fields are assigned offsets.
429 * NOTE: we have a contract with the garbage collector here. Static
430 * reference fields must not be resolved, until after they have storage
431 * assigned which is the check used by the collector to see if it
432 * should indirect the static field reference and mark the object
433 * pointed to.
435 * Most fields are resolved lazily (i.e. have their class-type
436 * assigned) when they are accessed the first time by calling as part
437 * of _Jv_ResolveField, which is allways called after _Jv_PrepareClass.
438 * Static fields with initializers are resolved as part of this
439 * function, as are fields with primitive types.
442 if (! _Jv_IsInterpretedClass (klass))
443 return;
445 if (klass->state >= JV_STATE_PREPARED)
446 return;
448 // Make sure super-class is linked. This involves taking a lock on
449 // the super class, so we use the Java method resolveClass, which
450 // will unlock it properly, should an exception happen. If there's
451 // no superclass, do nothing -- Object will already have been
452 // resolved.
454 if (klass->superclass)
455 java::lang::VMClassLoader::resolveClass (klass->superclass);
457 _Jv_InterpClass *iclass = (_Jv_InterpClass*)klass->aux_info;
459 /************ PART ONE: OBJECT LAYOUT ***************/
461 // Compute the alignment for this type by searching through the
462 // superclasses and finding the maximum required alignment. We
463 // could consider caching this in the Class.
464 int max_align = __alignof__ (java::lang::Object);
465 jclass super = klass->superclass;
466 while (super != NULL)
468 int num = JvNumInstanceFields (super);
469 _Jv_Field *field = JvGetFirstInstanceField (super);
470 while (num > 0)
472 int field_align = get_alignment_from_class (field->type);
473 if (field_align > max_align)
474 max_align = field_align;
475 ++field;
476 --num;
478 super = super->superclass;
481 int instance_size;
482 int static_size = 0;
484 // Although java.lang.Object is never interpreted, an interface can
485 // have a null superclass. Note that we have to lay out an
486 // interface because it might have static fields.
487 if (klass->superclass)
488 instance_size = klass->superclass->size();
489 else
490 instance_size = java::lang::Object::class$.size();
492 for (int i = 0; i < klass->field_count; i++)
494 int field_size;
495 int field_align;
497 _Jv_Field *field = &klass->fields[i];
499 if (! field->isRef ())
501 // it's safe to resolve the field here, since it's
502 // a primitive class, which does not cause loading to happen.
503 _Jv_ResolveField (field, klass->loader);
505 field_size = field->type->size ();
506 field_align = get_alignment_from_class (field->type);
508 else
510 field_size = sizeof (jobject);
511 field_align = __alignof__ (jobject);
514 #ifndef COMPACT_FIELDS
515 field->bsize = field_size;
516 #endif
518 if (field->flags & Modifier::STATIC)
520 /* this computes an offset into a region we'll allocate
521 shortly, and then add this offset to the start address */
523 static_size = ROUND (static_size, field_align);
524 field->u.boffset = static_size;
525 static_size += field_size;
527 else
529 instance_size = ROUND (instance_size, field_align);
530 field->u.boffset = instance_size;
531 instance_size += field_size;
532 if (field_align > max_align)
533 max_align = field_align;
537 // Set the instance size for the class. Note that first we round it
538 // to the alignment required for this object; this keeps us in sync
539 // with our current ABI.
540 instance_size = ROUND (instance_size, max_align);
541 klass->size_in_bytes = instance_size;
543 // allocate static memory
544 if (static_size != 0)
546 char *static_data = (char*)_Jv_AllocBytes (static_size);
548 memset (static_data, 0, static_size);
550 for (int i = 0; i < klass->field_count; i++)
552 _Jv_Field *field = &klass->fields[i];
554 if ((field->flags & Modifier::STATIC) != 0)
556 field->u.addr = static_data + field->u.boffset;
558 if (iclass->field_initializers[i] != 0)
560 _Jv_ResolveField (field, klass->loader);
561 _Jv_InitField (0, klass, i);
566 // now we don't need the field_initializers anymore, so let the
567 // collector get rid of it!
569 iclass->field_initializers = 0;
572 /************ PART TWO: VTABLE LAYOUT ***************/
574 /* preparation: build the vtable stubs (even interfaces can)
575 have code -- for static constructors. */
576 for (int i = 0; i < klass->method_count; i++)
578 _Jv_MethodBase *imeth = iclass->interpreted_methods[i];
580 if ((klass->methods[i].accflags & Modifier::NATIVE) != 0)
582 // You might think we could use a virtual `ncode' method in
583 // the _Jv_MethodBase and unify the native and non-native
584 // cases. Well, we can't, because we don't allocate these
585 // objects using `new', and thus they don't get a vtable.
586 _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
587 klass->methods[i].ncode = jnim->ncode ();
589 else if (imeth != 0) // it could be abstract
591 _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
592 _Jv_VerifyMethod (im);
593 klass->methods[i].ncode = im->ncode ();
595 // Resolve ctable entries pointing to this method. See
596 // _Jv_Defer_Resolution.
597 void **code = (void **)imeth->deferred;
598 while (code)
600 void **target = (void **)*code;
601 *code = klass->methods[i].ncode;
602 code = target;
607 if ((klass->accflags & Modifier::INTERFACE))
609 klass->state = JV_STATE_PREPARED;
610 klass->notifyAll ();
611 return;
614 // A class might have so-called "Miranda methods". This is a method
615 // that is declared in an interface and not re-declared in an
616 // abstract class. Some compilers don't emit declarations for such
617 // methods in the class; this will give us problems since we expect
618 // a declaration for any method requiring a vtable entry. We handle
619 // this here by searching for such methods and constructing new
620 // internal declarations for them. We only need to do this for
621 // abstract classes.
622 if ((klass->accflags & Modifier::ABSTRACT))
623 _Jv_PrepareMissingMethods (klass, klass);
625 klass->vtable_method_count = -1;
626 _Jv_MakeVTable (klass);
628 /* wooha! we're done. */
629 klass->state = JV_STATE_PREPARED;
630 klass->notifyAll ();
633 /** Do static initialization for fields with a constant initializer */
634 void
635 _Jv_InitField (jobject obj, jclass klass, int index)
637 using namespace java::lang::reflect;
639 if (obj != 0 && klass == 0)
640 klass = obj->getClass ();
642 if (!_Jv_IsInterpretedClass (klass))
643 return;
645 _Jv_InterpClass *iclass = (_Jv_InterpClass*)klass->aux_info;
647 _Jv_Field * field = (&klass->fields[0]) + index;
649 if (index > klass->field_count)
650 throw_internal_error ("field out of range");
652 int init = iclass->field_initializers[index];
653 if (init == 0)
654 return;
656 _Jv_Constants *pool = &klass->constants;
657 int tag = pool->tags[init];
659 if (! field->isResolved ())
660 throw_internal_error ("initializing unresolved field");
662 if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
663 throw_internal_error ("initializing non-static field with no object");
665 void *addr = 0;
667 if ((field->flags & Modifier::STATIC) != 0)
668 addr = (void*) field->u.addr;
669 else
670 addr = (void*) (((char*)obj) + field->u.boffset);
672 switch (tag)
674 case JV_CONSTANT_String:
676 _Jv_MonitorEnter (klass);
677 jstring str;
678 str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
679 pool->data[init].string = str;
680 pool->tags[init] = JV_CONSTANT_ResolvedString;
681 _Jv_MonitorExit (klass);
683 /* fall through */
685 case JV_CONSTANT_ResolvedString:
686 if (! (field->type == &StringClass
687 || field->type == &java::lang::Class::class$))
688 throw_class_format_error ("string initialiser to non-string field");
690 *(jstring*)addr = pool->data[init].string;
691 break;
693 case JV_CONSTANT_Integer:
695 int value = pool->data[init].i;
697 if (field->type == JvPrimClass (boolean))
698 *(jboolean*)addr = (jboolean)value;
700 else if (field->type == JvPrimClass (byte))
701 *(jbyte*)addr = (jbyte)value;
703 else if (field->type == JvPrimClass (char))
704 *(jchar*)addr = (jchar)value;
706 else if (field->type == JvPrimClass (short))
707 *(jshort*)addr = (jshort)value;
709 else if (field->type == JvPrimClass (int))
710 *(jint*)addr = (jint)value;
712 else
713 throw_class_format_error ("erroneous field initializer");
715 break;
717 case JV_CONSTANT_Long:
718 if (field->type != JvPrimClass (long))
719 throw_class_format_error ("erroneous field initializer");
721 *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
722 break;
724 case JV_CONSTANT_Float:
725 if (field->type != JvPrimClass (float))
726 throw_class_format_error ("erroneous field initializer");
728 *(jfloat*)addr = pool->data[init].f;
729 break;
731 case JV_CONSTANT_Double:
732 if (field->type != JvPrimClass (double))
733 throw_class_format_error ("erroneous field initializer");
735 *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
736 break;
738 default:
739 throw_class_format_error ("erroneous field initializer");
743 template<typename T>
744 struct aligner
746 T field;
749 #define ALIGNOF(TYPE) (__alignof__ (((aligner<TYPE> *) 0)->field))
751 // This returns the alignment of a type as it would appear in a
752 // structure. This can be different from the alignment of the type
753 // itself. For instance on x86 double is 8-aligned but struct{double}
754 // is 4-aligned.
755 static int
756 get_alignment_from_class (jclass klass)
758 if (klass == JvPrimClass (byte))
759 return ALIGNOF (jbyte);
760 else if (klass == JvPrimClass (short))
761 return ALIGNOF (jshort);
762 else if (klass == JvPrimClass (int))
763 return ALIGNOF (jint);
764 else if (klass == JvPrimClass (long))
765 return ALIGNOF (jlong);
766 else if (klass == JvPrimClass (boolean))
767 return ALIGNOF (jboolean);
768 else if (klass == JvPrimClass (char))
769 return ALIGNOF (jchar);
770 else if (klass == JvPrimClass (float))
771 return ALIGNOF (jfloat);
772 else if (klass == JvPrimClass (double))
773 return ALIGNOF (jdouble);
774 else
775 return ALIGNOF (jobject);
779 inline static unsigned char*
780 skip_one_type (unsigned char* ptr)
782 int ch = *ptr++;
784 while (ch == '[')
786 ch = *ptr++;
789 if (ch == 'L')
791 do { ch = *ptr++; } while (ch != ';');
794 return ptr;
797 static ffi_type*
798 get_ffi_type_from_signature (unsigned char* ptr)
800 switch (*ptr)
802 case 'L':
803 case '[':
804 return &ffi_type_pointer;
805 break;
807 case 'Z':
808 // On some platforms a bool is a byte, on others an int.
809 if (sizeof (jboolean) == sizeof (jbyte))
810 return &ffi_type_sint8;
811 else
813 JvAssert (sizeof (jbyte) == sizeof (jint));
814 return &ffi_type_sint32;
816 break;
818 case 'B':
819 return &ffi_type_sint8;
820 break;
822 case 'C':
823 return &ffi_type_uint16;
824 break;
826 case 'S':
827 return &ffi_type_sint16;
828 break;
830 case 'I':
831 return &ffi_type_sint32;
832 break;
834 case 'J':
835 return &ffi_type_sint64;
836 break;
838 case 'F':
839 return &ffi_type_float;
840 break;
842 case 'D':
843 return &ffi_type_double;
844 break;
846 case 'V':
847 return &ffi_type_void;
848 break;
851 throw_internal_error ("unknown type in signature");
854 /* this function yields the number of actual arguments, that is, if the
855 * function is non-static, then one is added to the number of elements
856 * found in the signature */
858 int
859 _Jv_count_arguments (_Jv_Utf8Const *signature,
860 jboolean staticp)
862 unsigned char *ptr = (unsigned char*) signature->chars();
863 int arg_count = staticp ? 0 : 1;
865 /* first, count number of arguments */
867 // skip '('
868 ptr++;
870 // count args
871 while (*ptr != ')')
873 ptr = skip_one_type (ptr);
874 arg_count += 1;
877 return arg_count;
880 /* This beast will build a cif, given the signature. Memory for
881 * the cif itself and for the argument types must be allocated by the
882 * caller.
885 static int
886 init_cif (_Jv_Utf8Const* signature,
887 int arg_count,
888 jboolean staticp,
889 ffi_cif *cif,
890 ffi_type **arg_types,
891 ffi_type **rtype_p)
893 unsigned char *ptr = (unsigned char*) signature->chars();
895 int arg_index = 0; // arg number
896 int item_count = 0; // stack-item count
898 // setup receiver
899 if (!staticp)
901 arg_types[arg_index++] = &ffi_type_pointer;
902 item_count += 1;
905 // skip '('
906 ptr++;
908 // assign arg types
909 while (*ptr != ')')
911 arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
913 if (*ptr == 'J' || *ptr == 'D')
914 item_count += 2;
915 else
916 item_count += 1;
918 ptr = skip_one_type (ptr);
921 // skip ')'
922 ptr++;
923 ffi_type *rtype = get_ffi_type_from_signature (ptr);
925 ptr = skip_one_type (ptr);
926 if (ptr != (unsigned char*)signature->chars() + signature->len())
927 throw_internal_error ("did not find end of signature");
929 if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
930 arg_count, rtype, arg_types) != FFI_OK)
931 throw_internal_error ("ffi_prep_cif failed");
933 if (rtype_p != NULL)
934 *rtype_p = rtype;
936 return item_count;
939 #if FFI_NATIVE_RAW_API
940 # define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure
941 # define FFI_RAW_SIZE ffi_raw_size
942 #else
943 # define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure
944 # define FFI_RAW_SIZE ffi_java_raw_size
945 #endif
947 /* we put this one here, and not in interpret.cc because it
948 * calls the utility routines _Jv_count_arguments
949 * which are static to this module. The following struct defines the
950 * layout we use for the stubs, it's only used in the ncode method. */
952 typedef struct {
953 ffi_raw_closure closure;
954 ffi_cif cif;
955 ffi_type *arg_types[0];
956 } ncode_closure;
958 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
960 void *
961 _Jv_InterpMethod::ncode ()
963 using namespace java::lang::reflect;
965 if (self->ncode != 0)
966 return self->ncode;
968 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
969 int arg_count = _Jv_count_arguments (self->signature, staticp);
971 ncode_closure *closure =
972 (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
973 + arg_count * sizeof (ffi_type*));
975 init_cif (self->signature,
976 arg_count,
977 staticp,
978 &closure->cif,
979 &closure->arg_types[0],
980 NULL);
982 ffi_closure_fun fun;
984 args_raw_size = FFI_RAW_SIZE (&closure->cif);
986 JvAssert ((self->accflags & Modifier::NATIVE) == 0);
988 if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
990 if (staticp)
991 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
992 else
993 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object;
995 else
997 if (staticp)
998 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_class;
999 else
1000 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
1003 FFI_PREP_RAW_CLOSURE (&closure->closure,
1004 &closure->cif,
1005 fun,
1006 (void*)this);
1008 self->ncode = (void*)closure;
1009 return self->ncode;
1012 void *
1013 _Jv_JNIMethod::ncode ()
1015 using namespace java::lang::reflect;
1017 if (self->ncode != 0)
1018 return self->ncode;
1020 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1021 int arg_count = _Jv_count_arguments (self->signature, staticp);
1023 ncode_closure *closure =
1024 (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
1025 + arg_count * sizeof (ffi_type*));
1027 ffi_type *rtype;
1028 init_cif (self->signature,
1029 arg_count,
1030 staticp,
1031 &closure->cif,
1032 &closure->arg_types[0],
1033 &rtype);
1035 ffi_closure_fun fun;
1037 args_raw_size = FFI_RAW_SIZE (&closure->cif);
1039 // Initialize the argument types and CIF that represent the actual
1040 // underlying JNI function.
1041 int extra_args = 1;
1042 if ((self->accflags & Modifier::STATIC))
1043 ++extra_args;
1044 jni_arg_types = (ffi_type **) _Jv_Malloc ((extra_args + arg_count)
1045 * sizeof (ffi_type *));
1046 int offset = 0;
1047 jni_arg_types[offset++] = &ffi_type_pointer;
1048 if ((self->accflags & Modifier::STATIC))
1049 jni_arg_types[offset++] = &ffi_type_pointer;
1050 memcpy (&jni_arg_types[offset], &closure->arg_types[0],
1051 arg_count * sizeof (ffi_type *));
1053 if (ffi_prep_cif (&jni_cif, _Jv_platform_ffi_abi,
1054 extra_args + arg_count, rtype,
1055 jni_arg_types) != FFI_OK)
1056 throw_internal_error ("ffi_prep_cif failed for JNI function");
1058 JvAssert ((self->accflags & Modifier::NATIVE) != 0);
1060 // FIXME: for now we assume that all native methods for
1061 // interpreted code use JNI.
1062 fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
1064 FFI_PREP_RAW_CLOSURE (&closure->closure,
1065 &closure->cif,
1066 fun,
1067 (void*) this);
1069 self->ncode = (void *) closure;
1070 return self->ncode;
1074 /* A _Jv_ResolvedMethod is what is put in the constant pool for a
1075 * MethodRef or InterfacemethodRef. */
1076 static _Jv_ResolvedMethod*
1077 _Jv_BuildResolvedMethod (_Jv_Method* method,
1078 jclass klass,
1079 jboolean staticp,
1080 jint vtable_index)
1082 int arg_count = _Jv_count_arguments (method->signature, staticp);
1084 _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
1085 _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
1086 + arg_count*sizeof (ffi_type*));
1088 result->stack_item_count
1089 = init_cif (method->signature,
1090 arg_count,
1091 staticp,
1092 &result->cif,
1093 &result->arg_types[0],
1094 NULL);
1096 result->vtable_index = vtable_index;
1097 result->method = method;
1098 result->klass = klass;
1100 return result;
1104 static void
1105 throw_class_format_error (jstring msg)
1107 throw (msg
1108 ? new java::lang::ClassFormatError (msg)
1109 : new java::lang::ClassFormatError);
1112 static void
1113 throw_class_format_error (char *msg)
1115 throw_class_format_error (JvNewStringLatin1 (msg));
1118 static void
1119 throw_internal_error (char *msg)
1121 throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1125 #endif /* INTERPRETER */