49bc0f4eb8853e2542839d73b8ff97220a2e843e
[platform/upstream/gcc.git] / libjava / verify.cc
1 // defineclass.cc - defining a class from .class format.
2
3 /* Copyright (C) 2001  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 // Writte by Tom Tromey <tromey@redhat.com>
12
13 #include <config.h>
14
15 #include <jvm.h>
16 #include <gcj/cni.h>
17 #include <java-insns.h>
18 #include <java-interp.h>
19
20 #ifdef INTERPRETER
21
22 #include <java/lang/Class.h>
23 #include <java/lang/VerifyError.h>
24 #include <java/lang/Throwable.h>
25 #include <java/lang/reflect/Modifier.h>
26
27
28 // TO DO
29 // * read more about when classes must be loaded
30 // * there are bugs with boolean arrays?
31 // * class loader madness
32 // * Lots and lots of debugging and testing
33 // * type representation is still ugly.  look for the big switches
34 // * at least one GC problem :-(
35
36
37 // This is global because __attribute__ doesn't seem to work on static
38 // methods.
39 static void verify_fail (char *s) __attribute__ ((__noreturn__));
40
41 class _Jv_BytecodeVerifier
42 {
43 private:
44
45   static const int FLAG_INSN_START = 1;
46   static const int FLAG_BRANCH_TARGET = 2;
47   static const int FLAG_JSR_TARGET = 4;
48
49   struct state;
50   struct type;
51   struct subr_info;
52
53   // The current PC.
54   int PC;
55   // The PC corresponding to the start of the current instruction.
56   int start_PC;
57
58   // The current state of the stack, locals, etc.
59   state *current_state;
60
61   // We store the state at branch targets, for merging.  This holds
62   // such states.
63   state **states;
64
65   // We keep a linked list of all the PCs which we must reverify.
66   // The link is done using the PC values.  This is the head of the
67   // list.
68   int next_verify_pc;
69
70   // We keep some flags for each instruction.  The values are the
71   // FLAG_* constants defined above.
72   char *flags;
73
74   // We need to keep track of which instructions can call a given
75   // subroutine.  FIXME: this is inefficient.  We keep a linked list
76   // of all calling `jsr's at at each jsr target.
77   subr_info **jsr_ptrs;
78
79   // The current top of the stack, in terms of slots.
80   int stacktop;
81   // The current depth of the stack.  This will be larger than
82   // STACKTOP when wide types are on the stack.
83   int stackdepth;
84
85   // The bytecode itself.
86   unsigned char *bytecode;
87   // The exceptions.
88   _Jv_InterpException *exception;
89
90   // Defining class.
91   jclass current_class;
92   // This method.
93   _Jv_InterpMethod *current_method;
94
95   // This enum holds a list of tags for all the different types we
96   // need to handle.  Reference types are treated specially by the
97   // type class.
98   enum type_val
99   {
100     void_type,
101
102     // The values for primitive types are chosen to correspond to values
103     // specified to newarray.
104     boolean_type = 4,
105     char_type = 5,
106     float_type = 6,
107     double_type = 7,
108     byte_type = 8,
109     short_type = 9,
110     int_type = 10,
111     long_type = 11,
112
113     // Used when overwriting second word of a double or long in the
114     // local variables.  Also used after merging local variable states
115     // to indicate an unusable value.
116     unsuitable_type,
117     return_address_type,
118     continuation_type,
119
120     // Everything after `reference_type' must be a reference type.
121     reference_type,
122     null_type,
123     unresolved_reference_type,
124     uninitialized_reference_type,
125     uninitialized_unresolved_reference_type
126   };
127
128   // Return the type_val corresponding to a primitive signature
129   // character.  For instance `I' returns `int.class'.
130   static type_val get_type_val_for_signature (jchar sig)
131   {
132     type_val rt;
133     switch (sig)
134       {
135       case 'Z':
136         rt = boolean_type;
137         break;
138       case 'C':
139         rt = char_type;
140         break;
141       case 'S':
142         rt = short_type;
143         break;
144       case 'I':
145         rt = int_type;
146         break;
147       case 'J':
148         rt = long_type;
149         break;
150       case 'F':
151         rt = float_type;
152         break;
153       case 'D':
154         rt = double_type;
155         break;
156       case 'V':
157         rt = void_type;
158         break;
159       default:
160         verify_fail ("invalid signature");
161       }
162     return rt;
163   }
164
165   // Return the type_val corresponding to a primitive class.
166   static type_val get_type_val_for_signature (jclass k)
167   {
168     return get_type_val_for_signature ((jchar) k->method_count);
169   }
170
171   // This is used to keep track of which `jsr's correspond to a given
172   // jsr target.
173   struct subr_info
174   {
175     // PC of the instruction just after the jsr.
176     int pc;
177     // Link.
178     subr_info *next;
179   };
180
181   // The `type' class is used to represent a single type in the
182   // verifier.
183   struct type
184   {
185     // The type.
186     type_val key;
187     // Some associated data.
188     union
189     {
190       // For a resolved reference type, this is a pointer to the class.
191       jclass klass;
192       // For other reference types, this it the name of the class.
193       _Jv_Utf8Const *name;
194     } data;
195     // This is used when constructing a new object.  It is the PC of the
196     // `new' instruction which created the object.  We use the special
197     // value -2 to mean that this is uninitialized, and the special
198     // value -1 for the case where the current method is itself the
199     // <init> method.
200     int pc;
201
202     static const int UNINIT = -2;
203     static const int SELF = -1;
204
205     // Basic constructor.
206     type ()
207     {
208       key = unsuitable_type;
209       data.klass = NULL;
210       pc = UNINIT;
211     }
212
213     // Make a new instance given the type tag.  We assume a generic
214     // `reference_type' means Object.
215     type (type_val k)
216     {
217       key = k;
218       data.klass = NULL;
219       if (key == reference_type)
220         data.klass = &java::lang::Object::class$;
221       pc = UNINIT;
222     }
223
224     // Make a new instance given a class.
225     type (jclass klass)
226     {
227       key = reference_type;
228       data.klass = klass;
229       pc = UNINIT;
230     }
231
232     // Make a new instance given the name of a class.
233     type (_Jv_Utf8Const *n)
234     {
235       key = unresolved_reference_type;
236       data.name = n;
237       pc = UNINIT;
238     }
239
240     // Copy constructor.
241     type (const type &t)
242     {
243       key = t.key;
244       data = t.data;
245       pc = t.pc;
246     }
247
248     // These operators are required because libgcj can't link in
249     // -lstdc++.
250     void *operator new[] (size_t bytes)
251     {
252       return _Jv_Malloc (bytes);
253     }
254
255     void operator delete[] (void *mem)
256     {
257       _Jv_Free (mem);
258     }
259
260     type& operator= (type_val k)
261     {
262       key = k;
263       data.klass = NULL;
264       pc = UNINIT;
265       return *this;
266     }
267
268     type& operator= (const type& t)
269     {
270       key = t.key;
271       data = t.data;
272       pc = t.pc;
273       return *this;
274     }
275
276     // Promote a numeric type.
277     void promote ()
278     {
279       if (key == boolean_type || key == char_type
280           || key == byte_type || key == short_type)
281         key = int_type;
282     }
283
284     // If *THIS is an unresolved reference type, resolve it.
285     void resolve ()
286     {
287       if (key != unresolved_reference_type
288           && key != uninitialized_unresolved_reference_type)
289         return;
290
291       // FIXME: class loader
292       using namespace java::lang;
293       // We might see either kind of name.  Sigh.
294       if (data.name->data[0] == 'L'
295           && data.name->data[data.name->length - 1] == ';')
296         data.klass = _Jv_FindClassFromSignature (data.name->data, NULL);
297       else
298         data.klass = Class::forName (_Jv_NewStringUtf8Const (data.name),
299                                      false, NULL);
300       key = (key == unresolved_reference_type
301              ? reference_type
302              : uninitialized_reference_type);
303     }
304
305     // Mark this type as the uninitialized result of `new'.
306     void set_uninitialized (int pc)
307     {
308       if (key != reference_type && key != unresolved_reference_type)
309         verify_fail ("internal error in type::uninitialized");
310       key = (key == reference_type
311              ? uninitialized_reference_type
312              : uninitialized_unresolved_reference_type);
313       pc = pc;
314     }
315
316     // Mark this type as now initialized.
317     void set_initialized (int npc)
318     {
319       if (pc == npc)
320         {
321           key = (key == uninitialized_reference_type
322                  ? reference_type
323                  : unresolved_reference_type);
324           pc = UNINIT;
325         }
326     }
327
328
329     // Return true if an object of type K can be assigned to a variable
330     // of type *THIS.  Handle various special cases too.  Might modify
331     // *THIS or K.  Note however that this does not perform numeric
332     // promotion.
333     bool compatible (type &k)
334     {
335       // Any type is compatible with the unsuitable type.
336       if (key == unsuitable_type)
337         return true;
338
339       if (key < reference_type || k.key < reference_type)
340         return key == k.key;
341
342       // The `null' type is convertible to any reference type.
343       // FIXME: is this correct for THIS?
344       if (key == null_type || k.key == null_type)
345         return true;
346
347       // Any reference type is convertible to Object.  This is a special
348       // case so we don't need to unnecessarily resolve a class.
349       if (key == reference_type
350           && data.klass == &java::lang::Object::class$)
351         return true;
352
353       // An initialized type and an uninitialized type are not
354       // compatible.
355       if (isinitialized () != k.isinitialized ())
356         return false;
357
358       // Two uninitialized objects are compatible if either:
359       // * The PCs are identical, or
360       // * One PC is UNINIT.
361       if (! isinitialized ())
362         {
363           if (pc != k.pc && pc != UNINIT && k.pc != UNINIT)
364             return false;
365         }
366
367       // Two unresolved types are equal if their names are the same.
368       if (! isresolved ()
369           && ! k.isresolved ()
370           && _Jv_equalUtf8Consts (data.name, k.data.name))
371         return true;
372
373       // We must resolve both types and check assignability.
374       resolve ();
375       k.resolve ();
376       return data.klass->isAssignableFrom (k.data.klass);
377     }
378
379     bool isvoid () const
380     {
381       return key == void_type;
382     }
383
384     bool iswide () const
385     {
386       return key == long_type || key == double_type;
387     }
388
389     // Return number of stack or local variable slots taken by this
390     // type.
391     int depth () const
392     {
393       return iswide () ? 2 : 1;
394     }
395
396     bool isarray () const
397     {
398       // We treat null_type as not an array.  This is ok based on the
399       // current uses of this method.
400       if (key == reference_type)
401         return data.klass->isArray ();
402       else if (key == unresolved_reference_type)
403         return data.name->data[0] == '[';
404       return false;
405     }
406
407     bool isinterface ()
408     {
409       resolve ();
410       if (key != reference_type)
411         return false;
412       return data.klass->isInterface ();
413     }
414
415     bool isabstract ()
416     {
417       resolve ();
418       if (key != reference_type)
419         return false;
420       using namespace java::lang::reflect;
421       return Modifier::isAbstract (data.klass->getModifiers ());
422     }
423
424     // Return the element type of an array.
425     type element_type ()
426     {
427       // FIXME: maybe should do string manipulation here.
428       resolve ();
429       if (key != reference_type)
430         verify_fail ("programmer error in type::element_type()");
431
432       jclass k = data.klass->getComponentType ();
433       if (k->isPrimitive ())
434         return type (get_type_val_for_signature (k));
435       return type (k);
436     }
437
438     bool isreference () const
439     {
440       return key >= reference_type;
441     }
442
443     int get_pc () const
444     {
445       return pc;
446     }
447
448     bool isinitialized () const
449     {
450       return (key == reference_type
451               || key == null_type
452               || key == unresolved_reference_type);
453     }
454
455     bool isresolved () const
456     {
457       return (key == reference_type
458               || key == null_type
459               || key == uninitialized_reference_type);
460     }
461
462     void verify_dimensions (int ndims)
463     {
464       // The way this is written, we don't need to check isarray().
465       if (key == reference_type)
466         {
467           jclass k = data.klass;
468           while (k->isArray () && ndims > 0)
469             {
470               k = k->getComponentType ();
471               --ndims;
472             }
473         }
474       else
475         {
476           // We know KEY == unresolved_reference_type.
477           char *p = data.name->data;
478           while (*p++ == '[' && ndims-- > 0)
479             ;
480         }
481
482       if (ndims > 0)
483         verify_fail ("array type has fewer dimensions than required");
484     }
485
486     // Merge OLD_TYPE into this.  On error throw exception.
487     bool merge (type& old_type, bool local_semantics = false)
488     {
489       bool changed = false;
490       bool refo = old_type.isreference ();
491       bool refn = isreference ();
492       if (refo && refn)
493         {
494           if (old_type.key == null_type)
495             ;
496           else if (key == null_type)
497             {
498               *this = old_type;
499               changed = true;
500             }
501           else if (isinitialized () != old_type.isinitialized ())
502             verify_fail ("merging initialized and uninitialized types");
503           else
504             {
505               if (! isinitialized ())
506                 {
507                   if (pc == UNINIT)
508                     pc = old_type.pc;
509                   else if (old_type.pc == UNINIT)
510                     ;
511                   else if (pc != old_type.pc)
512                     verify_fail ("merging different uninitialized types");
513                 }
514
515               if (! isresolved ()
516                   && ! old_type.isresolved ()
517                   && _Jv_equalUtf8Consts (data.name, old_type.data.name))
518                 {
519                   // Types are identical.
520                 }
521               else
522                 {
523                   resolve ();
524                   old_type.resolve ();
525
526                   jclass k = data.klass;
527                   jclass oldk = old_type.data.klass;
528
529                   int arraycount = 0;
530                   while (k->isArray () && oldk->isArray ())
531                     {
532                       ++arraycount;
533                       k = k->getComponentType ();
534                       oldk = oldk->getComponentType ();
535                     }
536
537                   // This loop will end when we hit Object.
538                   while (true)
539                     {
540                       if (k->isAssignableFrom (oldk))
541                         break;
542                       k = k->getSuperclass ();
543                       changed = true;
544                     }
545
546                   if (changed)
547                     {
548                       while (arraycount > 0)
549                         {
550                           // FIXME: Class loader.
551                           k = _Jv_GetArrayClass (k, NULL);
552                           --arraycount;
553                         }
554                       data.klass = k;
555                     }
556                 }
557             }
558         }
559       else if (refo || refn || key != old_type.key)
560         {
561           if (local_semantics)
562             {
563               key = unsuitable_type;
564               changed = true;
565             }
566           else
567             verify_fail ("unmergeable type");
568         }
569       return changed;
570     }
571   };
572
573   // This class holds all the state information we need for a given
574   // location.
575   struct state
576   {
577     // Current top of stack.
578     int stacktop;
579     // Current stack depth.  This is like the top of stack but it
580     // includes wide variable information.
581     int stackdepth;
582     // The stack.
583     type *stack;
584     // The local variables.
585     type *locals;
586     // This is used in subroutines to keep track of which local
587     // variables have been accessed.
588     bool *local_changed;
589     // If not 0, then we are in a subroutine.  The value is the PC of
590     // the subroutine's entry point.  We can use 0 as an exceptional
591     // value because PC=0 can never be a subroutine.
592     int subroutine;
593     // This is used to keep a linked list of all the states which
594     // require re-verification.  We use the PC to keep track.
595     int next;
596
597     // INVALID marks a state which is not on the linked list of states
598     // requiring reverification.
599     static const int INVALID = -1;
600     // NO_NEXT marks the state at the end of the reverification list.
601     static const int NO_NEXT = -2;
602
603     state ()
604     {
605       stack = NULL;
606       locals = NULL;
607       local_changed = NULL;
608     }
609
610     state (int max_stack, int max_locals)
611     {
612       stacktop = 0;
613       stackdepth = 0;
614       stack = new type[max_stack];
615       for (int i = 0; i < max_stack; ++i)
616         stack[i] = unsuitable_type;
617       locals = new type[max_locals];
618       local_changed = (bool *) _Jv_Malloc (sizeof (bool) * max_locals);
619       for (int i = 0; i < max_locals; ++i)
620         {
621           locals[i] = unsuitable_type;
622           local_changed[i] = false;
623         }
624       next = INVALID;
625       subroutine = 0;
626     }
627
628     state (const state *copy, int max_stack, int max_locals)
629     {
630       stack = new type[max_stack];
631       locals = new type[max_locals];
632       local_changed = (bool *) _Jv_Malloc (sizeof (bool) * max_locals);
633       *this = *copy;
634       next = INVALID;
635     }
636
637     ~state ()
638     {
639       if (stack)
640         delete[] stack;
641       if (locals)
642         delete[] locals;
643       if (local_changed)
644         _Jv_Free (local_changed);
645     }
646
647     void *operator new[] (size_t bytes)
648     {
649       return _Jv_Malloc (bytes);
650     }
651
652     void operator delete[] (void *mem)
653     {
654       _Jv_Free (mem);
655     }
656
657     void *operator new (size_t bytes)
658     {
659       return _Jv_Malloc (bytes);
660     }
661
662     void operator delete (void *mem)
663     {
664       _Jv_Free (mem);
665     }
666
667     void copy (const state *copy, int max_stack, int max_locals)
668     {
669       stacktop = copy->stacktop;
670       stackdepth = copy->stackdepth;
671       subroutine = copy->subroutine;
672       for (int i = 0; i < max_stack; ++i)
673         stack[i] = copy->stack[i];
674       for (int i = 0; i < max_locals; ++i)
675         {
676           locals[i] = copy->locals[i];
677           local_changed[i] = copy->local_changed[i];
678         }
679       // Don't modify `next'.
680     }
681
682     // Modify this state to reflect entry to an exception handler.
683     void set_exception (type t, int max_stack)
684     {
685       stackdepth = 1;
686       stacktop = 1;
687       stack[0] = t;
688       for (int i = stacktop; i < max_stack; ++i)
689         stack[i] = unsuitable_type;
690
691       // FIXME: subroutine handling?
692     }
693
694     // Merge STATE into this state.  Destructively modifies this state.
695     // Returns true if the new state was in fact changed.  Will throw an
696     // exception if the states are not mergeable.
697     bool merge (state *state_old, bool ret_semantics,
698                 int max_locals)
699     {
700       bool changed = false;
701
702       // Merge subroutine states.  *THIS and *STATE_OLD must be in the
703       // same subroutine.  Also, recursive subroutine calls must be
704       // avoided.
705       if (subroutine == state_old->subroutine)
706         {
707           // Nothing.
708         }
709       else if (subroutine == 0)
710         {
711           subroutine = state_old->subroutine;
712           changed = true;
713         }
714       else
715         verify_fail ("subroutines merged");
716
717       // Merge stacks.
718       if (state_old->stacktop != stacktop)
719         verify_fail ("stack sizes differ");
720       for (int i = 0; i < state_old->stacktop; ++i)
721         {
722           if (stack[i].merge (state_old->stack[i]))
723             changed = true;
724         }
725
726       // Merge local variables.
727       for (int i = 0; i < max_locals; ++i)
728         {
729           if (! ret_semantics || local_changed[i])
730             {
731               if (locals[i].merge (state_old->locals[i], true))
732                 {
733                   changed = true;
734                   note_variable (i);
735                 }
736             }
737
738           // If we're in a subroutine, we must compute the union of
739           // all the changed local variables.
740           if (state_old->local_changed[i])
741             note_variable (i);
742         }
743
744       return changed;
745     }
746
747     // Throw an exception if there is an uninitialized object on the
748     // stack or in a local variable.  EXCEPTION_SEMANTICS controls
749     // whether we're using backwards-branch or exception-handing
750     // semantics.
751     void check_no_uninitialized_objects (int max_locals,
752                                          bool exception_semantics = false)
753     {
754       if (! exception_semantics)
755         {
756           for (int i = 0; i < stacktop; ++i)
757             if (stack[i].isreference () && ! stack[i].isinitialized ())
758               verify_fail ("uninitialized object on stack");
759         }
760
761       for (int i = 0; i < max_locals; ++i)
762         if (locals[i].isreference () && ! locals[i].isinitialized ())
763           verify_fail ("uninitialized object in local variable");
764     }
765
766     // Note that a local variable was accessed or modified.
767     void note_variable (int index)
768     {
769       if (subroutine > 0)
770         local_changed[index] = true;
771     }
772
773     // Mark each `new'd object we know of that was allocated at PC as
774     // initialized.
775     void set_initialized (int pc, int max_locals)
776     {
777       for (int i = 0; i < stacktop; ++i)
778         stack[i].set_initialized (pc);
779       for (int i = 0; i < max_locals; ++i)
780         locals[i].set_initialized (pc);
781     }
782   };
783
784   type pop_raw ()
785   {
786     if (current_state->stacktop <= 0)
787       verify_fail ("stack empty");
788     type r = current_state->stack[--current_state->stacktop];
789     current_state->stackdepth -= r.depth ();
790     if (current_state->stackdepth < 0)
791       verify_fail ("stack empty");
792     return r;
793   }
794
795   type pop32 ()
796   {
797     type r = pop_raw ();
798     if (r.iswide ())
799       verify_fail ("narrow pop of wide type");
800     return r;
801   }
802
803   type pop64 ()
804   {
805     type r = pop_raw ();
806     if (! r.iswide ())
807       verify_fail ("wide pop of narrow type");
808     return r;
809   }
810
811   type pop_type (type match)
812   {
813     type t = pop_raw ();
814     if (! match.compatible (t))
815       verify_fail ("incompatible type on stack");
816     return t;
817   }
818
819   void push_type (type t)
820   {
821     // If T is a numeric type like short, promote it to int.
822     t.promote ();
823
824     int depth = t.depth ();
825     if (current_state->stackdepth + depth > current_method->max_stack)
826       verify_fail ("stack overflow");
827     current_state->stack[current_state->stacktop++] = t;
828     current_state->stackdepth += depth;
829   }
830
831   void set_variable (int index, type t)
832   {
833     // If T is a numeric type like short, promote it to int.
834     t.promote ();
835
836     int depth = t.depth ();
837     if (index > current_method->max_locals - depth)
838       verify_fail ("invalid local variable");
839     current_state->locals[index] = t;
840     current_state->note_variable (index);
841
842     if (depth == 2)
843       {
844         current_state->locals[index + 1] = continuation_type;
845         current_state->note_variable (index + 1);
846       }
847     if (index > 0 && current_state->locals[index - 1].iswide ())
848       {
849         current_state->locals[index - 1] = unsuitable_type;
850         // There's no need to call note_variable here.
851       }
852   }
853
854   type get_variable (int index, type t)
855   {
856     int depth = t.depth ();
857     if (index > current_method->max_locals - depth)
858       verify_fail ("invalid local variable");
859     if (! t.compatible (current_state->locals[index]))
860       verify_fail ("incompatible type in local variable");
861     if (depth == 2)
862       {
863         type t (continuation_type);
864         if (! current_state->locals[index + 1].compatible (t))
865           verify_fail ("invalid local variable");
866       }
867     current_state->note_variable (index);
868     return current_state->locals[index];
869   }
870
871   // Make sure ARRAY is an array type and that its elements are
872   // compatible with type ELEMENT.  Returns the actual element type.
873   type require_array_type (type array, type element)
874   {
875     if (! array.isarray ())
876       verify_fail ("array required");
877
878     type t = array.element_type ();
879     if (! element.compatible (t))
880       verify_fail ("incompatible array element type");
881
882     // Return T and not ELEMENT, because T might be specialized.
883     return t;
884   }
885
886   jint get_byte ()
887   {
888     if (PC >= current_method->code_length)
889       verify_fail ("premature end of bytecode");
890     return (jint) bytecode[PC++] & 0xff;
891   }
892
893   jint get_ushort ()
894   {
895     jbyte b1 = get_byte ();
896     jbyte b2 = get_byte ();
897     return (jint) ((b1 << 8) | b2) & 0xffff;
898   }
899
900   jint get_short ()
901   {
902     jbyte b1 = get_byte ();
903     jbyte b2 = get_byte ();
904     jshort s = (b1 << 8) | b2;
905     return (jint) s;
906   }
907
908   jint get_int ()
909   {
910     jbyte b1 = get_byte ();
911     jbyte b2 = get_byte ();
912     jbyte b3 = get_byte ();
913     jbyte b4 = get_byte ();
914     return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
915   }
916
917   int compute_jump (int offset)
918   {
919     int npc = start_PC + offset;
920     if (npc < 0 || npc >= current_method->code_length)
921       verify_fail ("branch out of range");
922     return npc;
923   }
924
925   // Merge the indicated state into a new state and schedule a new PC if
926   // there is a change.  If RET_SEMANTICS is true, then we are merging
927   // from a `ret' instruction into the instruction after a `jsr'.  This
928   // is a special case with its own modified semantics.
929   void push_jump_merge (int npc, state *nstate, bool ret_semantics = false)
930   {
931     bool changed = true;
932     if (states[npc] == NULL)
933       {
934         // FIXME: what if we reach this code from a `ret'?
935         
936         states[npc] = new state (nstate, current_method->max_stack,
937                                  current_method->max_locals);
938       }
939     else
940       changed = nstate->merge (states[npc], ret_semantics,
941                                current_method->max_stack);
942
943     if (changed && states[npc]->next == state::INVALID)
944       {
945         // The merge changed the state, and the new PC isn't yet on our
946         // list of PCs to re-verify.
947         states[npc]->next = next_verify_pc;
948         next_verify_pc = npc;
949       }
950   }
951
952   void push_jump (int offset)
953   {
954     int npc = compute_jump (offset);
955     if (npc < PC)
956       current_state->check_no_uninitialized_objects (current_method->max_stack);
957     push_jump_merge (npc, current_state);
958   }
959
960   void push_exception_jump (type t, int pc)
961   {
962     current_state->check_no_uninitialized_objects (current_method->max_stack,
963                                                   true);
964     state s (current_state, current_method->max_stack,
965              current_method->max_locals);
966     s.set_exception (t, current_method->max_stack);
967     push_jump_merge (pc, &s);
968   }
969
970   int pop_jump ()
971   {
972     int npc = next_verify_pc;
973     if (npc != state::NO_NEXT)
974       {
975         next_verify_pc = states[npc]->next;
976         states[npc]->next = state::INVALID;
977       }
978     return npc;
979   }
980
981   void invalidate_pc ()
982   {
983     PC = state::NO_NEXT;
984   }
985
986   void note_branch_target (int pc, bool is_jsr_target = false)
987   {
988     if (pc <= PC && ! (flags[pc] & FLAG_INSN_START))
989       verify_fail ("branch not to instruction start");
990     flags[pc] |= FLAG_BRANCH_TARGET;
991     if (is_jsr_target)
992       {
993         // Record the jsr which called this instruction.
994         subr_info *info = (subr_info *) _Jv_Malloc (sizeof (subr_info));
995         info->pc = PC;
996         info->next = jsr_ptrs[pc];
997         jsr_ptrs[pc] = info;
998         flags[pc] |= FLAG_JSR_TARGET;
999       }
1000   }
1001
1002   void skip_padding ()
1003   {
1004     while ((PC % 4) > 0)
1005       if (get_byte () != 0)
1006         verify_fail ("found nonzero padding byte");
1007   }
1008
1009   // Return the subroutine to which the instruction at PC belongs.
1010   int get_subroutine (int pc)
1011   {
1012     if (states[pc] == NULL)
1013       return 0;
1014     return states[pc]->subroutine;
1015   }
1016
1017   // Do the work for a `ret' instruction.  INDEX is the index into the
1018   // local variables.
1019   void handle_ret_insn (int index)
1020   {
1021     get_variable (index, return_address_type);
1022
1023     int csub = current_state->subroutine;
1024     if (csub == 0)
1025       verify_fail ("no subroutine");
1026
1027     for (subr_info *subr = jsr_ptrs[csub]; subr != NULL; subr = subr->next)
1028       {
1029         // Temporarily modify the current state so it looks like we're
1030         // in the enclosing context.
1031         current_state->subroutine = get_subroutine (subr->pc);
1032         if (subr->pc < PC)
1033           current_state->check_no_uninitialized_objects (current_method->max_stack);
1034         push_jump_merge (subr->pc, current_state, true);
1035       }
1036
1037     current_state->subroutine = csub;
1038     invalidate_pc ();
1039   }
1040
1041   // We're in the subroutine SUB, calling a subroutine at DEST.  Make
1042   // sure this subroutine isn't already on the stack.
1043   void check_nonrecursive_call (int sub, int dest)
1044   {
1045     if (sub == 0)
1046       return;
1047     if (sub == dest)
1048       verify_fail ("recursive subroutine call");
1049     for (subr_info *info = jsr_ptrs[sub]; info != NULL; info = info->next)
1050       check_nonrecursive_call (get_subroutine (info->pc), dest);
1051   }
1052
1053   void handle_jsr_insn (int offset)
1054   {
1055     int npc = compute_jump (offset);
1056
1057     if (npc < PC)
1058       current_state->check_no_uninitialized_objects (current_method->max_stack);
1059     check_nonrecursive_call (current_state->subroutine, npc);
1060
1061     // Temporarily modify the current state so that it looks like we are
1062     // in the subroutine.
1063     push_type (return_address_type);
1064     int save = current_state->subroutine;
1065     current_state->subroutine = npc;
1066
1067     // Merge into the subroutine.
1068     push_jump_merge (npc, current_state);
1069
1070     // Undo our modifications.
1071     current_state->subroutine = save;
1072     pop_type (return_address_type);
1073   }
1074
1075   jclass construct_primitive_array_type (type_val prim)
1076   {
1077     jclass k = NULL;
1078     switch (prim)
1079       {
1080       case boolean_type:
1081         k = JvPrimClass (boolean);
1082         break;
1083       case char_type:
1084         k = JvPrimClass (char);
1085         break;
1086       case float_type:
1087         k = JvPrimClass (float);
1088         break;
1089       case double_type:
1090         k = JvPrimClass (double);
1091         break;
1092       case byte_type:
1093         k = JvPrimClass (byte);
1094         break;
1095       case short_type:
1096         k = JvPrimClass (short);
1097         break;
1098       case int_type:
1099         k = JvPrimClass (int);
1100         break;
1101       case long_type:
1102         k = JvPrimClass (long);
1103         break;
1104       default:
1105         verify_fail ("unknown type in construct_primitive_array_type");
1106       }
1107     k = _Jv_GetArrayClass (k, NULL);
1108     return k;
1109   }
1110
1111   // This pass computes the location of branch targets and also
1112   // instruction starts.
1113   void branch_prepass ()
1114   {
1115     flags = (char *) _Jv_Malloc (current_method->code_length);
1116     jsr_ptrs = (subr_info **) _Jv_Malloc (sizeof (subr_info *)
1117                                           * current_method->code_length);
1118
1119     for (int i = 0; i < current_method->code_length; ++i)
1120       {
1121         flags[i] = 0;
1122         jsr_ptrs[i] = NULL;
1123       }
1124
1125     bool last_was_jsr = false;
1126
1127     PC = 0;
1128     while (PC < current_method->code_length)
1129       {
1130         flags[PC] |= FLAG_INSN_START;
1131
1132         // If the previous instruction was a jsr, then the next
1133         // instruction is a branch target -- the branch being the
1134         // corresponding `ret'.
1135         if (last_was_jsr)
1136           note_branch_target (PC);
1137         last_was_jsr = false;
1138
1139         start_PC = PC;
1140         unsigned char opcode = bytecode[PC++];
1141         switch (opcode)
1142           {
1143           case op_nop:
1144           case op_aconst_null:
1145           case op_iconst_m1:
1146           case op_iconst_0:
1147           case op_iconst_1:
1148           case op_iconst_2:
1149           case op_iconst_3:
1150           case op_iconst_4:
1151           case op_iconst_5:
1152           case op_lconst_0:
1153           case op_lconst_1:
1154           case op_fconst_0:
1155           case op_fconst_1:
1156           case op_fconst_2:
1157           case op_dconst_0:
1158           case op_dconst_1:
1159           case op_iload_0:
1160           case op_iload_1:
1161           case op_iload_2:
1162           case op_iload_3:
1163           case op_lload_0:
1164           case op_lload_1:
1165           case op_lload_2:
1166           case op_lload_3:
1167           case op_fload_0:
1168           case op_fload_1:
1169           case op_fload_2:
1170           case op_fload_3:
1171           case op_dload_0:
1172           case op_dload_1:
1173           case op_dload_2:
1174           case op_dload_3:
1175           case op_aload_0:
1176           case op_aload_1:
1177           case op_aload_2:
1178           case op_aload_3:
1179           case op_iaload:
1180           case op_laload:
1181           case op_faload:
1182           case op_daload:
1183           case op_aaload:
1184           case op_baload:
1185           case op_caload:
1186           case op_saload:
1187           case op_istore_0:
1188           case op_istore_1:
1189           case op_istore_2:
1190           case op_istore_3:
1191           case op_lstore_0:
1192           case op_lstore_1:
1193           case op_lstore_2:
1194           case op_lstore_3:
1195           case op_fstore_0:
1196           case op_fstore_1:
1197           case op_fstore_2:
1198           case op_fstore_3:
1199           case op_dstore_0:
1200           case op_dstore_1:
1201           case op_dstore_2:
1202           case op_dstore_3:
1203           case op_astore_0:
1204           case op_astore_1:
1205           case op_astore_2:
1206           case op_astore_3:
1207           case op_iastore:
1208           case op_lastore:
1209           case op_fastore:
1210           case op_dastore:
1211           case op_aastore:
1212           case op_bastore:
1213           case op_castore:
1214           case op_sastore:
1215           case op_pop:
1216           case op_pop2:
1217           case op_dup:
1218           case op_dup_x1:
1219           case op_dup_x2:
1220           case op_dup2:
1221           case op_dup2_x1:
1222           case op_dup2_x2:
1223           case op_swap:
1224           case op_iadd:
1225           case op_isub:
1226           case op_imul:
1227           case op_idiv:
1228           case op_irem:
1229           case op_ishl:
1230           case op_ishr:
1231           case op_iushr:
1232           case op_iand:
1233           case op_ior:
1234           case op_ixor:
1235           case op_ladd:
1236           case op_lsub:
1237           case op_lmul:
1238           case op_ldiv:
1239           case op_lrem:
1240           case op_lshl:
1241           case op_lshr:
1242           case op_lushr:
1243           case op_land:
1244           case op_lor:
1245           case op_lxor:
1246           case op_fadd:
1247           case op_fsub:
1248           case op_fmul:
1249           case op_fdiv:
1250           case op_frem:
1251           case op_dadd:
1252           case op_dsub:
1253           case op_dmul:
1254           case op_ddiv:
1255           case op_drem:
1256           case op_ineg:
1257           case op_i2b:
1258           case op_i2c:
1259           case op_i2s:
1260           case op_lneg:
1261           case op_fneg:
1262           case op_dneg:
1263           case op_iinc:
1264           case op_i2l:
1265           case op_i2f:
1266           case op_i2d:
1267           case op_l2i:
1268           case op_l2f:
1269           case op_l2d:
1270           case op_f2i:
1271           case op_f2l:
1272           case op_f2d:
1273           case op_d2i:
1274           case op_d2l:
1275           case op_d2f:
1276           case op_lcmp:
1277           case op_fcmpl:
1278           case op_fcmpg:
1279           case op_dcmpl:
1280           case op_dcmpg:
1281           case op_monitorenter:
1282           case op_monitorexit:
1283           case op_ireturn:
1284           case op_lreturn:
1285           case op_freturn:
1286           case op_dreturn:
1287           case op_areturn:
1288           case op_return:
1289           case op_athrow:
1290             break;
1291
1292           case op_bipush:
1293           case op_sipush:
1294           case op_ldc:
1295           case op_iload:
1296           case op_lload:
1297           case op_fload:
1298           case op_dload:
1299           case op_aload:
1300           case op_istore:
1301           case op_lstore:
1302           case op_fstore:
1303           case op_dstore:
1304           case op_astore:
1305           case op_arraylength:
1306           case op_ret:
1307             get_byte ();
1308             break;
1309
1310           case op_ldc_w:
1311           case op_ldc2_w:
1312           case op_getstatic:
1313           case op_getfield:
1314           case op_putfield:
1315           case op_putstatic:
1316           case op_new:
1317           case op_anewarray:
1318           case op_instanceof:
1319           case op_checkcast:
1320           case op_invokespecial:
1321           case op_invokestatic:
1322           case op_invokevirtual:
1323             get_short ();
1324             break;
1325
1326           case op_multianewarray:
1327             get_short ();
1328             get_byte ();
1329             break;
1330
1331           case op_jsr:
1332             last_was_jsr = true;
1333             // Fall through.
1334           case op_ifeq:
1335           case op_ifne:
1336           case op_iflt:
1337           case op_ifge:
1338           case op_ifgt:
1339           case op_ifle:
1340           case op_if_icmpeq:
1341           case op_if_icmpne:
1342           case op_if_icmplt:
1343           case op_if_icmpge:
1344           case op_if_icmpgt:
1345           case op_if_icmple:
1346           case op_if_acmpeq:
1347           case op_if_acmpne:
1348           case op_ifnull:
1349           case op_ifnonnull:
1350           case op_goto:
1351             note_branch_target (compute_jump (get_short ()), last_was_jsr);
1352             break;
1353
1354           case op_tableswitch:
1355             {
1356               skip_padding ();
1357               note_branch_target (compute_jump (get_int ()));
1358               jint low = get_int ();
1359               jint hi = get_int ();
1360               if (low > hi)
1361                 verify_fail ("invalid tableswitch");
1362               for (int i = low; i <= hi; ++i)
1363                 note_branch_target (compute_jump (get_int ()));
1364             }
1365             break;
1366
1367           case op_lookupswitch:
1368             {
1369               skip_padding ();
1370               note_branch_target (compute_jump (get_int ()));
1371               int npairs = get_int ();
1372               if (npairs < 0)
1373                 verify_fail ("too few pairs in lookupswitch");
1374               while (npairs-- > 0)
1375                 {
1376                   get_int ();
1377                   note_branch_target (compute_jump (get_int ()));
1378                 }
1379             }
1380             break;
1381
1382           case op_invokeinterface:
1383             get_short ();
1384             get_byte ();
1385             get_byte ();
1386             break;
1387
1388           case op_wide:
1389             {
1390               opcode = get_byte ();
1391               get_short ();
1392               if (opcode == (unsigned char) op_iinc)
1393                 get_short ();
1394             }
1395             break;
1396
1397           case op_jsr_w:
1398             last_was_jsr = true;
1399             // Fall through.
1400           case op_goto_w:
1401             note_branch_target (compute_jump (get_int ()), last_was_jsr);
1402             break;
1403
1404           default:
1405             verify_fail ("unrecognized instruction");
1406           }
1407
1408         // See if any previous branch tried to branch to the middle of
1409         // this instruction.
1410         for (int pc = start_PC + 1; pc < PC; ++pc)
1411           {
1412             if ((flags[pc] & FLAG_BRANCH_TARGET))
1413               verify_fail ("branch not to instruction start");
1414           }
1415       }
1416
1417     // Verify exception handlers.
1418     for (int i = 0; i < current_method->exc_count; ++i)
1419       {
1420         if (! (flags[exception[i].handler_pc] & FLAG_INSN_START))
1421           verify_fail ("exception handler not at instruction start");
1422         if (exception[i].start_pc > exception[i].end_pc)
1423           verify_fail ("exception range inverted");
1424         if (! (flags[exception[i].start_pc] & FLAG_INSN_START)
1425             || ! (flags[exception[i].start_pc] & FLAG_INSN_START))
1426           verify_fail ("exception endpoint not at instruction start");
1427
1428         flags[exception[i].handler_pc] |= FLAG_BRANCH_TARGET;
1429       }
1430   }
1431
1432   void check_pool_index (int index)
1433   {
1434     if (index < 0 || index >= current_class->constants.size)
1435       verify_fail ("constant pool index out of range");
1436   }
1437
1438   type check_class_constant (int index)
1439   {
1440     check_pool_index (index);
1441     _Jv_Constants *pool = &current_class->constants;
1442     if (pool->tags[index] == JV_CONSTANT_ResolvedClass)
1443       return type (pool->data[index].clazz);
1444     else if (pool->tags[index] == JV_CONSTANT_Class)
1445       return type (pool->data[index].utf8);
1446     verify_fail ("expected class constant");
1447   }
1448
1449   type check_constant (int index)
1450   {
1451     check_pool_index (index);
1452     _Jv_Constants *pool = &current_class->constants;
1453     if (pool->tags[index] == JV_CONSTANT_ResolvedString
1454         || pool->tags[index] == JV_CONSTANT_String)
1455       return type (&java::lang::String::class$);
1456     else if (pool->tags[index] == JV_CONSTANT_Integer)
1457       return type (int_type);
1458     else if (pool->tags[index] == JV_CONSTANT_Float)
1459       return type (float_type);
1460     verify_fail ("String, int, or float constant expected");
1461   }
1462
1463   // Helper for both field and method.  These are laid out the same in
1464   // the constant pool.
1465   type handle_field_or_method (int index, int expected,
1466                                _Jv_Utf8Const **name,
1467                                _Jv_Utf8Const **fmtype)
1468   {
1469     check_pool_index (index);
1470     _Jv_Constants *pool = &current_class->constants;
1471     if (pool->tags[index] != expected)
1472       verify_fail ("didn't see expected constant");
1473     // Once we know we have a Fieldref or Methodref we assume that it
1474     // is correctly laid out in the constant pool.  I think the code
1475     // in defineclass.cc guarantees this.
1476     _Jv_ushort class_index, name_and_type_index;
1477     _Jv_loadIndexes (&pool->data[index],
1478                      class_index,
1479                      name_and_type_index);
1480     _Jv_ushort name_index, desc_index;
1481     _Jv_loadIndexes (&pool->data[name_and_type_index],
1482                      name_index, desc_index);
1483
1484     *name = pool->data[name_index].utf8;
1485     *fmtype = pool->data[desc_index].utf8;
1486
1487     return check_class_constant (class_index);
1488   }
1489
1490   // Return field's type, compute class' type if requested.
1491   type check_field_constant (int index, type *class_type = NULL)
1492   {
1493     _Jv_Utf8Const *name, *field_type;
1494     type ct = handle_field_or_method (index,
1495                                       JV_CONSTANT_Fieldref,
1496                                       &name, &field_type);
1497     if (class_type)
1498       *class_type = ct;
1499     return type (field_type);
1500   }
1501
1502   type check_method_constant (int index, bool is_interface,
1503                               _Jv_Utf8Const **method_name,
1504                               _Jv_Utf8Const **method_signature)
1505   {
1506     return handle_field_or_method (index,
1507                                    (is_interface
1508                                     ? JV_CONSTANT_InterfaceMethodref
1509                                     : JV_CONSTANT_Methodref),
1510                                    method_name, method_signature);
1511   }
1512
1513   type get_one_type (char *&p)
1514   {
1515     char *start = p;
1516
1517     int arraycount = 0;
1518     while (*p == '[')
1519       {
1520         ++arraycount;
1521         ++p;
1522       }
1523
1524     char v = *p++;
1525
1526     if (v == 'L')
1527       {
1528         while (*p != ';')
1529           ++p;
1530         ++p;
1531         // FIXME!  This will get collected!
1532         _Jv_Utf8Const *name = _Jv_makeUtf8Const (start, p - start);
1533         return type (name);
1534       }
1535
1536     // Casting to jchar here is ok since we are looking at an ASCII
1537     // character.
1538     type_val rt = get_type_val_for_signature (jchar (v));
1539
1540     if (arraycount == 0)
1541       return type (rt);
1542
1543     jclass k = construct_primitive_array_type (rt);
1544     while (--arraycount > 0)
1545       k = _Jv_GetArrayClass (k, NULL);
1546     return type (k);
1547   }
1548
1549   void compute_argument_types (_Jv_Utf8Const *signature,
1550                                type *types)
1551   {
1552     char *p = signature->data;
1553     // Skip `('.
1554     ++p;
1555
1556     int i = 0;
1557     while (*p != ')')
1558       types[i++] = get_one_type (p);
1559   }
1560
1561   type compute_return_type (_Jv_Utf8Const *signature)
1562   {
1563     char *p = signature->data;
1564     while (*p != ')')
1565       ++p;
1566     ++p;
1567     return get_one_type (p);
1568   }
1569
1570   void check_return_type (type expected)
1571   {
1572     type rt = compute_return_type (current_method->self->signature);
1573     if (! expected.compatible (rt))
1574       verify_fail ("incompatible return type");
1575   }
1576
1577   void verify_instructions_0 ()
1578   {
1579     current_state = new state (current_method->max_stack,
1580                                current_method->max_locals);
1581
1582     PC = 0;
1583
1584     {
1585       int var = 0;
1586
1587       using namespace java::lang::reflect;
1588       if (! Modifier::isStatic (current_method->self->accflags))
1589         {
1590           type kurr (current_class);
1591           if (_Jv_equalUtf8Consts (current_method->self->name, gcj::init_name))
1592             kurr.set_uninitialized (type::SELF);
1593           set_variable (0, kurr);
1594           ++var;
1595         }
1596
1597       if (var + _Jv_count_arguments (current_method->self->signature)
1598           > current_method->max_locals)
1599         verify_fail ("too many arguments");
1600       compute_argument_types (current_method->self->signature,
1601                               &current_state->locals[var]);
1602     }
1603
1604     states = (state **) _Jv_Malloc (sizeof (state *)
1605                                     * current_method->code_length);
1606     for (int i = 0; i < current_method->code_length; ++i)
1607       states[i] = NULL;
1608
1609     next_verify_pc = state::NO_NEXT;
1610
1611     while (true)
1612       {
1613         // If the PC was invalidated, get a new one from the work list.
1614         if (PC == state::NO_NEXT)
1615           {
1616             PC = pop_jump ();
1617             if (PC == state::INVALID)
1618               verify_fail ("saw state::INVALID");
1619             if (PC == state::NO_NEXT)
1620               break;
1621             // Set up the current state.
1622             *current_state = *states[PC];
1623           }
1624
1625         // Control can't fall off the end of the bytecode.
1626         if (PC >= current_method->code_length)
1627           verify_fail ("fell off end");
1628
1629         if (states[PC] != NULL)
1630           {
1631             // We've already visited this instruction.  So merge the
1632             // states together.  If this yields no change then we don't
1633             // have to re-verify.
1634             if (! current_state->merge (states[PC], false,
1635                                         current_method->max_stack))
1636               {
1637                 invalidate_pc ();
1638                 continue;
1639               }
1640             // Save a copy of it for later.
1641             states[PC]->copy (current_state, current_method->max_stack,
1642                               current_method->max_locals);
1643           }
1644         else if ((flags[PC] & FLAG_BRANCH_TARGET))
1645           {
1646             // We only have to keep saved state at branch targets.
1647             states[PC] = new state (current_state, current_method->max_stack,
1648                                     current_method->max_locals);
1649           }
1650
1651         // Update states for all active exception handlers.  Ordinarily
1652         // there are not many exception handlers.  So we simply run
1653         // through them all.
1654         for (int i = 0; i < current_method->exc_count; ++i)
1655           {
1656             if (PC >= exception[i].start_pc && PC < exception[i].end_pc)
1657               {
1658                 type handler = reference_type;
1659                 if (exception[i].handler_type != 0)
1660                   handler = check_class_constant (exception[i].handler_type);
1661                 push_exception_jump (handler, exception[i].handler_pc);
1662               }
1663           }
1664
1665         start_PC = PC;
1666         unsigned char opcode = bytecode[PC++];
1667         switch (opcode)
1668           {
1669           case op_nop:
1670             break;
1671
1672           case op_aconst_null:
1673             push_type (null_type);
1674             break;
1675
1676           case op_iconst_m1:
1677           case op_iconst_0:
1678           case op_iconst_1:
1679           case op_iconst_2:
1680           case op_iconst_3:
1681           case op_iconst_4:
1682           case op_iconst_5:
1683             push_type (int_type);
1684             break;
1685
1686           case op_lconst_0:
1687           case op_lconst_1:
1688             push_type (long_type);
1689             break;
1690
1691           case op_fconst_0:
1692           case op_fconst_1:
1693           case op_fconst_2:
1694             push_type (float_type);
1695             break;
1696
1697           case op_dconst_0:
1698           case op_dconst_1:
1699             push_type (double_type);
1700             break;
1701
1702           case op_bipush:
1703             get_byte ();
1704             push_type (int_type);
1705             break;
1706
1707           case op_sipush:
1708             get_short ();
1709             push_type (int_type);
1710             break;
1711
1712           case op_ldc:
1713             push_type (check_constant (get_byte ()));
1714             break;
1715           case op_ldc_w:
1716             push_type (check_constant (get_ushort ()));
1717             break;
1718           case op_ldc2_w:
1719             push_type (check_constant (get_ushort ()));
1720             break;
1721
1722           case op_iload:
1723             push_type (get_variable (get_byte (), int_type));
1724             break;
1725           case op_lload:
1726             push_type (get_variable (get_byte (), long_type));
1727             break;
1728           case op_fload:
1729             push_type (get_variable (get_byte (), float_type));
1730             break;
1731           case op_dload:
1732             push_type (get_variable (get_byte (), double_type));
1733             break;
1734           case op_aload:
1735             push_type (get_variable (get_byte (), reference_type));
1736             break;
1737
1738           case op_iload_0:
1739           case op_iload_1:
1740           case op_iload_2:
1741           case op_iload_3:
1742             push_type (get_variable (opcode - op_iload_0, int_type));
1743             break;
1744           case op_lload_0:
1745           case op_lload_1:
1746           case op_lload_2:
1747           case op_lload_3:
1748             push_type (get_variable (opcode - op_lload_0, long_type));
1749             break;
1750           case op_fload_0:
1751           case op_fload_1:
1752           case op_fload_2:
1753           case op_fload_3:
1754             push_type (get_variable (opcode - op_fload_0, float_type));
1755             break;
1756           case op_dload_0:
1757           case op_dload_1:
1758           case op_dload_2:
1759           case op_dload_3:
1760             push_type (get_variable (opcode - op_dload_0, double_type));
1761             break;
1762           case op_aload_0:
1763           case op_aload_1:
1764           case op_aload_2:
1765           case op_aload_3:
1766             push_type (get_variable (opcode - op_aload_0, reference_type));
1767             break;
1768           case op_iaload:
1769             pop_type (int_type);
1770             push_type (require_array_type (pop_type (reference_type),
1771                                            int_type));
1772             break;
1773           case op_laload:
1774             pop_type (int_type);
1775             push_type (require_array_type (pop_type (reference_type),
1776                                            long_type));
1777             break;
1778           case op_faload:
1779             pop_type (int_type);
1780             push_type (require_array_type (pop_type (reference_type),
1781                                            float_type));
1782             break;
1783           case op_daload:
1784             pop_type (int_type);
1785             push_type (require_array_type (pop_type (reference_type),
1786                                            double_type));
1787             break;
1788           case op_aaload:
1789             pop_type (int_type);
1790             push_type (require_array_type (pop_type (reference_type),
1791                                            reference_type));
1792             break;
1793           case op_baload:
1794             pop_type (int_type);
1795             require_array_type (pop_type (reference_type), byte_type);
1796             push_type (int_type);
1797             break;
1798           case op_caload:
1799             pop_type (int_type);
1800             require_array_type (pop_type (reference_type), char_type);
1801             push_type (int_type);
1802             break;
1803           case op_saload:
1804             pop_type (int_type);
1805             require_array_type (pop_type (reference_type), short_type);
1806             push_type (int_type);
1807             break;
1808           case op_istore:
1809             set_variable (get_byte (), pop_type (int_type));
1810             break;
1811           case op_lstore:
1812             set_variable (get_byte (), pop_type (long_type));
1813             break;
1814           case op_fstore:
1815             set_variable (get_byte (), pop_type (float_type));
1816             break;
1817           case op_dstore:
1818             set_variable (get_byte (), pop_type (double_type));
1819             break;
1820           case op_astore:
1821             set_variable (get_byte (), pop_type (reference_type));
1822             break;
1823           case op_istore_0:
1824           case op_istore_1:
1825           case op_istore_2:
1826           case op_istore_3:
1827             set_variable (opcode - op_istore_0, pop_type (int_type));
1828             break;
1829           case op_lstore_0:
1830           case op_lstore_1:
1831           case op_lstore_2:
1832           case op_lstore_3:
1833             set_variable (opcode - op_lstore_0, pop_type (long_type));
1834             break;
1835           case op_fstore_0:
1836           case op_fstore_1:
1837           case op_fstore_2:
1838           case op_fstore_3:
1839             set_variable (opcode - op_fstore_0, pop_type (float_type));
1840             break;
1841           case op_dstore_0:
1842           case op_dstore_1:
1843           case op_dstore_2:
1844           case op_dstore_3:
1845             set_variable (opcode - op_dstore_0, pop_type (double_type));
1846             break;
1847           case op_astore_0:
1848           case op_astore_1:
1849           case op_astore_2:
1850           case op_astore_3:
1851             set_variable (opcode - op_astore_0, pop_type (reference_type));
1852             break;
1853           case op_iastore:
1854             pop_type (int_type);
1855             pop_type (int_type);
1856             require_array_type (pop_type (reference_type), int_type);
1857             break;
1858           case op_lastore:
1859             pop_type (long_type);
1860             pop_type (int_type);
1861             require_array_type (pop_type (reference_type), long_type);
1862             break;
1863           case op_fastore:
1864             pop_type (float_type);
1865             pop_type (int_type);
1866             require_array_type (pop_type (reference_type), float_type);
1867             break;
1868           case op_dastore:
1869             pop_type (double_type);
1870             pop_type (int_type);
1871             require_array_type (pop_type (reference_type), double_type);
1872             break;
1873           case op_aastore:
1874             pop_type (reference_type);
1875             pop_type (int_type);
1876             require_array_type (pop_type (reference_type), reference_type);
1877             break;
1878           case op_bastore:
1879             pop_type (int_type);
1880             pop_type (int_type);
1881             require_array_type (pop_type (reference_type), byte_type);
1882             break;
1883           case op_castore:
1884             pop_type (int_type);
1885             pop_type (int_type);
1886             require_array_type (pop_type (reference_type), char_type);
1887             break;
1888           case op_sastore:
1889             pop_type (int_type);
1890             pop_type (int_type);
1891             require_array_type (pop_type (reference_type), short_type);
1892             break;
1893           case op_pop:
1894             pop32 ();
1895             break;
1896           case op_pop2:
1897             pop64 ();
1898             break;
1899           case op_dup:
1900             {
1901               type t = pop32 ();
1902               push_type (t);
1903               push_type (t);
1904             }
1905             break;
1906           case op_dup_x1:
1907             {
1908               type t1 = pop32 ();
1909               type t2 = pop32 ();
1910               push_type (t1);
1911               push_type (t2);
1912               push_type (t1);
1913             }
1914             break;
1915           case op_dup_x2:
1916             {
1917               type t1 = pop32 ();
1918               type t2 = pop32 ();
1919               type t3 = pop32 ();
1920               push_type (t1);
1921               push_type (t3);
1922               push_type (t2);
1923               push_type (t1);
1924             }
1925             break;
1926           case op_dup2:
1927             {
1928               type t = pop64 ();
1929               push_type (t);
1930               push_type (t);
1931             }
1932             break;
1933           case op_dup2_x1:
1934             {
1935               type t1 = pop64 ();
1936               type t2 = pop64 ();
1937               push_type (t1);
1938               push_type (t2);
1939               push_type (t1);
1940             }
1941             break;
1942           case op_dup2_x2:
1943             {
1944               type t1 = pop64 ();
1945               type t2 = pop64 ();
1946               type t3 = pop64 ();
1947               push_type (t1);
1948               push_type (t3);
1949               push_type (t2);
1950               push_type (t1);
1951             }
1952             break;
1953           case op_swap:
1954             {
1955               type t1 = pop32 ();
1956               type t2 = pop32 ();
1957               push_type (t1);
1958               push_type (t2);
1959             }
1960             break;
1961           case op_iadd:
1962           case op_isub:
1963           case op_imul:
1964           case op_idiv:
1965           case op_irem:
1966           case op_ishl:
1967           case op_ishr:
1968           case op_iushr:
1969           case op_iand:
1970           case op_ior:
1971           case op_ixor:
1972             pop_type (int_type);
1973             push_type (pop_type (int_type));
1974             break;
1975           case op_ladd:
1976           case op_lsub:
1977           case op_lmul:
1978           case op_ldiv:
1979           case op_lrem:
1980           case op_lshl:
1981           case op_lshr:
1982           case op_lushr:
1983           case op_land:
1984           case op_lor:
1985           case op_lxor:
1986             pop_type (long_type);
1987             push_type (pop_type (long_type));
1988             break;
1989           case op_fadd:
1990           case op_fsub:
1991           case op_fmul:
1992           case op_fdiv:
1993           case op_frem:
1994             pop_type (float_type);
1995             push_type (pop_type (float_type));
1996             break;
1997           case op_dadd:
1998           case op_dsub:
1999           case op_dmul:
2000           case op_ddiv:
2001           case op_drem:
2002             pop_type (double_type);
2003             push_type (pop_type (double_type));
2004             break;
2005           case op_ineg:
2006           case op_i2b:
2007           case op_i2c:
2008           case op_i2s:
2009             push_type (pop_type (int_type));
2010             break;
2011           case op_lneg:
2012             push_type (pop_type (long_type));
2013             break;
2014           case op_fneg:
2015             push_type (pop_type (float_type));
2016             break;
2017           case op_dneg:
2018             push_type (pop_type (double_type));
2019             break;
2020           case op_iinc:
2021             get_variable (get_byte (), int_type);
2022             get_byte ();
2023             break;
2024           case op_i2l:
2025             pop_type (int_type);
2026             push_type (long_type);
2027             break;
2028           case op_i2f:
2029             pop_type (int_type);
2030             push_type (float_type);
2031             break;
2032           case op_i2d:
2033             pop_type (int_type);
2034             push_type (double_type);
2035             break;
2036           case op_l2i:
2037             pop_type (long_type);
2038             push_type (int_type);
2039             break;
2040           case op_l2f:
2041             pop_type (long_type);
2042             push_type (float_type);
2043             break;
2044           case op_l2d:
2045             pop_type (long_type);
2046             push_type (double_type);
2047             break;
2048           case op_f2i:
2049             pop_type (float_type);
2050             push_type (int_type);
2051             break;
2052           case op_f2l:
2053             pop_type (float_type);
2054             push_type (long_type);
2055             break;
2056           case op_f2d:
2057             pop_type (float_type);
2058             push_type (double_type);
2059             break;
2060           case op_d2i:
2061             pop_type (double_type);
2062             push_type (int_type);
2063             break;
2064           case op_d2l:
2065             pop_type (double_type);
2066             push_type (long_type);
2067             break;
2068           case op_d2f:
2069             pop_type (double_type);
2070             push_type (float_type);
2071             break;
2072           case op_lcmp:
2073             pop_type (long_type);
2074             pop_type (long_type);
2075             push_type (int_type);
2076             break;
2077           case op_fcmpl:
2078           case op_fcmpg:
2079             pop_type (float_type);
2080             pop_type (float_type);
2081             push_type (int_type);
2082             break;
2083           case op_dcmpl:
2084           case op_dcmpg:
2085             pop_type (double_type);
2086             pop_type (double_type);
2087             push_type (int_type);
2088             break;
2089           case op_ifeq:
2090           case op_ifne:
2091           case op_iflt:
2092           case op_ifge:
2093           case op_ifgt:
2094           case op_ifle:
2095             pop_type (int_type);
2096             push_jump (get_short ());
2097             break;
2098           case op_if_icmpeq:
2099           case op_if_icmpne:
2100           case op_if_icmplt:
2101           case op_if_icmpge:
2102           case op_if_icmpgt:
2103           case op_if_icmple:
2104             pop_type (int_type);
2105             pop_type (int_type);
2106             push_jump (get_short ());
2107             break;
2108           case op_if_acmpeq:
2109           case op_if_acmpne:
2110             pop_type (reference_type);
2111             pop_type (reference_type);
2112             push_jump (get_short ());
2113             break;
2114           case op_goto:
2115             push_jump (get_short ());
2116             invalidate_pc ();
2117             break;
2118           case op_jsr:
2119             handle_jsr_insn (get_short ());
2120             break;
2121           case op_ret:
2122             handle_ret_insn (get_byte ());
2123             break;
2124           case op_tableswitch:
2125             {
2126               pop_type (int_type);
2127               skip_padding ();
2128               push_jump (get_int ());
2129               jint low = get_int ();
2130               jint high = get_int ();
2131               // Already checked LOW -vs- HIGH.
2132               for (int i = low; i <= high; ++i)
2133                 push_jump (get_int ());
2134               invalidate_pc ();
2135             }
2136             break;
2137
2138           case op_lookupswitch:
2139             {
2140               pop_type (int_type);
2141               skip_padding ();
2142               push_jump (get_int ());
2143               jint npairs = get_int ();
2144               // Already checked NPAIRS >= 0.
2145               jint lastkey = 0;
2146               for (int i = 0; i < npairs; ++i)
2147                 {
2148                   jint key = get_int ();
2149                   if (i > 0 && key <= lastkey)
2150                     verify_fail ("lookupswitch pairs unsorted");
2151                   lastkey = key;
2152                   push_jump (get_int ());
2153                 }
2154               invalidate_pc ();
2155             }
2156             break;
2157           case op_ireturn:
2158             check_return_type (pop_type (int_type));
2159             invalidate_pc ();
2160             break;
2161           case op_lreturn:
2162             check_return_type (pop_type (long_type));
2163             invalidate_pc ();
2164             break;
2165           case op_freturn:
2166             check_return_type (pop_type (float_type));
2167             invalidate_pc ();
2168             break;
2169           case op_dreturn:
2170             check_return_type (pop_type (double_type));
2171             invalidate_pc ();
2172             break;
2173           case op_areturn:
2174             check_return_type (pop_type (reference_type));
2175             invalidate_pc ();
2176             break;
2177           case op_return:
2178             check_return_type (void_type);
2179             invalidate_pc ();
2180             break;
2181           case op_getstatic:
2182             push_type (check_field_constant (get_ushort ()));
2183             break;
2184           case op_putstatic:
2185             pop_type (check_field_constant (get_ushort ()));
2186             break;
2187           case op_getfield:
2188             {
2189               type klass;
2190               type field = check_field_constant (get_ushort (), &klass);
2191               pop_type (klass);
2192               push_type (field);
2193             }
2194             break;
2195           case op_putfield:
2196             {
2197               type klass;
2198               type field = check_field_constant (get_ushort (), &klass);
2199               pop_type (field);
2200               pop_type (klass);
2201             }
2202             break;
2203
2204           case op_invokevirtual:
2205           case op_invokespecial:
2206           case op_invokestatic:
2207           case op_invokeinterface:
2208             {
2209               _Jv_Utf8Const *method_name, *method_signature;
2210               type class_type
2211                 = check_method_constant (get_ushort (),
2212                                          opcode == (unsigned char) op_invokeinterface,
2213                                          &method_name,
2214                                          &method_signature);
2215               int arg_count = _Jv_count_arguments (method_signature);
2216               if (opcode == (unsigned char) op_invokeinterface)
2217                 {
2218                   int nargs = get_byte ();
2219                   if (nargs == 0)
2220                     verify_fail ("too few arguments to invokeinterface");
2221                   if (get_byte () != 0)
2222                     verify_fail ("invokeinterface dummy byte is wrong");
2223                   if (nargs - 1 != arg_count)
2224                     verify_fail ("wrong argument count for invokeinterface");
2225                 }
2226
2227               bool is_init = false;
2228               if (_Jv_equalUtf8Consts (method_name, gcj::init_name))
2229                 {
2230                   is_init = true;
2231                   if (opcode != (unsigned char) op_invokespecial)
2232                     verify_fail ("can't invoke <init>");
2233                 }
2234               else if (method_name->data[0] == '<')
2235                 verify_fail ("can't invoke method starting with `<'");
2236
2237               // Pop arguments and check types.
2238               type arg_types[arg_count];
2239               compute_argument_types (method_signature, arg_types);
2240               for (int i = arg_count - 1; i >= 0; --i)
2241                 pop_type (arg_types[i]);
2242
2243               if (opcode != (unsigned char) op_invokestatic)
2244                 {
2245                   type t = class_type;
2246                   if (is_init)
2247                     {
2248                       // In this case the PC doesn't matter.
2249                       t.set_uninitialized (type::UNINIT);
2250                     }
2251                   t = pop_type (t);
2252                   if (is_init)
2253                     current_state->set_initialized (t.get_pc (),
2254                                                     current_method->max_locals);
2255                 }
2256
2257               type rt = compute_return_type (method_signature);
2258               if (! rt.isvoid ())
2259                 push_type (rt);
2260             }
2261             break;
2262
2263           case op_new:
2264             {
2265               type t = check_class_constant (get_ushort ());
2266               if (t.isarray () || t.isinterface () || t.isabstract ())
2267                 verify_fail ("type is array, interface, or abstract");
2268               t.set_uninitialized (start_PC);
2269               push_type (t);
2270             }
2271             break;
2272
2273           case op_newarray:
2274             {
2275               int atype = get_byte ();
2276               // We intentionally have chosen constants to make this
2277               // valid.
2278               if (atype < boolean_type || atype > long_type)
2279                 verify_fail ("type not primitive");
2280               pop_type (int_type);
2281               push_type (construct_primitive_array_type (type_val (atype)));
2282             }
2283             break;
2284           case op_anewarray:
2285             pop_type (int_type);
2286             push_type (check_class_constant (get_ushort ()));
2287             break;
2288           case op_arraylength:
2289             {
2290               type t = pop_type (reference_type);
2291               if (! t.isarray ())
2292                 verify_fail ("array type expected");
2293               push_type (int_type);
2294             }
2295             break;
2296           case op_athrow:
2297             pop_type (type (&java::lang::Throwable::class$));
2298             invalidate_pc ();
2299             break;
2300           case op_checkcast:
2301             pop_type (reference_type);
2302             push_type (check_class_constant (get_ushort ()));
2303             break;
2304           case op_instanceof:
2305             pop_type (reference_type);
2306             check_class_constant (get_ushort ());
2307             push_type (int_type);
2308             break;
2309           case op_monitorenter:
2310             pop_type (reference_type);
2311             break;
2312           case op_monitorexit:
2313             pop_type (reference_type);
2314             break;
2315           case op_wide:
2316             {
2317               switch (get_byte ())
2318                 {
2319                 case op_iload:
2320                   push_type (get_variable (get_ushort (), int_type));
2321                   break;
2322                 case op_lload:
2323                   push_type (get_variable (get_ushort (), long_type));
2324                   break;
2325                 case op_fload:
2326                   push_type (get_variable (get_ushort (), float_type));
2327                   break;
2328                 case op_dload:
2329                   push_type (get_variable (get_ushort (), double_type));
2330                   break;
2331                 case op_aload:
2332                   push_type (get_variable (get_ushort (), reference_type));
2333                   break;
2334                 case op_istore:
2335                   set_variable (get_ushort (), pop_type (int_type));
2336                   break;
2337                 case op_lstore:
2338                   set_variable (get_ushort (), pop_type (long_type));
2339                   break;
2340                 case op_fstore:
2341                   set_variable (get_ushort (), pop_type (float_type));
2342                   break;
2343                 case op_dstore:
2344                   set_variable (get_ushort (), pop_type (double_type));
2345                   break;
2346                 case op_astore:
2347                   set_variable (get_ushort (), pop_type (reference_type));
2348                   break;
2349                 case op_ret:
2350                   handle_ret_insn (get_short ());
2351                   break;
2352                 case op_iinc:
2353                   get_variable (get_ushort (), int_type);
2354                   get_short ();
2355                   break;
2356                 default:
2357                   verify_fail ("unrecognized wide instruction");
2358                 }
2359             }
2360             break;
2361           case op_multianewarray:
2362             {
2363               type atype = check_class_constant (get_ushort ());
2364               int dim = get_byte ();
2365               if (dim < 1)
2366                 verify_fail ("too few dimensions to multianewarray");
2367               atype.verify_dimensions (dim);
2368               for (int i = 0; i < dim; ++i)
2369                 pop_type (int_type);
2370               push_type (atype);
2371             }
2372             break;
2373           case op_ifnull:
2374           case op_ifnonnull:
2375             pop_type (reference_type);
2376             push_jump (get_short ());
2377             break;
2378           case op_goto_w:
2379             push_jump (get_int ());
2380             invalidate_pc ();
2381             break;
2382           case op_jsr_w:
2383             handle_jsr_insn (get_int ());
2384             break;
2385
2386           default:
2387             // Unrecognized opcode.
2388             verify_fail ("unrecognized instruction");
2389           }
2390       }
2391   }
2392
2393 public:
2394
2395   void verify_instructions ()
2396   {
2397     branch_prepass ();
2398     verify_instructions_0 ();
2399   }
2400
2401   _Jv_BytecodeVerifier (_Jv_InterpMethod *m)
2402   {
2403     current_method = m;
2404     bytecode = m->bytecode ();
2405     exception = m->exceptions ();
2406     current_class = m->defining_class;
2407
2408     states = NULL;
2409     flags = NULL;
2410     jsr_ptrs = NULL;
2411   }
2412
2413   ~_Jv_BytecodeVerifier ()
2414   {
2415     if (states)
2416       _Jv_Free (states);
2417     if (flags)
2418       _Jv_Free (flags);
2419     if (jsr_ptrs)
2420       _Jv_Free (jsr_ptrs);
2421   }
2422 };
2423
2424 void
2425 _Jv_VerifyMethod (_Jv_InterpMethod *meth)
2426 {
2427   _Jv_BytecodeVerifier v (meth);
2428   v.verify_instructions ();
2429 }
2430
2431 // FIXME: add more info, like PC, when required.
2432 static void
2433 verify_fail (char *s)
2434 {
2435   char buf[1024];
2436   strcpy (buf, "verification failed: ");
2437   strcat (buf, s);
2438   throw new java::lang::VerifyError (JvNewStringLatin1 (buf));
2439 }
2440
2441 #endif  /* INTERPRETER */