OSDN Git Service

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