OSDN Git Service

2007-05-03 Andrew Haley <aph@redhat.com>
[pf3gnuchains/gcc-fork.git] / libjava / interpret.cc
1 // interpret.cc - Code for the interpreter
2
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 /* Author: Kresten Krab Thorup <krab@gnu.org>  */
12
13 #include <config.h>
14 #include <platform.h>
15
16 #pragma implementation "java-interp.h"
17
18 #include <jvm.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>
39
40 #include <jvmti.h>
41 #include "jvmti-int.h"
42
43 #include <gnu/classpath/jdwp/Jdwp.h>
44 #include <gnu/gcj/jvmti/Breakpoint.h>
45 #include <gnu/gcj/jvmti/BreakpointManager.h>
46 #include <gnu/gcj/jvmti/ExceptionEvent.h>
47
48 #ifdef INTERPRETER
49
50 // Execution engine for interpreted code.
51 _Jv_InterpreterEngine _Jv_soleInterpreterEngine;
52
53 #include <stdlib.h>
54
55 using namespace gcj;
56
57 static void throw_internal_error (const char *msg)
58   __attribute__ ((__noreturn__));
59 static void throw_incompatible_class_change_error (jstring msg)
60   __attribute__ ((__noreturn__));
61 static void throw_null_pointer_exception ()
62   __attribute__ ((__noreturn__));
63
64 static void throw_class_format_error (jstring msg)
65         __attribute__ ((__noreturn__));
66 static void throw_class_format_error (const char *msg)
67         __attribute__ ((__noreturn__));
68
69 #ifdef DIRECT_THREADED
70 // Lock to ensure that methods are not compiled concurrently.
71 // We could use a finer-grained lock here, however it is not safe to use
72 // the Class monitor as user code in another thread could hold it.
73 static _Jv_Mutex_t compile_mutex;
74
75 void
76 _Jv_InitInterpreter()
77 {
78   _Jv_MutexInit (&compile_mutex);
79 }
80 #else
81 void _Jv_InitInterpreter() {}
82 #endif
83
84 // The breakpoint instruction. For the direct threaded case,
85 // _Jv_InterpMethod::compile will initialize breakpoint_insn
86 // the first time it is called.
87 #ifdef DIRECT_THREADED
88 insn_slot _Jv_InterpMethod::bp_insn_slot;
89 pc_t _Jv_InterpMethod::breakpoint_insn = NULL;
90 #else
91 unsigned char _Jv_InterpMethod::bp_insn_opcode
92   = static_cast<unsigned char> (op_breakpoint);
93 pc_t _Jv_InterpMethod::breakpoint_insn = &_Jv_InterpMethod::bp_insn_opcode;
94 #endif
95
96 extern "C" double __ieee754_fmod (double,double);
97
98 static inline void dupx (_Jv_word *sp, int n, int x)
99 {
100   // first "slide" n+x elements n to the right
101   int top = n-1;
102   for (int i = 0; i < n+x; i++)
103     {
104       sp[(top-i)] = sp[(top-i)-n];
105     }
106   
107   // next, copy the n top elements, n+x down
108   for (int i = 0; i < n; i++)
109     {
110       sp[top-(n+x)-i] = sp[top-i];
111     }
112 }
113
114 // Used to convert from floating types to integral types.
115 template<typename TO, typename FROM>
116 static inline TO
117 convert (FROM val, TO min, TO max)
118 {
119   TO ret;
120   if (val >= (FROM) max)
121     ret = max;
122   else if (val <= (FROM) min)
123     ret = min;
124   else if (val != val)
125     ret = 0;
126   else
127     ret = (TO) val;
128   return ret;
129 }
130
131 #define PUSHA(V)  (sp++)->o = (V)
132 #define PUSHI(V)  (sp++)->i = (V)
133 #define PUSHF(V)  (sp++)->f = (V)
134 #if SIZEOF_VOID_P == 8
135 # define PUSHL(V)   (sp->l = (V), sp += 2)
136 # define PUSHD(V)   (sp->d = (V), sp += 2)
137 #else
138 # define PUSHL(V)  do { _Jv_word2 w2; w2.l=(V); \
139                         (sp++)->ia[0] = w2.ia[0]; \
140                         (sp++)->ia[0] = w2.ia[1]; } while (0)
141 # define PUSHD(V)  do { _Jv_word2 w2; w2.d=(V); \
142                         (sp++)->ia[0] = w2.ia[0]; \
143                         (sp++)->ia[0] = w2.ia[1]; } while (0)
144 #endif
145
146 #define POPA()    ((--sp)->o)
147 #define POPI()    ((jint) (--sp)->i) // cast since it may be promoted
148 #define POPF()    ((jfloat) (--sp)->f)
149 #if SIZEOF_VOID_P == 8
150 # define POPL()   (sp -= 2, (jlong) sp->l)
151 # define POPD()   (sp -= 2, (jdouble) sp->d)
152 #else
153 # define POPL()    ({ _Jv_word2 w2; \
154                      w2.ia[1] = (--sp)->ia[0]; \
155                      w2.ia[0] = (--sp)->ia[0]; w2.l; })
156 # define POPD()    ({ _Jv_word2 w2; \
157                      w2.ia[1] = (--sp)->ia[0]; \
158                      w2.ia[0] = (--sp)->ia[0]; w2.d; })
159 #endif
160
161 #define LOADA(I)  (sp++)->o = locals[I].o
162 #define LOADI(I)  (sp++)->i = locals[I].i
163 #define LOADF(I)  (sp++)->f = locals[I].f
164 #if SIZEOF_VOID_P == 8
165 # define LOADL(I)  (sp->l = locals[I].l, sp += 2)
166 # define LOADD(I)  (sp->d = locals[I].d, sp += 2)
167 #else
168 # define LOADL(I)  do { jint __idx = (I); \
169                         (sp++)->ia[0] = locals[__idx].ia[0]; \
170                         (sp++)->ia[0] = locals[__idx+1].ia[0]; \
171                    } while (0)
172 # define LOADD(I)  LOADL(I)
173 #endif
174
175 #define STOREA(I)               \
176   do {                          \
177     DEBUG_LOCALS_INSN (I, 'o'); \
178     locals[I].o = (--sp)->o;    \
179   } while (0)
180 #define STOREI(I)               \
181   do {                          \
182     DEBUG_LOCALS_INSN (I, 'i'); \
183     locals[I].i = (--sp)->i;    \
184   } while (0)
185 #define STOREF(I)               \
186   do {                          \
187     DEBUG_LOCALS_INSN (I, 'f'); \
188     locals[I].f = (--sp)->f;    \
189   } while (0)
190 #if SIZEOF_VOID_P == 8
191 # define STOREL(I)                   \
192   do {                               \
193     DEBUG_LOCALS_INSN (I, 'l');      \
194     DEBUG_LOCALS_INSN (I + 1, 'x');  \
195     (sp -= 2, locals[I].l = sp->l);  \
196   } while (0)
197 # define STORED(I)                   \
198   do {                               \
199     DEBUG_LOCALS_INSN (I, 'd');      \
200     DEBUG_LOCALS_INSN (I + 1, 'x');  \
201     (sp -= 2, locals[I].d = sp->d);  \
202   } while (0)
203
204 #else
205 # define STOREL(I)                   \
206   do {                               \
207     DEBUG_LOCALS_INSN (I, 'l');      \
208     DEBUG_LOCALS_INSN (I + 1, 'x');  \
209     jint __idx = (I);                \
210     locals[__idx+1].ia[0] = (--sp)->ia[0];  \
211     locals[__idx].ia[0] = (--sp)->ia[0];    \
212   } while (0)
213 # define STORED(I)                   \
214   do {                               \
215     DEBUG_LOCALS_INSN (I, 'd');      \
216     DEBUG_LOCALS_INSN (I + 1, 'x');  \
217     jint __idx = (I);                \
218     locals[__idx+1].ia[0] = (--sp)->ia[0];  \
219     locals[__idx].ia[0] = (--sp)->ia[0];    \
220   } while (0)
221 #endif
222
223 #define PEEKI(I)  (locals+(I))->i
224 #define PEEKA(I)  (locals+(I))->o
225
226 #define POKEI(I,V)                              \
227   DEBUG_LOCALS_INSN(I,'i');                     \
228   ((locals+(I))->i = (V))
229
230
231 #define BINOPI(OP) { \
232    jint value2 = POPI(); \
233    jint value1 = POPI(); \
234    PUSHI(value1 OP value2); \
235 }
236
237 #define BINOPF(OP) { \
238    jfloat value2 = POPF(); \
239    jfloat value1 = POPF(); \
240    PUSHF(value1 OP value2); \
241 }
242
243 #define BINOPL(OP) { \
244    jlong value2 = POPL(); \
245    jlong value1 = POPL(); \
246    PUSHL(value1 OP value2); \
247 }
248
249 #define BINOPD(OP) { \
250    jdouble value2 = POPD(); \
251    jdouble value1 = POPD(); \
252    PUSHD(value1 OP value2); \
253 }
254
255 static inline jint
256 get1s (unsigned char* loc)
257 {
258   return *(signed char*)loc;
259 }
260
261 static inline jint
262 get1u (unsigned char* loc)
263 {
264   return *loc;
265 }
266
267 static inline jint
268 get2s(unsigned char* loc)
269 {
270   return (((jint)*(signed char*)loc) << 8) | ((jint)*(loc+1));
271 }
272
273 static inline jint
274 get2u (unsigned char* loc)
275 {
276   return (((jint)(*loc)) << 8) | ((jint)*(loc+1));
277 }
278
279 static jint
280 get4 (unsigned char* loc)
281 {
282   return (((jint)(loc[0])) << 24) 
283        | (((jint)(loc[1])) << 16) 
284        | (((jint)(loc[2])) << 8) 
285        | (((jint)(loc[3])) << 0);
286 }
287
288 #define SAVE_PC() frame_desc.pc = pc
289
290 // We used to define this conditionally, depending on HANDLE_SEGV.
291 // However, that runs into a problem if a chunk in low memory is
292 // mapped and we try to look at a field near the end of a large
293 // object.  See PR 26858 for details.  It is, most likely, relatively
294 // inexpensive to simply do this check always.
295 #define NULLCHECK(X) \
296   do { SAVE_PC(); if ((X)==NULL) throw_null_pointer_exception (); } while (0)
297
298 // Note that we can still conditionally define NULLARRAYCHECK, since
299 // we know that all uses of an array will first reference the length
300 // field, which is first -- and thus will trigger a SEGV.
301 #ifdef HANDLE_SEGV
302 #define NULLARRAYCHECK(X) SAVE_PC()
303 #else
304 #define NULLARRAYCHECK(X)                                       \
305   do                                                            \
306     {                                                           \
307       SAVE_PC();                                                \
308       if ((X) == NULL) { throw_null_pointer_exception (); }     \
309     } while (0)
310 #endif
311
312 #define ARRAYBOUNDSCHECK(array, index)                          \
313   do                                                            \
314     {                                                           \
315       if (((unsigned) index) >= (unsigned) (array->length))     \
316         _Jv_ThrowBadArrayIndex (index);                         \
317     } while (0)
318
319 void
320 _Jv_InterpMethod::run_normal (ffi_cif *,
321                               void *ret,
322                               ffi_raw *args,
323                               void *__this)
324 {
325   _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
326   run (ret, args, _this);
327 }
328
329 void
330 _Jv_InterpMethod::run_normal_debug (ffi_cif *,
331                                     void *ret,
332                                     ffi_raw *args,
333                                     void *__this)
334 {
335   _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
336   run_debug (ret, args, _this);
337 }
338
339 void
340 _Jv_InterpMethod::run_synch_object (ffi_cif *,
341                                     void *ret,
342                                     ffi_raw *args,
343                                     void *__this)
344 {
345   _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
346
347   jobject rcv = (jobject) args[0].ptr;
348   JvSynchronize mutex (rcv);
349
350   run (ret, args, _this);
351 }
352
353 void
354 _Jv_InterpMethod::run_synch_object_debug (ffi_cif *,
355                                           void *ret,
356                                           ffi_raw *args,
357                                           void *__this)
358 {
359   _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
360
361   jobject rcv = (jobject) args[0].ptr;
362   JvSynchronize mutex (rcv);
363
364   run_debug (ret, args, _this);
365 }
366
367 void
368 _Jv_InterpMethod::run_class (ffi_cif *,
369                              void *ret,
370                              ffi_raw *args,
371                              void *__this)
372 {
373   _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
374   _Jv_InitClass (_this->defining_class);
375   run (ret, args, _this);
376 }
377
378 void
379 _Jv_InterpMethod::run_class_debug (ffi_cif *,
380                                    void *ret,
381                                    ffi_raw *args,
382                                    void *__this)
383 {
384   _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
385   _Jv_InitClass (_this->defining_class);
386   run_debug (ret, args, _this);
387 }
388
389 void
390 _Jv_InterpMethod::run_synch_class (ffi_cif *,
391                                    void *ret,
392                                    ffi_raw *args,
393                                    void *__this)
394 {
395   _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
396
397   jclass sync = _this->defining_class;
398   _Jv_InitClass (sync);
399   JvSynchronize mutex (sync);
400
401   run (ret, args, _this);
402 }
403
404 void
405 _Jv_InterpMethod::run_synch_class_debug (ffi_cif *,
406                                          void *ret,
407                                          ffi_raw *args,
408                                          void *__this)
409 {
410   _Jv_InterpMethod *_this = (_Jv_InterpMethod *) __this;
411
412   jclass sync = _this->defining_class;
413   _Jv_InitClass (sync);
414   JvSynchronize mutex (sync);
415
416   run_debug (ret, args, _this);
417 }
418
419 #ifdef DIRECT_THREADED
420 // "Compile" a method by turning it from bytecode to direct-threaded
421 // code.
422 void
423 _Jv_InterpMethod::compile (const void * const *insn_targets)
424 {
425   insn_slot *insns = NULL;
426   int next = 0;
427   unsigned char *codestart = bytecode ();
428   unsigned char *end = codestart + code_length;
429   _Jv_word *pool_data = defining_class->constants.data;
430
431 #define SET_ONE(Field, Value)                                                 \
432   do                                                                          \
433     {                                                                         \
434       if (first_pass)                                                         \
435         ++next;                                                               \
436       else                                                                    \
437         insns[next++].Field = Value;                                          \
438     }                                                                         \
439   while (0)
440
441 #define SET_INSN(Value) SET_ONE (insn, (void *) Value)
442 #define SET_INT(Value) SET_ONE (int_val, Value)
443 #define SET_DATUM(Value) SET_ONE (datum, Value)
444
445   // Map from bytecode PC to slot in INSNS.
446   int *pc_mapping = (int *) __builtin_alloca (sizeof (int) * code_length);
447   for (int i = 0; i < code_length; ++i)
448     pc_mapping[i] = -1;
449
450   for (int i = 0; i < 2; ++i)
451     {
452       jboolean first_pass = i == 0;
453
454       if (! first_pass)
455         {
456           insns = (insn_slot *) _Jv_AllocBytes (sizeof (insn_slot) * next);
457           number_insn_slots = next;
458           next = 0;
459         }
460
461       unsigned char *pc = codestart;
462       while (pc < end)
463         {
464           int base_pc_val = pc - codestart;
465           if (first_pass)
466             pc_mapping[base_pc_val] = next;
467
468           java_opcode opcode = (java_opcode) *pc++;
469           // Just elide NOPs.
470           if (opcode == op_nop)
471             continue;
472           SET_INSN (insn_targets[opcode]);
473
474           switch (opcode)
475             {
476             case op_nop:
477             case op_aconst_null:
478             case op_iconst_m1:
479             case op_iconst_0:
480             case op_iconst_1:
481             case op_iconst_2:
482             case op_iconst_3:
483             case op_iconst_4:
484             case op_iconst_5:
485             case op_lconst_0:
486             case op_lconst_1:
487             case op_fconst_0:
488             case op_fconst_1:
489             case op_fconst_2:
490             case op_dconst_0:
491             case op_dconst_1:
492             case op_iload_0:
493             case op_iload_1:
494             case op_iload_2:
495             case op_iload_3:
496             case op_lload_0:
497             case op_lload_1:
498             case op_lload_2:
499             case op_lload_3:
500             case op_fload_0:
501             case op_fload_1:
502             case op_fload_2:
503             case op_fload_3:
504             case op_dload_0:
505             case op_dload_1:
506             case op_dload_2:
507             case op_dload_3:
508             case op_aload_0:
509             case op_aload_1:
510             case op_aload_2:
511             case op_aload_3:
512             case op_iaload:
513             case op_laload:
514             case op_faload:
515             case op_daload:
516             case op_aaload:
517             case op_baload:
518             case op_caload:
519             case op_saload:
520             case op_istore_0:
521             case op_istore_1:
522             case op_istore_2:
523             case op_istore_3:
524             case op_lstore_0:
525             case op_lstore_1:
526             case op_lstore_2:
527             case op_lstore_3:
528             case op_fstore_0:
529             case op_fstore_1:
530             case op_fstore_2:
531             case op_fstore_3:
532             case op_dstore_0:
533             case op_dstore_1:
534             case op_dstore_2:
535             case op_dstore_3:
536             case op_astore_0:
537             case op_astore_1:
538             case op_astore_2:
539             case op_astore_3:
540             case op_iastore:
541             case op_lastore:
542             case op_fastore:
543             case op_dastore:
544             case op_aastore:
545             case op_bastore:
546             case op_castore:
547             case op_sastore:
548             case op_pop:
549             case op_pop2:
550             case op_dup:
551             case op_dup_x1:
552             case op_dup_x2:
553             case op_dup2:
554             case op_dup2_x1:
555             case op_dup2_x2:
556             case op_swap:
557             case op_iadd:
558             case op_isub:
559             case op_imul:
560             case op_idiv:
561             case op_irem:
562             case op_ishl:
563             case op_ishr:
564             case op_iushr:
565             case op_iand:
566             case op_ior:
567             case op_ixor:
568             case op_ladd:
569             case op_lsub:
570             case op_lmul:
571             case op_ldiv:
572             case op_lrem:
573             case op_lshl:
574             case op_lshr:
575             case op_lushr:
576             case op_land:
577             case op_lor:
578             case op_lxor:
579             case op_fadd:
580             case op_fsub:
581             case op_fmul:
582             case op_fdiv:
583             case op_frem:
584             case op_dadd:
585             case op_dsub:
586             case op_dmul:
587             case op_ddiv:
588             case op_drem:
589             case op_ineg:
590             case op_i2b:
591             case op_i2c:
592             case op_i2s:
593             case op_lneg:
594             case op_fneg:
595             case op_dneg:
596             case op_i2l:
597             case op_i2f:
598             case op_i2d:
599             case op_l2i:
600             case op_l2f:
601             case op_l2d:
602             case op_f2i:
603             case op_f2l:
604             case op_f2d:
605             case op_d2i:
606             case op_d2l:
607             case op_d2f:
608             case op_lcmp:
609             case op_fcmpl:
610             case op_fcmpg:
611             case op_dcmpl:
612             case op_dcmpg:
613             case op_monitorenter:
614             case op_monitorexit:
615             case op_ireturn:
616             case op_lreturn:
617             case op_freturn:
618             case op_dreturn:
619             case op_areturn:
620             case op_return:
621             case op_athrow:
622             case op_arraylength:
623               // No argument, nothing else to do.
624               break;
625
626             case op_bipush:
627               SET_INT (get1s (pc));
628               ++pc;
629               break;
630
631             case op_ldc:
632               {
633                 int index = get1u (pc);
634                 ++pc;
635                 // For an unresolved class we want to delay resolution
636                 // until execution.
637                 if (defining_class->constants.tags[index] == JV_CONSTANT_Class)
638                   {
639                     --next;
640                     SET_INSN (insn_targets[int (op_jsr_w) + 1]);
641                     SET_INT (index);
642                   }
643                 else
644                   SET_DATUM (pool_data[index].o);
645               }
646               break;
647
648             case op_ret:
649             case op_iload:
650             case op_lload:
651             case op_fload:
652             case op_dload:
653             case op_aload:
654             case op_istore:
655             case op_lstore:
656             case op_fstore:
657             case op_dstore:
658             case op_astore:
659             case op_newarray:
660               SET_INT (get1u (pc));
661               ++pc;
662               break;
663
664             case op_iinc:
665               SET_INT (get1u (pc));
666               SET_INT (get1s (pc + 1));
667               pc += 2;
668               break;
669
670             case op_ldc_w:
671               {
672                 int index = get2u (pc);
673                 pc += 2;
674                 // For an unresolved class we want to delay resolution
675                 // until execution.
676                 if (defining_class->constants.tags[index] == JV_CONSTANT_Class)
677                   {
678                     --next;
679                     SET_INSN (insn_targets[int (op_jsr_w) + 1]);
680                     SET_INT (index);
681                   }
682                 else
683                   SET_DATUM (pool_data[index].o);
684               }
685               break;
686
687             case op_ldc2_w:
688               {
689                 int index = get2u (pc);
690                 pc += 2;
691                 SET_DATUM (&pool_data[index]);
692               }
693               break;
694
695             case op_sipush:
696               SET_INT (get2s (pc));
697               pc += 2;
698               break;
699
700             case op_new:
701             case op_getstatic:
702             case op_getfield:
703             case op_putfield:
704             case op_putstatic:
705             case op_anewarray:
706             case op_instanceof:
707             case op_checkcast:
708             case op_invokespecial:
709             case op_invokestatic:
710             case op_invokevirtual:
711               SET_INT (get2u (pc));
712               pc += 2;
713               break;
714
715             case op_multianewarray:
716               SET_INT (get2u (pc));
717               SET_INT (get1u (pc + 2));
718               pc += 3;
719               break;
720
721             case op_jsr:
722             case op_ifeq:
723             case op_ifne:
724             case op_iflt:
725             case op_ifge:
726             case op_ifgt:
727             case op_ifle:
728             case op_if_icmpeq:
729             case op_if_icmpne:
730             case op_if_icmplt:
731             case op_if_icmpge:
732             case op_if_icmpgt:
733             case op_if_icmple:
734             case op_if_acmpeq:
735             case op_if_acmpne:
736             case op_ifnull:
737             case op_ifnonnull:
738             case op_goto:
739               {
740                 int offset = get2s (pc);
741                 pc += 2;
742
743                 int new_pc = base_pc_val + offset;
744
745                 bool orig_was_goto = opcode == op_goto;
746
747                 // Thread jumps.  We limit the loop count; this lets
748                 // us avoid infinite loops if the bytecode contains
749                 // such.  `10' is arbitrary.
750                 int count = 10;
751                 while (codestart[new_pc] == op_goto && count-- > 0)
752                   new_pc += get2s (&codestart[new_pc + 1]);
753
754                 // If the jump takes us to a `return' instruction and
755                 // the original branch was an unconditional goto, then
756                 // we hoist the return.
757                 opcode = (java_opcode) codestart[new_pc];
758                 if (orig_was_goto
759                     && (opcode == op_ireturn || opcode == op_lreturn
760                         || opcode == op_freturn || opcode == op_dreturn
761                         || opcode == op_areturn || opcode == op_return))
762                   {
763                     --next;
764                     SET_INSN (insn_targets[opcode]);
765                   }
766                 else
767                   SET_DATUM (&insns[pc_mapping[new_pc]]);
768               }
769               break;
770
771             case op_tableswitch:
772               {
773                 while ((pc - codestart) % 4 != 0)
774                   ++pc;
775
776                 jint def = get4 (pc);
777                 SET_DATUM (&insns[pc_mapping[base_pc_val + def]]);
778                 pc += 4;
779
780                 int low = get4 (pc);
781                 SET_INT (low);
782                 pc += 4;
783                 int high = get4 (pc);
784                 SET_INT (high);
785                 pc += 4;
786
787                 for (int i = low; i <= high; ++i)
788                   {
789                     SET_DATUM (&insns[pc_mapping[base_pc_val + get4 (pc)]]);
790                     pc += 4;
791                   }
792               }
793               break;
794
795             case op_lookupswitch:
796               {
797                 while ((pc - codestart) % 4 != 0)
798                   ++pc;
799
800                 jint def = get4 (pc);
801                 SET_DATUM (&insns[pc_mapping[base_pc_val + def]]);
802                 pc += 4;
803
804                 jint npairs = get4 (pc);
805                 pc += 4;
806                 SET_INT (npairs);
807
808                 while (npairs-- > 0)
809                   {
810                     jint match = get4 (pc);
811                     jint offset = get4 (pc + 4);
812                     SET_INT (match);
813                     SET_DATUM (&insns[pc_mapping[base_pc_val + offset]]);
814                     pc += 8;
815                   }
816               }
817               break;
818
819             case op_invokeinterface:
820               {
821                 jint index = get2u (pc);
822                 pc += 2;
823                 // We ignore the next two bytes.
824                 pc += 2;
825                 SET_INT (index);
826               }
827               break;
828
829             case op_wide:
830               {
831                 opcode = (java_opcode) get1u (pc);
832                 pc += 1;
833                 jint val = get2u (pc);
834                 pc += 2;
835
836                 // We implement narrow and wide instructions using the
837                 // same code in the interpreter.  So we rewrite the
838                 // instruction slot here.
839                 if (! first_pass)
840                   insns[next - 1].insn = (void *) insn_targets[opcode];
841                 SET_INT (val);
842
843                 if (opcode == op_iinc)
844                   {
845                     SET_INT (get2s (pc));
846                     pc += 2;
847                   }
848               }
849               break;
850
851             case op_jsr_w:
852             case op_goto_w:
853               {
854                 jint offset = get4 (pc);
855                 pc += 4;
856                 SET_DATUM (&insns[pc_mapping[base_pc_val + offset]]);
857               }
858               break;
859
860             // Some "can't happen" cases that we include for
861             // error-checking purposes.
862             case op_putfield_1:
863             case op_putfield_2:
864             case op_putfield_4:
865             case op_putfield_8:
866             case op_putfield_a:
867             case op_putstatic_1:
868             case op_putstatic_2:
869             case op_putstatic_4:
870             case op_putstatic_8:
871             case op_putstatic_a:
872             case op_getfield_1:
873             case op_getfield_2s:
874             case op_getfield_2u:
875             case op_getfield_4:
876             case op_getfield_8:
877             case op_getfield_a:
878             case op_getstatic_1:
879             case op_getstatic_2s:
880             case op_getstatic_2u:
881             case op_getstatic_4:
882             case op_getstatic_8:
883             case op_getstatic_a:
884             case op_breakpoint:
885             default:
886               // Fail somehow.
887               break;
888             }
889         }
890     }
891
892   // Now update exceptions.
893   _Jv_InterpException *exc = exceptions ();
894   for (int i = 0; i < exc_count; ++i)
895     {
896       exc[i].start_pc.p = &insns[pc_mapping[exc[i].start_pc.i]];
897       exc[i].end_pc.p = &insns[pc_mapping[exc[i].end_pc.i]];
898       exc[i].handler_pc.p = &insns[pc_mapping[exc[i].handler_pc.i]];
899       // FIXME: resolve_pool_entry can throw - we shouldn't be doing this
900       // during compilation.
901       jclass handler
902         = (_Jv_Linker::resolve_pool_entry (defining_class,
903                                              exc[i].handler_type.i)).clazz;
904       exc[i].handler_type.p = handler;
905     }
906
907   // Translate entries in the LineNumberTable from bytecode PC's to direct
908   // threaded interpreter instruction values.
909   for (int i = 0; i < line_table_len; i++)
910     {
911       int byte_pc = line_table[i].bytecode_pc;
912       // It isn't worth throwing an exception if this table is
913       // corrupted, but at the same time we don't want a crash.
914       if (byte_pc < 0 || byte_pc >= code_length)
915         byte_pc = 0;
916       line_table[i].pc = &insns[pc_mapping[byte_pc]];
917     }  
918
919   prepared = insns;
920
921   if (breakpoint_insn == NULL)
922     {
923       bp_insn_slot.insn = const_cast<void *> (insn_targets[op_breakpoint]);
924       breakpoint_insn = &bp_insn_slot;
925     }
926 }
927 #endif /* DIRECT_THREADED */
928
929 /* Run the given method.
930    When args is NULL, don't run anything -- just compile it. */
931 void
932 _Jv_InterpMethod::run (void *retp, ffi_raw *args, _Jv_InterpMethod *meth)
933 {
934 #undef DEBUG
935 #undef DEBUG_LOCALS_INSN
936 #define DEBUG_LOCALS_INSN(s, t) do {} while (0)
937
938 #include "interpret-run.cc"
939 }
940
941 void
942 _Jv_InterpMethod::run_debug (void *retp, ffi_raw *args, _Jv_InterpMethod *meth)
943 {
944 #define DEBUG
945 #undef DEBUG_LOCALS_INSN
946 #define DEBUG_LOCALS_INSN(s, t)  \
947   do    \
948     {   \
949       frame_desc.locals_type[s] = t;  \
950     }   \
951   while (0)
952
953 #include "interpret-run.cc"
954 }
955
956 static void
957 throw_internal_error (const char *msg)
958 {
959   throw new java::lang::InternalError (JvNewStringLatin1 (msg));
960 }
961
962 static void 
963 throw_incompatible_class_change_error (jstring msg)
964 {
965   throw new java::lang::IncompatibleClassChangeError (msg);
966 }
967
968 static void 
969 throw_null_pointer_exception ()
970 {
971   throw new java::lang::NullPointerException;
972 }
973
974 /* Look up source code line number for given bytecode (or direct threaded
975    interpreter) PC. */
976 int
977 _Jv_InterpMethod::get_source_line(pc_t mpc)
978 {
979   int line = line_table_len > 0 ? line_table[0].line : -1;
980   for (int i = 1; i < line_table_len; i++)
981     if (line_table[i].pc > mpc)
982       break;
983     else
984       line = line_table[i].line;
985
986   return line;
987 }
988
989 /** Do static initialization for fields with a constant initializer */
990 void
991 _Jv_InitField (jobject obj, jclass klass, int index)
992 {
993   using namespace java::lang::reflect;
994
995   if (obj != 0 && klass == 0)
996     klass = obj->getClass ();
997
998   if (!_Jv_IsInterpretedClass (klass))
999     return;
1000
1001   _Jv_InterpClass *iclass = (_Jv_InterpClass*)klass->aux_info;
1002
1003   _Jv_Field * field = (&klass->fields[0]) + index;
1004
1005   if (index > klass->field_count)
1006     throw_internal_error ("field out of range");
1007
1008   int init = iclass->field_initializers[index];
1009   if (init == 0)
1010     return;
1011
1012   _Jv_Constants *pool = &klass->constants;
1013   int tag = pool->tags[init];
1014
1015   if (! field->isResolved ())
1016     throw_internal_error ("initializing unresolved field");
1017
1018   if (obj==0 && ((field->flags & Modifier::STATIC) == 0))
1019     throw_internal_error ("initializing non-static field with no object");
1020
1021   void *addr = 0;
1022
1023   if ((field->flags & Modifier::STATIC) != 0)
1024     addr = (void*) field->u.addr;
1025   else
1026     addr = (void*) (((char*)obj) + field->u.boffset);
1027
1028   switch (tag)
1029     {
1030     case JV_CONSTANT_String:
1031       {
1032         jstring str;
1033         str = _Jv_NewStringUtf8Const (pool->data[init].utf8);
1034         pool->data[init].string = str;
1035         pool->tags[init] = JV_CONSTANT_ResolvedString;
1036       }
1037       /* fall through */
1038
1039     case JV_CONSTANT_ResolvedString:
1040       if (! (field->type == &java::lang::String::class$
1041              || field->type == &java::lang::Class::class$))
1042         throw_class_format_error ("string initialiser to non-string field");
1043
1044       *(jstring*)addr = pool->data[init].string;
1045       break;
1046
1047     case JV_CONSTANT_Integer:
1048       {
1049         int value = pool->data[init].i;
1050
1051         if (field->type == JvPrimClass (boolean))
1052           *(jboolean*)addr = (jboolean)value;
1053         
1054         else if (field->type == JvPrimClass (byte))
1055           *(jbyte*)addr = (jbyte)value;
1056         
1057         else if (field->type == JvPrimClass (char))
1058           *(jchar*)addr = (jchar)value;
1059
1060         else if (field->type == JvPrimClass (short))
1061           *(jshort*)addr = (jshort)value;
1062         
1063         else if (field->type == JvPrimClass (int))
1064           *(jint*)addr = (jint)value;
1065
1066         else
1067           throw_class_format_error ("erroneous field initializer");
1068       }  
1069       break;
1070
1071     case JV_CONSTANT_Long:
1072       if (field->type != JvPrimClass (long))
1073         throw_class_format_error ("erroneous field initializer");
1074
1075       *(jlong*)addr = _Jv_loadLong (&pool->data[init]);
1076       break;
1077
1078     case JV_CONSTANT_Float:
1079       if (field->type != JvPrimClass (float))
1080         throw_class_format_error ("erroneous field initializer");
1081
1082       *(jfloat*)addr = pool->data[init].f;
1083       break;
1084
1085     case JV_CONSTANT_Double:
1086       if (field->type != JvPrimClass (double))
1087         throw_class_format_error ("erroneous field initializer");
1088
1089       *(jdouble*)addr = _Jv_loadDouble (&pool->data[init]);
1090       break;
1091
1092     default:
1093       throw_class_format_error ("erroneous field initializer");
1094     }
1095 }
1096
1097 inline static unsigned char*
1098 skip_one_type (unsigned char* ptr)
1099 {
1100   int ch = *ptr++;
1101
1102   while (ch == '[')
1103     { 
1104       ch = *ptr++;
1105     }
1106   
1107   if (ch == 'L')
1108     {
1109       do { ch = *ptr++; } while (ch != ';');
1110     }
1111
1112   return ptr;
1113 }
1114
1115 static ffi_type*
1116 get_ffi_type_from_signature (unsigned char* ptr)
1117 {
1118   switch (*ptr) 
1119     {
1120     case 'L':
1121     case '[':
1122       return &ffi_type_pointer;
1123       break;
1124
1125     case 'Z':
1126       // On some platforms a bool is a byte, on others an int.
1127       if (sizeof (jboolean) == sizeof (jbyte))
1128         return &ffi_type_sint8;
1129       else
1130         {
1131           JvAssert (sizeof (jbyte) == sizeof (jint));
1132           return &ffi_type_sint32;
1133         }
1134       break;
1135
1136     case 'B':
1137       return &ffi_type_sint8;
1138       break;
1139       
1140     case 'C':
1141       return &ffi_type_uint16;
1142       break;
1143           
1144     case 'S': 
1145       return &ffi_type_sint16;
1146       break;
1147           
1148     case 'I':
1149       return &ffi_type_sint32;
1150       break;
1151           
1152     case 'J':
1153       return &ffi_type_sint64;
1154       break;
1155           
1156     case 'F':
1157       return &ffi_type_float;
1158       break;
1159           
1160     case 'D':
1161       return &ffi_type_double;
1162       break;
1163
1164     case 'V':
1165       return &ffi_type_void;
1166       break;
1167     }
1168
1169   throw_internal_error ("unknown type in signature");
1170 }
1171
1172 /* this function yields the number of actual arguments, that is, if the
1173  * function is non-static, then one is added to the number of elements
1174  * found in the signature */
1175
1176 int 
1177 _Jv_count_arguments (_Jv_Utf8Const *signature,
1178                      jboolean staticp)
1179 {
1180   unsigned char *ptr = (unsigned char*) signature->chars();
1181   int arg_count = staticp ? 0 : 1;
1182
1183   /* first, count number of arguments */
1184
1185   // skip '('
1186   ptr++;
1187
1188   // count args
1189   while (*ptr != ')')
1190     {
1191       ptr = skip_one_type (ptr);
1192       arg_count += 1;
1193     }
1194
1195   return arg_count;
1196 }
1197
1198 /* This beast will build a cif, given the signature.  Memory for
1199  * the cif itself and for the argument types must be allocated by the
1200  * caller.
1201  */
1202
1203 int 
1204 _Jv_init_cif (_Jv_Utf8Const* signature,
1205               int arg_count,
1206               jboolean staticp,
1207               ffi_cif *cif,
1208               ffi_type **arg_types,
1209               ffi_type **rtype_p)
1210 {
1211   unsigned char *ptr = (unsigned char*) signature->chars();
1212
1213   int arg_index = 0;            // arg number
1214   int item_count = 0;           // stack-item count
1215
1216   // setup receiver
1217   if (!staticp)
1218     {
1219       arg_types[arg_index++] = &ffi_type_pointer;
1220       item_count += 1;
1221     }
1222
1223   // skip '('
1224   ptr++;
1225
1226   // assign arg types
1227   while (*ptr != ')')
1228     {
1229       arg_types[arg_index++] = get_ffi_type_from_signature (ptr);
1230
1231       if (*ptr == 'J' || *ptr == 'D')
1232         item_count += 2;
1233       else
1234         item_count += 1;
1235
1236       ptr = skip_one_type (ptr);
1237     }
1238
1239   // skip ')'
1240   ptr++;
1241   ffi_type *rtype = get_ffi_type_from_signature (ptr);
1242
1243   ptr = skip_one_type (ptr);
1244   if (ptr != (unsigned char*)signature->chars() + signature->len())
1245     throw_internal_error ("did not find end of signature");
1246
1247   if (ffi_prep_cif (cif, FFI_DEFAULT_ABI,
1248                     arg_count, rtype, arg_types) != FFI_OK)
1249     throw_internal_error ("ffi_prep_cif failed");
1250
1251   if (rtype_p != NULL)
1252     *rtype_p = rtype;
1253
1254   return item_count;
1255 }
1256
1257 #if FFI_NATIVE_RAW_API
1258 #   define FFI_PREP_RAW_CLOSURE ffi_prep_raw_closure_loc
1259 #   define FFI_RAW_SIZE ffi_raw_size
1260 #else
1261 #   define FFI_PREP_RAW_CLOSURE ffi_prep_java_raw_closure_loc
1262 #   define FFI_RAW_SIZE ffi_java_raw_size
1263 #endif
1264
1265 /* we put this one here, and not in interpret.cc because it
1266  * calls the utility routines _Jv_count_arguments 
1267  * which are static to this module.  The following struct defines the
1268  * layout we use for the stubs, it's only used in the ncode method. */
1269
1270 typedef struct {
1271   ffi_raw_closure  closure;
1272   _Jv_ClosureList list;
1273   ffi_cif   cif;
1274   ffi_type *arg_types[0];
1275 } ncode_closure;
1276
1277 typedef void (*ffi_closure_fun) (ffi_cif*,void*,ffi_raw*,void*);
1278
1279 void *
1280 _Jv_InterpMethod::ncode (jclass klass)
1281 {
1282   using namespace java::lang::reflect;
1283
1284   if (self->ncode != 0)
1285     return self->ncode;
1286
1287   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1288   int arg_count = _Jv_count_arguments (self->signature, staticp);
1289
1290   void *code;
1291   ncode_closure *closure =
1292     (ncode_closure*)ffi_closure_alloc (sizeof (ncode_closure)
1293                                        + arg_count * sizeof (ffi_type*),
1294                                        &code);
1295   closure->list.registerClosure (klass, closure);
1296
1297   _Jv_init_cif (self->signature,
1298                 arg_count,
1299                 staticp,
1300                 &closure->cif,
1301                 &closure->arg_types[0],
1302                 NULL);
1303
1304   ffi_closure_fun fun;
1305
1306   args_raw_size = FFI_RAW_SIZE (&closure->cif);
1307
1308   JvAssert ((self->accflags & Modifier::NATIVE) == 0);
1309
1310   if ((self->accflags & Modifier::SYNCHRONIZED) != 0)
1311     {
1312       if (staticp)
1313         {
1314           if (JVMTI::enabled)
1315             fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class_debug;
1316           else
1317             fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_class;
1318         }
1319       else
1320         {
1321           if (JVMTI::enabled)
1322             fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object_debug;
1323           else
1324             fun = (ffi_closure_fun)&_Jv_InterpMethod::run_synch_object;
1325         }
1326     }
1327   else
1328     {
1329       if (staticp)
1330         {
1331           if (JVMTI::enabled)
1332             fun = (ffi_closure_fun)&_Jv_InterpMethod::run_class_debug;
1333           else
1334             fun = (ffi_closure_fun)&_Jv_InterpMethod::run_class;
1335         }
1336       else
1337         {
1338           if (JVMTI::enabled)
1339             fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal_debug;
1340           else
1341             fun = (ffi_closure_fun)&_Jv_InterpMethod::run_normal;
1342         }
1343     }
1344
1345   FFI_PREP_RAW_CLOSURE (&closure->closure,
1346                         &closure->cif, 
1347                         fun,
1348                         (void*)this,
1349                         code);
1350
1351   self->ncode = code;
1352
1353   return self->ncode;
1354 }
1355
1356 /* Find the index of the given insn in the array of insn slots
1357    for this method. Returns -1 if not found. */
1358 jlong
1359 _Jv_InterpMethod::insn_index (pc_t pc)
1360 {
1361   jlong left = 0;
1362 #ifdef DIRECT_THREADED
1363   jlong right = number_insn_slots;
1364   pc_t insns = prepared;
1365 #else
1366   jlong right = code_length;
1367   pc_t insns = bytecode ();
1368 #endif
1369
1370   while (right >= 0)
1371     {
1372       jlong mid = (left + right) / 2;
1373       if (&insns[mid] == pc)
1374         return mid;
1375
1376       if (pc < &insns[mid])
1377         right = mid - 1;
1378       else
1379         left = mid + 1;
1380     }
1381
1382   return -1;
1383 }
1384
1385 // Method to check if an exception is caught at some location in a method
1386 // (meth).  Returns true if this method (meth) contains a catch block for the
1387 // exception (ex). False otherwise.  If there is a catch block, it sets the pc
1388 // to the location of the beginning of the catch block.
1389 jboolean
1390 _Jv_InterpMethod::check_handler (pc_t *pc, _Jv_InterpMethod *meth,
1391                                 java::lang::Throwable *ex)
1392 {
1393 #ifdef DIRECT_THREADED
1394   void *logical_pc = (void *) ((insn_slot *) (*pc) - 1);
1395 #else
1396   int logical_pc = (*pc) - 1 - meth->bytecode ();
1397 #endif
1398   _Jv_InterpException *exc = meth->exceptions ();
1399   jclass exc_class = ex->getClass ();
1400
1401   for (int i = 0; i < meth->exc_count; i++)
1402     {
1403       if (PCVAL (exc[i].start_pc) <= logical_pc
1404           && logical_pc < PCVAL (exc[i].end_pc))
1405         {
1406 #ifdef DIRECT_THREADED
1407               jclass handler = (jclass) exc[i].handler_type.p;
1408 #else
1409               jclass handler = NULL;
1410               if (exc[i].handler_type.i != 0)
1411                     handler
1412                       = (_Jv_Linker::resolve_pool_entry (meth->defining_class,
1413                                                                              ex$
1414 #endif /* DIRECT_THREADED */
1415               if (handler == NULL || handler->isAssignableFrom (exc_class))
1416                 {
1417 #ifdef DIRECT_THREADED
1418                   (*pc) = (insn_slot *) exc[i].handler_pc.p;
1419 #else
1420                   (*pc) = meth->bytecode () + exc[i].handler_pc.i;
1421 #endif /* DIRECT_THREADED */
1422                   return true;
1423                 }
1424           }
1425       }
1426   return false;
1427 }
1428
1429
1430 void
1431 _Jv_InterpMethod::get_line_table (jlong& start, jlong& end,
1432                                   jintArray& line_numbers,
1433                                   jlongArray& code_indices)
1434 {
1435 #ifdef DIRECT_THREADED
1436   /* For the DIRECT_THREADED case, if the method has not yet been
1437    * compiled, the linetable will change to insn slots instead of
1438    * bytecode PCs. It is probably easiest, in this case, to simply
1439    * compile the method and guarantee that we are using insn
1440    * slots.
1441    */
1442   _Jv_CompileMethod (this);
1443
1444   if (line_table_len > 0)
1445     {
1446       start = 0;
1447       end = number_insn_slots;
1448       line_numbers = JvNewIntArray (line_table_len);
1449       code_indices = JvNewLongArray (line_table_len);
1450
1451       jint* lines = elements (line_numbers);
1452       jlong* indices = elements (code_indices);
1453       for (int i = 0; i < line_table_len; ++i)
1454         {
1455           lines[i] = line_table[i].line;
1456           indices[i] = insn_index (line_table[i].pc);
1457         }
1458     }
1459 #else // !DIRECT_THREADED
1460   if (line_table_len > 0)
1461     {
1462       start = 0;
1463       end = code_length;
1464       line_numbers = JvNewIntArray (line_table_len);
1465       code_indices = JvNewLongArray (line_table_len);
1466
1467       jint* lines = elements (line_numbers);
1468       jlong* indices = elements (code_indices);
1469       for (int i = 0; i < line_table_len; ++i)
1470         {
1471           lines[i] = line_table[i].line;
1472           indices[i] = (jlong) line_table[i].bytecode_pc;
1473         }
1474     }
1475 #endif // !DIRECT_THREADED
1476 }
1477
1478 int 
1479 _Jv_InterpMethod::get_local_var_table (char **name, char **sig, 
1480                                        char **generic_sig, jlong *startloc,
1481                                        jint *length, jint *slot, 
1482                                        int table_slot)
1483 {       
1484   if (local_var_table == NULL)
1485     return -2;
1486   if (table_slot >= local_var_table_len)
1487     return -1;
1488   else
1489     {
1490       *name = local_var_table[table_slot].name;
1491       *sig = local_var_table[table_slot].descriptor;
1492       *generic_sig = local_var_table[table_slot].descriptor;
1493
1494       *startloc = static_cast<jlong> 
1495                     (local_var_table[table_slot].bytecode_start_pc);
1496       *length = static_cast<jint> (local_var_table[table_slot].length);
1497       *slot = static_cast<jint> (local_var_table[table_slot].slot);
1498     }
1499   return local_var_table_len - table_slot -1;
1500 }
1501
1502 pc_t
1503 _Jv_InterpMethod::install_break (jlong index)
1504 {
1505   return set_insn (index, breakpoint_insn);
1506 }
1507
1508 pc_t
1509 _Jv_InterpMethod::get_insn (jlong index)
1510 {
1511   pc_t code;
1512
1513 #ifdef DIRECT_THREADED
1514   if (index >= number_insn_slots || index < 0)
1515     return NULL;
1516
1517   code = prepared;
1518 #else // !DIRECT_THREADED
1519   if (index >= code_length || index < 0)
1520     return NULL;
1521
1522   code = reinterpret_cast<pc_t> (bytecode ());
1523 #endif // !DIRECT_THREADED
1524
1525   return &code[index];
1526 }
1527
1528 pc_t
1529 _Jv_InterpMethod::set_insn (jlong index, pc_t insn)
1530 {
1531 #ifdef DIRECT_THREADED
1532   if (index >= number_insn_slots || index < 0)
1533     return NULL;
1534
1535   pc_t code = prepared;
1536   code[index].insn = insn->insn;
1537 #else // !DIRECT_THREADED
1538   if (index >= code_length || index < 0)
1539     return NULL;
1540
1541   pc_t code = reinterpret_cast<pc_t> (bytecode ());
1542   code[index] = *insn;
1543 #endif // !DIRECT_THREADED
1544
1545   return &code[index];
1546 }
1547
1548 void *
1549 _Jv_JNIMethod::ncode (jclass klass)
1550 {
1551   using namespace java::lang::reflect;
1552
1553   if (self->ncode != 0)
1554     return self->ncode;
1555
1556   jboolean staticp = (self->accflags & Modifier::STATIC) != 0;
1557   int arg_count = _Jv_count_arguments (self->signature, staticp);
1558
1559   void *code;
1560   ncode_closure *closure =
1561     (ncode_closure*)ffi_closure_alloc (sizeof (ncode_closure)
1562                                        + arg_count * sizeof (ffi_type*),
1563                                        &code);
1564   closure->list.registerClosure (klass, closure);
1565
1566   ffi_type *rtype;
1567   _Jv_init_cif (self->signature,
1568                 arg_count,
1569                 staticp,
1570                 &closure->cif,
1571                 &closure->arg_types[0],
1572                 &rtype);
1573
1574   ffi_closure_fun fun;
1575
1576   args_raw_size = FFI_RAW_SIZE (&closure->cif);
1577
1578   // Initialize the argument types and CIF that represent the actual
1579   // underlying JNI function.
1580   int extra_args = 1;
1581   if ((self->accflags & Modifier::STATIC))
1582     ++extra_args;
1583   jni_arg_types = (ffi_type **) _Jv_AllocBytes ((extra_args + arg_count)
1584                                                 * sizeof (ffi_type *));
1585   int offset = 0;
1586   jni_arg_types[offset++] = &ffi_type_pointer;
1587   if ((self->accflags & Modifier::STATIC))
1588     jni_arg_types[offset++] = &ffi_type_pointer;
1589   memcpy (&jni_arg_types[offset], &closure->arg_types[0],
1590           arg_count * sizeof (ffi_type *));
1591
1592   if (ffi_prep_cif (&jni_cif, _Jv_platform_ffi_abi,
1593                     extra_args + arg_count, rtype,
1594                     jni_arg_types) != FFI_OK)
1595     throw_internal_error ("ffi_prep_cif failed for JNI function");
1596
1597   JvAssert ((self->accflags & Modifier::NATIVE) != 0);
1598
1599   // FIXME: for now we assume that all native methods for
1600   // interpreted code use JNI.
1601   fun = (ffi_closure_fun) &_Jv_JNIMethod::call;
1602
1603   FFI_PREP_RAW_CLOSURE (&closure->closure,
1604                         &closure->cif, 
1605                         fun,
1606                         (void*) this,
1607                         code);
1608
1609   self->ncode = code;
1610   return self->ncode;
1611 }
1612
1613 static void
1614 throw_class_format_error (jstring msg)
1615 {
1616   throw (msg
1617          ? new java::lang::ClassFormatError (msg)
1618          : new java::lang::ClassFormatError);
1619 }
1620
1621 static void
1622 throw_class_format_error (const char *msg)
1623 {
1624   throw_class_format_error (JvNewStringLatin1 (msg));
1625 }
1626
1627 \f
1628
1629 void
1630 _Jv_InterpreterEngine::do_verify (jclass klass)
1631 {
1632   _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1633   for (int i = 0; i < klass->method_count; i++)
1634     {
1635       using namespace java::lang::reflect;
1636       _Jv_MethodBase *imeth = iclass->interpreted_methods[i];
1637       _Jv_ushort accflags = klass->methods[i].accflags;
1638       if ((accflags & (Modifier::NATIVE | Modifier::ABSTRACT)) == 0)
1639         {
1640           _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
1641           _Jv_VerifyMethod (im);
1642         }
1643     }
1644 }
1645
1646 void
1647 _Jv_InterpreterEngine::do_create_ncode (jclass klass)
1648 {
1649   _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1650   for (int i = 0; i < klass->method_count; i++)
1651     {
1652       // Just skip abstract methods.  This is particularly important
1653       // because we don't resize the interpreted_methods array when
1654       // miranda methods are added to it.
1655       if ((klass->methods[i].accflags
1656            & java::lang::reflect::Modifier::ABSTRACT)
1657           != 0)
1658         continue;
1659
1660       _Jv_MethodBase *imeth = iclass->interpreted_methods[i];
1661
1662       if ((klass->methods[i].accflags & java::lang::reflect::Modifier::NATIVE)
1663           != 0)
1664         {
1665           // You might think we could use a virtual `ncode' method in
1666           // the _Jv_MethodBase and unify the native and non-native
1667           // cases.  Well, we can't, because we don't allocate these
1668           // objects using `new', and thus they don't get a vtable.
1669           _Jv_JNIMethod *jnim = reinterpret_cast<_Jv_JNIMethod *> (imeth);
1670           klass->methods[i].ncode = jnim->ncode (klass);
1671         }
1672       else if (imeth != 0)              // it could be abstract
1673         {
1674           _Jv_InterpMethod *im = reinterpret_cast<_Jv_InterpMethod *> (imeth);
1675           klass->methods[i].ncode = im->ncode (klass);
1676         }
1677     }
1678 }
1679
1680 _Jv_ClosureList **
1681 _Jv_InterpreterEngine::do_get_closure_list (jclass klass)
1682 {
1683   _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1684
1685   if (!iclass->closures)
1686     iclass->closures = _Jv_ClosureListFinalizer ();
1687
1688   return iclass->closures;
1689 }
1690
1691 void
1692 _Jv_InterpreterEngine::do_allocate_static_fields (jclass klass,
1693                                                   int pointer_size,
1694                                                   int other_size)
1695 {
1696   _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1697
1698   // Splitting the allocations here lets us scan reference fields and
1699   // avoid scanning non-reference fields.  How reference fields are
1700   // scanned is a bit tricky: we allocate using _Jv_AllocRawObj, which
1701   // means that this memory will be scanned conservatively (same
1702   // difference, since we know all the contents here are pointers).
1703   // Then we put pointers into this memory into the 'fields'
1704   // structure.  Most of these are interior pointers, which is ok (but
1705   // even so the pointer to the first reference field will be used and
1706   // that is not an interior pointer).  The 'fields' array is also
1707   // allocated with _Jv_AllocRawObj (see defineclass.cc), so it will
1708   // be scanned.  A pointer to this array is held by Class and thus
1709   // seen by the collector.
1710   char *reference_fields = (char *) _Jv_AllocRawObj (pointer_size);
1711   char *non_reference_fields = (char *) _Jv_AllocBytes (other_size);
1712
1713   for (int i = 0; i < klass->field_count; i++)
1714     {
1715       _Jv_Field *field = &klass->fields[i];
1716
1717       if ((field->flags & java::lang::reflect::Modifier::STATIC) == 0)
1718         continue;
1719
1720       char *base = field->isRef() ? reference_fields : non_reference_fields;
1721       field->u.addr  = base + field->u.boffset;
1722
1723       if (iclass->field_initializers[i] != 0)
1724         {
1725           _Jv_Linker::resolve_field (field, klass->loader);
1726           _Jv_InitField (0, klass, i);
1727         }
1728     }
1729
1730   // Now we don't need the field_initializers anymore, so let the
1731   // collector get rid of it.
1732   iclass->field_initializers = 0;
1733 }
1734
1735 _Jv_ResolvedMethod *
1736 _Jv_InterpreterEngine::do_resolve_method (_Jv_Method *method, jclass klass,
1737                                           jboolean staticp)
1738 {
1739   int arg_count = _Jv_count_arguments (method->signature, staticp);
1740
1741   _Jv_ResolvedMethod* result = (_Jv_ResolvedMethod*)
1742     _Jv_AllocBytes (sizeof (_Jv_ResolvedMethod)
1743                     + arg_count*sizeof (ffi_type*));
1744
1745   result->stack_item_count
1746     = _Jv_init_cif (method->signature,
1747                     arg_count,
1748                     staticp,
1749                     &result->cif,
1750                     &result->arg_types[0],
1751                     NULL);
1752
1753   result->method              = method;
1754   result->klass               = klass;
1755
1756   return result;
1757 }
1758
1759 void
1760 _Jv_InterpreterEngine::do_post_miranda_hook (jclass klass)
1761 {
1762   _Jv_InterpClass *iclass = (_Jv_InterpClass *) klass->aux_info;
1763   for (int i = 0; i < klass->method_count; i++)
1764     {
1765       // Just skip abstract methods.  This is particularly important
1766       // because we don't resize the interpreted_methods array when
1767       // miranda methods are added to it.
1768       if ((klass->methods[i].accflags
1769            & java::lang::reflect::Modifier::ABSTRACT)
1770           != 0)
1771         continue;
1772       // Miranda method additions mean that the `methods' array moves.
1773       // We cache a pointer into this array, so we have to update.
1774       iclass->interpreted_methods[i]->self = &klass->methods[i];
1775     }
1776 }
1777
1778 #ifdef DIRECT_THREADED
1779 void
1780 _Jv_CompileMethod (_Jv_InterpMethod* method)
1781 {
1782   if (method->prepared == NULL)
1783     {
1784       if (JVMTI::enabled)
1785         _Jv_InterpMethod::run_debug (NULL, NULL, method);
1786       else
1787       _Jv_InterpMethod::run (NULL, NULL, method);
1788     }
1789 }
1790 #endif // DIRECT_THREADED
1791
1792 #endif // INTERPRETER