PR c++/11595
[official-gcc.git] / libjava / resolve.cc
blobd79affea9ebc3f8cad80906b785e8019f9d0ed01
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 if (_Jv_CheckAccess (klass, cls, field->flags))
171 /* resove the field using the class' own loader
172 if necessary */
174 if (!field->isResolved ())
175 _Jv_ResolveField (field, cls->loader);
177 if (field_type != 0 && field->type != field_type)
178 throw new java::lang::LinkageError
179 (JvNewStringLatin1
180 ("field type mismatch with different loaders"));
182 the_field = field;
183 goto end_of_field_search;
185 else
187 throw new java::lang::IllegalAccessError;
192 end_of_field_search:
193 if (the_field == 0)
195 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
196 sb->append(JvNewStringLatin1("field "));
197 sb->append(owner->getName());
198 sb->append(JvNewStringLatin1("."));
199 sb->append(_Jv_NewStringUTF(field_name->data));
200 sb->append(JvNewStringLatin1(" was not found."));
201 throw_incompatible_class_change_error(sb->toString());
204 pool->data[index].field = the_field;
205 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
207 break;
209 case JV_CONSTANT_Methodref:
210 case JV_CONSTANT_InterfaceMethodref:
212 _Jv_ushort class_index, name_and_type_index;
213 _Jv_loadIndexes (&pool->data[index],
214 class_index,
215 name_and_type_index);
216 jclass owner = (_Jv_ResolvePoolEntry (klass, class_index)).clazz;
218 if (owner != klass)
219 _Jv_InitClass (owner);
221 _Jv_ushort name_index, type_index;
222 _Jv_loadIndexes (&pool->data[name_and_type_index],
223 name_index,
224 type_index);
226 _Jv_Utf8Const *method_name = pool->data[name_index].utf8;
227 _Jv_Utf8Const *method_signature = pool->data[type_index].utf8;
229 _Jv_Method *the_method = 0;
230 jclass found_class = 0;
232 // First search the class itself.
233 the_method = _Jv_SearchMethodInClass (owner, klass,
234 method_name, method_signature);
236 if (the_method != 0)
238 found_class = owner;
239 goto end_of_method_search;
242 // If we are resolving an interface method, search the
243 // interface's superinterfaces (A superinterface is not an
244 // interface's superclass - a superinterface is implemented by
245 // the interface).
246 if (pool->tags[index] == JV_CONSTANT_InterfaceMethodref)
248 _Jv_ifaces ifaces;
249 ifaces.count = 0;
250 ifaces.len = 4;
251 ifaces.list = (jclass *) _Jv_Malloc (ifaces.len * sizeof (jclass *));
253 _Jv_GetInterfaces (owner, &ifaces);
255 for (int i = 0; i < ifaces.count; i++)
257 jclass cls = ifaces.list[i];
258 the_method = _Jv_SearchMethodInClass (cls, klass, method_name,
259 method_signature);
260 if (the_method != 0)
262 found_class = cls;
263 break;
267 _Jv_Free (ifaces.list);
269 if (the_method != 0)
270 goto end_of_method_search;
273 // Finally, search superclasses.
274 for (jclass cls = owner->getSuperclass (); cls != 0;
275 cls = cls->getSuperclass ())
277 the_method = _Jv_SearchMethodInClass (cls, klass,
278 method_name, method_signature);
279 if (the_method != 0)
281 found_class = cls;
282 break;
286 end_of_method_search:
288 // FIXME: if (cls->loader != klass->loader), then we
289 // must actually check that the types of arguments
290 // correspond. That is, for each argument type, and
291 // the return type, doing _Jv_FindClassFromSignature
292 // with either loader should produce the same result,
293 // i.e., exactly the same jclass object. JVMS 5.4.3.3
295 if (the_method == 0)
297 java::lang::StringBuffer *sb = new java::lang::StringBuffer();
298 sb->append(JvNewStringLatin1("method "));
299 sb->append(owner->getName());
300 sb->append(JvNewStringLatin1("."));
301 sb->append(_Jv_NewStringUTF(method_name->data));
302 sb->append(JvNewStringLatin1(" was not found."));
303 throw new java::lang::NoSuchMethodError (sb->toString());
306 int vtable_index = -1;
307 if (pool->tags[index] != JV_CONSTANT_InterfaceMethodref)
308 vtable_index = (jshort)the_method->index;
310 pool->data[index].rmethod =
311 _Jv_BuildResolvedMethod(the_method,
312 found_class,
313 (the_method->accflags & Modifier::STATIC) != 0,
314 vtable_index);
315 pool->tags[index] |= JV_CONSTANT_ResolvedFlag;
317 break;
321 return pool->data[index];
324 // Find a method declared in the cls that is referenced from klass and
325 // perform access checks.
326 _Jv_Method *
327 _Jv_SearchMethodInClass (jclass cls, jclass klass,
328 _Jv_Utf8Const *method_name,
329 _Jv_Utf8Const *method_signature)
331 using namespace java::lang::reflect;
333 for (int i = 0; i < cls->method_count; i++)
335 _Jv_Method *method = &cls->methods[i];
336 if ( (!_Jv_equalUtf8Consts (method->name,
337 method_name))
338 || (!_Jv_equalUtf8Consts (method->signature,
339 method_signature)))
340 continue;
342 if (_Jv_CheckAccess (klass, cls, method->accflags))
343 return method;
344 else
345 throw new java::lang::IllegalAccessError;
347 return 0;
350 // A helper for _Jv_PrepareClass. This adds missing `Miranda methods'
351 // to a class.
352 void
353 _Jv_PrepareMissingMethods (jclass base2, jclass iface_class)
355 _Jv_InterpClass *base = reinterpret_cast<_Jv_InterpClass *> (base2);
356 for (int i = 0; i < iface_class->interface_count; ++i)
358 for (int j = 0; j < iface_class->interfaces[i]->method_count; ++j)
360 _Jv_Method *meth = &iface_class->interfaces[i]->methods[j];
361 // Don't bother with <clinit>.
362 if (meth->name->data[0] == '<')
363 continue;
364 _Jv_Method *new_meth = _Jv_LookupDeclaredMethod (base, meth->name,
365 meth->signature);
366 if (! new_meth)
368 // We assume that such methods are very unlikely, so we
369 // just reallocate the method array each time one is
370 // found. This greatly simplifies the searching --
371 // otherwise we have to make sure that each such method
372 // found is really unique among all superinterfaces.
373 int new_count = base->method_count + 1;
374 _Jv_Method *new_m
375 = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method)
376 * new_count);
377 memcpy (new_m, base->methods,
378 sizeof (_Jv_Method) * base->method_count);
380 // Add new method.
381 new_m[base->method_count] = *meth;
382 new_m[base->method_count].index = (_Jv_ushort) -1;
383 new_m[base->method_count].accflags
384 |= java::lang::reflect::Modifier::INVISIBLE;
386 _Jv_MethodBase **new_im
387 = (_Jv_MethodBase **) _Jv_AllocBytes (sizeof (_Jv_MethodBase *)
388 * new_count);
389 memcpy (new_im, base->interpreted_methods,
390 sizeof (_Jv_MethodBase *) * base->method_count);
392 base->methods = new_m;
393 base->interpreted_methods = new_im;
394 base->method_count = new_count;
398 _Jv_PrepareMissingMethods (base, iface_class->interfaces[i]);
402 void
403 _Jv_PrepareClass(jclass klass)
405 using namespace java::lang::reflect;
408 * The job of this function is to: 1) assign storage to fields, and 2)
409 * build the vtable. static fields are assigned real memory, instance
410 * fields are assigned offsets.
412 * NOTE: we have a contract with the garbage collector here. Static
413 * reference fields must not be resolved, until after they have storage
414 * assigned which is the check used by the collector to see if it
415 * should indirect the static field reference and mark the object
416 * pointed to.
418 * Most fields are resolved lazily (i.e. have their class-type
419 * assigned) when they are accessed the first time by calling as part
420 * of _Jv_ResolveField, which is allways called after _Jv_PrepareClass.
421 * Static fields with initializers are resolved as part of this
422 * function, as are fields with primitive types.
425 if (! _Jv_IsInterpretedClass (klass))
426 return;
428 if (klass->state >= JV_STATE_PREPARED)
429 return;
431 // Make sure super-class is linked. This involves taking a lock on
432 // the super class, so we use the Java method resolveClass, which
433 // will unlock it properly, should an exception happen. If there's
434 // no superclass, do nothing -- Object will already have been
435 // resolved.
437 if (klass->superclass)
438 java::lang::ClassLoader::resolveClass0 (klass->superclass);
440 _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
442 /************ PART ONE: OBJECT LAYOUT ***************/
444 // Compute the alignment for this type by searching through the
445 // superclasses and finding the maximum required alignment. We
446 // could consider caching this in the Class.
447 int max_align = __alignof__ (java::lang::Object);
448 jclass super = clz->superclass;
449 while (super != NULL)
451 int num = JvNumInstanceFields (super);
452 _Jv_Field *field = JvGetFirstInstanceField (super);
453 while (num > 0)
455 int field_align = get_alignment_from_class (field->type);
456 if (field_align > max_align)
457 max_align = field_align;
458 ++field;
459 --num;
461 super = super->superclass;
464 int instance_size;
465 int static_size = 0;
467 // Although java.lang.Object is never interpreted, an interface can
468 // have a null superclass. Note that we have to lay out an
469 // interface because it might have static fields.
470 if (clz->superclass)
471 instance_size = clz->superclass->size();
472 else
473 instance_size = java::lang::Object::class$.size();
475 for (int i = 0; i < clz->field_count; i++)
477 int field_size;
478 int field_align;
480 _Jv_Field *field = &clz->fields[i];
482 if (! field->isRef ())
484 // it's safe to resolve the field here, since it's
485 // a primitive class, which does not cause loading to happen.
486 _Jv_ResolveField (field, clz->loader);
488 field_size = field->type->size ();
489 field_align = get_alignment_from_class (field->type);
491 else
493 field_size = sizeof (jobject);
494 field_align = __alignof__ (jobject);
497 #ifndef COMPACT_FIELDS
498 field->bsize = field_size;
499 #endif
501 if (field->flags & Modifier::STATIC)
503 /* this computes an offset into a region we'll allocate
504 shortly, and then add this offset to the start address */
506 static_size = ROUND (static_size, field_align);
507 field->u.boffset = static_size;
508 static_size += field_size;
510 else
512 instance_size = ROUND (instance_size, field_align);
513 field->u.boffset = instance_size;
514 instance_size += field_size;
515 if (field_align > max_align)
516 max_align = field_align;
520 // Set the instance size for the class. Note that first we round it
521 // to the alignment required for this object; this keeps us in sync
522 // with our current ABI.
523 instance_size = ROUND (instance_size, max_align);
524 clz->size_in_bytes = instance_size;
526 // allocate static memory
527 if (static_size != 0)
529 char *static_data = (char*)_Jv_AllocBytes (static_size);
531 memset (static_data, 0, static_size);
533 for (int i = 0; i < clz->field_count; i++)
535 _Jv_Field *field = &clz->fields[i];
537 if ((field->flags & Modifier::STATIC) != 0)
539 field->u.addr = static_data + field->u.boffset;
541 if (clz->field_initializers[i] != 0)
543 _Jv_ResolveField (field, clz->loader);
544 _Jv_InitField (0, clz, i);
549 // now we don't need the field_initializers anymore, so let the
550 // collector get rid of it!
552 clz->field_initializers = 0;
555 /************ PART TWO: VTABLE LAYOUT ***************/
557 /* preparation: build the vtable stubs (even interfaces can)
558 have code -- for static constructors. */
559 for (int i = 0; i < clz->method_count; i++)
561 _Jv_MethodBase *imeth = clz->interpreted_methods[i];
563 if ((clz->methods[i].accflags & Modifier::NATIVE) != 0)
565 // You might think we could use a virtual `ncode' method in
566 // the _Jv_MethodBase and unify the native and non-native
567 // cases. Well, we can't, because we don't allocate these
568 // objects using `new', and thus they don't get a vtable.
569 _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
570 clz->methods[i].ncode = jnim->ncode ();
572 else if (imeth != 0) // it could be abstract
574 _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
575 _Jv_VerifyMethod (im);
576 clz->methods[i].ncode = im->ncode ();
580 if ((clz->accflags & Modifier::INTERFACE))
582 clz->state = JV_STATE_PREPARED;
583 clz->notifyAll ();
584 return;
587 // A class might have so-called "Miranda methods". This is a method
588 // that is declared in an interface and not re-declared in an
589 // abstract class. Some compilers don't emit declarations for such
590 // methods in the class; this will give us problems since we expect
591 // a declaration for any method requiring a vtable entry. We handle
592 // this here by searching for such methods and constructing new
593 // internal declarations for them. We only need to do this for
594 // abstract classes.
595 if ((clz->accflags & Modifier::ABSTRACT))
596 _Jv_PrepareMissingMethods (clz, clz);
598 clz->vtable_method_count = -1;
599 _Jv_MakeVTable (clz);
601 /* wooha! we're done. */
602 clz->state = JV_STATE_PREPARED;
603 clz->notifyAll ();
606 /** Do static initialization for fields with a constant initializer */
607 void
608 _Jv_InitField (jobject obj, jclass klass, int index)
610 using namespace java::lang::reflect;
612 if (obj != 0 && klass == 0)
613 klass = obj->getClass ();
615 if (!_Jv_IsInterpretedClass (klass))
616 return;
618 _Jv_InterpClass *clz = (_Jv_InterpClass*)klass;
620 _Jv_Field * field = (&clz->fields[0]) + index;
622 if (index > clz->field_count)
623 throw_internal_error ("field out of range");
625 int init = clz->field_initializers[index];
626 if (init == 0)
627 return;
629 _Jv_Constants *pool = &clz->constants;
630 int tag = pool->tags[init];
632 if (! field->isResolved ())
633 throw_internal_error ("initializing unresolved field");
635 if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
636 throw_internal_error ("initializing non-static field with no object");
638 void *addr = 0;
640 if ((field->flags & Modifier::STATIC) != 0)
641 addr = (void*) field->u.addr;
642 else
643 addr = (void*) (((char*)obj) + field->u.boffset);
645 switch (tag)
647 case JV_CONSTANT_String:
649 _Jv_MonitorEnter (clz);
650 jstring str;
651 str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
652 pool->data[init].string = str;
653 pool->tags[init] = JV_CONSTANT_ResolvedString;
654 _Jv_MonitorExit (clz);
656 /* fall through */
658 case JV_CONSTANT_ResolvedString:
659 if (! (field->type == &StringClass
660 || field->type == &java::lang::Class::class$))
661 throw_class_format_error ("string initialiser to non-string field");
663 *(jstring*)addr = pool->data[init].string;
664 break;
666 case JV_CONSTANT_Integer:
668 int value = pool->data[init].i;
670 if (field->type == JvPrimClass (boolean))
671 *(jboolean*)addr = (jboolean)value;
673 else if (field->type == JvPrimClass (byte))
674 *(jbyte*)addr = (jbyte)value;
676 else if (field->type == JvPrimClass (char))
677 *(jchar*)addr = (jchar)value;
679 else if (field->type == JvPrimClass (short))
680 *(jshort*)addr = (jshort)value;
682 else if (field->type == JvPrimClass (int))
683 *(jint*)addr = (jint)value;
685 else
686 throw_class_format_error ("erroneous field initializer");
688 break;
690 case JV_CONSTANT_Long:
691 if (field->type != JvPrimClass (long))
692 throw_class_format_error ("erroneous field initializer");
694 *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
695 break;
697 case JV_CONSTANT_Float:
698 if (field->type != JvPrimClass (float))
699 throw_class_format_error ("erroneous field initializer");
701 *(jfloat*)addr = pool->data[init].f;
702 break;
704 case JV_CONSTANT_Double:
705 if (field->type != JvPrimClass (double))
706 throw_class_format_error ("erroneous field initializer");
708 *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
709 break;
711 default:
712 throw_class_format_error ("erroneous field initializer");
716 template<typename T>
717 struct aligner
719 T field;
722 #define ALIGNOF(TYPE) (__alignof__ (((aligner<TYPE> *) 0)->field))
724 // This returns the alignment of a type as it would appear in a
725 // structure. This can be different from the alignment of the type
726 // itself. For instance on x86 double is 8-aligned but struct{double}
727 // is 4-aligned.
728 static int
729 get_alignment_from_class (jclass klass)
731 if (klass == JvPrimClass (byte))
732 return ALIGNOF (jbyte);
733 else if (klass == JvPrimClass (short))
734 return ALIGNOF (jshort);
735 else if (klass == JvPrimClass (int))
736 return ALIGNOF (jint);
737 else if (klass == JvPrimClass (long))
738 return ALIGNOF (jlong);
739 else if (klass == JvPrimClass (boolean))
740 return ALIGNOF (jboolean);
741 else if (klass == JvPrimClass (char))
742 return ALIGNOF (jchar);
743 else if (klass == JvPrimClass (float))
744 return ALIGNOF (jfloat);
745 else if (klass == JvPrimClass (double))
746 return ALIGNOF (jdouble);
747 else
748 return ALIGNOF (jobject);
752 inline static unsigned char*
753 skip_one_type (unsigned char* ptr)
755 int ch = *ptr++;
757 while (ch == '[')
759 ch = *ptr++;
762 if (ch == 'L')
764 do { ch = *ptr++; } while (ch != ';');
767 return ptr;
770 static ffi_type*
771 get_ffi_type_from_signature (unsigned char* ptr)
773 switch (*ptr)
775 case 'L':
776 case '[':
777 return &ffi_type_pointer;
778 break;
780 case 'Z':
781 // On some platforms a bool is a byte, on others an int.
782 if (sizeof (jboolean) == sizeof (jbyte))
783 return &ffi_type_sint8;
784 else
786 JvAssert (sizeof (jbyte) == sizeof (jint));
787 return &ffi_type_sint32;
789 break;
791 case 'B':
792 return &ffi_type_sint8;
793 break;
795 case 'C':
796 return &ffi_type_uint16;
797 break;
799 case 'S':
800 return &ffi_type_sint16;
801 break;
803 case 'I':
804 return &ffi_type_sint32;
805 break;
807 case 'J':
808 return &ffi_type_sint64;
809 break;
811 case 'F':
812 return &ffi_type_float;
813 break;
815 case 'D':
816 return &ffi_type_double;
817 break;
819 case 'V':
820 return &ffi_type_void;
821 break;
824 throw_internal_error ("unknown type in signature");
827 /* this function yields the number of actual arguments, that is, if the
828 * function is non-static, then one is added to the number of elements
829 * found in the signature */
831 int
832 _Jv_count_arguments (_Jv_Utf8Const *signature,
833 jboolean staticp)
835 unsigned char *ptr = (unsigned char*) signature->data;
836 int arg_count = staticp ? 0 : 1;
838 /* first, count number of arguments */
840 // skip '('
841 ptr++;
843 // count args
844 while (*ptr != ')')
846 ptr = skip_one_type (ptr);
847 arg_count += 1;
850 return arg_count;
853 /* This beast will build a cif, given the signature. Memory for
854 * the cif itself and for the argument types must be allocated by the
855 * caller.
858 static int
859 init_cif (_Jv_Utf8Const* signature,
860 int arg_count,
861 jboolean staticp,
862 ffi_cif *cif,
863 ffi_type **arg_types,
864 ffi_type **rtype_p)
866 unsigned char *ptr = (unsigned char*) signature->data;
868 int arg_index = 0; // arg number
869 int item_count = 0; // stack-item count
871 // setup receiver
872 if (!staticp)
874 arg_types[arg_index++] = &ffi_type_pointer;
875 item_count += 1;
878 // skip '('
879 ptr++;
881 // assign arg types
882 while (*ptr != ')')
884 arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
886 if (*ptr == 'J' || *ptr == 'D')
887 item_count += 2;
888 else
889 item_count += 1;
891 ptr = skip_one_type (ptr);
894 // skip ')'
895 ptr++;
896 ffi_type *rtype = get_ffi_type_from_signature (ptr);
898 ptr = skip_one_type (ptr);
899 if (ptr != (unsigned char*)signature->data + signature->length)
900 throw_internal_error ("did not find end of signature");
902 if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
903 arg_count, rtype, arg_types) != FFI_OK)
904 throw_internal_error ("ffi_prep_cif failed");
906 if (rtype_p != NULL)
907 *rtype_p = rtype;
909 return item_count;
912 #if FFI_NATIVE_RAW_API
913 # define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure
914 # define FFI_RAW_SIZE ffi_raw_size
915 #else
916 # define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure
917 # define FFI_RAW_SIZE ffi_java_raw_size
918 #endif
920 /* we put this one here, and not in interpret.cc because it
921 * calls the utility routines _Jv_count_arguments
922 * which are static to this module. The following struct defines the
923 * layout we use for the stubs, it's only used in the ncode method. */
925 typedef struct {
926 ffi_raw_closure closure;
927 ffi_cif cif;
928 ffi_type *arg_types[0];
929 } ncode_closure;
931 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
933 void *
934 _Jv_InterpMethod::ncode ()
936 using namespace java::lang::reflect;
938 if (self->ncode != 0)
939 return self->ncode;
941 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
942 int arg_count = _Jv_count_arguments (self->signature, staticp);
944 ncode_closure *closure =
945 (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
946 + arg_count * sizeof (ffi_type*));
948 init_cif (self->signature,
949 arg_count,
950 staticp,
951 &closure->cif,
952 &closure->arg_types[0],
953 NULL);
955 ffi_closure_fun fun;
957 args_raw_size = FFI_RAW_SIZE (&closure->cif);
959 JvAssert ((self->accflags & Modifier::NATIVE) == 0);
961 if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
963 if (staticp)
964 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
965 else
966 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object;
968 else
970 if (staticp)
971 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_class;
972 else
973 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
976 FFI_PREP_RAW_CLOSURE (&closure->closure,
977 &closure->cif,
978 fun,
979 (void*)this);
981 self->ncode = (void*)closure;
982 return self->ncode;
985 void *
986 _Jv_JNIMethod::ncode ()
988 using namespace java::lang::reflect;
990 if (self->ncode != 0)
991 return self->ncode;
993 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
994 int arg_count = _Jv_count_arguments (self->signature, staticp);
996 ncode_closure *closure =
997 (ncode_closure*)_Jv_AllocBytes (sizeof (ncode_closure)
998 + arg_count * sizeof (ffi_type*));
1000 ffi_type *rtype;
1001 init_cif (self->signature,
1002 arg_count,
1003 staticp,
1004 &closure->cif,
1005 &closure->arg_types[0],
1006 &rtype);
1008 ffi_closure_fun fun;
1010 args_raw_size = FFI_RAW_SIZE (&closure->cif);
1012 // Initialize the argument types and CIF that represent the actual
1013 // underlying JNI function.
1014 int extra_args = 1;
1015 if ((self->accflags & Modifier::STATIC))
1016 ++extra_args;
1017 jni_arg_types = (ffi_type **) _Jv_Malloc ((extra_args + arg_count)
1018 * sizeof (ffi_type *));
1019 int offset = 0;
1020 jni_arg_types[offset++] = &ffi_type_pointer;
1021 if ((self->accflags & Modifier::STATIC))
1022 jni_arg_types[offset++] = &ffi_type_pointer;
1023 memcpy (&jni_arg_types[offset], &closure->arg_types[0],
1024 arg_count * sizeof (ffi_type *));
1026 if (ffi_prep_cif (&jni_cif, _Jv_platform_ffi_abi,
1027 extra_args + arg_count, rtype,
1028 jni_arg_types) != FFI_OK)
1029 throw_internal_error ("ffi_prep_cif failed for JNI function");
1031 JvAssert ((self->accflags & Modifier::NATIVE) != 0);
1033 // FIXME: for now we assume that all native methods for
1034 // interpreted code use JNI.
1035 fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
1037 FFI_PREP_RAW_CLOSURE (&closure->closure,
1038 &closure->cif,
1039 fun,
1040 (void*) this);
1042 self->ncode = (void *) closure;
1043 return self->ncode;
1047 /* A _Jv_ResolvedMethod is what is put in the constant pool for a
1048 * MethodRef or InterfacemethodRef. */
1049 static _Jv_ResolvedMethod*
1050 _Jv_BuildResolvedMethod (_Jv_Method* method,
1051 jclass klass,
1052 jboolean staticp,
1053 jint vtable_index)
1055 int arg_count = _Jv_count_arguments (method->signature, staticp);
1057 _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
1058 _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
1059 + arg_count*sizeof (ffi_type*));
1061 result->stack_item_count
1062 = init_cif (method->signature,
1063 arg_count,
1064 staticp,
1065 &result->cif,
1066 &result->arg_types[0],
1067 NULL);
1069 result->vtable_index = vtable_index;
1070 result->method = method;
1071 result->klass = klass;
1073 return result;
1077 static void
1078 throw_class_format_error (jstring msg)
1080 throw (msg
1081 ? new java::lang::ClassFormatError (msg)
1082 : new java::lang::ClassFormatError);
1085 static void
1086 throw_class_format_error (char *msg)
1088 throw_class_format_error (JvNewStringLatin1 (msg));
1091 static void
1092 throw_internal_error (char *msg)
1094 throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1098 #endif /* INTERPRETER */