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