* verify.cc (type::compatible): Backed out broken change.
[platform/upstream/gcc.git] / libjava / verify.cc
1 // defineclass.cc - defining a class from .class format.
2
3 /* Copyright (C) 2001, 2002  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 // Written by Tom Tromey <tromey@redhat.com>
12
13 // Define VERIFY_DEBUG to enable debugging output.
14
15 #include <config.h>
16
17 #include <jvm.h>
18 #include <gcj/cni.h>
19 #include <java-insns.h>
20 #include <java-interp.h>
21
22 #ifdef INTERPRETER
23
24 #include <java/lang/Class.h>
25 #include <java/lang/VerifyError.h>
26 #include <java/lang/Throwable.h>
27 #include <java/lang/reflect/Modifier.h>
28 #include <java/lang/StringBuffer.h>
29
30 #ifdef VERIFY_DEBUG
31 #include <stdio.h>
32 #endif /* VERIFY_DEBUG */
33
34
35 static void debug_print (const char *fmt, ...)
36   __attribute__ ((format (printf, 1, 2)));
37
38 static inline void
39 debug_print (const char *fmt, ...)
40 {
41 #ifdef VERIFY_DEBUG
42   va_list ap;
43   va_start (ap, fmt);
44   vfprintf (stderr, fmt, ap);
45   va_end (ap);
46 #endif /* VERIFY_DEBUG */
47 }
48
49 class _Jv_BytecodeVerifier
50 {
51 private:
52
53   static const int FLAG_INSN_START = 1;
54   static const int FLAG_BRANCH_TARGET = 2;
55
56   struct state;
57   struct type;
58   struct subr_info;
59   struct subr_entry_info;
60   struct linked_utf8;
61
62   // The current PC.
63   int PC;
64   // The PC corresponding to the start of the current instruction.
65   int start_PC;
66
67   // The current state of the stack, locals, etc.
68   state *current_state;
69
70   // We store the state at branch targets, for merging.  This holds
71   // such states.
72   state **states;
73
74   // We keep a linked list of all the PCs which we must reverify.
75   // The link is done using the PC values.  This is the head of the
76   // list.
77   int next_verify_pc;
78
79   // We keep some flags for each instruction.  The values are the
80   // FLAG_* constants defined above.
81   char *flags;
82
83   // We need to keep track of which instructions can call a given
84   // subroutine.  FIXME: this is inefficient.  We keep a linked list
85   // of all calling `jsr's at at each jsr target.
86   subr_info **jsr_ptrs;
87
88   // We keep a linked list of entries which map each `ret' instruction
89   // to its unique subroutine entry point.  We expect that there won't
90   // be many `ret' instructions, so a linked list is ok.
91   subr_entry_info *entry_points;
92
93   // The bytecode itself.
94   unsigned char *bytecode;
95   // The exceptions.
96   _Jv_InterpException *exception;
97
98   // Defining class.
99   jclass current_class;
100   // This method.
101   _Jv_InterpMethod *current_method;
102
103   // A linked list of utf8 objects we allocate.  This is really ugly,
104   // but without this our utf8 objects would be collected.
105   linked_utf8 *utf8_list;
106
107   struct linked_utf8
108   {
109     _Jv_Utf8Const *val;
110     linked_utf8 *next;
111   };
112
113   _Jv_Utf8Const *make_utf8_const (char *s, int len)
114   {
115     _Jv_Utf8Const *val = _Jv_makeUtf8Const (s, len);
116     _Jv_Utf8Const *r = (_Jv_Utf8Const *) _Jv_Malloc (sizeof (_Jv_Utf8Const)
117                                                      + val->length
118                                                      + 1);
119     r->length = val->length;
120     r->hash = val->hash;
121     memcpy (r->data, val->data, val->length + 1);
122
123     linked_utf8 *lu = (linked_utf8 *) _Jv_Malloc (sizeof (linked_utf8));
124     lu->val = r;
125     lu->next = utf8_list;
126     utf8_list = lu;
127
128     return r;
129   }
130
131   // This enum holds a list of tags for all the different types we
132   // need to handle.  Reference types are treated specially by the
133   // type class.
134   enum type_val
135   {
136     void_type,
137
138     // The values for primitive types are chosen to correspond to values
139     // specified to newarray.
140     boolean_type = 4,
141     char_type = 5,
142     float_type = 6,
143     double_type = 7,
144     byte_type = 8,
145     short_type = 9,
146     int_type = 10,
147     long_type = 11,
148
149     // Used when overwriting second word of a double or long in the
150     // local variables.  Also used after merging local variable states
151     // to indicate an unusable value.
152     unsuitable_type,
153     return_address_type,
154     continuation_type,
155
156     // There is an obscure special case which requires us to note when
157     // a local variable has not been used by a subroutine.  See
158     // push_jump_merge for more information.
159     unused_by_subroutine_type,
160
161     // Everything after `reference_type' must be a reference type.
162     reference_type,
163     null_type,
164     unresolved_reference_type,
165     uninitialized_reference_type,
166     uninitialized_unresolved_reference_type
167   };
168
169   // Return the type_val corresponding to a primitive signature
170   // character.  For instance `I' returns `int.class'.
171   type_val get_type_val_for_signature (jchar sig)
172   {
173     type_val rt;
174     switch (sig)
175       {
176       case 'Z':
177         rt = boolean_type;
178         break;
179       case 'B':
180         rt = byte_type;
181         break;
182       case 'C':
183         rt = char_type;
184         break;
185       case 'S':
186         rt = short_type;
187         break;
188       case 'I':
189         rt = int_type;
190         break;
191       case 'J':
192         rt = long_type;
193         break;
194       case 'F':
195         rt = float_type;
196         break;
197       case 'D':
198         rt = double_type;
199         break;
200       case 'V':
201         rt = void_type;
202         break;
203       default:
204         verify_fail ("invalid signature");
205       }
206     return rt;
207   }
208
209   // Return the type_val corresponding to a primitive class.
210   type_val get_type_val_for_signature (jclass k)
211   {
212     return get_type_val_for_signature ((jchar) k->method_count);
213   }
214
215   // This is like _Jv_IsAssignableFrom, but it works even if SOURCE or
216   // TARGET haven't been prepared.
217   static bool is_assignable_from_slow (jclass target, jclass source)
218   {
219     // This will terminate when SOURCE==Object.
220     while (true)
221       {
222         if (source == target)
223           return true;
224
225         if (target->isPrimitive () || source->isPrimitive ())
226           return false;
227
228         if (target->isArray ())
229           {
230             if (! source->isArray ())
231               return false;
232             target = target->getComponentType ();
233             source = source->getComponentType ();
234           }
235         else if (target->isInterface ())
236           {
237             for (int i = 0; i < source->interface_count; ++i)
238               {
239                 // We use a recursive call because we also need to
240                 // check superinterfaces.
241                 if (is_assignable_from_slow (target, source->interfaces[i]))
242                     return true;
243               }
244             source = source->getSuperclass ();
245             if (source == NULL)
246               return false;
247           }
248         // We must do this check before we check to see if SOURCE is
249         // an interface.  This way we know that any interface is
250         // assignable to an Object.
251         else if (target == &java::lang::Object::class$)
252           return true;
253         else if (source->isInterface ())
254           {
255             for (int i = 0; i < target->interface_count; ++i)
256               {
257                 // We use a recursive call because we also need to
258                 // check superinterfaces.
259                 if (is_assignable_from_slow (target->interfaces[i], source))
260                   return true;
261               }
262             target = target->getSuperclass ();
263             if (target == NULL)
264               return false;
265           }
266         else if (source == &java::lang::Object::class$)
267           return false;
268         else
269           source = source->getSuperclass ();
270       }
271   }
272
273   // This is used to keep track of which `jsr's correspond to a given
274   // jsr target.
275   struct subr_info
276   {
277     // PC of the instruction just after the jsr.
278     int pc;
279     // Link.
280     subr_info *next;
281   };
282
283   // This is used to keep track of which subroutine entry point
284   // corresponds to which `ret' instruction.
285   struct subr_entry_info
286   {
287     // PC of the subroutine entry point.
288     int pc;
289     // PC of the `ret' instruction.
290     int ret_pc;
291     // Link.
292     subr_entry_info *next;
293   };
294
295   // The `type' class is used to represent a single type in the
296   // verifier.
297   struct type
298   {
299     // The type.
300     type_val key;
301     // Some associated data.
302     union
303     {
304       // For a resolved reference type, this is a pointer to the class.
305       jclass klass;
306       // For other reference types, this it the name of the class.
307       _Jv_Utf8Const *name;
308     } data;
309     // This is used when constructing a new object.  It is the PC of the
310     // `new' instruction which created the object.  We use the special
311     // value -2 to mean that this is uninitialized, and the special
312     // value -1 for the case where the current method is itself the
313     // <init> method.
314     int pc;
315
316     static const int UNINIT = -2;
317     static const int SELF = -1;
318
319     // Basic constructor.
320     type ()
321     {
322       key = unsuitable_type;
323       data.klass = NULL;
324       pc = UNINIT;
325     }
326
327     // Make a new instance given the type tag.  We assume a generic
328     // `reference_type' means Object.
329     type (type_val k)
330     {
331       key = k;
332       data.klass = NULL;
333       if (key == reference_type)
334         data.klass = &java::lang::Object::class$;
335       pc = UNINIT;
336     }
337
338     // Make a new instance given a class.
339     type (jclass klass)
340     {
341       key = reference_type;
342       data.klass = klass;
343       pc = UNINIT;
344     }
345
346     // Make a new instance given the name of a class.
347     type (_Jv_Utf8Const *n)
348     {
349       key = unresolved_reference_type;
350       data.name = n;
351       pc = UNINIT;
352     }
353
354     // Copy constructor.
355     type (const type &t)
356     {
357       key = t.key;
358       data = t.data;
359       pc = t.pc;
360     }
361
362     // These operators are required because libgcj can't link in
363     // -lstdc++.
364     void *operator new[] (size_t bytes)
365     {
366       return _Jv_Malloc (bytes);
367     }
368
369     void operator delete[] (void *mem)
370     {
371       _Jv_Free (mem);
372     }
373
374     type& operator= (type_val k)
375     {
376       key = k;
377       data.klass = NULL;
378       pc = UNINIT;
379       return *this;
380     }
381
382     type& operator= (const type& t)
383     {
384       key = t.key;
385       data = t.data;
386       pc = t.pc;
387       return *this;
388     }
389
390     // Promote a numeric type.
391     type &promote ()
392     {
393       if (key == boolean_type || key == char_type
394           || key == byte_type || key == short_type)
395         key = int_type;
396       return *this;
397     }
398
399     // If *THIS is an unresolved reference type, resolve it.
400     void resolve (_Jv_BytecodeVerifier *verifier)
401     {
402       if (key != unresolved_reference_type
403           && key != uninitialized_unresolved_reference_type)
404         return;
405
406       using namespace java::lang;
407       java::lang::ClassLoader *loader
408         = verifier->current_class->getClassLoader();
409       // We might see either kind of name.  Sigh.
410       if (data.name->data[0] == 'L'
411           && data.name->data[data.name->length - 1] == ';')
412         data.klass = _Jv_FindClassFromSignature (data.name->data, loader);
413       else
414         data.klass = Class::forName (_Jv_NewStringUtf8Const (data.name),
415                                      false, loader);
416       key = (key == unresolved_reference_type
417              ? reference_type
418              : uninitialized_reference_type);
419     }
420
421     // Mark this type as the uninitialized result of `new'.
422     void set_uninitialized (int npc, _Jv_BytecodeVerifier *verifier)
423     {
424       if (key == reference_type)
425         key = uninitialized_reference_type;
426       else if (key == unresolved_reference_type)
427         key = uninitialized_unresolved_reference_type;
428       else
429         verifier->verify_fail ("internal error in type::uninitialized");
430       pc = npc;
431     }
432
433     // Mark this type as now initialized.
434     void set_initialized (int npc)
435     {
436       if (npc != UNINIT && pc == npc
437           && (key == uninitialized_reference_type
438               || key == uninitialized_unresolved_reference_type))
439         {
440           key = (key == uninitialized_reference_type
441                  ? reference_type
442                  : unresolved_reference_type);
443           pc = UNINIT;
444         }
445     }
446
447
448     // Return true if an object of type K can be assigned to a variable
449     // of type *THIS.  Handle various special cases too.  Might modify
450     // *THIS or K.  Note however that this does not perform numeric
451     // promotion.
452     bool compatible (type &k, _Jv_BytecodeVerifier *verifier)
453     {
454       // Any type is compatible with the unsuitable type.
455       if (key == unsuitable_type)
456         return true;
457
458       if (key < reference_type || k.key < reference_type)
459         return key == k.key;
460
461       // The `null' type is convertible to any reference type.
462       if (key == null_type || k.key == null_type)
463         return true;
464
465       // Any reference type is convertible to Object.  This is a special
466       // case so we don't need to unnecessarily resolve a class.
467       if (key == reference_type
468           && data.klass == &java::lang::Object::class$)
469         return true;
470
471       // An initialized type and an uninitialized type are not
472       // compatible.
473       if (isinitialized () != k.isinitialized ())
474         return false;
475
476       // Two uninitialized objects are compatible if either:
477       // * The PCs are identical, or
478       // * One PC is UNINIT.
479       if (! isinitialized ())
480         {
481           if (pc != k.pc && pc != UNINIT && k.pc != UNINIT)
482             return false;
483         }
484
485       // Two unresolved types are equal if their names are the same.
486       if (! isresolved ()
487           && ! k.isresolved ()
488           && _Jv_equalUtf8Consts (data.name, k.data.name))
489         return true;
490
491       // We must resolve both types and check assignability.
492       resolve (verifier);
493       k.resolve (verifier);
494       return is_assignable_from_slow (data.klass, k.data.klass);
495     }
496
497     bool isvoid () const
498     {
499       return key == void_type;
500     }
501
502     bool iswide () const
503     {
504       return key == long_type || key == double_type;
505     }
506
507     // Return number of stack or local variable slots taken by this
508     // type.
509     int depth () const
510     {
511       return iswide () ? 2 : 1;
512     }
513
514     bool isarray () const
515     {
516       // We treat null_type as not an array.  This is ok based on the
517       // current uses of this method.
518       if (key == reference_type)
519         return data.klass->isArray ();
520       else if (key == unresolved_reference_type)
521         return data.name->data[0] == '[';
522       return false;
523     }
524
525     bool isnull () const
526     {
527       return key == null_type;
528     }
529
530     bool isinterface (_Jv_BytecodeVerifier *verifier)
531     {
532       resolve (verifier);
533       if (key != reference_type)
534         return false;
535       return data.klass->isInterface ();
536     }
537
538     bool isabstract (_Jv_BytecodeVerifier *verifier)
539     {
540       resolve (verifier);
541       if (key != reference_type)
542         return false;
543       using namespace java::lang::reflect;
544       return Modifier::isAbstract (data.klass->getModifiers ());
545     }
546
547     // Return the element type of an array.
548     type element_type (_Jv_BytecodeVerifier *verifier)
549     {
550       // FIXME: maybe should do string manipulation here.
551       resolve (verifier);
552       if (key != reference_type)
553         verifier->verify_fail ("programmer error in type::element_type()", -1);
554
555       jclass k = data.klass->getComponentType ();
556       if (k->isPrimitive ())
557         return type (verifier->get_type_val_for_signature (k));
558       return type (k);
559     }
560
561     // Return the array type corresponding to an initialized
562     // reference.  We could expand this to work for other kinds of
563     // types, but currently we don't need to.
564     type to_array (_Jv_BytecodeVerifier *verifier)
565     {
566       // Resolving isn't ideal, because it might force us to load
567       // another class, but it's easy.  FIXME?
568       if (key == unresolved_reference_type)
569         resolve (verifier);
570
571       if (key == reference_type)
572         return type (_Jv_GetArrayClass (data.klass,
573                                         data.klass->getClassLoader ()));
574       else
575         verifier->verify_fail ("internal error in type::to_array()");
576     }
577
578     bool isreference () const
579     {
580       return key >= reference_type;
581     }
582
583     int get_pc () const
584     {
585       return pc;
586     }
587
588     bool isinitialized () const
589     {
590       return (key == reference_type
591               || key == null_type
592               || key == unresolved_reference_type);
593     }
594
595     bool isresolved () const
596     {
597       return (key == reference_type
598               || key == null_type
599               || key == uninitialized_reference_type);
600     }
601
602     void verify_dimensions (int ndims, _Jv_BytecodeVerifier *verifier)
603     {
604       // The way this is written, we don't need to check isarray().
605       if (key == reference_type)
606         {
607           jclass k = data.klass;
608           while (k->isArray () && ndims > 0)
609             {
610               k = k->getComponentType ();
611               --ndims;
612             }
613         }
614       else
615         {
616           // We know KEY == unresolved_reference_type.
617           char *p = data.name->data;
618           while (*p++ == '[' && ndims-- > 0)
619             ;
620         }
621
622       if (ndims > 0)
623         verifier->verify_fail ("array type has fewer dimensions than required");
624     }
625
626     // Merge OLD_TYPE into this.  On error throw exception.
627     bool merge (type& old_type, bool local_semantics,
628                 _Jv_BytecodeVerifier *verifier)
629     {
630       bool changed = false;
631       bool refo = old_type.isreference ();
632       bool refn = isreference ();
633       if (refo && refn)
634         {
635           if (old_type.key == null_type)
636             ;
637           else if (key == null_type)
638             {
639               *this = old_type;
640               changed = true;
641             }
642           else if (isinitialized () != old_type.isinitialized ())
643             verifier->verify_fail ("merging initialized and uninitialized types");
644           else
645             {
646               if (! isinitialized ())
647                 {
648                   if (pc == UNINIT)
649                     pc = old_type.pc;
650                   else if (old_type.pc == UNINIT)
651                     ;
652                   else if (pc != old_type.pc)
653                     verifier->verify_fail ("merging different uninitialized types");
654                 }
655
656               if (! isresolved ()
657                   && ! old_type.isresolved ()
658                   && _Jv_equalUtf8Consts (data.name, old_type.data.name))
659                 {
660                   // Types are identical.
661                 }
662               else
663                 {
664                   resolve (verifier);
665                   old_type.resolve (verifier);
666
667                   jclass k = data.klass;
668                   jclass oldk = old_type.data.klass;
669
670                   int arraycount = 0;
671                   while (k->isArray () && oldk->isArray ())
672                     {
673                       ++arraycount;
674                       k = k->getComponentType ();
675                       oldk = oldk->getComponentType ();
676                     }
677
678                   // Ordinarily this terminates when we hit Object...
679                   while (k != NULL)
680                     {
681                       if (is_assignable_from_slow (k, oldk))
682                         break;
683                       k = k->getSuperclass ();
684                       changed = true;
685                     }
686                   // ... but K could have been an interface, in which
687                   // case we'll end up here.  We just convert this
688                   // into Object.
689                   if (k == NULL)
690                     k = &java::lang::Object::class$;
691
692                   if (changed)
693                     {
694                       while (arraycount > 0)
695                         {
696                           java::lang::ClassLoader *loader
697                             = verifier->current_class->getClassLoader();
698                           k = _Jv_GetArrayClass (k, loader);
699                           --arraycount;
700                         }
701                       data.klass = k;
702                     }
703                 }
704             }
705         }
706       else if (refo || refn || key != old_type.key)
707         {
708           if (local_semantics)
709             {
710               // If we're merging into an "unused" slot, then we
711               // simply accept whatever we're merging from.
712               if (key == unused_by_subroutine_type)
713                 {
714                   *this = old_type;
715                   changed = true;
716                 }
717               else if (old_type.key == unused_by_subroutine_type)
718                 {
719                   // Do nothing.
720                 }
721               // If we already have an `unsuitable' type, then we
722               // don't need to change again.
723               else if (key != unsuitable_type)
724                 {
725                   key = unsuitable_type;
726                   changed = true;
727                 }
728             }
729           else
730             verifier->verify_fail ("unmergeable type");
731         }
732       return changed;
733     }
734
735 #ifdef VERIFY_DEBUG
736     void print (void) const
737     {
738       char c = '?';
739       switch (key)
740         {
741         case boolean_type: c = 'Z'; break;
742         case byte_type: c = 'B'; break;
743         case char_type: c = 'C'; break;
744         case short_type: c = 'S'; break;
745         case int_type: c = 'I'; break;
746         case long_type: c = 'J'; break;
747         case float_type: c = 'F'; break;
748         case double_type: c = 'D'; break;
749         case void_type: c = 'V'; break;
750         case unsuitable_type: c = '-'; break;
751         case return_address_type: c = 'r'; break;
752         case continuation_type: c = '+'; break;
753         case unused_by_subroutine_type: c = '_'; break;
754         case reference_type: c = 'L'; break;
755         case null_type: c = '@'; break;
756         case unresolved_reference_type: c = 'l'; break;
757         case uninitialized_reference_type: c = 'U'; break;
758         case uninitialized_unresolved_reference_type: c = 'u'; break;
759         }
760       debug_print ("%c", c);
761     }
762 #endif /* VERIFY_DEBUG */
763   };
764
765   // This class holds all the state information we need for a given
766   // location.
767   struct state
768   {
769     // The current top of the stack, in terms of slots.
770     int stacktop;
771     // The current depth of the stack.  This will be larger than
772     // STACKTOP when wide types are on the stack.
773     int stackdepth;
774     // The stack.
775     type *stack;
776     // The local variables.
777     type *locals;
778     // This is used in subroutines to keep track of which local
779     // variables have been accessed.
780     bool *local_changed;
781     // If not 0, then we are in a subroutine.  The value is the PC of
782     // the subroutine's entry point.  We can use 0 as an exceptional
783     // value because PC=0 can never be a subroutine.
784     int subroutine;
785     // This is used to keep a linked list of all the states which
786     // require re-verification.  We use the PC to keep track.
787     int next;
788     // We keep track of the type of `this' specially.  This is used to
789     // ensure that an instance initializer invokes another initializer
790     // on `this' before returning.  We must keep track of this
791     // specially because otherwise we might be confused by code which
792     // assigns to locals[0] (overwriting `this') and then returns
793     // without really initializing.
794     type this_type;
795
796     // INVALID marks a state which is not on the linked list of states
797     // requiring reverification.
798     static const int INVALID = -1;
799     // NO_NEXT marks the state at the end of the reverification list.
800     static const int NO_NEXT = -2;
801
802     // This is used to mark the stack depth at the instruction just
803     // after a `jsr' when we haven't yet processed the corresponding
804     // `ret'.  See handle_jsr_insn for more information.
805     static const int NO_STACK = -1;
806
807     state ()
808       : this_type ()
809     {
810       stack = NULL;
811       locals = NULL;
812       local_changed = NULL;
813     }
814
815     state (int max_stack, int max_locals)
816       : this_type ()
817     {
818       stacktop = 0;
819       stackdepth = 0;
820       stack = new type[max_stack];
821       for (int i = 0; i < max_stack; ++i)
822         stack[i] = unsuitable_type;
823       locals = new type[max_locals];
824       local_changed = (bool *) _Jv_Malloc (sizeof (bool) * max_locals);
825       for (int i = 0; i < max_locals; ++i)
826         {
827           locals[i] = unsuitable_type;
828           local_changed[i] = false;
829         }
830       next = INVALID;
831       subroutine = 0;
832     }
833
834     state (const state *orig, int max_stack, int max_locals,
835            bool ret_semantics = false)
836     {
837       stack = new type[max_stack];
838       locals = new type[max_locals];
839       local_changed = (bool *) _Jv_Malloc (sizeof (bool) * max_locals);
840       copy (orig, max_stack, max_locals, ret_semantics);
841       next = INVALID;
842     }
843
844     ~state ()
845     {
846       if (stack)
847         delete[] stack;
848       if (locals)
849         delete[] locals;
850       if (local_changed)
851         _Jv_Free (local_changed);
852     }
853
854     void *operator new[] (size_t bytes)
855     {
856       return _Jv_Malloc (bytes);
857     }
858
859     void operator delete[] (void *mem)
860     {
861       _Jv_Free (mem);
862     }
863
864     void *operator new (size_t bytes)
865     {
866       return _Jv_Malloc (bytes);
867     }
868
869     void operator delete (void *mem)
870     {
871       _Jv_Free (mem);
872     }
873
874     void copy (const state *copy, int max_stack, int max_locals,
875                bool ret_semantics = false)
876     {
877       stacktop = copy->stacktop;
878       stackdepth = copy->stackdepth;
879       subroutine = copy->subroutine;
880       for (int i = 0; i < max_stack; ++i)
881         stack[i] = copy->stack[i];
882       for (int i = 0; i < max_locals; ++i)
883         {
884           // See push_jump_merge to understand this case.
885           if (ret_semantics)
886             locals[i] = type (copy->local_changed[i]
887                               ? unsuitable_type
888                               : unused_by_subroutine_type);
889           else
890             locals[i] = copy->locals[i];
891           local_changed[i] = copy->local_changed[i];
892         }
893       this_type = copy->this_type;
894       // Don't modify `next'.
895     }
896
897     // Modify this state to reflect entry to an exception handler.
898     void set_exception (type t, int max_stack)
899     {
900       stackdepth = 1;
901       stacktop = 1;
902       stack[0] = t;
903       for (int i = stacktop; i < max_stack; ++i)
904         stack[i] = unsuitable_type;
905     }
906
907     // Modify this state to reflect entry into a subroutine.
908     void enter_subroutine (int npc, int max_locals)
909     {
910       subroutine = npc;
911       // Mark all items as unchanged.  Each subroutine needs to keep
912       // track of its `changed' state independently.  In the case of
913       // nested subroutines, this information will be merged back into
914       // parent by the `ret'.
915       for (int i = 0; i < max_locals; ++i)
916         local_changed[i] = false;
917     }
918
919     // Merge STATE_OLD into this state.  Destructively modifies this
920     // state.  Returns true if the new state was in fact changed.
921     // Will throw an exception if the states are not mergeable.
922     bool merge (state *state_old, bool ret_semantics,
923                 int max_locals, _Jv_BytecodeVerifier *verifier)
924     {
925       bool changed = false;
926
927       // Special handling for `this'.  If one or the other is
928       // uninitialized, then the merge is uninitialized.
929       if (this_type.isinitialized ())
930         this_type = state_old->this_type;
931
932       // Merge subroutine states.  Here we just keep track of what
933       // subroutine we think we're in.  We only check for a merge
934       // (which is invalid) when we see a `ret'.
935       if (subroutine == state_old->subroutine)
936         {
937           // Nothing.
938         }
939       else if (subroutine == 0)
940         {
941           subroutine = state_old->subroutine;
942           changed = true;
943         }
944       else
945         {
946           // If the subroutines differ, indicate that the state
947           // changed.  This is needed to detect when subroutines have
948           // merged.
949           changed = true;
950         }
951
952       // Merge stacks.  Special handling for NO_STACK case.
953       if (state_old->stacktop == NO_STACK)
954         {
955           // Nothing to do in this case; we don't care about modifying
956           // the old state.
957         }
958       else if (stacktop == NO_STACK)
959         {
960           stacktop = state_old->stacktop;
961           stackdepth = state_old->stackdepth;
962           for (int i = 0; i < stacktop; ++i)
963             stack[i] = state_old->stack[i];
964           changed = true;
965         }
966       else if (state_old->stacktop != stacktop)
967         verifier->verify_fail ("stack sizes differ");
968       else
969         {
970           for (int i = 0; i < state_old->stacktop; ++i)
971             {
972               if (stack[i].merge (state_old->stack[i], false, verifier))
973                 changed = true;
974             }
975         }
976
977       // Merge local variables.
978       for (int i = 0; i < max_locals; ++i)
979         {
980           // If we're not processing a `ret', then we merge every
981           // local variable.  If we are processing a `ret', then we
982           // only merge locals which changed in the subroutine.  When
983           // processing a `ret', STATE_OLD is the state at the point
984           // of the `ret', and THIS is the state just after the `jsr'.
985           if (! ret_semantics || state_old->local_changed[i])
986             {
987               if (locals[i].merge (state_old->locals[i], true, verifier))
988                 {
989                   // Note that we don't call `note_variable' here.
990                   // This change doesn't represent a real change to a
991                   // local, but rather a merge artifact.  If we're in
992                   // a subroutine which is called with two
993                   // incompatible types in a slot that is unused by
994                   // the subroutine, then we don't want to mark that
995                   // variable as having been modified.
996                   changed = true;
997                 }
998             }
999
1000           // If we're in a subroutine, we must compute the union of
1001           // all the changed local variables.
1002           if (state_old->local_changed[i])
1003             note_variable (i);
1004         }
1005
1006       return changed;
1007     }
1008
1009     // Throw an exception if there is an uninitialized object on the
1010     // stack or in a local variable.  EXCEPTION_SEMANTICS controls
1011     // whether we're using backwards-branch or exception-handing
1012     // semantics.
1013     void check_no_uninitialized_objects (int max_locals,
1014                                          _Jv_BytecodeVerifier *verifier,
1015                                          bool exception_semantics = false)
1016     {
1017       if (! exception_semantics)
1018         {
1019           for (int i = 0; i < stacktop; ++i)
1020             if (stack[i].isreference () && ! stack[i].isinitialized ())
1021               verifier->verify_fail ("uninitialized object on stack");
1022         }
1023
1024       for (int i = 0; i < max_locals; ++i)
1025         if (locals[i].isreference () && ! locals[i].isinitialized ())
1026           verifier->verify_fail ("uninitialized object in local variable");
1027
1028       check_this_initialized (verifier);
1029     }
1030
1031     // Ensure that `this' has been initialized.
1032     void check_this_initialized (_Jv_BytecodeVerifier *verifier)
1033     {
1034       if (this_type.isreference () && ! this_type.isinitialized ())
1035         verifier->verify_fail ("`this' is uninitialized");
1036     }
1037
1038     // Set type of `this'.
1039     void set_this_type (const type &k)
1040     {
1041       this_type = k;
1042     }
1043
1044     // Note that a local variable was modified.
1045     void note_variable (int index)
1046     {
1047       if (subroutine > 0)
1048         local_changed[index] = true;
1049     }
1050
1051     // Mark each `new'd object we know of that was allocated at PC as
1052     // initialized.
1053     void set_initialized (int pc, int max_locals)
1054     {
1055       for (int i = 0; i < stacktop; ++i)
1056         stack[i].set_initialized (pc);
1057       for (int i = 0; i < max_locals; ++i)
1058         locals[i].set_initialized (pc);
1059       this_type.set_initialized (pc);
1060     }
1061
1062     // Return true if this state is the unmerged result of a `ret'.
1063     bool is_unmerged_ret_state (int max_locals) const
1064     {
1065       if (stacktop == NO_STACK)
1066         return true;
1067       for (int i = 0; i < max_locals; ++i)
1068         {
1069           if (locals[i].key == unused_by_subroutine_type)
1070             return true;
1071         }
1072       return false;
1073     }
1074
1075 #ifdef VERIFY_DEBUG
1076     void print (const char *leader, int pc,
1077                 int max_stack, int max_locals) const
1078     {
1079       debug_print ("%s [%4d]:   [stack] ", leader, pc);
1080       int i;
1081       for (i = 0; i < stacktop; ++i)
1082         stack[i].print ();
1083       for (; i < max_stack; ++i)
1084         debug_print (".");
1085       debug_print ("    [local] ");
1086       for (i = 0; i < max_locals; ++i)
1087         {
1088           locals[i].print ();
1089           debug_print (local_changed[i] ? "+" : " ");
1090         }
1091       if (subroutine == 0)
1092         debug_print ("   | None");
1093       else
1094         debug_print ("   | %4d", subroutine);
1095       debug_print (" | %p\n", this);
1096     }
1097 #else
1098     inline void print (const char *, int, int, int) const
1099     {
1100     }
1101 #endif /* VERIFY_DEBUG */
1102   };
1103
1104   type pop_raw ()
1105   {
1106     if (current_state->stacktop <= 0)
1107       verify_fail ("stack empty");
1108     type r = current_state->stack[--current_state->stacktop];
1109     current_state->stackdepth -= r.depth ();
1110     if (current_state->stackdepth < 0)
1111       verify_fail ("stack empty", start_PC);
1112     return r;
1113   }
1114
1115   type pop32 ()
1116   {
1117     type r = pop_raw ();
1118     if (r.iswide ())
1119       verify_fail ("narrow pop of wide type");
1120     return r;
1121   }
1122
1123   type pop64 ()
1124   {
1125     type r = pop_raw ();
1126     if (! r.iswide ())
1127       verify_fail ("wide pop of narrow type");
1128     return r;
1129   }
1130
1131   type pop_type (type match)
1132   {
1133     match.promote ();
1134     type t = pop_raw ();
1135     if (! match.compatible (t, this))
1136       verify_fail ("incompatible type on stack");
1137     return t;
1138   }
1139
1140   // Pop a reference type or a return address.
1141   type pop_ref_or_return ()
1142   {
1143     type t = pop_raw ();
1144     if (! t.isreference () && t.key != return_address_type)
1145       verify_fail ("expected reference or return address on stack");
1146     return t;
1147   }
1148
1149   void push_type (type t)
1150   {
1151     // If T is a numeric type like short, promote it to int.
1152     t.promote ();
1153
1154     int depth = t.depth ();
1155     if (current_state->stackdepth + depth > current_method->max_stack)
1156       verify_fail ("stack overflow");
1157     current_state->stack[current_state->stacktop++] = t;
1158     current_state->stackdepth += depth;
1159   }
1160
1161   void set_variable (int index, type t)
1162   {
1163     // If T is a numeric type like short, promote it to int.
1164     t.promote ();
1165
1166     int depth = t.depth ();
1167     if (index > current_method->max_locals - depth)
1168       verify_fail ("invalid local variable");
1169     current_state->locals[index] = t;
1170     current_state->note_variable (index);
1171
1172     if (depth == 2)
1173       {
1174         current_state->locals[index + 1] = continuation_type;
1175         current_state->note_variable (index + 1);
1176       }
1177     if (index > 0 && current_state->locals[index - 1].iswide ())
1178       {
1179         current_state->locals[index - 1] = unsuitable_type;
1180         // There's no need to call note_variable here.
1181       }
1182   }
1183
1184   type get_variable (int index, type t)
1185   {
1186     int depth = t.depth ();
1187     if (index > current_method->max_locals - depth)
1188       verify_fail ("invalid local variable");
1189     if (! t.compatible (current_state->locals[index], this))
1190       verify_fail ("incompatible type in local variable");
1191     if (depth == 2)
1192       {
1193         type t (continuation_type);
1194         if (! current_state->locals[index + 1].compatible (t, this))
1195           verify_fail ("invalid local variable");
1196       }
1197     return current_state->locals[index];
1198   }
1199
1200   // Make sure ARRAY is an array type and that its elements are
1201   // compatible with type ELEMENT.  Returns the actual element type.
1202   type require_array_type (type array, type element)
1203   {
1204     // An odd case.  Here we just pretend that everything went ok.  If
1205     // the requested element type is some kind of reference, return
1206     // the null type instead.
1207     if (array.isnull ())
1208       return element.isreference () ? type (null_type) : element;
1209
1210     if (! array.isarray ())
1211       verify_fail ("array required");
1212
1213     type t = array.element_type (this);
1214     if (! element.compatible (t, this))
1215       {
1216         // Special case for byte arrays, which must also be boolean
1217         // arrays.
1218         bool ok = true;
1219         if (element.key == byte_type)
1220           {
1221             type e2 (boolean_type);
1222             ok = e2.compatible (t, this);
1223           }
1224         if (! ok)
1225           verify_fail ("incompatible array element type");
1226       }
1227
1228     // Return T and not ELEMENT, because T might be specialized.
1229     return t;
1230   }
1231
1232   jint get_byte ()
1233   {
1234     if (PC >= current_method->code_length)
1235       verify_fail ("premature end of bytecode");
1236     return (jint) bytecode[PC++] & 0xff;
1237   }
1238
1239   jint get_ushort ()
1240   {
1241     jint b1 = get_byte ();
1242     jint b2 = get_byte ();
1243     return (jint) ((b1 << 8) | b2) & 0xffff;
1244   }
1245
1246   jint get_short ()
1247   {
1248     jint b1 = get_byte ();
1249     jint b2 = get_byte ();
1250     jshort s = (b1 << 8) | b2;
1251     return (jint) s;
1252   }
1253
1254   jint get_int ()
1255   {
1256     jint b1 = get_byte ();
1257     jint b2 = get_byte ();
1258     jint b3 = get_byte ();
1259     jint b4 = get_byte ();
1260     return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
1261   }
1262
1263   int compute_jump (int offset)
1264   {
1265     int npc = start_PC + offset;
1266     if (npc < 0 || npc >= current_method->code_length)
1267       verify_fail ("branch out of range", start_PC);
1268     return npc;
1269   }
1270
1271   // Merge the indicated state into the state at the branch target and
1272   // schedule a new PC if there is a change.  If RET_SEMANTICS is
1273   // true, then we are merging from a `ret' instruction into the
1274   // instruction after a `jsr'.  This is a special case with its own
1275   // modified semantics.
1276   void push_jump_merge (int npc, state *nstate, bool ret_semantics = false)
1277   {
1278     bool changed = true;
1279     if (states[npc] == NULL)
1280       {
1281         // There's a weird situation here.  If are examining the
1282         // branch that results from a `ret', and there is not yet a
1283         // state available at the branch target (the instruction just
1284         // after the `jsr'), then we have to construct a special kind
1285         // of state at that point for future merging.  This special
1286         // state has the type `unused_by_subroutine_type' in each slot
1287         // which was not modified by the subroutine.
1288         states[npc] = new state (nstate, current_method->max_stack,
1289                                  current_method->max_locals, ret_semantics);
1290         debug_print ("== New state in push_jump_merge\n");
1291         states[npc]->print ("New", npc, current_method->max_stack,
1292                             current_method->max_locals);
1293       }
1294     else
1295       {
1296         debug_print ("== Merge states in push_jump_merge\n");
1297         nstate->print ("Frm", start_PC, current_method->max_stack,
1298                        current_method->max_locals);
1299         states[npc]->print (" To", npc, current_method->max_stack,
1300                             current_method->max_locals);
1301         changed = states[npc]->merge (nstate, ret_semantics,
1302                                       current_method->max_locals, this);
1303         states[npc]->print ("New", npc, current_method->max_stack,
1304                             current_method->max_locals);
1305       }
1306
1307     if (changed && states[npc]->next == state::INVALID)
1308       {
1309         // The merge changed the state, and the new PC isn't yet on our
1310         // list of PCs to re-verify.
1311         states[npc]->next = next_verify_pc;
1312         next_verify_pc = npc;
1313       }
1314   }
1315
1316   void push_jump (int offset)
1317   {
1318     int npc = compute_jump (offset);
1319     if (npc < PC)
1320       current_state->check_no_uninitialized_objects (current_method->max_locals, this);
1321     push_jump_merge (npc, current_state);
1322   }
1323
1324   void push_exception_jump (type t, int pc)
1325   {
1326     current_state->check_no_uninitialized_objects (current_method->max_locals,
1327                                                    this, true);
1328     state s (current_state, current_method->max_stack,
1329              current_method->max_locals);
1330     if (current_method->max_stack < 1)
1331       verify_fail ("stack overflow at exception handler");
1332     s.set_exception (t, current_method->max_stack);
1333     push_jump_merge (pc, &s);
1334   }
1335
1336   int pop_jump ()
1337   {
1338     int *prev_loc = &next_verify_pc;
1339     int npc = next_verify_pc;
1340     bool skipped = false;
1341
1342     while (npc != state::NO_NEXT)
1343       {
1344         // If the next available PC is an unmerged `ret' state, then
1345         // we aren't yet ready to handle it.  That's because we would
1346         // need all kind of special cases to do so.  So instead we
1347         // defer this jump until after we've processed it via a
1348         // fall-through.  This has to happen because the instruction
1349         // before this one must be a `jsr'.
1350         if (! states[npc]->is_unmerged_ret_state (current_method->max_locals))
1351           {
1352             *prev_loc = states[npc]->next;
1353             states[npc]->next = state::INVALID;
1354             return npc;
1355           }
1356
1357         skipped = true;
1358         prev_loc = &states[npc]->next;
1359         npc = states[npc]->next;
1360       }
1361
1362     // Note that we might have gotten here even when there are
1363     // remaining states to process.  That can happen if we find a
1364     // `jsr' without a `ret'.
1365     return state::NO_NEXT;
1366   }
1367
1368   void invalidate_pc ()
1369   {
1370     PC = state::NO_NEXT;
1371   }
1372
1373   void note_branch_target (int pc, bool is_jsr_target = false)
1374   {
1375     // Don't check `pc <= PC', because we've advanced PC after
1376     // fetching the target and we haven't yet checked the next
1377     // instruction.
1378     if (pc < PC && ! (flags[pc] & FLAG_INSN_START))
1379       verify_fail ("branch not to instruction start", start_PC);
1380     flags[pc] |= FLAG_BRANCH_TARGET;
1381     if (is_jsr_target)
1382       {
1383         // Record the jsr which called this instruction.
1384         subr_info *info = (subr_info *) _Jv_Malloc (sizeof (subr_info));
1385         info->pc = PC;
1386         info->next = jsr_ptrs[pc];
1387         jsr_ptrs[pc] = info;
1388       }
1389   }
1390
1391   void skip_padding ()
1392   {
1393     while ((PC % 4) > 0)
1394       if (get_byte () != 0)
1395         verify_fail ("found nonzero padding byte");
1396   }
1397
1398   // Return the subroutine to which the instruction at PC belongs.
1399   int get_subroutine (int pc)
1400   {
1401     if (states[pc] == NULL)
1402       return 0;
1403     return states[pc]->subroutine;
1404   }
1405
1406   // Do the work for a `ret' instruction.  INDEX is the index into the
1407   // local variables.
1408   void handle_ret_insn (int index)
1409   {
1410     get_variable (index, return_address_type);
1411
1412     int csub = current_state->subroutine;
1413     if (csub == 0)
1414       verify_fail ("no subroutine");
1415
1416     // Check to see if we've merged subroutines.
1417     subr_entry_info *entry;
1418     for (entry = entry_points; entry != NULL; entry = entry->next)
1419       {
1420         if (entry->ret_pc == start_PC)
1421           break;
1422       }
1423     if (entry == NULL)
1424       {
1425         entry = (subr_entry_info *) _Jv_Malloc (sizeof (subr_entry_info));
1426         entry->pc = csub;
1427         entry->ret_pc = start_PC;
1428         entry->next = entry_points;
1429         entry_points = entry;
1430       }
1431     else if (entry->pc != csub)
1432       verify_fail ("subroutines merged");
1433
1434     for (subr_info *subr = jsr_ptrs[csub]; subr != NULL; subr = subr->next)
1435       {
1436         // Temporarily modify the current state so it looks like we're
1437         // in the enclosing context.
1438         current_state->subroutine = get_subroutine (subr->pc);
1439         if (subr->pc < PC)
1440           current_state->check_no_uninitialized_objects (current_method->max_locals, this);
1441         push_jump_merge (subr->pc, current_state, true);
1442       }
1443
1444     current_state->subroutine = csub;
1445     invalidate_pc ();
1446   }
1447
1448   // We're in the subroutine SUB, calling a subroutine at DEST.  Make
1449   // sure this subroutine isn't already on the stack.
1450   void check_nonrecursive_call (int sub, int dest)
1451   {
1452     if (sub == 0)
1453       return;
1454     if (sub == dest)
1455       verify_fail ("recursive subroutine call");
1456     for (subr_info *info = jsr_ptrs[sub]; info != NULL; info = info->next)
1457       check_nonrecursive_call (get_subroutine (info->pc), dest);
1458   }
1459
1460   void handle_jsr_insn (int offset)
1461   {
1462     int npc = compute_jump (offset);
1463
1464     if (npc < PC)
1465       current_state->check_no_uninitialized_objects (current_method->max_locals, this);
1466     check_nonrecursive_call (current_state->subroutine, npc);
1467
1468     // Modify our state as appropriate for entry into a subroutine.
1469     push_type (return_address_type);
1470     push_jump_merge (npc, current_state);
1471     // Clean up.
1472     pop_type (return_address_type);
1473
1474     // On entry to the subroutine, the subroutine number must be set
1475     // and the locals must be marked as cleared.  We do this after
1476     // merging state so that we don't erroneously "notice" a variable
1477     // change merely on entry.
1478     states[npc]->enter_subroutine (npc, current_method->max_locals);
1479
1480     // Indicate that we don't know the stack depth of the instruction
1481     // following the `jsr'.  The idea here is that we need to merge
1482     // the local variable state across the jsr, but the subroutine
1483     // might change the stack depth, so we can't make any assumptions
1484     // about it.  So we have yet another special case.  We know that
1485     // at this point PC points to the instruction after the jsr.
1486
1487     // FIXME: what if we have a jsr at the end of the code, but that
1488     // jsr has no corresponding ret?  Is this verifiable, or is it
1489     // not?  If it is then we need a special case here.
1490     if (PC >= current_method->code_length)
1491       verify_fail ("fell off end");
1492
1493     current_state->stacktop = state::NO_STACK;
1494     push_jump_merge (PC, current_state);
1495     invalidate_pc ();
1496   }
1497
1498   jclass construct_primitive_array_type (type_val prim)
1499   {
1500     jclass k = NULL;
1501     switch (prim)
1502       {
1503       case boolean_type:
1504         k = JvPrimClass (boolean);
1505         break;
1506       case char_type:
1507         k = JvPrimClass (char);
1508         break;
1509       case float_type:
1510         k = JvPrimClass (float);
1511         break;
1512       case double_type:
1513         k = JvPrimClass (double);
1514         break;
1515       case byte_type:
1516         k = JvPrimClass (byte);
1517         break;
1518       case short_type:
1519         k = JvPrimClass (short);
1520         break;
1521       case int_type:
1522         k = JvPrimClass (int);
1523         break;
1524       case long_type:
1525         k = JvPrimClass (long);
1526         break;
1527
1528       // These aren't used here but we call them out to avoid
1529       // warnings.
1530       case void_type:
1531       case unsuitable_type:
1532       case return_address_type:
1533       case continuation_type:
1534       case unused_by_subroutine_type:
1535       case reference_type:
1536       case null_type:
1537       case unresolved_reference_type:
1538       case uninitialized_reference_type:
1539       case uninitialized_unresolved_reference_type:
1540       default:
1541         verify_fail ("unknown type in construct_primitive_array_type");
1542       }
1543     k = _Jv_GetArrayClass (k, NULL);
1544     return k;
1545   }
1546
1547   // This pass computes the location of branch targets and also
1548   // instruction starts.
1549   void branch_prepass ()
1550   {
1551     flags = (char *) _Jv_Malloc (current_method->code_length);
1552     jsr_ptrs = (subr_info **) _Jv_Malloc (sizeof (subr_info *)
1553                                           * current_method->code_length);
1554
1555     for (int i = 0; i < current_method->code_length; ++i)
1556       {
1557         flags[i] = 0;
1558         jsr_ptrs[i] = NULL;
1559       }
1560
1561     bool last_was_jsr = false;
1562
1563     PC = 0;
1564     while (PC < current_method->code_length)
1565       {
1566         // Set `start_PC' early so that error checking can have the
1567         // correct value.
1568         start_PC = PC;
1569         flags[PC] |= FLAG_INSN_START;
1570
1571         // If the previous instruction was a jsr, then the next
1572         // instruction is a branch target -- the branch being the
1573         // corresponding `ret'.
1574         if (last_was_jsr)
1575           note_branch_target (PC);
1576         last_was_jsr = false;
1577
1578         java_opcode opcode = (java_opcode) bytecode[PC++];
1579         switch (opcode)
1580           {
1581           case op_nop:
1582           case op_aconst_null:
1583           case op_iconst_m1:
1584           case op_iconst_0:
1585           case op_iconst_1:
1586           case op_iconst_2:
1587           case op_iconst_3:
1588           case op_iconst_4:
1589           case op_iconst_5:
1590           case op_lconst_0:
1591           case op_lconst_1:
1592           case op_fconst_0:
1593           case op_fconst_1:
1594           case op_fconst_2:
1595           case op_dconst_0:
1596           case op_dconst_1:
1597           case op_iload_0:
1598           case op_iload_1:
1599           case op_iload_2:
1600           case op_iload_3:
1601           case op_lload_0:
1602           case op_lload_1:
1603           case op_lload_2:
1604           case op_lload_3:
1605           case op_fload_0:
1606           case op_fload_1:
1607           case op_fload_2:
1608           case op_fload_3:
1609           case op_dload_0:
1610           case op_dload_1:
1611           case op_dload_2:
1612           case op_dload_3:
1613           case op_aload_0:
1614           case op_aload_1:
1615           case op_aload_2:
1616           case op_aload_3:
1617           case op_iaload:
1618           case op_laload:
1619           case op_faload:
1620           case op_daload:
1621           case op_aaload:
1622           case op_baload:
1623           case op_caload:
1624           case op_saload:
1625           case op_istore_0:
1626           case op_istore_1:
1627           case op_istore_2:
1628           case op_istore_3:
1629           case op_lstore_0:
1630           case op_lstore_1:
1631           case op_lstore_2:
1632           case op_lstore_3:
1633           case op_fstore_0:
1634           case op_fstore_1:
1635           case op_fstore_2:
1636           case op_fstore_3:
1637           case op_dstore_0:
1638           case op_dstore_1:
1639           case op_dstore_2:
1640           case op_dstore_3:
1641           case op_astore_0:
1642           case op_astore_1:
1643           case op_astore_2:
1644           case op_astore_3:
1645           case op_iastore:
1646           case op_lastore:
1647           case op_fastore:
1648           case op_dastore:
1649           case op_aastore:
1650           case op_bastore:
1651           case op_castore:
1652           case op_sastore:
1653           case op_pop:
1654           case op_pop2:
1655           case op_dup:
1656           case op_dup_x1:
1657           case op_dup_x2:
1658           case op_dup2:
1659           case op_dup2_x1:
1660           case op_dup2_x2:
1661           case op_swap:
1662           case op_iadd:
1663           case op_isub:
1664           case op_imul:
1665           case op_idiv:
1666           case op_irem:
1667           case op_ishl:
1668           case op_ishr:
1669           case op_iushr:
1670           case op_iand:
1671           case op_ior:
1672           case op_ixor:
1673           case op_ladd:
1674           case op_lsub:
1675           case op_lmul:
1676           case op_ldiv:
1677           case op_lrem:
1678           case op_lshl:
1679           case op_lshr:
1680           case op_lushr:
1681           case op_land:
1682           case op_lor:
1683           case op_lxor:
1684           case op_fadd:
1685           case op_fsub:
1686           case op_fmul:
1687           case op_fdiv:
1688           case op_frem:
1689           case op_dadd:
1690           case op_dsub:
1691           case op_dmul:
1692           case op_ddiv:
1693           case op_drem:
1694           case op_ineg:
1695           case op_i2b:
1696           case op_i2c:
1697           case op_i2s:
1698           case op_lneg:
1699           case op_fneg:
1700           case op_dneg:
1701           case op_i2l:
1702           case op_i2f:
1703           case op_i2d:
1704           case op_l2i:
1705           case op_l2f:
1706           case op_l2d:
1707           case op_f2i:
1708           case op_f2l:
1709           case op_f2d:
1710           case op_d2i:
1711           case op_d2l:
1712           case op_d2f:
1713           case op_lcmp:
1714           case op_fcmpl:
1715           case op_fcmpg:
1716           case op_dcmpl:
1717           case op_dcmpg:
1718           case op_monitorenter:
1719           case op_monitorexit:
1720           case op_ireturn:
1721           case op_lreturn:
1722           case op_freturn:
1723           case op_dreturn:
1724           case op_areturn:
1725           case op_return:
1726           case op_athrow:
1727           case op_arraylength:
1728             break;
1729
1730           case op_bipush:
1731           case op_ldc:
1732           case op_iload:
1733           case op_lload:
1734           case op_fload:
1735           case op_dload:
1736           case op_aload:
1737           case op_istore:
1738           case op_lstore:
1739           case op_fstore:
1740           case op_dstore:
1741           case op_astore:
1742           case op_ret:
1743           case op_newarray:
1744             get_byte ();
1745             break;
1746
1747           case op_iinc:
1748           case op_sipush:
1749           case op_ldc_w:
1750           case op_ldc2_w:
1751           case op_getstatic:
1752           case op_getfield:
1753           case op_putfield:
1754           case op_putstatic:
1755           case op_new:
1756           case op_anewarray:
1757           case op_instanceof:
1758           case op_checkcast:
1759           case op_invokespecial:
1760           case op_invokestatic:
1761           case op_invokevirtual:
1762             get_short ();
1763             break;
1764
1765           case op_multianewarray:
1766             get_short ();
1767             get_byte ();
1768             break;
1769
1770           case op_jsr:
1771             last_was_jsr = true;
1772             // Fall through.
1773           case op_ifeq:
1774           case op_ifne:
1775           case op_iflt:
1776           case op_ifge:
1777           case op_ifgt:
1778           case op_ifle:
1779           case op_if_icmpeq:
1780           case op_if_icmpne:
1781           case op_if_icmplt:
1782           case op_if_icmpge:
1783           case op_if_icmpgt:
1784           case op_if_icmple:
1785           case op_if_acmpeq:
1786           case op_if_acmpne:
1787           case op_ifnull:
1788           case op_ifnonnull:
1789           case op_goto:
1790             note_branch_target (compute_jump (get_short ()), last_was_jsr);
1791             break;
1792
1793           case op_tableswitch:
1794             {
1795               skip_padding ();
1796               note_branch_target (compute_jump (get_int ()));
1797               jint low = get_int ();
1798               jint hi = get_int ();
1799               if (low > hi)
1800                 verify_fail ("invalid tableswitch", start_PC);
1801               for (int i = low; i <= hi; ++i)
1802                 note_branch_target (compute_jump (get_int ()));
1803             }
1804             break;
1805
1806           case op_lookupswitch:
1807             {
1808               skip_padding ();
1809               note_branch_target (compute_jump (get_int ()));
1810               int npairs = get_int ();
1811               if (npairs < 0)
1812                 verify_fail ("too few pairs in lookupswitch", start_PC);
1813               while (npairs-- > 0)
1814                 {
1815                   get_int ();
1816                   note_branch_target (compute_jump (get_int ()));
1817                 }
1818             }
1819             break;
1820
1821           case op_invokeinterface:
1822             get_short ();
1823             get_byte ();
1824             get_byte ();
1825             break;
1826
1827           case op_wide:
1828             {
1829               opcode = (java_opcode) get_byte ();
1830               get_short ();
1831               if (opcode == op_iinc)
1832                 get_short ();
1833             }
1834             break;
1835
1836           case op_jsr_w:
1837             last_was_jsr = true;
1838             // Fall through.
1839           case op_goto_w:
1840             note_branch_target (compute_jump (get_int ()), last_was_jsr);
1841             break;
1842
1843           // These are unused here, but we call them out explicitly
1844           // so that -Wswitch-enum doesn't complain.
1845           case op_putfield_1:
1846           case op_putfield_2:
1847           case op_putfield_4:
1848           case op_putfield_8:
1849           case op_putfield_a:
1850           case op_putstatic_1:
1851           case op_putstatic_2:
1852           case op_putstatic_4:
1853           case op_putstatic_8:
1854           case op_putstatic_a:
1855           case op_getfield_1:
1856           case op_getfield_2s:
1857           case op_getfield_2u:
1858           case op_getfield_4:
1859           case op_getfield_8:
1860           case op_getfield_a:
1861           case op_getstatic_1:
1862           case op_getstatic_2s:
1863           case op_getstatic_2u:
1864           case op_getstatic_4:
1865           case op_getstatic_8:
1866           case op_getstatic_a:
1867           default:
1868             verify_fail ("unrecognized instruction in branch_prepass",
1869                          start_PC);
1870           }
1871
1872         // See if any previous branch tried to branch to the middle of
1873         // this instruction.
1874         for (int pc = start_PC + 1; pc < PC; ++pc)
1875           {
1876             if ((flags[pc] & FLAG_BRANCH_TARGET))
1877               verify_fail ("branch to middle of instruction", pc);
1878           }
1879       }
1880
1881     // Verify exception handlers.
1882     for (int i = 0; i < current_method->exc_count; ++i)
1883       {
1884         if (! (flags[exception[i].handler_pc.i] & FLAG_INSN_START))
1885           verify_fail ("exception handler not at instruction start",
1886                        exception[i].handler_pc.i);
1887         if (! (flags[exception[i].start_pc.i] & FLAG_INSN_START))
1888           verify_fail ("exception start not at instruction start",
1889                        exception[i].start_pc.i);
1890         if (exception[i].end_pc.i != current_method->code_length
1891             && ! (flags[exception[i].end_pc.i] & FLAG_INSN_START))
1892           verify_fail ("exception end not at instruction start",
1893                        exception[i].end_pc.i);
1894
1895         flags[exception[i].handler_pc.i] |= FLAG_BRANCH_TARGET;
1896       }
1897   }
1898
1899   void check_pool_index (int index)
1900   {
1901     if (index < 0 || index >= current_class->constants.size)
1902       verify_fail ("constant pool index out of range", start_PC);
1903   }
1904
1905   type check_class_constant (int index)
1906   {
1907     check_pool_index (index);
1908     _Jv_Constants *pool = &current_class->constants;
1909     if (pool->tags[index] == JV_CONSTANT_ResolvedClass)
1910       return type (pool->data[index].clazz);
1911     else if (pool->tags[index] == JV_CONSTANT_Class)
1912       return type (pool->data[index].utf8);
1913     verify_fail ("expected class constant", start_PC);
1914   }
1915
1916   type check_constant (int index)
1917   {
1918     check_pool_index (index);
1919     _Jv_Constants *pool = &current_class->constants;
1920     if (pool->tags[index] == JV_CONSTANT_ResolvedString
1921         || pool->tags[index] == JV_CONSTANT_String)
1922       return type (&java::lang::String::class$);
1923     else if (pool->tags[index] == JV_CONSTANT_Integer)
1924       return type (int_type);
1925     else if (pool->tags[index] == JV_CONSTANT_Float)
1926       return type (float_type);
1927     verify_fail ("String, int, or float constant expected", start_PC);
1928   }
1929
1930   type check_wide_constant (int index)
1931   {
1932     check_pool_index (index);
1933     _Jv_Constants *pool = &current_class->constants;
1934     if (pool->tags[index] == JV_CONSTANT_Long)
1935       return type (long_type);
1936     else if (pool->tags[index] == JV_CONSTANT_Double)
1937       return type (double_type);
1938     verify_fail ("long or double constant expected", start_PC);
1939   }
1940
1941   // Helper for both field and method.  These are laid out the same in
1942   // the constant pool.
1943   type handle_field_or_method (int index, int expected,
1944                                _Jv_Utf8Const **name,
1945                                _Jv_Utf8Const **fmtype)
1946   {
1947     check_pool_index (index);
1948     _Jv_Constants *pool = &current_class->constants;
1949     if (pool->tags[index] != expected)
1950       verify_fail ("didn't see expected constant", start_PC);
1951     // Once we know we have a Fieldref or Methodref we assume that it
1952     // is correctly laid out in the constant pool.  I think the code
1953     // in defineclass.cc guarantees this.
1954     _Jv_ushort class_index, name_and_type_index;
1955     _Jv_loadIndexes (&pool->data[index],
1956                      class_index,
1957                      name_and_type_index);
1958     _Jv_ushort name_index, desc_index;
1959     _Jv_loadIndexes (&pool->data[name_and_type_index],
1960                      name_index, desc_index);
1961
1962     *name = pool->data[name_index].utf8;
1963     *fmtype = pool->data[desc_index].utf8;
1964
1965     return check_class_constant (class_index);
1966   }
1967
1968   // Return field's type, compute class' type if requested.
1969   type check_field_constant (int index, type *class_type = NULL)
1970   {
1971     _Jv_Utf8Const *name, *field_type;
1972     type ct = handle_field_or_method (index,
1973                                       JV_CONSTANT_Fieldref,
1974                                       &name, &field_type);
1975     if (class_type)
1976       *class_type = ct;
1977     if (field_type->data[0] == '[' || field_type->data[0] == 'L')
1978       return type (field_type);
1979     return get_type_val_for_signature (field_type->data[0]);
1980   }
1981
1982   type check_method_constant (int index, bool is_interface,
1983                               _Jv_Utf8Const **method_name,
1984                               _Jv_Utf8Const **method_signature)
1985   {
1986     return handle_field_or_method (index,
1987                                    (is_interface
1988                                     ? JV_CONSTANT_InterfaceMethodref
1989                                     : JV_CONSTANT_Methodref),
1990                                    method_name, method_signature);
1991   }
1992
1993   type get_one_type (char *&p)
1994   {
1995     char *start = p;
1996
1997     int arraycount = 0;
1998     while (*p == '[')
1999       {
2000         ++arraycount;
2001         ++p;
2002       }
2003
2004     char v = *p++;
2005
2006     if (v == 'L')
2007       {
2008         while (*p != ';')
2009           ++p;
2010         ++p;
2011         _Jv_Utf8Const *name = make_utf8_const (start, p - start);
2012         return type (name);
2013       }
2014
2015     // Casting to jchar here is ok since we are looking at an ASCII
2016     // character.
2017     type_val rt = get_type_val_for_signature (jchar (v));
2018
2019     if (arraycount == 0)
2020       {
2021         // Callers of this function eventually push their arguments on
2022         // the stack.  So, promote them here.
2023         return type (rt).promote ();
2024       }
2025
2026     jclass k = construct_primitive_array_type (rt);
2027     while (--arraycount > 0)
2028       k = _Jv_GetArrayClass (k, NULL);
2029     return type (k);
2030   }
2031
2032   void compute_argument_types (_Jv_Utf8Const *signature,
2033                                type *types)
2034   {
2035     char *p = signature->data;
2036     // Skip `('.
2037     ++p;
2038
2039     int i = 0;
2040     while (*p != ')')
2041       types[i++] = get_one_type (p);
2042   }
2043
2044   type compute_return_type (_Jv_Utf8Const *signature)
2045   {
2046     char *p = signature->data;
2047     while (*p != ')')
2048       ++p;
2049     ++p;
2050     return get_one_type (p);
2051   }
2052
2053   void check_return_type (type onstack)
2054   {
2055     type rt = compute_return_type (current_method->self->signature);
2056     if (! rt.compatible (onstack, this))
2057       verify_fail ("incompatible return type");
2058   }
2059
2060   // Initialize the stack for the new method.  Returns true if this
2061   // method is an instance initializer.
2062   bool initialize_stack ()
2063   {
2064     int var = 0;
2065     bool is_init = false;
2066
2067     using namespace java::lang::reflect;
2068     if (! Modifier::isStatic (current_method->self->accflags))
2069       {
2070         type kurr (current_class);
2071         if (_Jv_equalUtf8Consts (current_method->self->name, gcj::init_name))
2072           {
2073             kurr.set_uninitialized (type::SELF, this);
2074             is_init = true;
2075           }
2076         set_variable (0, kurr);
2077         current_state->set_this_type (kurr);
2078         ++var;
2079       }
2080
2081     // We have to handle wide arguments specially here.
2082     int arg_count = _Jv_count_arguments (current_method->self->signature);
2083     type arg_types[arg_count];
2084     compute_argument_types (current_method->self->signature, arg_types);
2085     for (int i = 0; i < arg_count; ++i)
2086       {
2087         set_variable (var, arg_types[i]);
2088         ++var;
2089         if (arg_types[i].iswide ())
2090           ++var;
2091       }
2092
2093     return is_init;
2094   }
2095
2096   void verify_instructions_0 ()
2097   {
2098     current_state = new state (current_method->max_stack,
2099                                current_method->max_locals);
2100
2101     PC = 0;
2102     start_PC = 0;
2103
2104     // True if we are verifying an instance initializer.
2105     bool this_is_init = initialize_stack ();
2106
2107     states = (state **) _Jv_Malloc (sizeof (state *)
2108                                     * current_method->code_length);
2109     for (int i = 0; i < current_method->code_length; ++i)
2110       states[i] = NULL;
2111
2112     next_verify_pc = state::NO_NEXT;
2113
2114     while (true)
2115       {
2116         // If the PC was invalidated, get a new one from the work list.
2117         if (PC == state::NO_NEXT)
2118           {
2119             PC = pop_jump ();
2120             if (PC == state::INVALID)
2121               verify_fail ("can't happen: saw state::INVALID");
2122             if (PC == state::NO_NEXT)
2123               break;
2124             debug_print ("== State pop from pending list\n");
2125             // Set up the current state.
2126             current_state->copy (states[PC], current_method->max_stack,
2127                                  current_method->max_locals);
2128           }
2129         else
2130           {
2131             // Control can't fall off the end of the bytecode.  We
2132             // only need to check this in the fall-through case,
2133             // because branch bounds are checked when they are
2134             // pushed.
2135             if (PC >= current_method->code_length)
2136               verify_fail ("fell off end");
2137
2138             // We only have to do this checking in the situation where
2139             // control flow falls through from the previous
2140             // instruction.  Otherwise merging is done at the time we
2141             // push the branch.
2142             if (states[PC] != NULL)
2143               {
2144                 // We've already visited this instruction.  So merge
2145                 // the states together.  If this yields no change then
2146                 // we don't have to re-verify.  However, if the new
2147                 // state is an the result of an unmerged `ret', we
2148                 // must continue through it.
2149                 debug_print ("== Fall through merge\n");
2150                 states[PC]->print ("Old", PC, current_method->max_stack,
2151                                    current_method->max_locals);
2152                 current_state->print ("Cur", PC, current_method->max_stack,
2153                                       current_method->max_locals);
2154                 if (! current_state->merge (states[PC], false,
2155                                             current_method->max_locals, this)
2156                     && ! states[PC]->is_unmerged_ret_state (current_method->max_locals))
2157                   {
2158                     debug_print ("== Fall through optimization\n");
2159                     invalidate_pc ();
2160                     continue;
2161                   }
2162                 // Save a copy of it for later.
2163                 states[PC]->copy (current_state, current_method->max_stack,
2164                                   current_method->max_locals);
2165                 current_state->print ("New", PC, current_method->max_stack,
2166                                       current_method->max_locals);
2167               }
2168           }
2169
2170         // We only have to keep saved state at branch targets.  If
2171         // we're at a branch target and the state here hasn't been set
2172         // yet, we set it now.
2173         if (states[PC] == NULL && (flags[PC] & FLAG_BRANCH_TARGET))
2174           {
2175             states[PC] = new state (current_state, current_method->max_stack,
2176                                     current_method->max_locals);
2177           }
2178
2179         // Set this before handling exceptions so that debug output is
2180         // sane.
2181         start_PC = PC;
2182
2183         // Update states for all active exception handlers.  Ordinarily
2184         // there are not many exception handlers.  So we simply run
2185         // through them all.
2186         for (int i = 0; i < current_method->exc_count; ++i)
2187           {
2188             if (PC >= exception[i].start_pc.i && PC < exception[i].end_pc.i)
2189               {
2190                 type handler (&java::lang::Throwable::class$);
2191                 if (exception[i].handler_type.i != 0)
2192                   handler = check_class_constant (exception[i].handler_type.i);
2193                 push_exception_jump (handler, exception[i].handler_pc.i);
2194               }
2195           }
2196
2197         current_state->print ("   ", PC, current_method->max_stack,
2198                               current_method->max_locals);
2199         java_opcode opcode = (java_opcode) bytecode[PC++];
2200         switch (opcode)
2201           {
2202           case op_nop:
2203             break;
2204
2205           case op_aconst_null:
2206             push_type (null_type);
2207             break;
2208
2209           case op_iconst_m1:
2210           case op_iconst_0:
2211           case op_iconst_1:
2212           case op_iconst_2:
2213           case op_iconst_3:
2214           case op_iconst_4:
2215           case op_iconst_5:
2216             push_type (int_type);
2217             break;
2218
2219           case op_lconst_0:
2220           case op_lconst_1:
2221             push_type (long_type);
2222             break;
2223
2224           case op_fconst_0:
2225           case op_fconst_1:
2226           case op_fconst_2:
2227             push_type (float_type);
2228             break;
2229
2230           case op_dconst_0:
2231           case op_dconst_1:
2232             push_type (double_type);
2233             break;
2234
2235           case op_bipush:
2236             get_byte ();
2237             push_type (int_type);
2238             break;
2239
2240           case op_sipush:
2241             get_short ();
2242             push_type (int_type);
2243             break;
2244
2245           case op_ldc:
2246             push_type (check_constant (get_byte ()));
2247             break;
2248           case op_ldc_w:
2249             push_type (check_constant (get_ushort ()));
2250             break;
2251           case op_ldc2_w:
2252             push_type (check_wide_constant (get_ushort ()));
2253             break;
2254
2255           case op_iload:
2256             push_type (get_variable (get_byte (), int_type));
2257             break;
2258           case op_lload:
2259             push_type (get_variable (get_byte (), long_type));
2260             break;
2261           case op_fload:
2262             push_type (get_variable (get_byte (), float_type));
2263             break;
2264           case op_dload:
2265             push_type (get_variable (get_byte (), double_type));
2266             break;
2267           case op_aload:
2268             push_type (get_variable (get_byte (), reference_type));
2269             break;
2270
2271           case op_iload_0:
2272           case op_iload_1:
2273           case op_iload_2:
2274           case op_iload_3:
2275             push_type (get_variable (opcode - op_iload_0, int_type));
2276             break;
2277           case op_lload_0:
2278           case op_lload_1:
2279           case op_lload_2:
2280           case op_lload_3:
2281             push_type (get_variable (opcode - op_lload_0, long_type));
2282             break;
2283           case op_fload_0:
2284           case op_fload_1:
2285           case op_fload_2:
2286           case op_fload_3:
2287             push_type (get_variable (opcode - op_fload_0, float_type));
2288             break;
2289           case op_dload_0:
2290           case op_dload_1:
2291           case op_dload_2:
2292           case op_dload_3:
2293             push_type (get_variable (opcode - op_dload_0, double_type));
2294             break;
2295           case op_aload_0:
2296           case op_aload_1:
2297           case op_aload_2:
2298           case op_aload_3:
2299             push_type (get_variable (opcode - op_aload_0, reference_type));
2300             break;
2301           case op_iaload:
2302             pop_type (int_type);
2303             push_type (require_array_type (pop_type (reference_type),
2304                                            int_type));
2305             break;
2306           case op_laload:
2307             pop_type (int_type);
2308             push_type (require_array_type (pop_type (reference_type),
2309                                            long_type));
2310             break;
2311           case op_faload:
2312             pop_type (int_type);
2313             push_type (require_array_type (pop_type (reference_type),
2314                                            float_type));
2315             break;
2316           case op_daload:
2317             pop_type (int_type);
2318             push_type (require_array_type (pop_type (reference_type),
2319                                            double_type));
2320             break;
2321           case op_aaload:
2322             pop_type (int_type);
2323             push_type (require_array_type (pop_type (reference_type),
2324                                            reference_type));
2325             break;
2326           case op_baload:
2327             pop_type (int_type);
2328             require_array_type (pop_type (reference_type), byte_type);
2329             push_type (int_type);
2330             break;
2331           case op_caload:
2332             pop_type (int_type);
2333             require_array_type (pop_type (reference_type), char_type);
2334             push_type (int_type);
2335             break;
2336           case op_saload:
2337             pop_type (int_type);
2338             require_array_type (pop_type (reference_type), short_type);
2339             push_type (int_type);
2340             break;
2341           case op_istore:
2342             set_variable (get_byte (), pop_type (int_type));
2343             break;
2344           case op_lstore:
2345             set_variable (get_byte (), pop_type (long_type));
2346             break;
2347           case op_fstore:
2348             set_variable (get_byte (), pop_type (float_type));
2349             break;
2350           case op_dstore:
2351             set_variable (get_byte (), pop_type (double_type));
2352             break;
2353           case op_astore:
2354             set_variable (get_byte (), pop_ref_or_return ());
2355             break;
2356           case op_istore_0:
2357           case op_istore_1:
2358           case op_istore_2:
2359           case op_istore_3:
2360             set_variable (opcode - op_istore_0, pop_type (int_type));
2361             break;
2362           case op_lstore_0:
2363           case op_lstore_1:
2364           case op_lstore_2:
2365           case op_lstore_3:
2366             set_variable (opcode - op_lstore_0, pop_type (long_type));
2367             break;
2368           case op_fstore_0:
2369           case op_fstore_1:
2370           case op_fstore_2:
2371           case op_fstore_3:
2372             set_variable (opcode - op_fstore_0, pop_type (float_type));
2373             break;
2374           case op_dstore_0:
2375           case op_dstore_1:
2376           case op_dstore_2:
2377           case op_dstore_3:
2378             set_variable (opcode - op_dstore_0, pop_type (double_type));
2379             break;
2380           case op_astore_0:
2381           case op_astore_1:
2382           case op_astore_2:
2383           case op_astore_3:
2384             set_variable (opcode - op_astore_0, pop_ref_or_return ());
2385             break;
2386           case op_iastore:
2387             pop_type (int_type);
2388             pop_type (int_type);
2389             require_array_type (pop_type (reference_type), int_type);
2390             break;
2391           case op_lastore:
2392             pop_type (long_type);
2393             pop_type (int_type);
2394             require_array_type (pop_type (reference_type), long_type);
2395             break;
2396           case op_fastore:
2397             pop_type (float_type);
2398             pop_type (int_type);
2399             require_array_type (pop_type (reference_type), float_type);
2400             break;
2401           case op_dastore:
2402             pop_type (double_type);
2403             pop_type (int_type);
2404             require_array_type (pop_type (reference_type), double_type);
2405             break;
2406           case op_aastore:
2407             pop_type (reference_type);
2408             pop_type (int_type);
2409             require_array_type (pop_type (reference_type), reference_type);
2410             break;
2411           case op_bastore:
2412             pop_type (int_type);
2413             pop_type (int_type);
2414             require_array_type (pop_type (reference_type), byte_type);
2415             break;
2416           case op_castore:
2417             pop_type (int_type);
2418             pop_type (int_type);
2419             require_array_type (pop_type (reference_type), char_type);
2420             break;
2421           case op_sastore:
2422             pop_type (int_type);
2423             pop_type (int_type);
2424             require_array_type (pop_type (reference_type), short_type);
2425             break;
2426           case op_pop:
2427             pop32 ();
2428             break;
2429           case op_pop2:
2430             pop64 ();
2431             break;
2432           case op_dup:
2433             {
2434               type t = pop32 ();
2435               push_type (t);
2436               push_type (t);
2437             }
2438             break;
2439           case op_dup_x1:
2440             {
2441               type t1 = pop32 ();
2442               type t2 = pop32 ();
2443               push_type (t1);
2444               push_type (t2);
2445               push_type (t1);
2446             }
2447             break;
2448           case op_dup_x2:
2449             {
2450               type t1 = pop32 ();
2451               type t2 = pop_raw ();
2452               if (! t2.iswide ())
2453                 {
2454                   type t3 = pop32 ();
2455                   push_type (t1);
2456                   push_type (t3);
2457                 }
2458               else
2459                 push_type (t1);
2460               push_type (t2);
2461               push_type (t1);
2462             }
2463             break;
2464           case op_dup2:
2465             {
2466               type t = pop_raw ();
2467               if (! t.iswide ())
2468                 {
2469                   type t2 = pop32 ();
2470                   push_type (t2);
2471                   push_type (t);
2472                   push_type (t2);
2473                 }
2474               else
2475                 push_type (t);
2476               push_type (t);
2477             }
2478             break;
2479           case op_dup2_x1:
2480             {
2481               type t1 = pop_raw ();
2482               type t2 = pop32 ();
2483               if (! t1.iswide ())
2484                 {
2485                   type t3 = pop32 ();
2486                   push_type (t2);
2487                   push_type (t1);
2488                   push_type (t3);
2489                 }
2490               else
2491                 push_type (t1);
2492               push_type (t2);
2493               push_type (t1);
2494             }
2495             break;
2496           case op_dup2_x2:
2497             {
2498               type t1 = pop_raw ();
2499               if (t1.iswide ())
2500                 {
2501                   type t2 = pop_raw ();
2502                   if (t2.iswide ())
2503                     {
2504                       push_type (t1);
2505                       push_type (t2);
2506                     }
2507                   else
2508                     {
2509                       type t3 = pop32 ();
2510                       push_type (t1);
2511                       push_type (t3);
2512                       push_type (t2);
2513                     }
2514                   push_type (t1);
2515                 }
2516               else
2517                 {
2518                   type t2 = pop32 ();
2519                   type t3 = pop_raw ();
2520                   if (t3.iswide ())
2521                     {
2522                       push_type (t2);
2523                       push_type (t1);
2524                     }
2525                   else
2526                     {
2527                       type t4 = pop32 ();
2528                       push_type (t2);
2529                       push_type (t1);
2530                       push_type (t4);
2531                     }
2532                   push_type (t3);
2533                   push_type (t2);
2534                   push_type (t1);
2535                 }
2536             }
2537             break;
2538           case op_swap:
2539             {
2540               type t1 = pop32 ();
2541               type t2 = pop32 ();
2542               push_type (t1);
2543               push_type (t2);
2544             }
2545             break;
2546           case op_iadd:
2547           case op_isub:
2548           case op_imul:
2549           case op_idiv:
2550           case op_irem:
2551           case op_ishl:
2552           case op_ishr:
2553           case op_iushr:
2554           case op_iand:
2555           case op_ior:
2556           case op_ixor:
2557             pop_type (int_type);
2558             push_type (pop_type (int_type));
2559             break;
2560           case op_ladd:
2561           case op_lsub:
2562           case op_lmul:
2563           case op_ldiv:
2564           case op_lrem:
2565           case op_land:
2566           case op_lor:
2567           case op_lxor:
2568             pop_type (long_type);
2569             push_type (pop_type (long_type));
2570             break;
2571           case op_lshl:
2572           case op_lshr:
2573           case op_lushr:
2574             pop_type (int_type);
2575             push_type (pop_type (long_type));
2576             break;
2577           case op_fadd:
2578           case op_fsub:
2579           case op_fmul:
2580           case op_fdiv:
2581           case op_frem:
2582             pop_type (float_type);
2583             push_type (pop_type (float_type));
2584             break;
2585           case op_dadd:
2586           case op_dsub:
2587           case op_dmul:
2588           case op_ddiv:
2589           case op_drem:
2590             pop_type (double_type);
2591             push_type (pop_type (double_type));
2592             break;
2593           case op_ineg:
2594           case op_i2b:
2595           case op_i2c:
2596           case op_i2s:
2597             push_type (pop_type (int_type));
2598             break;
2599           case op_lneg:
2600             push_type (pop_type (long_type));
2601             break;
2602           case op_fneg:
2603             push_type (pop_type (float_type));
2604             break;
2605           case op_dneg:
2606             push_type (pop_type (double_type));
2607             break;
2608           case op_iinc:
2609             get_variable (get_byte (), int_type);
2610             get_byte ();
2611             break;
2612           case op_i2l:
2613             pop_type (int_type);
2614             push_type (long_type);
2615             break;
2616           case op_i2f:
2617             pop_type (int_type);
2618             push_type (float_type);
2619             break;
2620           case op_i2d:
2621             pop_type (int_type);
2622             push_type (double_type);
2623             break;
2624           case op_l2i:
2625             pop_type (long_type);
2626             push_type (int_type);
2627             break;
2628           case op_l2f:
2629             pop_type (long_type);
2630             push_type (float_type);
2631             break;
2632           case op_l2d:
2633             pop_type (long_type);
2634             push_type (double_type);
2635             break;
2636           case op_f2i:
2637             pop_type (float_type);
2638             push_type (int_type);
2639             break;
2640           case op_f2l:
2641             pop_type (float_type);
2642             push_type (long_type);
2643             break;
2644           case op_f2d:
2645             pop_type (float_type);
2646             push_type (double_type);
2647             break;
2648           case op_d2i:
2649             pop_type (double_type);
2650             push_type (int_type);
2651             break;
2652           case op_d2l:
2653             pop_type (double_type);
2654             push_type (long_type);
2655             break;
2656           case op_d2f:
2657             pop_type (double_type);
2658             push_type (float_type);
2659             break;
2660           case op_lcmp:
2661             pop_type (long_type);
2662             pop_type (long_type);
2663             push_type (int_type);
2664             break;
2665           case op_fcmpl:
2666           case op_fcmpg:
2667             pop_type (float_type);
2668             pop_type (float_type);
2669             push_type (int_type);
2670             break;
2671           case op_dcmpl:
2672           case op_dcmpg:
2673             pop_type (double_type);
2674             pop_type (double_type);
2675             push_type (int_type);
2676             break;
2677           case op_ifeq:
2678           case op_ifne:
2679           case op_iflt:
2680           case op_ifge:
2681           case op_ifgt:
2682           case op_ifle:
2683             pop_type (int_type);
2684             push_jump (get_short ());
2685             break;
2686           case op_if_icmpeq:
2687           case op_if_icmpne:
2688           case op_if_icmplt:
2689           case op_if_icmpge:
2690           case op_if_icmpgt:
2691           case op_if_icmple:
2692             pop_type (int_type);
2693             pop_type (int_type);
2694             push_jump (get_short ());
2695             break;
2696           case op_if_acmpeq:
2697           case op_if_acmpne:
2698             pop_type (reference_type);
2699             pop_type (reference_type);
2700             push_jump (get_short ());
2701             break;
2702           case op_goto:
2703             push_jump (get_short ());
2704             invalidate_pc ();
2705             break;
2706           case op_jsr:
2707             handle_jsr_insn (get_short ());
2708             break;
2709           case op_ret:
2710             handle_ret_insn (get_byte ());
2711             break;
2712           case op_tableswitch:
2713             {
2714               pop_type (int_type);
2715               skip_padding ();
2716               push_jump (get_int ());
2717               jint low = get_int ();
2718               jint high = get_int ();
2719               // Already checked LOW -vs- HIGH.
2720               for (int i = low; i <= high; ++i)
2721                 push_jump (get_int ());
2722               invalidate_pc ();
2723             }
2724             break;
2725
2726           case op_lookupswitch:
2727             {
2728               pop_type (int_type);
2729               skip_padding ();
2730               push_jump (get_int ());
2731               jint npairs = get_int ();
2732               // Already checked NPAIRS >= 0.
2733               jint lastkey = 0;
2734               for (int i = 0; i < npairs; ++i)
2735                 {
2736                   jint key = get_int ();
2737                   if (i > 0 && key <= lastkey)
2738                     verify_fail ("lookupswitch pairs unsorted", start_PC);
2739                   lastkey = key;
2740                   push_jump (get_int ());
2741                 }
2742               invalidate_pc ();
2743             }
2744             break;
2745           case op_ireturn:
2746             check_return_type (pop_type (int_type));
2747             invalidate_pc ();
2748             break;
2749           case op_lreturn:
2750             check_return_type (pop_type (long_type));
2751             invalidate_pc ();
2752             break;
2753           case op_freturn:
2754             check_return_type (pop_type (float_type));
2755             invalidate_pc ();
2756             break;
2757           case op_dreturn:
2758             check_return_type (pop_type (double_type));
2759             invalidate_pc ();
2760             break;
2761           case op_areturn:
2762             check_return_type (pop_type (reference_type));
2763             invalidate_pc ();
2764             break;
2765           case op_return:
2766             // We only need to check this when the return type is
2767             // void, because all instance initializers return void.
2768             if (this_is_init)
2769               current_state->check_this_initialized (this);
2770             check_return_type (void_type);
2771             invalidate_pc ();
2772             break;
2773           case op_getstatic:
2774             push_type (check_field_constant (get_ushort ()));
2775             break;
2776           case op_putstatic:
2777             pop_type (check_field_constant (get_ushort ()));
2778             break;
2779           case op_getfield:
2780             {
2781               type klass;
2782               type field = check_field_constant (get_ushort (), &klass);
2783               pop_type (klass);
2784               push_type (field);
2785             }
2786             break;
2787           case op_putfield:
2788             {
2789               type klass;
2790               type field = check_field_constant (get_ushort (), &klass);
2791               pop_type (field);
2792
2793               // We have an obscure special case here: we can use
2794               // `putfield' on a field declared in this class, even if
2795               // `this' has not yet been initialized.
2796               if (! current_state->this_type.isinitialized ()
2797                   && current_state->this_type.pc == type::SELF)
2798                 klass.set_uninitialized (type::SELF, this);
2799               pop_type (klass);
2800             }
2801             break;
2802
2803           case op_invokevirtual:
2804           case op_invokespecial:
2805           case op_invokestatic:
2806           case op_invokeinterface:
2807             {
2808               _Jv_Utf8Const *method_name, *method_signature;
2809               type class_type
2810                 = check_method_constant (get_ushort (),
2811                                          opcode == op_invokeinterface,
2812                                          &method_name,
2813                                          &method_signature);
2814               // NARGS is only used when we're processing
2815               // invokeinterface.  It is simplest for us to compute it
2816               // here and then verify it later.
2817               int nargs = 0;
2818               if (opcode == op_invokeinterface)
2819                 {
2820                   nargs = get_byte ();
2821                   if (get_byte () != 0)
2822                     verify_fail ("invokeinterface dummy byte is wrong");
2823                 }
2824
2825               bool is_init = false;
2826               if (_Jv_equalUtf8Consts (method_name, gcj::init_name))
2827                 {
2828                   is_init = true;
2829                   if (opcode != op_invokespecial)
2830                     verify_fail ("can't invoke <init>");
2831                 }
2832               else if (method_name->data[0] == '<')
2833                 verify_fail ("can't invoke method starting with `<'");
2834
2835               // Pop arguments and check types.
2836               int arg_count = _Jv_count_arguments (method_signature);
2837               type arg_types[arg_count];
2838               compute_argument_types (method_signature, arg_types);
2839               for (int i = arg_count - 1; i >= 0; --i)
2840                 {
2841                   // This is only used for verifying the byte for
2842                   // invokeinterface.
2843                   nargs -= arg_types[i].depth ();
2844                   pop_type (arg_types[i]);
2845                 }
2846
2847               if (opcode == op_invokeinterface
2848                   && nargs != 1)
2849                 verify_fail ("wrong argument count for invokeinterface");
2850
2851               if (opcode != op_invokestatic)
2852                 {
2853                   type t = class_type;
2854                   if (is_init)
2855                     {
2856                       // In this case the PC doesn't matter.
2857                       t.set_uninitialized (type::UNINIT, this);
2858                     }
2859                   type raw = pop_raw ();
2860                   bool ok = false;
2861                   if (t.compatible (raw, this))
2862                     {
2863                       ok = true;
2864                     }
2865                   else if (opcode == op_invokeinterface)
2866                     {
2867                       // This is a hack.  We might have merged two
2868                       // items and gotten `Object'.  This can happen
2869                       // because we don't keep track of where merges
2870                       // come from.  This is safe as long as the
2871                       // interpreter checks interfaces at runtime.
2872                       type obj (&java::lang::Object::class$);
2873                       ok = raw.compatible (obj, this);
2874                     }
2875
2876                   if (! ok)
2877                     verify_fail ("incompatible type on stack");
2878
2879                   if (is_init)
2880                     current_state->set_initialized (raw.get_pc (),
2881                                                     current_method->max_locals);
2882                 }
2883
2884               type rt = compute_return_type (method_signature);
2885               if (! rt.isvoid ())
2886                 push_type (rt);
2887             }
2888             break;
2889
2890           case op_new:
2891             {
2892               type t = check_class_constant (get_ushort ());
2893               if (t.isarray () || t.isinterface (this) || t.isabstract (this))
2894                 verify_fail ("type is array, interface, or abstract");
2895               t.set_uninitialized (start_PC, this);
2896               push_type (t);
2897             }
2898             break;
2899
2900           case op_newarray:
2901             {
2902               int atype = get_byte ();
2903               // We intentionally have chosen constants to make this
2904               // valid.
2905               if (atype < boolean_type || atype > long_type)
2906                 verify_fail ("type not primitive", start_PC);
2907               pop_type (int_type);
2908               push_type (construct_primitive_array_type (type_val (atype)));
2909             }
2910             break;
2911           case op_anewarray:
2912             pop_type (int_type);
2913             push_type (check_class_constant (get_ushort ()).to_array (this));
2914             break;
2915           case op_arraylength:
2916             {
2917               type t = pop_type (reference_type);
2918               if (! t.isarray () && ! t.isnull ())
2919                 verify_fail ("array type expected");
2920               push_type (int_type);
2921             }
2922             break;
2923           case op_athrow:
2924             pop_type (type (&java::lang::Throwable::class$));
2925             invalidate_pc ();
2926             break;
2927           case op_checkcast:
2928             pop_type (reference_type);
2929             push_type (check_class_constant (get_ushort ()));
2930             break;
2931           case op_instanceof:
2932             pop_type (reference_type);
2933             check_class_constant (get_ushort ());
2934             push_type (int_type);
2935             break;
2936           case op_monitorenter:
2937             pop_type (reference_type);
2938             break;
2939           case op_monitorexit:
2940             pop_type (reference_type);
2941             break;
2942           case op_wide:
2943             {
2944               switch (get_byte ())
2945                 {
2946                 case op_iload:
2947                   push_type (get_variable (get_ushort (), int_type));
2948                   break;
2949                 case op_lload:
2950                   push_type (get_variable (get_ushort (), long_type));
2951                   break;
2952                 case op_fload:
2953                   push_type (get_variable (get_ushort (), float_type));
2954                   break;
2955                 case op_dload:
2956                   push_type (get_variable (get_ushort (), double_type));
2957                   break;
2958                 case op_aload:
2959                   push_type (get_variable (get_ushort (), reference_type));
2960                   break;
2961                 case op_istore:
2962                   set_variable (get_ushort (), pop_type (int_type));
2963                   break;
2964                 case op_lstore:
2965                   set_variable (get_ushort (), pop_type (long_type));
2966                   break;
2967                 case op_fstore:
2968                   set_variable (get_ushort (), pop_type (float_type));
2969                   break;
2970                 case op_dstore:
2971                   set_variable (get_ushort (), pop_type (double_type));
2972                   break;
2973                 case op_astore:
2974                   set_variable (get_ushort (), pop_type (reference_type));
2975                   break;
2976                 case op_ret:
2977                   handle_ret_insn (get_short ());
2978                   break;
2979                 case op_iinc:
2980                   get_variable (get_ushort (), int_type);
2981                   get_short ();
2982                   break;
2983                 default:
2984                   verify_fail ("unrecognized wide instruction", start_PC);
2985                 }
2986             }
2987             break;
2988           case op_multianewarray:
2989             {
2990               type atype = check_class_constant (get_ushort ());
2991               int dim = get_byte ();
2992               if (dim < 1)
2993                 verify_fail ("too few dimensions to multianewarray", start_PC);
2994               atype.verify_dimensions (dim, this);
2995               for (int i = 0; i < dim; ++i)
2996                 pop_type (int_type);
2997               push_type (atype);
2998             }
2999             break;
3000           case op_ifnull:
3001           case op_ifnonnull:
3002             pop_type (reference_type);
3003             push_jump (get_short ());
3004             break;
3005           case op_goto_w:
3006             push_jump (get_int ());
3007             invalidate_pc ();
3008             break;
3009           case op_jsr_w:
3010             handle_jsr_insn (get_int ());
3011             break;
3012
3013           // These are unused here, but we call them out explicitly
3014           // so that -Wswitch-enum doesn't complain.
3015           case op_putfield_1:
3016           case op_putfield_2:
3017           case op_putfield_4:
3018           case op_putfield_8:
3019           case op_putfield_a:
3020           case op_putstatic_1:
3021           case op_putstatic_2:
3022           case op_putstatic_4:
3023           case op_putstatic_8:
3024           case op_putstatic_a:
3025           case op_getfield_1:
3026           case op_getfield_2s:
3027           case op_getfield_2u:
3028           case op_getfield_4:
3029           case op_getfield_8:
3030           case op_getfield_a:
3031           case op_getstatic_1:
3032           case op_getstatic_2s:
3033           case op_getstatic_2u:
3034           case op_getstatic_4:
3035           case op_getstatic_8:
3036           case op_getstatic_a:
3037           default:
3038             // Unrecognized opcode.
3039             verify_fail ("unrecognized instruction in verify_instructions_0",
3040                          start_PC);
3041           }
3042       }
3043   }
3044
3045   __attribute__ ((__noreturn__)) void verify_fail (char *s, jint pc = -1)
3046   {
3047     using namespace java::lang;
3048     StringBuffer *buf = new StringBuffer ();
3049
3050     buf->append (JvNewStringLatin1 ("verification failed"));
3051     if (pc == -1)
3052       pc = start_PC;
3053     if (pc != -1)
3054       {
3055         buf->append (JvNewStringLatin1 (" at PC "));
3056         buf->append (pc);
3057       }
3058
3059     _Jv_InterpMethod *method = current_method;
3060     buf->append (JvNewStringLatin1 (" in "));
3061     buf->append (current_class->getName());
3062     buf->append ((jchar) ':');
3063     buf->append (JvNewStringUTF (method->get_method()->name->data));
3064     buf->append ((jchar) '(');
3065     buf->append (JvNewStringUTF (method->get_method()->signature->data));
3066     buf->append ((jchar) ')');
3067
3068     buf->append (JvNewStringLatin1 (": "));
3069     buf->append (JvNewStringLatin1 (s));
3070     throw new java::lang::VerifyError (buf->toString ());
3071   }
3072
3073 public:
3074
3075   void verify_instructions ()
3076   {
3077     branch_prepass ();
3078     verify_instructions_0 ();
3079   }
3080
3081   _Jv_BytecodeVerifier (_Jv_InterpMethod *m)
3082   {
3083     // We just print the text as utf-8.  This is just for debugging
3084     // anyway.
3085     debug_print ("--------------------------------\n");
3086     debug_print ("-- Verifying method `%s'\n", m->self->name->data);
3087
3088     current_method = m;
3089     bytecode = m->bytecode ();
3090     exception = m->exceptions ();
3091     current_class = m->defining_class;
3092
3093     states = NULL;
3094     flags = NULL;
3095     jsr_ptrs = NULL;
3096     utf8_list = NULL;
3097     entry_points = NULL;
3098   }
3099
3100   ~_Jv_BytecodeVerifier ()
3101   {
3102     if (states)
3103       _Jv_Free (states);
3104     if (flags)
3105       _Jv_Free (flags);
3106
3107     if (jsr_ptrs)
3108       {
3109         for (int i = 0; i < current_method->code_length; ++i)
3110           {
3111             if (jsr_ptrs[i] != NULL)
3112               {
3113                 subr_info *info = jsr_ptrs[i];
3114                 while (info != NULL)
3115                   {
3116                     subr_info *next = info->next;
3117                     _Jv_Free (info);
3118                     info = next;
3119                   }
3120               }
3121           }
3122         _Jv_Free (jsr_ptrs);
3123       }
3124
3125     while (utf8_list != NULL)
3126       {
3127         linked_utf8 *n = utf8_list->next;
3128         _Jv_Free (utf8_list->val);
3129         _Jv_Free (utf8_list);
3130         utf8_list = n;
3131       }
3132
3133     while (entry_points != NULL)
3134       {
3135         subr_entry_info *next = entry_points->next;
3136         _Jv_Free (entry_points);
3137         entry_points = next;
3138       }
3139   }
3140 };
3141
3142 void
3143 _Jv_VerifyMethod (_Jv_InterpMethod *meth)
3144 {
3145   _Jv_BytecodeVerifier v (meth);
3146   v.verify_instructions ();
3147 }
3148 #endif  /* INTERPRETER */