gcc:
[official-gcc.git] / libjava / resolve.cc
blobfbdc284945f9f03ec375d0d9f89fdde6569a5261
1 // resolve.cc - Code for linking and resolving classes and pool entries.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003 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/reflect/Modifier.h>
37 using namespace gcj;
39 void
40 _Jv_ResolveField (_Jv_Field *field, java::lang::ClassLoader *loader)
42 if (! field->isResolved ())
44 _Jv_Utf8Const *sig = (_Jv_Utf8Const*)field->type;
45 field->type = _Jv_FindClassFromSignature (sig->data, loader);
46 field->flags &= ~_Jv_FIELD_UNRESOLVED_FLAG;
50 #ifdef INTERPRETER
52 static void throw_internal_error (char *msg)
53 __attribute__ ((__noreturn__));
54 static void throw_class_format_error (jstring msg)
55 __attribute__ ((__noreturn__));
56 static void throw_class_format_error (char *msg)
57 __attribute__ ((__noreturn__));
59 static int get_alignment_from_class (jclass);
61 static _Jv_ResolvedMethod*
62 _Jv_BuildResolvedMethod (_Jv_Method*,
63 jclass,
64 jboolean,
65 jint);
68 static void throw_incompatible_class_change_error (jstring msg)
70 throw new java::lang::IncompatibleClassChangeError (msg);
73 _Jv_word
74 _Jv_ResolvePoolEntry (jclass klass, int index)
76 using namespace java::lang::reflect;
78 _Jv_Constants *pool = &klass->constants;
80 if ((pool->tags[index] & JV_CONSTANT_ResolvedFlag) != 0)
81 return pool->data[index];
83 switch (pool->tags[index]) {
84 case JV_CONSTANT_Class:
86 _Jv_Utf8Const *name = pool->data[index].utf8;
88 jclass found;
89 if (name->data[0] == '[')
90 found = _Jv_FindClassFromSignature (&name->data[0],
91 klass->loader);
92 else
93 found = _Jv_FindClass (name, klass->loader);
95 if (! found)
97 jstring str = _Jv_NewStringUTF (name->data);
98 // This exception is specified in JLS 2nd Ed, section 5.1.
99 throw new java::lang::NoClassDefFoundError (str);
102 if ((found->accflags & Modifier::PUBLIC) == Modifier::PUBLIC
103 || (_Jv_ClassNameSamePackage (found->name,
104 klass->name)))
106 pool->data[index].clazz = found;
107 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
109 else
111 throw new java::lang::IllegalAccessError (found->getName());
114 break;
116 case JV_CONSTANT_String:
118 jstring str;
119 str = _Jv_NewStringUtf8Const (pool->data[index].utf8);
120 pool->data[index].o = str;
121 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
123 break;
126 case JV_CONSTANT_Fieldref:
128 _Jv_ushort class_index, name_and_type_index;
129 _Jv_loadIndexes (&pool->data[index],
130 class_index,
131 name_and_type_index);
132 jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
134 if (owner != klass)
135 _Jv_InitClass (owner);
137 _Jv_ushort name_index, type_index;
138 _Jv_loadIndexes (&pool->data[name_and_type_index],
139 name_index,
140 type_index);
142 _Jv_Utf8Const *field_name = pool->data[name_index].utf8;
143 _Jv_Utf8Const *field_type_name = pool->data[type_index].utf8;
145 // FIXME: The implementation of this function
146 // (_Jv_FindClassFromSignature) will generate an instance of
147 // _Jv_Utf8Const for each call if the field type is a class name
148 // (Lxx.yy.Z;). This may be too expensive to do for each and
149 // every fieldref being resolved. For now, we fix the problem by
150 // only doing it when we have a loader different from the class
151 // declaring the field.
153 jclass field_type = 0;
155 if (owner->loader != klass->loader)
156 field_type = _Jv_FindClassFromSignature (field_type_name->data,
157 klass->loader);
159 _Jv_Field* the_field = 0;
161 for (jclass cls = owner; cls != 0; cls = cls->getSuperclass ())
163 for (int i = 0; i < cls->field_count; i++)
165 _Jv_Field *field = &cls->fields[i];
166 if (! _Jv_equalUtf8Consts (field->name, field_name))
167 continue;
169 // now, check field access.
171 if ( (cls == klass)
172 || ((field->flags & Modifier::PUBLIC) != 0)
173 || (((field->flags & Modifier::PROTECTED) != 0)
174 && cls->isAssignableFrom (klass))
175 || (((field->flags & Modifier::PRIVATE) == 0)
176 && _Jv_ClassNameSamePackage (cls->name,
177 klass->name)))
179 /* resove the field using the class' own loader
180 if necessary */
182 if (!field->isResolved ())
183 _Jv_ResolveField (field, cls->loader);
185 if (field_type != 0 && field->type != field_type)
186 throw new java::lang::LinkageError
187 (JvNewStringLatin1
188 ("field type mismatch with different loaders"));
190 the_field = field;
191 goto end_of_field_search;
193 else
195 throw new java::lang::IllegalAccessError;
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(_Jv_NewStringUTF(field_name->data));
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(_Jv_NewStringUTF(method_name->data));
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 (cls == klass
351 || ((method->accflags & Modifier::PUBLIC) != 0)
352 || (((method->accflags & Modifier::PROTECTED) != 0)
353 && cls->isAssignableFrom (klass))
354 || (((method->accflags & Modifier::PRIVATE) == 0)
355 && _Jv_ClassNameSamePackage (cls->name,
356 klass->name)))
358 return method;
360 else
362 throw new java::lang::IllegalAccessError;
365 return 0;
368 // A helper for _Jv_PrepareClass. This adds missing `Miranda methods'
369 // to a class.
370 void
371 _Jv_PrepareMissingMethods (jclass base2, jclass iface_class)
373 _Jv_InterpClass *base = reinterpret_cast<_Jv_InterpClass *> (base2);
374 for (int i = 0; i < iface_class->interface_count; ++i)
376 for (int j = 0; j < iface_class->interfaces[i]->method_count; ++j)
378 _Jv_Method *meth = &iface_class->interfaces[i]->methods[j];
379 // Don't bother with <clinit>.
380 if (meth->name->data[0] == '<')
381 continue;
382 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
383 meth->signature);
384 if (! new_meth)
386 // We assume that such methods are very unlikely, so we
387 // just reallocate the method array each time one is
388 // found. This greatly simplifies the searching --
389 // otherwise we have to make sure that each such method
390 // found is really unique among all superinterfaces.
391 int new_count = base->method_count + 1;
392 _Jv_Method *new_m
393 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
394 * new_count);
395 memcpy (new_m, base->methods,
396 sizeof (_Jv_Method) * base->method_count);
398 // Add new method.
399 new_m[base->method_count] = *meth;
400 new_m[base->method_count].index = (_Jv_ushort) -1;
401 new_m[base->method_count].accflags
402 |= java::lang::reflect::Modifier::INVISIBLE;
404 _Jv_MethodBase **new_im
405 = (_Jv_MethodBase **) _Jv_AllocBytes (sizeof (_Jv_MethodBase *)
406 * new_count);
407 memcpy (new_im, base->interpreted_methods,
408 sizeof (_Jv_MethodBase *) * base->method_count);
410 base->methods = new_m;
411 base->interpreted_methods = new_im;
412 base->method_count = new_count;
416 _Jv_PrepareMissingMethods (base, iface_class->interfaces[i]);
420 void
421 _Jv_PrepareClass(jclass klass)
423 using namespace java::lang::reflect;
426 * The job of this function is to: 1) assign storage to fields, and 2)
427 * build the vtable. static fields are assigned real memory, instance
428 * fields are assigned offsets.
430 * NOTE: we have a contract with the garbage collector here. Static
431 * reference fields must not be resolved, until after they have storage
432 * assigned which is the check used by the collector to see if it
433 * should indirect the static field reference and mark the object
434 * pointed to.
436 * Most fields are resolved lazily (i.e. have their class-type
437 * assigned) when they are accessed the first time by calling as part
438 * of _Jv_ResolveField, which is allways called after _Jv_PrepareClass.
439 * Static fields with initializers are resolved as part of this
440 * function, as are fields with primitive types.
443 if (! _Jv_IsInterpretedClass (klass))
444 return;
446 if (klass->state >= JV_STATE_PREPARED)
447 return;
449 // Make sure super-class is linked. This involves taking a lock on
450 // the super class, so we use the Java method resolveClass, which
451 // will unlock it properly, should an exception happen. If there's
452 // no superclass, do nothing -- Object will already have been
453 // resolved.
455 if (klass->superclass)
456 java::lang::ClassLoader::resolveClass0 (klass->superclass);
458 _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
460 /************ PART ONE: OBJECT LAYOUT ***************/
462 int instance_size;
463 int static_size;
465 // Although java.lang.Object is never interpreted, an interface can
466 // have a null superclass.
467 if (clz->superclass)
468 instance_size = clz->superclass->size();
469 else
470 instance_size = java::lang::Object::class$.size();
471 static_size = 0;
473 for (int i = 0; i < clz->field_count; i++)
475 int field_size;
476 int field_align;
478 _Jv_Field *field = &clz->fields[i];
480 if (! field->isRef ())
482 // it's safe to resolve the field here, since it's
483 // a primitive class, which does not cause loading to happen.
484 _Jv_ResolveField (field, clz->loader);
486 field_size = field->type->size ();
487 field_align = get_alignment_from_class (field->type);
489 else
491 field_size = sizeof (jobject);
492 field_align = __alignof__ (jobject);
495 #ifndef COMPACT_FIELDS
496 field->bsize = field_size;
497 #endif
499 if (field->flags & Modifier::STATIC)
501 /* this computes an offset into a region we'll allocate
502 shortly, and then add this offset to the start address */
504 static_size = ROUND (static_size, field_align);
505 field->u.boffset = static_size;
506 static_size += field_size;
508 else
510 instance_size = ROUND (instance_size, field_align);
511 field->u.boffset = instance_size;
512 instance_size += field_size;
516 // Set the instance size for the class. Note that first we round it
517 // to the alignment required for Object; this keeps us in sync with
518 // our current ABI.
519 instance_size = ROUND (instance_size, __alignof__ (java::lang::Object));
520 clz->size_in_bytes = instance_size;
522 // allocate static memory
523 if (static_size != 0)
525 char *static_data = (char*)_Jv_AllocBytes (static_size);
527 memset (static_data, 0, static_size);
529 for (int i = 0; i < clz->field_count; i++)
531 _Jv_Field *field = &clz->fields[i];
533 if ((field->flags & Modifier::STATIC) != 0)
535 field->u.addr = static_data + field->u.boffset;
537 if (clz->field_initializers[i] != 0)
539 _Jv_ResolveField (field, clz->loader);
540 _Jv_InitField (0, clz, i);
545 // now we don't need the field_initializers anymore, so let the
546 // collector get rid of it!
548 clz->field_initializers = 0;
551 /************ PART TWO: VTABLE LAYOUT ***************/
553 /* preparation: build the vtable stubs (even interfaces can)
554 have code -- for static constructors. */
555 for (int i = 0; i < clz->method_count; i++)
557 _Jv_MethodBase *imeth = clz->interpreted_methods[i];
559 if ((clz->methods[i].accflags & Modifier::NATIVE) != 0)
561 // You might think we could use a virtual `ncode' method in
562 // the _Jv_MethodBase and unify the native and non-native
563 // cases. Well, we can't, because we don't allocate these
564 // objects using `new', and thus they don't get a vtable.
565 _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
566 clz->methods[i].ncode = jnim->ncode ();
568 else if (imeth != 0) // it could be abstract
570 _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
571 _Jv_VerifyMethod (im);
572 clz->methods[i].ncode = im->ncode ();
576 if ((clz->accflags & Modifier::INTERFACE))
578 clz->state = JV_STATE_PREPARED;
579 clz->notifyAll ();
580 return;
583 // A class might have so-called "Miranda methods". This is a method
584 // that is declared in an interface and not re-declared in an
585 // abstract class. Some compilers don't emit declarations for such
586 // methods in the class; this will give us problems since we expect
587 // a declaration for any method requiring a vtable entry. We handle
588 // this here by searching for such methods and constructing new
589 // internal declarations for them. We only need to do this for
590 // abstract classes.
591 if ((clz->accflags & Modifier::ABSTRACT))
592 _Jv_PrepareMissingMethods (clz, clz);
594 clz->vtable_method_count = -1;
595 _Jv_MakeVTable (clz);
597 /* wooha! we're done. */
598 clz->state = JV_STATE_PREPARED;
599 clz->notifyAll ();
602 /** Do static initialization for fields with a constant initializer */
603 void
604 _Jv_InitField (jobject obj, jclass klass, int index)
606 using namespace java::lang::reflect;
608 if (obj != 0 && klass == 0)
609 klass = obj->getClass ();
611 if (!_Jv_IsInterpretedClass (klass))
612 return;
614 _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
616 _Jv_Field * field = (&clz->fields[0]) + index;
618 if (index > clz->field_count)
619 throw_internal_error ("field out of range");
621 int init = clz->field_initializers[index];
622 if (init == 0)
623 return;
625 _Jv_Constants *pool = &clz->constants;
626 int tag = pool->tags[init];
628 if (! field->isResolved ())
629 throw_internal_error ("initializing unresolved field");
631 if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
632 throw_internal_error ("initializing non-static field with no object");
634 void *addr = 0;
636 if ((field->flags & Modifier::STATIC) != 0)
637 addr = (void*) field->u.addr;
638 else
639 addr = (void*) (((char*)obj) + field->u.boffset);
641 switch (tag)
643 case JV_CONSTANT_String:
645 _Jv_MonitorEnter (clz);
646 jstring str;
647 str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
648 pool->data[init].string = str;
649 pool->tags[init] = JV_CONSTANT_ResolvedString;
650 _Jv_MonitorExit (clz);
652 /* fall through */
654 case JV_CONSTANT_ResolvedString:
655 if (! (field->type == &StringClass
656 || field->type == &java::lang::Class::class$))
657 throw_class_format_error ("string initialiser to non-string field");
659 *(jstring*)addr = pool->data[init].string;
660 break;
662 case JV_CONSTANT_Integer:
664 int value = pool->data[init].i;
666 if (field->type == JvPrimClass (boolean))
667 *(jboolean*)addr = (jboolean)value;
669 else if (field->type == JvPrimClass (byte))
670 *(jbyte*)addr = (jbyte)value;
672 else if (field->type == JvPrimClass (char))
673 *(jchar*)addr = (jchar)value;
675 else if (field->type == JvPrimClass (short))
676 *(jshort*)addr = (jshort)value;
678 else if (field->type == JvPrimClass (int))
679 *(jint*)addr = (jint)value;
681 else
682 throw_class_format_error ("erroneous field initializer");
684 break;
686 case JV_CONSTANT_Long:
687 if (field->type != JvPrimClass (long))
688 throw_class_format_error ("erroneous field initializer");
690 *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
691 break;
693 case JV_CONSTANT_Float:
694 if (field->type != JvPrimClass (float))
695 throw_class_format_error ("erroneous field initializer");
697 *(jfloat*)addr = pool->data[init].f;
698 break;
700 case JV_CONSTANT_Double:
701 if (field->type != JvPrimClass (double))
702 throw_class_format_error ("erroneous field initializer");
704 *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
705 break;
707 default:
708 throw_class_format_error ("erroneous field initializer");
712 static int
713 get_alignment_from_class (jclass klass)
715 if (klass == JvPrimClass (byte))
716 return __alignof__ (jbyte);
717 else if (klass == JvPrimClass (short))
718 return __alignof__ (jshort);
719 else if (klass == JvPrimClass (int))
720 return __alignof__ (jint);
721 else if (klass == JvPrimClass (long))
722 return __alignof__ (jlong);
723 else if (klass == JvPrimClass (boolean))
724 return __alignof__ (jboolean);
725 else if (klass == JvPrimClass (char))
726 return __alignof__ (jchar);
727 else if (klass == JvPrimClass (float))
728 return __alignof__ (jfloat);
729 else if (klass == JvPrimClass (double))
730 return __alignof__ (jdouble);
731 else
732 return __alignof__ (jobject);
736 inline static unsigned char*
737 skip_one_type (unsigned char* ptr)
739 int ch = *ptr++;
741 while (ch == '[')
743 ch = *ptr++;
746 if (ch == 'L')
748 do { ch = *ptr++; } while (ch != ';');
751 return ptr;
754 static ffi_type*
755 get_ffi_type_from_signature (unsigned char* ptr)
757 switch (*ptr)
759 case 'L':
760 case '[':
761 return &ffi_type_pointer;
762 break;
764 case 'Z':
765 // On some platforms a bool is a byte, on others an int.
766 if (sizeof (jboolean) == sizeof (jbyte))
767 return &ffi_type_sint8;
768 else
770 JvAssert (sizeof (jbyte) == sizeof (jint));
771 return &ffi_type_sint32;
773 break;
775 case 'B':
776 return &ffi_type_sint8;
777 break;
779 case 'C':
780 return &ffi_type_uint16;
781 break;
783 case 'S':
784 return &ffi_type_sint16;
785 break;
787 case 'I':
788 return &ffi_type_sint32;
789 break;
791 case 'J':
792 return &ffi_type_sint64;
793 break;
795 case 'F':
796 return &ffi_type_float;
797 break;
799 case 'D':
800 return &ffi_type_double;
801 break;
803 case 'V':
804 return &ffi_type_void;
805 break;
808 throw_internal_error ("unknown type in signature");
811 /* this function yields the number of actual arguments, that is, if the
812 * function is non-static, then one is added to the number of elements
813 * found in the signature */
815 int
816 _Jv_count_arguments (_Jv_Utf8Const *signature,
817 jboolean staticp)
819 unsigned char *ptr = (unsigned char*) signature->data;
820 int arg_count = staticp ? 0 : 1;
822 /* first, count number of arguments */
824 // skip '('
825 ptr++;
827 // count args
828 while (*ptr != ')')
830 ptr = skip_one_type (ptr);
831 arg_count += 1;
834 return arg_count;
837 /* This beast will build a cif, given the signature. Memory for
838 * the cif itself and for the argument types must be allocated by the
839 * caller.
842 static int
843 init_cif (_Jv_Utf8Const* signature,
844 int arg_count,
845 jboolean staticp,
846 ffi_cif *cif,
847 ffi_type **arg_types,
848 ffi_type **rtype_p)
850 unsigned char *ptr = (unsigned char*) signature->data;
852 int arg_index = 0; // arg number
853 int item_count = 0; // stack-item count
855 // setup receiver
856 if (!staticp)
858 arg_types[arg_index++] = &ffi_type_pointer;
859 item_count += 1;
862 // skip '('
863 ptr++;
865 // assign arg types
866 while (*ptr != ')')
868 arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
870 if (*ptr == 'J' || *ptr == 'D')
871 item_count += 2;
872 else
873 item_count += 1;
875 ptr = skip_one_type (ptr);
878 // skip ')'
879 ptr++;
880 ffi_type *rtype = get_ffi_type_from_signature (ptr);
882 ptr = skip_one_type (ptr);
883 if (ptr != (unsigned char*)signature->data + signature->length)
884 throw_internal_error ("did not find end of signature");
886 if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
887 arg_count, rtype, arg_types) != FFI_OK)
888 throw_internal_error ("ffi_prep_cif failed");
890 if (rtype_p != NULL)
891 *rtype_p = rtype;
893 return item_count;
896 #if FFI_NATIVE_RAW_API
897 # define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure
898 # define FFI_RAW_SIZE ffi_raw_size
899 #else
900 # define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure
901 # define FFI_RAW_SIZE ffi_java_raw_size
902 #endif
904 /* we put this one here, and not in interpret.cc because it
905 * calls the utility routines _Jv_count_arguments
906 * which are static to this module. The following struct defines the
907 * layout we use for the stubs, it's only used in the ncode method. */
909 typedef struct {
910 ffi_raw_closure closure;
911 ffi_cif cif;
912 ffi_type *arg_types[0];
913 } ncode_closure;
915 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
917 void *
918 _Jv_InterpMethod::ncode ()
920 using namespace java::lang::reflect;
922 if (self->ncode != 0)
923 return self->ncode;
925 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
926 int arg_count = _Jv_count_arguments (self->signature, staticp);
928 ncode_closure *closure =
929 (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
930 + arg_count * sizeof (ffi_type*));
932 init_cif (self->signature,
933 arg_count,
934 staticp,
935 &closure->cif,
936 &closure->arg_types[0],
937 NULL);
939 ffi_closure_fun fun;
941 args_raw_size = FFI_RAW_SIZE (&closure->cif);
943 JvAssert ((self->accflags & Modifier::NATIVE) == 0);
945 if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
947 if (staticp)
948 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
949 else
950 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object;
952 else
954 if (staticp)
955 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_class;
956 else
957 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
960 FFI_PREP_RAW_CLOSURE (&closure->closure,
961 &closure->cif,
962 fun,
963 (void*)this);
965 self->ncode = (void*)closure;
966 return self->ncode;
969 void *
970 _Jv_JNIMethod::ncode ()
972 using namespace java::lang::reflect;
974 if (self->ncode != 0)
975 return self->ncode;
977 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
978 int arg_count = _Jv_count_arguments (self->signature, staticp);
980 ncode_closure *closure =
981 (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
982 + arg_count * sizeof (ffi_type*));
984 ffi_type *rtype;
985 init_cif (self->signature,
986 arg_count,
987 staticp,
988 &closure->cif,
989 &closure->arg_types[0],
990 &rtype);
992 ffi_closure_fun fun;
994 args_raw_size = FFI_RAW_SIZE (&closure->cif);
996 // Initialize the argument types and CIF that represent the actual
997 // underlying JNI function.
998 int extra_args = 1;
999 if ((self->accflags & Modifier::STATIC))
1000 ++extra_args;
1001 jni_arg_types = (ffi_type **) _Jv_Malloc ((extra_args + arg_count)
1002 * sizeof (ffi_type *));
1003 int offset = 0;
1004 jni_arg_types[offset++] = &ffi_type_pointer;
1005 if ((self->accflags & Modifier::STATIC))
1006 jni_arg_types[offset++] = &ffi_type_pointer;
1007 memcpy (&jni_arg_types[offset], &closure->arg_types[0],
1008 arg_count * sizeof (ffi_type *));
1010 if (ffi_prep_cif (&jni_cif, _Jv_platform_ffi_abi,
1011 extra_args + arg_count, rtype,
1012 jni_arg_types) != FFI_OK)
1013 throw_internal_error ("ffi_prep_cif failed for JNI function");
1015 JvAssert ((self->accflags & Modifier::NATIVE) != 0);
1017 // FIXME: for now we assume that all native methods for
1018 // interpreted code use JNI.
1019 fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
1021 FFI_PREP_RAW_CLOSURE (&closure->closure,
1022 &closure->cif,
1023 fun,
1024 (void*) this);
1026 self->ncode = (void *) closure;
1027 return self->ncode;
1031 /* A _Jv_ResolvedMethod is what is put in the constant pool for a
1032 * MethodRef or InterfacemethodRef. */
1033 static _Jv_ResolvedMethod*
1034 _Jv_BuildResolvedMethod (_Jv_Method* method,
1035 jclass klass,
1036 jboolean staticp,
1037 jint vtable_index)
1039 int arg_count = _Jv_count_arguments (method->signature, staticp);
1041 _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
1042 _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
1043 + arg_count*sizeof (ffi_type*));
1045 result->stack_item_count
1046 = init_cif (method->signature,
1047 arg_count,
1048 staticp,
1049 &result->cif,
1050 &result->arg_types[0],
1051 NULL);
1053 result->vtable_index = vtable_index;
1054 result->method = method;
1055 result->klass = klass;
1057 return result;
1061 static void
1062 throw_class_format_error (jstring msg)
1064 throw (msg
1065 ? new java::lang::ClassFormatError (msg)
1066 : new java::lang::ClassFormatError);
1069 static void
1070 throw_class_format_error (char *msg)
1072 throw_class_format_error (JvNewStringLatin1 (msg));
1075 static void
1076 throw_internal_error (char *msg)
1078 throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1082 #endif /* INTERPRETER */