OSDN Git Service

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