1 // interpret.cc - Code for the interpreter
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
11 /* Author: Kresten Krab Thorup <krab@gnu.org> */
16 #pragma implementation "java-interp.h"
19 #include <java-cpool.h>
20 #include <java-interp.h>
21 #include <java/lang/System.h>
22 #include <java/lang/String.h>
23 #include <java/lang/Integer.h>
24 #include <java/lang/Long.h>
25 #include <java/lang/StringBuffer.h>
26 #include <java/lang/Class.h>
27 #include <java/lang/reflect/Modifier.h>
28 #include <java/lang/InternalError.h>
29 #include <java/lang/NullPointerException.h>
30 #include <java/lang/ArithmeticException.h>
31 #include <java/lang/IncompatibleClassChangeError.h>
32 #include <java/lang/InstantiationException.h>
33 #include <java/lang/Thread.h>
34 #include <java-insns.h>
35 #include <java-signal.h>
36 #include <java/lang/ClassFormatError.h>
37 #include <execution.h>
38 #include <java/lang/reflect/Modifier.h>
41 #include "jvmti-int.h"
43 #include <gnu/gcj/jvmti/Breakpoint.h>
44 #include <gnu/gcj/jvmti/BreakpointManager.h>
48 // Execution engine for interpreted code.
49 _Jv_InterpreterEngine _Jv_soleInterpreterEngine;
55 static void throw_internal_error (const char *msg)
56 __attribute__ ((__noreturn__));
57 static void throw_incompatible_class_change_error (jstring msg)
58 __attribute__ ((__noreturn__));
59 static void throw_null_pointer_exception ()
60 __attribute__ ((__noreturn__));
62 static void throw_class_format_error (jstring msg)
63 __attribute__ ((__noreturn__));
64 static void throw_class_format_error (const char *msg)
65 __attribute__ ((__noreturn__));
67 static void find_catch_location (jthrowable, jthread, jmethodID *, jlong *);
69 // A macro to facilitate JVMTI exception reporting
70 #define REPORT_EXCEPTION(Jthrowable) \
72 if (JVMTI_REQUESTED_EVENT (Exception)) \
73 _Jv_ReportJVMTIExceptionThrow (Jthrowable); \
77 #ifdef DIRECT_THREADED
78 // Lock to ensure that methods are not compiled concurrently.
79 // We could use a finer-grained lock here, however it is not safe to use
80 // the Class monitor as user code in another thread could hold it.
81 static _Jv_Mutex_t compile_mutex;
86 _Jv_MutexInit (&compile_mutex);
89 void _Jv_InitInterpreter() {}
92 // The breakpoint instruction. For the direct threaded case,
93 // _Jv_InterpMethod::compile will initialize breakpoint_insn
94 // the first time it is called.
95 #ifdef DIRECT_THREADED
96 insn_slot _Jv_InterpMethod::bp_insn_slot;
97 pc_t _Jv_InterpMethod::breakpoint_insn = NULL;
99 unsigned char _Jv_InterpMethod::bp_insn_opcode
100 = static_cast<unsigned char> (op_breakpoint);
101 pc_t _Jv_InterpMethod::breakpoint_insn = &_Jv_InterpMethod::bp_insn_opcode;
104 extern "C" double __ieee754_fmod (double,double);
106 static inline void dupx (_Jv_word *sp, int n, int x)
108 // first "slide" n+x elements n to the right
110 for (int i = 0; i < n+x; i++)
112 sp[(top-i)] = sp[(top-i)-n];
115 // next, copy the n top elements, n+x down
116 for (int i = 0; i < n; i++)
118 sp[top-(n+x)-i] = sp[top-i];
122 // Used to convert from floating types to integral types.
123 template<typename TO, typename FROM>
125 convert (FROM val, TO min, TO max)
128 if (val >= (FROM) max)
130 else if (val <= (FROM) min)
139 #define PUSHA(V) (sp++)->o = (V)
140 #define PUSHI(V) (sp++)->i = (V)
141 #define PUSHF(V) (sp++)->f = (V)
142 #if SIZEOF_VOID_P == 8
143 # define PUSHL(V) (sp->l = (V), sp += 2)
144 # define PUSHD(V) (sp->d = (V), sp += 2)
146 # define PUSHL(V) do { _Jv_word2 w2; w2.l=(V); \
147 (sp++)->ia[0] = w2.ia[0]; \
148 (sp++)->ia[0] = w2.ia[1]; } while (0)
149 # define PUSHD(V) do { _Jv_word2 w2; w2.d=(V); \
150 (sp++)->ia[0] = w2.ia[0]; \
151 (sp++)->ia[0] = w2.ia[1]; } while (0)
154 #define POPA() ((--sp)->o)
155 #define POPI() ((jint) (--sp)->i) // cast since it may be promoted
156 #define POPF() ((jfloat) (--sp)->f)
157 #if SIZEOF_VOID_P == 8
158 # define POPL() (sp -= 2, (jlong) sp->l)
159 # define POPD() (sp -= 2, (jdouble) sp->d)
161 # define POPL() ({ _Jv_word2 w2; \
162 w2.ia[1] = (--sp)->ia[0]; \
163 w2.ia[0] = (--sp)->ia[0]; w2.l; })
164 # define POPD() ({ _Jv_word2 w2; \
165 w2.ia[1] = (--sp)->ia[0]; \
166 w2.ia[0] = (--sp)->ia[0]; w2.d; })
169 #define LOADA(I) (sp++)->o = locals[I].o
170 #define LOADI(I) (sp++)->i = locals[I].i
171 #define LOADF(I) (sp++)->f = locals[I].f
172 #if SIZEOF_VOID_P == 8
173 # define LOADL(I) (sp->l = locals[I].l, sp += 2)
174 # define LOADD(I) (sp->d = locals[I].d, sp += 2)
176 # define LOADL(I) do { jint __idx = (I); \
177 (sp++)->ia[0] = locals[__idx].ia[0]; \
178 (sp++)->ia[0] = locals[__idx+1].ia[0]; \
180 # define LOADD(I) LOADL(I)
185 DEBUG_LOCALS_INSN (I, 'o'); \
186 locals[I].o = (--sp)->o; \
190 DEBUG_LOCALS_INSN (I, 'i'); \
191 locals[I].i = (--sp)->i; \
195 DEBUG_LOCALS_INSN (I, 'f'); \
196 locals[I].f = (--sp)->f; \
198 #if SIZEOF_VOID_P == 8
201 DEBUG_LOCALS_INSN (I, 'l'); \
202 DEBUG_LOCALS_INSN (I + 1, 'x'); \
203 (sp -= 2, locals[I].l = sp->l); \
207 DEBUG_LOCALS_INSN (I, 'd'); \
208 DEBUG_LOCALS_INSN (I + 1, 'x'); \
209 (sp -= 2, locals[I].d = sp->d); \
215 DEBUG_LOCALS_INSN (I, 'l'); \
216 DEBUG_LOCALS_INSN (I + 1, 'x'); \
218 locals[__idx+1].ia[0] = (--sp)->ia[0]; \
219 locals[__idx].ia[0] = (--sp)->ia[0]; \
223 DEBUG_LOCALS_INSN (I, 'd'); \
224 DEBUG_LOCALS_INSN (I + 1, 'x'); \
226 locals[__idx+1].ia[0] = (--sp)->ia[0]; \
227 locals[__idx].ia[0] = (--sp)->ia[0]; \
231 #define PEEKI(I) (locals+(I))->i
232 #define PEEKA(I) (locals+(I))->o
235 DEBUG_LOCALS_INSN(I,'i'); \
236 ((locals+(I))->i = (V))
239 #define BINOPI(OP) { \
240 jint value2 = POPI(); \
241 jint value1 = POPI(); \
242 PUSHI(value1 OP value2); \
245 #define BINOPF(OP) { \
246 jfloat value2 = POPF(); \
247 jfloat value1 = POPF(); \
248 PUSHF(value1 OP value2); \
251 #define BINOPL(OP) { \
252 jlong value2 = POPL(); \
253 jlong value1 = POPL(); \
254 PUSHL(value1 OP value2); \
257 #define BINOPD(OP) { \
258 jdouble value2 = POPD(); \
259 jdouble value1 = POPD(); \
260 PUSHD(value1 OP value2); \
264 get1s (unsigned char* loc)
266 return *(signed char*)loc;
270 get1u (unsigned char* loc)
276 get2s(unsigned char* loc)
278 return (((jint)*(signed char*)loc) << 8) | ((jint)*(loc+1));
282 get2u (unsigned char* loc)
284 return (((jint)(*loc)) << 8) | ((jint)*(loc+1));
288 get4 (unsigned char* loc)
290 return (((jint)(loc[0])) << 24)
291 | (((jint)(loc[1])) << 16)
292 | (((jint)(loc[2])) << 8)
293 | (((jint)(loc[3])) << 0);
296 #define SAVE_PC() frame_desc.pc = pc
298 // We used to define this conditionally, depending on HANDLE_SEGV.
299 // However, that runs into a problem if a chunk in low memory is
300 // mapped and we try to look at a field near the end of a large
301 // object. See PR 26858 for details. It is, most likely, relatively
302 // inexpensive to simply do this check always.
303 #define NULLCHECK(X) \
304 do { SAVE_PC(); if ((X)==NULL) throw_null_pointer_exception (); } while (0)
306 // Note that we can still conditionally define NULLARRAYCHECK, since
307 // we know that all uses of an array will first reference the length
308 // field, which is first -- and thus will trigger a SEGV.
310 #define NULLARRAYCHECK(X) SAVE_PC()
312 #define NULLARRAYCHECK(X) \
316 if ((X) == NULL) { throw_null_pointer_exception (); } \
320 #define ARRAYBOUNDSCHECK(array, index) \
323 if (((unsigned) index) >= (unsigned) (array->length)) \
324 _Jv_ThrowBadArrayIndex (index); \
328 _Jv_InterpMethod::run_normal (ffi_cif *,
333 _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
334 run (ret, args, _this);
338 _Jv_InterpMethod::run_normal_debug (ffi_cif *,
343 _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
344 run_debug (ret, args, _this);
348 _Jv_InterpMethod::run_synch_object (ffi_cif *,
353 _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
355 jobject rcv = (jobject) args[0].ptr;
356 JvSynchronize mutex (rcv);
358 run (ret, args, _this);
362 _Jv_InterpMethod::run_synch_object_debug (ffi_cif *,
367 _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
369 jobject rcv = (jobject) args[0].ptr;
370 JvSynchronize mutex (rcv);
372 run_debug (ret, args, _this);
376 _Jv_InterpMethod::run_class (ffi_cif *,
381 _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
382 _Jv_InitClass (_this->defining_class);
383 run (ret, args, _this);
387 _Jv_InterpMethod::run_class_debug (ffi_cif *,
392 _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
393 _Jv_InitClass (_this->defining_class);
394 run_debug (ret, args, _this);
398 _Jv_InterpMethod::run_synch_class (ffi_cif *,
403 _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
405 jclass sync = _this->defining_class;
406 _Jv_InitClass (sync);
407 JvSynchronize mutex (sync);
409 run (ret, args, _this);
413 _Jv_InterpMethod::run_synch_class_debug (ffi_cif *,
418 _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
420 jclass sync = _this->defining_class;
421 _Jv_InitClass (sync);
422 JvSynchronize mutex (sync);
424 run_debug (ret, args, _this);
427 #ifdef DIRECT_THREADED
428 // "Compile" a method by turning it from bytecode to direct-threaded
431 _Jv_InterpMethod::compile (const void * const *insn_targets)
433 insn_slot *insns = NULL;
435 unsigned char *codestart = bytecode ();
436 unsigned char *end = codestart + code_length;
437 _Jv_word *pool_data = defining_class->constants.data;
439 #define SET_ONE(Field, Value) \
445 insns[next++].Field = Value; \
449 #define SET_INSN(Value) SET_ONE (insn, (void *) Value)
450 #define SET_INT(Value) SET_ONE (int_val, Value)
451 #define SET_DATUM(Value) SET_ONE (datum, Value)
453 // Map from bytecode PC to slot in INSNS.
454 int *pc_mapping = (int *) __builtin_alloca (sizeof (int) * code_length);
455 for (int i = 0; i < code_length; ++i)
458 for (int i = 0; i < 2; ++i)
460 jboolean first_pass = i == 0;
464 insns = (insn_slot *) _Jv_AllocBytes (sizeof (insn_slot) * next);
465 number_insn_slots = next;
469 unsigned char *pc = codestart;
472 int base_pc_val = pc - codestart;
474 pc_mapping[base_pc_val] = next;
476 java_opcode opcode = (java_opcode) *pc++;
478 if (opcode == op_nop)
480 SET_INSN (insn_targets[opcode]);
621 case op_monitorenter:
631 // No argument, nothing else to do.
635 SET_INT (get1s (pc));
641 int index = get1u (pc);
643 // For an unresolved class we want to delay resolution
645 if (defining_class->constants.tags[index] == JV_CONSTANT_Class)
648 SET_INSN (insn_targets[int (op_jsr_w) + 1]);
652 SET_DATUM (pool_data[index].o);
668 SET_INT (get1u (pc));
673 SET_INT (get1u (pc));
674 SET_INT (get1s (pc + 1));
680 int index = get2u (pc);
682 // For an unresolved class we want to delay resolution
684 if (defining_class->constants.tags[index] == JV_CONSTANT_Class)
687 SET_INSN (insn_targets[int (op_jsr_w) + 1]);
691 SET_DATUM (pool_data[index].o);
697 int index = get2u (pc);
699 SET_DATUM (&pool_data[index]);
704 SET_INT (get2s (pc));
716 case op_invokespecial:
717 case op_invokestatic:
718 case op_invokevirtual:
719 SET_INT (get2u (pc));
723 case op_multianewarray:
724 SET_INT (get2u (pc));
725 SET_INT (get1u (pc + 2));
748 int offset = get2s (pc);
751 int new_pc = base_pc_val + offset;
753 bool orig_was_goto = opcode == op_goto;
755 // Thread jumps. We limit the loop count; this lets
756 // us avoid infinite loops if the bytecode contains
757 // such. `10' is arbitrary.
759 while (codestart[new_pc] == op_goto && count-- > 0)
760 new_pc += get2s (&codestart[new_pc + 1]);
762 // If the jump takes us to a `return' instruction and
763 // the original branch was an unconditional goto, then
764 // we hoist the return.
765 opcode = (java_opcode) codestart[new_pc];
767 && (opcode == op_ireturn || opcode == op_lreturn
768 || opcode == op_freturn || opcode == op_dreturn
769 || opcode == op_areturn || opcode == op_return))
772 SET_INSN (insn_targets[opcode]);
775 SET_DATUM (&insns[pc_mapping[new_pc]]);
781 while ((pc - codestart) % 4 != 0)
784 jint def = get4 (pc);
785 SET_DATUM (&insns[pc_mapping[base_pc_val + def]]);
791 int high = get4 (pc);
795 for (int i = low; i <= high; ++i)
797 SET_DATUM (&insns[pc_mapping[base_pc_val + get4 (pc)]]);
803 case op_lookupswitch:
805 while ((pc - codestart) % 4 != 0)
808 jint def = get4 (pc);
809 SET_DATUM (&insns[pc_mapping[base_pc_val + def]]);
812 jint npairs = get4 (pc);
818 jint match = get4 (pc);
819 jint offset = get4 (pc + 4);
821 SET_DATUM (&insns[pc_mapping[base_pc_val + offset]]);
827 case op_invokeinterface:
829 jint index = get2u (pc);
831 // We ignore the next two bytes.
839 opcode = (java_opcode) get1u (pc);
841 jint val = get2u (pc);
844 // We implement narrow and wide instructions using the
845 // same code in the interpreter. So we rewrite the
846 // instruction slot here.
848 insns[next - 1].insn = (void *) insn_targets[opcode];
851 if (opcode == op_iinc)
853 SET_INT (get2s (pc));
862 jint offset = get4 (pc);
864 SET_DATUM (&insns[pc_mapping[base_pc_val + offset]]);
868 // Some "can't happen" cases that we include for
869 // error-checking purposes.
887 case op_getstatic_2s:
888 case op_getstatic_2u:
900 // Now update exceptions.
901 _Jv_InterpException *exc = exceptions ();
902 for (int i = 0; i < exc_count; ++i)
904 exc[i].start_pc.p = &insns[pc_mapping[exc[i].start_pc.i]];
905 exc[i].end_pc.p = &insns[pc_mapping[exc[i].end_pc.i]];
906 exc[i].handler_pc.p = &insns[pc_mapping[exc[i].handler_pc.i]];
907 // FIXME: resolve_pool_entry can throw - we shouldn't be doing this
908 // during compilation.
910 = (_Jv_Linker::resolve_pool_entry (defining_class,
911 exc[i].handler_type.i)).clazz;
912 exc[i].handler_type.p = handler;
915 // Translate entries in the LineNumberTable from bytecode PC's to direct
916 // threaded interpreter instruction values.
917 for (int i = 0; i < line_table_len; i++)
919 int byte_pc = line_table[i].bytecode_pc;
920 // It isn't worth throwing an exception if this table is
921 // corrupted, but at the same time we don't want a crash.
922 if (byte_pc < 0 || byte_pc >= code_length)
924 line_table[i].pc = &insns[pc_mapping[byte_pc]];
929 if (breakpoint_insn == NULL)
931 bp_insn_slot.insn = const_cast<void *> (insn_targets[op_breakpoint]);
932 breakpoint_insn = &bp_insn_slot;
935 #endif /* DIRECT_THREADED */
937 /* Run the given method.
938 When args is NULL, don't run anything -- just compile it. */
940 _Jv_InterpMethod::run (void *retp, ffi_raw *args, _Jv_InterpMethod *meth)
943 #undef DEBUG_LOCALS_INSN
944 #define DEBUG_LOCALS_INSN(s, t) do {} while (0)
946 #include "interpret-run.cc"
950 _Jv_InterpMethod::run_debug (void *retp, ffi_raw *args, _Jv_InterpMethod *meth)
953 #undef DEBUG_LOCALS_INSN
954 #define DEBUG_LOCALS_INSN(s, t) \
957 frame_desc.locals_type[s] = t; \
961 #include "interpret-run.cc"
965 throw_internal_error (const char *msg)
967 jthrowable t = new java::lang::InternalError (JvNewStringLatin1 (msg));
968 REPORT_EXCEPTION (t);
973 throw_incompatible_class_change_error (jstring msg)
975 jthrowable t = new java::lang::IncompatibleClassChangeError (msg);
976 REPORT_EXCEPTION (t);
981 throw_null_pointer_exception ()
983 jthrowable t = new java::lang::NullPointerException;
984 REPORT_EXCEPTION (t);
988 /* Look up source code line number for given bytecode (or direct threaded
991 _Jv_InterpMethod::get_source_line(pc_t mpc)
993 int line = line_table_len > 0 ? line_table[0].line : -1;
994 for (int i = 1; i < line_table_len; i++)
995 if (line_table[i].pc > mpc)
998 line = line_table[i].line;
1003 /** Do static initialization for fields with a constant initializer */
1005 _Jv_InitField (jobject obj, jclass klass, int index)
1007 using namespace java::lang::reflect;
1009 if (obj != 0 && klass == 0)
1010 klass = obj->getClass ();
1012 if (!_Jv_IsInterpretedClass (klass))
1015 _Jv_InterpClass *iclass = (_Jv_InterpClass*)klass->aux_info;
1017 _Jv_Field * field = (&klass->fields[0]) + index;
1019 if (index > klass->field_count)
1020 throw_internal_error ("field out of range");
1022 int init = iclass->field_initializers[index];
1026 _Jv_Constants *pool = &klass->constants;
1027 int tag = pool->tags[init];
1029 if (! field->isResolved ())
1030 throw_internal_error ("initializing unresolved field");
1032 if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
1033 throw_internal_error ("initializing non-static field with no object");
1037 if ((field->flags & Modifier::STATIC) != 0)
1038 addr = (void*) field->u.addr;
1040 addr = (void*) (((char*)obj) + field->u.boffset);
1044 case JV_CONSTANT_String:
1047 str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
1048 pool->data[init].string = str;
1049 pool->tags[init] = JV_CONSTANT_ResolvedString;
1053 case JV_CONSTANT_ResolvedString:
1054 if (! (field->type == &java::lang::String::class$
1055 || field->type == &java::lang::Class::class$))
1056 throw_class_format_error ("string initialiser to non-string field");
1058 *(jstring*)addr = pool->data[init].string;
1061 case JV_CONSTANT_Integer:
1063 int value = pool->data[init].i;
1065 if (field->type == JvPrimClass (boolean))
1066 *(jboolean*)addr = (jboolean)value;
1068 else if (field->type == JvPrimClass (byte))
1069 *(jbyte*)addr = (jbyte)value;
1071 else if (field->type == JvPrimClass (char))
1072 *(jchar*)addr = (jchar)value;
1074 else if (field->type == JvPrimClass (short))
1075 *(jshort*)addr = (jshort)value;
1077 else if (field->type == JvPrimClass (int))
1078 *(jint*)addr = (jint)value;
1081 throw_class_format_error ("erroneous field initializer");
1085 case JV_CONSTANT_Long:
1086 if (field->type != JvPrimClass (long))
1087 throw_class_format_error ("erroneous field initializer");
1089 *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
1092 case JV_CONSTANT_Float:
1093 if (field->type != JvPrimClass (float))
1094 throw_class_format_error ("erroneous field initializer");
1096 *(jfloat*)addr = pool->data[init].f;
1099 case JV_CONSTANT_Double:
1100 if (field->type != JvPrimClass (double))
1101 throw_class_format_error ("erroneous field initializer");
1103 *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
1107 throw_class_format_error ("erroneous field initializer");
1111 inline static unsigned char*
1112 skip_one_type (unsigned char* ptr)
1123 do { ch = *ptr++; } while (ch != ';');
1130 get_ffi_type_from_signature (unsigned char* ptr)
1136 return &ffi_type_pointer;
1140 // On some platforms a bool is a byte, on others an int.
1141 if (sizeof (jboolean) == sizeof (jbyte))
1142 return &ffi_type_sint8;
1145 JvAssert (sizeof (jbyte) == sizeof (jint));
1146 return &ffi_type_sint32;
1151 return &ffi_type_sint8;
1155 return &ffi_type_uint16;
1159 return &ffi_type_sint16;
1163 return &ffi_type_sint32;
1167 return &ffi_type_sint64;
1171 return &ffi_type_float;
1175 return &ffi_type_double;
1179 return &ffi_type_void;
1183 throw_internal_error ("unknown type in signature");
1186 /* this function yields the number of actual arguments, that is, if the
1187 * function is non-static, then one is added to the number of elements
1188 * found in the signature */
1191 _Jv_count_arguments (_Jv_Utf8Const *signature,
1194 unsigned char *ptr = (unsigned char*) signature->chars();
1195 int arg_count = staticp ? 0 : 1;
1197 /* first, count number of arguments */
1205 ptr = skip_one_type (ptr);
1212 /* This beast will build a cif, given the signature. Memory for
1213 * the cif itself and for the argument types must be allocated by the
1218 _Jv_init_cif (_Jv_Utf8Const* signature,
1222 ffi_type **arg_types,
1225 unsigned char *ptr = (unsigned char*) signature->chars();
1227 int arg_index = 0; // arg number
1228 int item_count = 0; // stack-item count
1233 arg_types[arg_index++] = &ffi_type_pointer;
1243 arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
1245 if (*ptr == 'J' || *ptr == 'D')
1250 ptr = skip_one_type (ptr);
1255 ffi_type *rtype = get_ffi_type_from_signature (ptr);
1257 ptr = skip_one_type (ptr);
1258 if (ptr != (unsigned char*)signature->chars() + signature->len())
1259 throw_internal_error ("did not find end of signature");
1261 if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
1262 arg_count, rtype, arg_types) != FFI_OK)
1263 throw_internal_error ("ffi_prep_cif failed");
1265 if (rtype_p != NULL)
1271 #if FFI_NATIVE_RAW_API
1272 # define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure_loc
1273 # define FFI_RAW_SIZE ffi_raw_size
1275 # define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure_loc
1276 # define FFI_RAW_SIZE ffi_java_raw_size
1279 /* we put this one here, and not in interpret.cc because it
1280 * calls the utility routines _Jv_count_arguments
1281 * which are static to this module. The following struct defines the
1282 * layout we use for the stubs, it's only used in the ncode method. */
1285 ffi_raw_closure closure;
1286 _Jv_ClosureList list;
1288 ffi_type *arg_types[0];
1291 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
1294 _Jv_InterpMethod::ncode (jclass klass)
1296 using namespace java::lang::reflect;
1298 if (self->ncode != 0)
1301 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1302 int arg_count = _Jv_count_arguments (self->signature, staticp);
1305 ncode_closure *closure =
1306 (ncode_closure*)ffi_closure_alloc (sizeof (ncode_closure)
1307 + arg_count * sizeof (ffi_type*),
1309 closure->list.registerClosure (klass, closure);
1311 _Jv_init_cif (self->signature,
1315 &closure->arg_types[0],
1318 ffi_closure_fun fun;
1320 args_raw_size = FFI_RAW_SIZE (&closure->cif);
1322 JvAssert ((self->accflags & Modifier::NATIVE) == 0);
1324 if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
1329 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class_debug;
1331 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
1336 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object_debug;
1338 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object;
1346 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_class_debug;
1348 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_class;
1353 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal_debug;
1355 fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
1359 FFI_PREP_RAW_CLOSURE (&closure->closure,
1370 /* Find the index of the given insn in the array of insn slots
1371 for this method. Returns -1 if not found. */
1373 _Jv_InterpMethod::insn_index (pc_t pc)
1376 #ifdef DIRECT_THREADED
1377 jlong right = number_insn_slots;
1378 pc_t insns = prepared;
1380 jlong right = code_length;
1381 pc_t insns = bytecode ();
1386 jlong mid = (left + right) / 2;
1387 if (&insns[mid] == pc)
1390 if (pc < &insns[mid])
1399 // Method to check if an exception is caught at some location in a method
1400 // (meth). Returns true if this method (meth) contains a catch block for the
1401 // exception (ex). False otherwise. If there is a catch block, it sets the pc
1402 // to the location of the beginning of the catch block.
1404 _Jv_InterpMethod::check_handler (pc_t *pc, _Jv_InterpMethod *meth,
1405 java::lang::Throwable *ex)
1407 #ifdef DIRECT_THREADED
1408 void *logical_pc = (void *) ((insn_slot *) (*pc) - 1);
1410 int logical_pc = (*pc) - 1 - meth->bytecode ();
1412 _Jv_InterpException *exc = meth->exceptions ();
1413 jclass exc_class = ex->getClass ();
1415 for (int i = 0; i < meth->exc_count; i++)
1417 if (PCVAL (exc[i].start_pc) <= logical_pc
1418 && logical_pc < PCVAL (exc[i].end_pc))
1420 #ifdef DIRECT_THREADED
1421 jclass handler = (jclass) exc[i].handler_type.p;
1423 jclass handler = NULL;
1424 if (exc[i].handler_type.i != 0)
1426 = (_Jv_Linker::resolve_pool_entry (meth->defining_class,
1428 #endif /* DIRECT_THREADED */
1429 if (handler == NULL || handler->isAssignableFrom (exc_class))
1431 #ifdef DIRECT_THREADED
1432 (*pc) = (insn_slot *) exc[i].handler_pc.p;
1434 (*pc) = meth->bytecode () + exc[i].handler_pc.i;
1435 #endif /* DIRECT_THREADED */
1445 _Jv_InterpMethod::get_line_table (jlong& start, jlong& end,
1446 jintArray& line_numbers,
1447 jlongArray& code_indices)
1449 #ifdef DIRECT_THREADED
1450 /* For the DIRECT_THREADED case, if the method has not yet been
1451 * compiled, the linetable will change to insn slots instead of
1452 * bytecode PCs. It is probably easiest, in this case, to simply
1453 * compile the method and guarantee that we are using insn
1456 _Jv_CompileMethod (this);
1458 if (line_table_len > 0)
1461 end = number_insn_slots;
1462 line_numbers = JvNewIntArray (line_table_len);
1463 code_indices = JvNewLongArray (line_table_len);
1465 jint* lines = elements (line_numbers);
1466 jlong* indices = elements (code_indices);
1467 for (int i = 0; i < line_table_len; ++i)
1469 lines[i] = line_table[i].line;
1470 indices[i] = insn_index (line_table[i].pc);
1473 #else // !DIRECT_THREADED
1474 if (line_table_len > 0)
1478 line_numbers = JvNewIntArray (line_table_len);
1479 code_indices = JvNewLongArray (line_table_len);
1481 jint* lines = elements (line_numbers);
1482 jlong* indices = elements (code_indices);
1483 for (int i = 0; i < line_table_len; ++i)
1485 lines[i] = line_table[i].line;
1486 indices[i] = (jlong) line_table[i].bytecode_pc;
1489 #endif // !DIRECT_THREADED
1493 _Jv_InterpMethod::get_local_var_table (char **name, char **sig,
1494 char **generic_sig, jlong *startloc,
1495 jint *length, jint *slot,
1498 if (local_var_table == NULL)
1500 if (table_slot >= local_var_table_len)
1504 *name = local_var_table[table_slot].name;
1505 *sig = local_var_table[table_slot].descriptor;
1506 *generic_sig = local_var_table[table_slot].descriptor;
1508 *startloc = static_cast<jlong>
1509 (local_var_table[table_slot].bytecode_start_pc);
1510 *length = static_cast<jint> (local_var_table[table_slot].length);
1511 *slot = static_cast<jint> (local_var_table[table_slot].slot);
1513 return local_var_table_len - table_slot -1;
1517 _Jv_InterpMethod::install_break (jlong index)
1519 return set_insn (index, breakpoint_insn);
1523 _Jv_InterpMethod::get_insn (jlong index)
1527 #ifdef DIRECT_THREADED
1528 if (index >= number_insn_slots || index < 0)
1532 #else // !DIRECT_THREADED
1533 if (index >= code_length || index < 0)
1536 code = reinterpret_cast<pc_t> (bytecode ());
1537 #endif // !DIRECT_THREADED
1539 return &code[index];
1543 _Jv_InterpMethod::set_insn (jlong index, pc_t insn)
1545 #ifdef DIRECT_THREADED
1546 if (index >= number_insn_slots || index < 0)
1549 pc_t code = prepared;
1550 code[index].insn = insn->insn;
1551 #else // !DIRECT_THREADED
1552 if (index >= code_length || index < 0)
1555 pc_t code = reinterpret_cast<pc_t> (bytecode ());
1556 code[index] = *insn;
1557 #endif // !DIRECT_THREADED
1559 return &code[index];
1563 _Jv_JNIMethod::ncode (jclass klass)
1565 using namespace java::lang::reflect;
1567 if (self->ncode != 0)
1570 jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1571 int arg_count = _Jv_count_arguments (self->signature, staticp);
1574 ncode_closure *closure =
1575 (ncode_closure*)ffi_closure_alloc (sizeof (ncode_closure)
1576 + arg_count * sizeof (ffi_type*),
1578 closure->list.registerClosure (klass, closure);
1581 _Jv_init_cif (self->signature,
1585 &closure->arg_types[0],
1588 ffi_closure_fun fun;
1590 args_raw_size = FFI_RAW_SIZE (&closure->cif);
1592 // Initialize the argument types and CIF that represent the actual
1593 // underlying JNI function.
1595 if ((self->accflags & Modifier::STATIC))
1597 jni_arg_types = (ffi_type **) _Jv_AllocBytes ((extra_args + arg_count)
1598 * sizeof (ffi_type *));
1600 jni_arg_types[offset++] = &ffi_type_pointer;
1601 if ((self->accflags & Modifier::STATIC))
1602 jni_arg_types[offset++] = &ffi_type_pointer;
1603 memcpy (&jni_arg_types[offset], &closure->arg_types[0],
1604 arg_count * sizeof (ffi_type *));
1606 if (ffi_prep_cif (&jni_cif, _Jv_platform_ffi_abi,
1607 extra_args + arg_count, rtype,
1608 jni_arg_types) != FFI_OK)
1609 throw_internal_error ("ffi_prep_cif failed for JNI function");
1611 JvAssert ((self->accflags & Modifier::NATIVE) != 0);
1613 // FIXME: for now we assume that all native methods for
1614 // interpreted code use JNI.
1615 fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
1617 FFI_PREP_RAW_CLOSURE (&closure->closure,
1628 throw_class_format_error (jstring msg)
1631 ? new java::lang::ClassFormatError (msg)
1632 : new java::lang::ClassFormatError);
1633 REPORT_EXCEPTION (t);
1638 throw_class_format_error (const char *msg)
1640 throw_class_format_error (JvNewStringLatin1 (msg));
1643 /* This function finds the method and location where the exception EXC
1644 is caught in the stack frame. On return, it sets CATCH_METHOD and
1645 CATCH_LOCATION with the method and location where the catch will
1646 occur. If the exception is not caught, these are set to 0.
1648 This function should only be used with the DEBUG interpreter. */
1650 find_catch_location (::java::lang::Throwable *exc, jthread thread,
1651 jmethodID *catch_method, jlong *catch_loc)
1656 _Jv_InterpFrame *frame
1657 = reinterpret_cast<_Jv_InterpFrame *> (thread->interp_frame);
1658 while (frame != NULL)
1660 pc_t pc = frame->get_pc ();
1661 _Jv_InterpMethod *imeth
1662 = reinterpret_cast<_Jv_InterpMethod *> (frame->self);
1663 if (imeth->check_handler (&pc, imeth, exc))
1665 // This method handles the exception.
1666 *catch_method = imeth->get_method ();
1667 *catch_loc = imeth->insn_index (pc);
1671 frame = frame->next_interp;
1675 /* This method handles JVMTI notifications of thrown exceptions. It
1676 calls find_catch_location to figure out where the exception is
1677 caught (if it is caught).
1679 Like find_catch_location, this should only be called with the
1680 DEBUG interpreter. Since a few exceptions occur outside the
1681 interpreter proper, it is important to not call this function
1682 without checking JVMTI_REQUESTED_EVENT(Exception) first. */
1684 _Jv_ReportJVMTIExceptionThrow (jthrowable ex)
1686 jthread thread = ::java::lang::Thread::currentThread ();
1687 _Jv_Frame *frame = reinterpret_cast<_Jv_Frame *> (thread->frame);
1688 jmethodID throw_meth = frame->self->get_method ();
1689 jlocation throw_loc = -1;
1690 if (frame->frame_type == frame_interpreter)
1692 _Jv_InterpFrame * iframe
1693 = reinterpret_cast<_Jv_InterpFrame *> (frame);
1694 _Jv_InterpMethod *imeth
1695 = reinterpret_cast<_Jv_InterpMethod *> (frame->self);
1696 throw_loc = imeth->insn_index (iframe->get_pc ());
1700 jmethodID catch_method;
1701 find_catch_location (ex, thread, &catch_method, &catch_loc);
1702 _Jv_JVMTI_PostEvent (JVMTI_EVENT_EXCEPTION, thread,
1703 _Jv_GetCurrentJNIEnv (), throw_meth, throw_loc,
1704 ex, catch_method, catch_loc);
1710 _Jv_InterpreterEngine::do_verify (jclass klass)
1712 _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1713 for (int i = 0; i < klass->method_count; i++)
1715 using namespace java::lang::reflect;
1716 _Jv_MethodBase *imeth = iclass->interpreted_methods[i];
1717 _Jv_ushort accflags = klass->methods[i].accflags;
1718 if ((accflags & (Modifier::NATIVE | Modifier::ABSTRACT)) == 0)
1720 _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
1721 _Jv_VerifyMethod (im);
1727 _Jv_InterpreterEngine::do_create_ncode (jclass klass)
1729 _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1730 for (int i = 0; i < klass->method_count; i++)
1732 // Just skip abstract methods. This is particularly important
1733 // because we don't resize the interpreted_methods array when
1734 // miranda methods are added to it.
1735 if ((klass->methods[i].accflags
1736 & java::lang::reflect::Modifier::ABSTRACT)
1740 _Jv_MethodBase *imeth = iclass->interpreted_methods[i];
1742 if ((klass->methods[i].accflags & java::lang::reflect::Modifier::NATIVE)
1745 // You might think we could use a virtual `ncode' method in
1746 // the _Jv_MethodBase and unify the native and non-native
1747 // cases. Well, we can't, because we don't allocate these
1748 // objects using `new', and thus they don't get a vtable.
1749 _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
1750 klass->methods[i].ncode = jnim->ncode (klass);
1752 else if (imeth != 0) // it could be abstract
1754 _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
1755 klass->methods[i].ncode = im->ncode (klass);
1761 _Jv_InterpreterEngine::do_get_closure_list (jclass klass)
1763 _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1765 if (!iclass->closures)
1766 iclass->closures = _Jv_ClosureListFinalizer ();
1768 return iclass->closures;
1772 _Jv_InterpreterEngine::do_allocate_static_fields (jclass klass,
1776 _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1778 // Splitting the allocations here lets us scan reference fields and
1779 // avoid scanning non-reference fields. How reference fields are
1780 // scanned is a bit tricky: we allocate using _Jv_AllocRawObj, which
1781 // means that this memory will be scanned conservatively (same
1782 // difference, since we know all the contents here are pointers).
1783 // Then we put pointers into this memory into the 'fields'
1784 // structure. Most of these are interior pointers, which is ok (but
1785 // even so the pointer to the first reference field will be used and
1786 // that is not an interior pointer). The 'fields' array is also
1787 // allocated with _Jv_AllocRawObj (see defineclass.cc), so it will
1788 // be scanned. A pointer to this array is held by Class and thus
1789 // seen by the collector.
1790 char *reference_fields = (char *) _Jv_AllocRawObj (pointer_size);
1791 char *non_reference_fields = (char *) _Jv_AllocBytes (other_size);
1793 for (int i = 0; i < klass->field_count; i++)
1795 _Jv_Field *field = &klass->fields[i];
1797 if ((field->flags & java::lang::reflect::Modifier::STATIC) == 0)
1800 char *base = field->isRef() ? reference_fields : non_reference_fields;
1801 field->u.addr = base + field->u.boffset;
1803 if (iclass->field_initializers[i] != 0)
1805 _Jv_Linker::resolve_field (field, klass->loader);
1806 _Jv_InitField (0, klass, i);
1810 // Now we don't need the field_initializers anymore, so let the
1811 // collector get rid of it.
1812 iclass->field_initializers = 0;
1815 _Jv_ResolvedMethod *
1816 _Jv_InterpreterEngine::do_resolve_method (_Jv_Method *method, jclass klass,
1819 int arg_count = _Jv_count_arguments (method->signature, staticp);
1821 _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
1822 _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
1823 + arg_count*sizeof (ffi_type*));
1825 result->stack_item_count
1826 = _Jv_init_cif (method->signature,
1830 &result->arg_types[0],
1833 result->method = method;
1834 result->klass = klass;
1840 _Jv_InterpreterEngine::do_post_miranda_hook (jclass klass)
1842 _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1843 for (int i = 0; i < klass->method_count; i++)
1845 // Just skip abstract methods. This is particularly important
1846 // because we don't resize the interpreted_methods array when
1847 // miranda methods are added to it.
1848 if ((klass->methods[i].accflags
1849 & java::lang::reflect::Modifier::ABSTRACT)
1852 // Miranda method additions mean that the `methods' array moves.
1853 // We cache a pointer into this array, so we have to update.
1854 iclass->interpreted_methods[i]->self = &klass->methods[i];
1858 #ifdef DIRECT_THREADED
1860 _Jv_CompileMethod (_Jv_InterpMethod* method)
1862 if (method->prepared == NULL)
1865 _Jv_InterpMethod::run_debug (NULL, NULL, method);
1867 _Jv_InterpMethod::run (NULL, NULL, method);
1870 #endif // DIRECT_THREADED
1872 #endif // INTERPRETER