OSDN Git Service

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