OSDN Git Service

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