OSDN Git Service

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