1 // verify.cc - verify bytecode
3 /* Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
11 // Written by Tom Tromey <tromey@redhat.com>
13 // Define VERIFY_DEBUG to enable debugging output.
19 #include <java-insns.h>
20 #include <java-interp.h>
22 // On Solaris 10/x86, <signal.h> indirectly includes <ia32/sys/reg.h>, which
23 // defines PC since g++ predefines __EXTENSIONS__. Undef here to avoid clash
24 // with PC member of class _Jv_BytecodeVerifier below.
29 #include <java/lang/Class.h>
30 #include <java/lang/VerifyError.h>
31 #include <java/lang/Throwable.h>
32 #include <java/lang/reflect/Modifier.h>
33 #include <java/lang/StringBuffer.h>
37 #endif /* VERIFY_DEBUG */
40 // This is used to mark states which are not scheduled for
42 #define INVALID_STATE ((state *) -1)
44 static void debug_print (const char *fmt, ...)
45 __attribute__ ((format (printf, 1, 2)));
48 debug_print (MAYBE_UNUSED const char *fmt, ...)
53 vfprintf (stderr, fmt, ap);
55 #endif /* VERIFY_DEBUG */
58 // This started as a fairly ordinary verifier, and for the most part
59 // it remains so. It works in the obvious way, by modeling the effect
60 // of each opcode as it is encountered. For most opcodes, this is a
61 // straightforward operation.
63 // This verifier does not do type merging. It used to, but this
64 // results in difficulty verifying some relatively simple code
65 // involving interfaces, and it pushed some verification work into the
68 // Instead of merging reference types, when we reach a point where two
69 // flows of control merge, we simply keep the union of reference types
70 // from each branch. Then, when we need to verify a fact about a
71 // reference on the stack (e.g., that it is compatible with the
72 // argument type of a method), we check to ensure that all possible
73 // types satisfy the requirement.
75 // Another area this verifier differs from the norm is in its handling
76 // of subroutines. The JVM specification has some confusing things to
77 // say about subroutines. For instance, it makes claims about not
78 // allowing subroutines to merge and it rejects recursive subroutines.
79 // For the most part these are red herrings; we used to try to follow
80 // these things but they lead to problems. For example, the notion of
81 // "being in a subroutine" is not well-defined: is an exception
82 // handler in a subroutine? If you never execute the `ret' but
83 // instead `goto 1' do you remain in the subroutine?
85 // For clarity on what is really required for type safety, read
86 // "Simple Verification Technique for Complex Java Bytecode
87 // Subroutines" by Alessandro Coglio. Among other things this paper
88 // shows that recursive subroutines are not harmful to type safety.
89 // We implement something similar to what he proposes. Note that this
90 // means that this verifier will accept code that is rejected by some
93 // For those not wanting to read the paper, the basic observation is
94 // that we can maintain split states in subroutines. We maintain one
95 // state for each calling `jsr'. In other words, we re-verify a
96 // subroutine once for each caller, using the exact types held by the
97 // callers (as opposed to the old approach of merging types and
98 // keeping a bitmap registering what did or did not change). This
99 // approach lets us continue to verify correctly even when a
100 // subroutine is exited via `goto' or `athrow' and not `ret'.
102 // In some other areas the JVM specification is (mildly) incorrect,
103 // so we diverge. For instance, you cannot
104 // violate type safety by allocating an object with `new' and then
105 // failing to initialize it, no matter how one branches or where one
106 // stores the uninitialized reference. See "Improving the official
107 // specification of Java bytecode verification" by Alessandro Coglio.
109 // Note that there's no real point in enforcing that padding bytes or
110 // the mystery byte of invokeinterface must be 0, but we do that
113 // The verifier is currently neither completely lazy nor eager when it
114 // comes to loading classes. It tries to represent types by name when
115 // possible, and then loads them when it needs to verify a fact about
116 // the type. Checking types by name is valid because we only use
117 // names which come from the current class' constant pool. Since all
118 // such names are looked up using the same class loader, there is no
119 // danger that we might be fooled into comparing different types with
122 // In the future we plan to allow for a completely lazy mode of
123 // operation, where the verifier will construct a list of type
124 // assertions to be checked later.
126 // Some test cases for the verifier live in the "verify" module of the
127 // Mauve test suite. However, some of these are presently
128 // (2004-01-20) believed to be incorrect. (More precisely the notion
129 // of "correct" is not well-defined, and this verifier differs from
130 // others while remaining type-safe.) Some other tests live in the
131 // libgcj test suite.
132 class _Jv_BytecodeVerifier
136 static const int FLAG_INSN_START = 1;
137 static const int FLAG_BRANCH_TARGET = 2;
142 struct ref_intersection;
153 // The PC corresponding to the start of the current instruction.
156 // The current state of the stack, locals, etc.
157 state *current_state;
159 // At each branch target we keep a linked list of all the states we
160 // can process at that point. We'll only have multiple states at a
161 // given PC if they both have different return-address types in the
162 // same stack or local slot. This array is indexed by PC and holds
163 // the list of all such states.
164 linked<state> **states;
166 // We keep a linked list of all the states which we must reverify.
167 // This is the head of the list.
168 state *next_verify_state;
170 // We keep some flags for each instruction. The values are the
171 // FLAG_* constants defined above. This is an array indexed by PC.
174 // The bytecode itself.
175 unsigned char *bytecode;
177 _Jv_InterpException *exception;
180 jclass current_class;
182 _Jv_InterpMethod *current_method;
184 // A linked list of utf8 objects we allocate.
185 linked<_Jv_Utf8Const> *utf8_list;
187 // A linked list of all ref_intersection objects we allocate.
188 ref_intersection *isect_list;
190 // Create a new Utf-8 constant and return it. We do this to avoid
191 // having our Utf-8 constants prematurely collected.
192 _Jv_Utf8Const *make_utf8_const (char *s, int len)
194 linked<_Jv_Utf8Const> *lu = (linked<_Jv_Utf8Const> *)
195 _Jv_Malloc (sizeof (linked<_Jv_Utf8Const>)
196 + _Jv_Utf8Const::space_needed(s, len));
197 _Jv_Utf8Const *r = (_Jv_Utf8Const *) (lu + 1);
200 lu->next = utf8_list;
206 __attribute__ ((__noreturn__)) void verify_fail (char *s, jint pc = -1)
208 using namespace java::lang;
209 StringBuffer *buf = new StringBuffer ();
211 buf->append (JvNewStringLatin1 ("verification failed"));
216 buf->append (JvNewStringLatin1 (" at PC "));
220 _Jv_InterpMethod *method = current_method;
221 buf->append (JvNewStringLatin1 (" in "));
222 buf->append (current_class->getName());
223 buf->append ((jchar) ':');
224 buf->append (method->get_method()->name->toString());
225 buf->append ((jchar) '(');
226 buf->append (method->get_method()->signature->toString());
227 buf->append ((jchar) ')');
229 buf->append (JvNewStringLatin1 (": "));
230 buf->append (JvNewStringLatin1 (s));
231 throw new java::lang::VerifyError (buf->toString ());
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
241 // The values for primitive types are chosen to correspond to values
242 // specified to newarray.
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.
257 // This is the second word of a two-word value, i.e., a double or
261 // Everything after `reference_type' must be a reference type.
264 uninitialized_reference_type
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
273 struct ref_intersection
275 // Whether or not this type has been resolved.
281 // For a resolved reference type, this is a pointer to the class.
283 // For other reference types, this it the name of the class.
287 // Link to the next reference in the intersection.
288 ref_intersection *ref_next;
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;
295 ref_intersection (jclass klass, _Jv_BytecodeVerifier *verifier)
300 alloc_next = verifier->isect_list;
301 verifier->isect_list = this;
304 ref_intersection (_Jv_Utf8Const *name, _Jv_BytecodeVerifier *verifier)
309 alloc_next = verifier->isect_list;
310 verifier->isect_list = this;
313 ref_intersection (ref_intersection *dup, ref_intersection *tail,
314 _Jv_BytecodeVerifier *verifier)
317 is_resolved = dup->is_resolved;
319 alloc_next = verifier->isect_list;
320 verifier->isect_list = this;
323 bool equals (ref_intersection *other, _Jv_BytecodeVerifier *verifier)
325 if (! is_resolved && ! other->is_resolved
326 && _Jv_equalUtf8Consts (data.name, other->data.name))
330 if (! other->is_resolved)
331 other->resolve (verifier);
332 return data.klass == other->data.klass;
335 // Merge THIS type into OTHER, returning the result. This will
336 // return OTHER if all the classes in THIS already appear in
338 ref_intersection *merge (ref_intersection *other,
339 _Jv_BytecodeVerifier *verifier)
341 ref_intersection *tail = other;
342 for (ref_intersection *self = this; self != NULL; self = self->ref_next)
345 for (ref_intersection *iter = other; iter != NULL;
346 iter = iter->ref_next)
348 if (iter->equals (self, verifier))
356 tail = new ref_intersection (self, tail, verifier);
361 void resolve (_Jv_BytecodeVerifier *verifier)
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->first() == 'L' && data.name->limit()[-1] == ';')
371 data.klass = _Jv_FindClassFromSignature (data.name->chars(), loader);
373 data.klass = Class::forName (_Jv_NewStringUtf8Const (data.name),
378 // See if an object of type OTHER can be assigned to an object of
379 // type *THIS. This might resolve classes in one chain or the
381 bool compatible (ref_intersection *other,
382 _Jv_BytecodeVerifier *verifier)
384 ref_intersection *self = this;
386 for (; self != NULL; self = self->ref_next)
388 ref_intersection *other_iter = other;
390 for (; other_iter != NULL; other_iter = other_iter->ref_next)
392 // Avoid resolving if possible.
393 if (! self->is_resolved
394 && ! other_iter->is_resolved
395 && _Jv_equalUtf8Consts (self->data.name,
396 other_iter->data.name))
399 if (! self->is_resolved)
400 self->resolve(verifier);
401 if (! other_iter->is_resolved)
402 other_iter->resolve(verifier);
404 if (! is_assignable_from_slow (self->data.klass,
405 other_iter->data.klass))
415 // assert (ref_next == NULL);
417 return data.klass->isArray ();
419 return data.name->first() == '[';
422 bool isinterface (_Jv_BytecodeVerifier *verifier)
424 // assert (ref_next == NULL);
427 return data.klass->isInterface ();
430 bool isabstract (_Jv_BytecodeVerifier *verifier)
432 // assert (ref_next == NULL);
435 using namespace java::lang::reflect;
436 return Modifier::isAbstract (data.klass->getModifiers ());
439 jclass getclass (_Jv_BytecodeVerifier *verifier)
446 int count_dimensions ()
451 jclass k = data.klass;
452 while (k->isArray ())
454 k = k->getComponentType ();
460 char *p = data.name->chars();
467 void *operator new (size_t bytes)
469 return _Jv_Malloc (bytes);
472 void operator delete (void *mem)
478 // Return the type_val corresponding to a primitive signature
479 // character. For instance `I' returns `int.class'.
480 type_val get_type_val_for_signature (jchar sig)
513 verify_fail ("invalid signature");
518 // Return the type_val corresponding to a primitive class.
519 type_val get_type_val_for_signature (jclass k)
521 return get_type_val_for_signature ((jchar) k->method_count);
524 // This is like _Jv_IsAssignableFrom, but it works even if SOURCE or
525 // TARGET haven't been prepared.
526 static bool is_assignable_from_slow (jclass target, jclass source)
528 // First, strip arrays.
529 while (target->isArray ())
531 // If target is array, source must be as well.
532 if (! source->isArray ())
534 target = target->getComponentType ();
535 source = source->getComponentType ();
539 if (target == &java::lang::Object::class$)
544 if (source == target)
547 if (target->isPrimitive () || source->isPrimitive ())
550 if (target->isInterface ())
552 for (int i = 0; i < source->interface_count; ++i)
554 // We use a recursive call because we also need to
555 // check superinterfaces.
556 if (is_assignable_from_slow (target, source->getInterface (i)))
560 source = source->getSuperclass ();
562 while (source != NULL);
567 // The `type' class is used to represent a single type in the
574 // For reference types, the representation of the type.
575 ref_intersection *klass;
577 // This is used in two situations.
579 // First, when constructing a new object, it is the PC of the
580 // `new' instruction which created the object. We use the special
581 // value UNINIT to mean that this is uninitialized. The special
582 // value SELF is used for the case where the current method is
583 // itself the <init> method. the special value EITHER is used
584 // when we may optionally allow either an uninitialized or
585 // initialized reference to match.
587 // Second, when the key is return_address_type, this holds the PC
588 // of the instruction following the `jsr'.
591 static const int UNINIT = -2;
592 static const int SELF = -1;
593 static const int EITHER = -3;
595 // Basic constructor.
598 key = unsuitable_type;
603 // Make a new instance given the type tag. We assume a generic
604 // `reference_type' means Object.
608 // For reference_type, if KLASS==NULL then that means we are
609 // looking for a generic object of any kind, including an
610 // uninitialized reference.
615 // Make a new instance given a class.
616 type (jclass k, _Jv_BytecodeVerifier *verifier)
618 key = reference_type;
619 klass = new ref_intersection (k, verifier);
623 // Make a new instance given the name of a class.
624 type (_Jv_Utf8Const *n, _Jv_BytecodeVerifier *verifier)
626 key = reference_type;
627 klass = new ref_intersection (n, verifier);
639 // These operators are required because libgcj can't link in
641 void *operator new[] (size_t bytes)
643 return _Jv_Malloc (bytes);
646 void operator delete[] (void *mem)
651 type& operator= (type_val k)
659 type& operator= (const type& t)
667 // Promote a numeric type.
670 if (key == boolean_type || key == char_type
671 || key == byte_type || key == short_type)
676 // Mark this type as the uninitialized result of `new'.
677 void set_uninitialized (int npc, _Jv_BytecodeVerifier *verifier)
679 if (key == reference_type)
680 key = uninitialized_reference_type;
682 verifier->verify_fail ("internal error in type::uninitialized");
686 // Mark this type as now initialized.
687 void set_initialized (int npc)
689 if (npc != UNINIT && pc == npc && key == uninitialized_reference_type)
691 key = reference_type;
696 // Mark this type as a particular return address.
697 void set_return_address (int npc)
702 // Return true if this type and type OTHER are considered
703 // mergeable for the purposes of state merging. This is related
704 // to subroutine handling. For this purpose two types are
705 // considered unmergeable if they are both return-addresses but
706 // have different PCs.
707 bool state_mergeable_p (const type &other) const
709 return (key != return_address_type
710 || other.key != return_address_type
714 // Return true if an object of type K can be assigned to a variable
715 // of type *THIS. Handle various special cases too. Might modify
716 // *THIS or K. Note however that this does not perform numeric
718 bool compatible (type &k, _Jv_BytecodeVerifier *verifier)
720 // Any type is compatible with the unsuitable type.
721 if (key == unsuitable_type)
724 if (key < reference_type || k.key < reference_type)
727 // The `null' type is convertible to any initialized reference
729 if (key == null_type)
730 return k.key != uninitialized_reference_type;
731 if (k.key == null_type)
732 return key != uninitialized_reference_type;
734 // A special case for a generic reference.
738 verifier->verify_fail ("programmer error in type::compatible");
740 // Handle the special 'EITHER' case, which is only used in a
741 // special case of 'putfield'. Note that we only need to handle
742 // this on the LHS of a check.
743 if (! isinitialized () && pc == EITHER)
745 // If the RHS is uninitialized, it must be an uninitialized
747 if (! k.isinitialized () && k.pc != SELF)
750 else if (isinitialized () != k.isinitialized ())
752 // An initialized type and an uninitialized type are not
753 // otherwise compatible.
758 // Two uninitialized objects are compatible if either:
759 // * The PCs are identical, or
760 // * One PC is UNINIT.
761 if (! isinitialized ())
763 if (pc != k.pc && pc != UNINIT && k.pc != UNINIT)
768 return klass->compatible(k.klass, verifier);
771 bool equals (const type &other, _Jv_BytecodeVerifier *vfy)
773 // Only works for reference types.
774 if ((key != reference_type
775 && key != uninitialized_reference_type)
776 || (other.key != reference_type
777 && other.key != uninitialized_reference_type))
779 // Only for single-valued types.
780 if (klass->ref_next || other.klass->ref_next)
782 return klass->equals (other.klass, vfy);
787 return key == void_type;
792 return key == long_type || key == double_type;
795 // Return number of stack or local variable slots taken by this
799 return iswide () ? 2 : 1;
802 bool isarray () const
804 // We treat null_type as not an array. This is ok based on the
805 // current uses of this method.
806 if (key == reference_type)
807 return klass->isarray ();
813 return key == null_type;
816 bool isinterface (_Jv_BytecodeVerifier *verifier)
818 if (key != reference_type)
820 return klass->isinterface (verifier);
823 bool isabstract (_Jv_BytecodeVerifier *verifier)
825 if (key != reference_type)
827 return klass->isabstract (verifier);
830 // Return the element type of an array.
831 type element_type (_Jv_BytecodeVerifier *verifier)
833 if (key != reference_type)
834 verifier->verify_fail ("programmer error in type::element_type()", -1);
836 jclass k = klass->getclass (verifier)->getComponentType ();
837 if (k->isPrimitive ())
838 return type (verifier->get_type_val_for_signature (k));
839 return type (k, verifier);
842 // Return the array type corresponding to an initialized
843 // reference. We could expand this to work for other kinds of
844 // types, but currently we don't need to.
845 type to_array (_Jv_BytecodeVerifier *verifier)
847 if (key != reference_type)
848 verifier->verify_fail ("internal error in type::to_array()");
850 jclass k = klass->getclass (verifier);
851 return type (_Jv_GetArrayClass (k, k->getClassLoaderInternal()),
855 bool isreference () const
857 return key >= reference_type;
865 bool isinitialized () const
867 return key == reference_type || key == null_type;
870 bool isresolved () const
872 return (key == reference_type
874 || key == uninitialized_reference_type);
877 void verify_dimensions (int ndims, _Jv_BytecodeVerifier *verifier)
879 // The way this is written, we don't need to check isarray().
880 if (key != reference_type)
881 verifier->verify_fail ("internal error in verify_dimensions:"
882 " not a reference type");
884 if (klass->count_dimensions () < ndims)
885 verifier->verify_fail ("array type has fewer dimensions"
889 // Merge OLD_TYPE into this. On error throw exception. Return
890 // true if the merge caused a type change.
891 bool merge (type& old_type, bool local_semantics,
892 _Jv_BytecodeVerifier *verifier)
894 bool changed = false;
895 bool refo = old_type.isreference ();
896 bool refn = isreference ();
899 if (old_type.key == null_type)
901 else if (key == null_type)
906 else if (isinitialized () != old_type.isinitialized ())
907 verifier->verify_fail ("merging initialized and uninitialized types");
910 if (! isinitialized ())
914 else if (old_type.pc == UNINIT)
916 else if (pc != old_type.pc)
917 verifier->verify_fail ("merging different uninitialized types");
920 ref_intersection *merged = old_type.klass->merge (klass,
929 else if (refo || refn || key != old_type.key)
933 // If we already have an `unsuitable' type, then we
934 // don't need to change again.
935 if (key != unsuitable_type)
937 key = unsuitable_type;
942 verifier->verify_fail ("unmergeable type");
948 void print (void) const
953 case boolean_type: c = 'Z'; break;
954 case byte_type: c = 'B'; break;
955 case char_type: c = 'C'; break;
956 case short_type: c = 'S'; break;
957 case int_type: c = 'I'; break;
958 case long_type: c = 'J'; break;
959 case float_type: c = 'F'; break;
960 case double_type: c = 'D'; break;
961 case void_type: c = 'V'; break;
962 case unsuitable_type: c = '-'; break;
963 case return_address_type: c = 'r'; break;
964 case continuation_type: c = '+'; break;
965 case reference_type: c = 'L'; break;
966 case null_type: c = '@'; break;
967 case uninitialized_reference_type: c = 'U'; break;
969 debug_print ("%c", c);
971 #endif /* VERIFY_DEBUG */
974 // This class holds all the state information we need for a given
978 // The current top of the stack, in terms of slots.
980 // The current depth of the stack. This will be larger than
981 // STACKTOP when wide types are on the stack.
985 // The local variables.
987 // We keep track of the type of `this' specially. This is used to
988 // ensure that an instance initializer invokes another initializer
989 // on `this' before returning. We must keep track of this
990 // specially because otherwise we might be confused by code which
991 // assigns to locals[0] (overwriting `this') and then returns
992 // without really initializing.
995 // The PC for this state. This is only valid on states which are
996 // permanently attached to a given PC. For an object like
997 // `current_state', which is used transiently, this has no
1000 // We keep a linked list of all states requiring reverification.
1001 // If this is the special value INVALID_STATE then this state is
1002 // not on the list. NULL marks the end of the linked list.
1005 // NO_NEXT is the PC value meaning that a new state must be
1006 // acquired from the verification list.
1007 static const int NO_NEXT = -1;
1014 next = INVALID_STATE;
1017 state (int max_stack, int max_locals)
1022 stack = new type[max_stack];
1023 for (int i = 0; i < max_stack; ++i)
1024 stack[i] = unsuitable_type;
1025 locals = new type[max_locals];
1026 for (int i = 0; i < max_locals; ++i)
1027 locals[i] = unsuitable_type;
1029 next = INVALID_STATE;
1032 state (const state *orig, int max_stack, int max_locals)
1034 stack = new type[max_stack];
1035 locals = new type[max_locals];
1036 copy (orig, max_stack, max_locals);
1038 next = INVALID_STATE;
1049 void *operator new[] (size_t bytes)
1051 return _Jv_Malloc (bytes);
1054 void operator delete[] (void *mem)
1059 void *operator new (size_t bytes)
1061 return _Jv_Malloc (bytes);
1064 void operator delete (void *mem)
1069 void copy (const state *copy, int max_stack, int max_locals)
1071 stacktop = copy->stacktop;
1072 stackdepth = copy->stackdepth;
1073 for (int i = 0; i < max_stack; ++i)
1074 stack[i] = copy->stack[i];
1075 for (int i = 0; i < max_locals; ++i)
1076 locals[i] = copy->locals[i];
1078 this_type = copy->this_type;
1079 // Don't modify `next' or `pc'.
1082 // Modify this state to reflect entry to an exception handler.
1083 void set_exception (type t, int max_stack)
1088 for (int i = stacktop; i < max_stack; ++i)
1089 stack[i] = unsuitable_type;
1092 inline int get_pc () const
1097 void set_pc (int npc)
1102 // Merge STATE_OLD into this state. Destructively modifies this
1103 // state. Returns true if the new state was in fact changed.
1104 // Will throw an exception if the states are not mergeable.
1105 bool merge (state *state_old, int max_locals,
1106 _Jv_BytecodeVerifier *verifier)
1108 bool changed = false;
1110 // Special handling for `this'. If one or the other is
1111 // uninitialized, then the merge is uninitialized.
1112 if (this_type.isinitialized ())
1113 this_type = state_old->this_type;
1116 if (state_old->stacktop != stacktop) // FIXME stackdepth instead?
1117 verifier->verify_fail ("stack sizes differ");
1118 for (int i = 0; i < state_old->stacktop; ++i)
1120 if (stack[i].merge (state_old->stack[i], false, verifier))
1124 // Merge local variables.
1125 for (int i = 0; i < max_locals; ++i)
1127 if (locals[i].merge (state_old->locals[i], true, verifier))
1134 // Ensure that `this' has been initialized.
1135 void check_this_initialized (_Jv_BytecodeVerifier *verifier)
1137 if (this_type.isreference () && ! this_type.isinitialized ())
1138 verifier->verify_fail ("`this' is uninitialized");
1141 // Set type of `this'.
1142 void set_this_type (const type &k)
1147 // Mark each `new'd object we know of that was allocated at PC as
1149 void set_initialized (int pc, int max_locals)
1151 for (int i = 0; i < stacktop; ++i)
1152 stack[i].set_initialized (pc);
1153 for (int i = 0; i < max_locals; ++i)
1154 locals[i].set_initialized (pc);
1155 this_type.set_initialized (pc);
1158 // This tests to see whether two states can be considered "merge
1159 // compatible". If both states have a return-address in the same
1160 // slot, and the return addresses are different, then they are not
1161 // compatible and we must not try to merge them.
1162 bool state_mergeable_p (state *other, int max_locals,
1163 _Jv_BytecodeVerifier *verifier)
1165 // This is tricky: if the stack sizes differ, then not only are
1166 // these not mergeable, but in fact we should give an error, as
1167 // we've found two execution paths that reach a branch target
1168 // with different stack depths. FIXME stackdepth instead?
1169 if (stacktop != other->stacktop)
1170 verifier->verify_fail ("stack sizes differ");
1172 for (int i = 0; i < stacktop; ++i)
1173 if (! stack[i].state_mergeable_p (other->stack[i]))
1175 for (int i = 0; i < max_locals; ++i)
1176 if (! locals[i].state_mergeable_p (other->locals[i]))
1181 void reverify (_Jv_BytecodeVerifier *verifier)
1183 if (next == INVALID_STATE)
1185 next = verifier->next_verify_state;
1186 verifier->next_verify_state = this;
1191 void print (const char *leader, int pc,
1192 int max_stack, int max_locals) const
1194 debug_print ("%s [%4d]: [stack] ", leader, pc);
1196 for (i = 0; i < stacktop; ++i)
1198 for (; i < max_stack; ++i)
1200 debug_print (" [local] ");
1201 for (i = 0; i < max_locals; ++i)
1203 debug_print (" | %p\n", this);
1206 inline void print (const char *, int, int, int) const
1209 #endif /* VERIFY_DEBUG */
1214 if (current_state->stacktop <= 0)
1215 verify_fail ("stack empty");
1216 type r = current_state->stack[--current_state->stacktop];
1217 current_state->stackdepth -= r.depth ();
1218 if (current_state->stackdepth < 0)
1219 verify_fail ("stack empty", start_PC);
1225 type r = pop_raw ();
1227 verify_fail ("narrow pop of wide type");
1231 type pop_type (type match)
1234 type t = pop_raw ();
1235 if (! match.compatible (t, this))
1236 verify_fail ("incompatible type on stack");
1240 // Pop a reference which is guaranteed to be initialized. MATCH
1241 // doesn't have to be a reference type; in this case this acts like
1243 type pop_init_ref (type match)
1245 type t = pop_raw ();
1246 if (t.isreference () && ! t.isinitialized ())
1247 verify_fail ("initialized reference required");
1248 else if (! match.compatible (t, this))
1249 verify_fail ("incompatible type on stack");
1253 // Pop a reference type or a return address.
1254 type pop_ref_or_return ()
1256 type t = pop_raw ();
1257 if (! t.isreference () && t.key != return_address_type)
1258 verify_fail ("expected reference or return address on stack");
1262 void push_type (type t)
1264 // If T is a numeric type like short, promote it to int.
1267 int depth = t.depth ();
1268 if (current_state->stackdepth + depth > current_method->max_stack)
1269 verify_fail ("stack overflow");
1270 current_state->stack[current_state->stacktop++] = t;
1271 current_state->stackdepth += depth;
1274 void set_variable (int index, type t)
1276 // If T is a numeric type like short, promote it to int.
1279 int depth = t.depth ();
1280 if (index > current_method->max_locals - depth)
1281 verify_fail ("invalid local variable");
1282 current_state->locals[index] = t;
1285 current_state->locals[index + 1] = continuation_type;
1286 if (index > 0 && current_state->locals[index - 1].iswide ())
1287 current_state->locals[index - 1] = unsuitable_type;
1290 type get_variable (int index, type t)
1292 int depth = t.depth ();
1293 if (index > current_method->max_locals - depth)
1294 verify_fail ("invalid local variable");
1295 if (! t.compatible (current_state->locals[index], this))
1296 verify_fail ("incompatible type in local variable");
1299 type t (continuation_type);
1300 if (! current_state->locals[index + 1].compatible (t, this))
1301 verify_fail ("invalid local variable");
1303 return current_state->locals[index];
1306 // Make sure ARRAY is an array type and that its elements are
1307 // compatible with type ELEMENT. Returns the actual element type.
1308 type require_array_type (type array, type element)
1310 // An odd case. Here we just pretend that everything went ok. If
1311 // the requested element type is some kind of reference, return
1312 // the null type instead.
1313 if (array.isnull ())
1314 return element.isreference () ? type (null_type) : element;
1316 if (! array.isarray ())
1317 verify_fail ("array required");
1319 type t = array.element_type (this);
1320 if (! element.compatible (t, this))
1322 // Special case for byte arrays, which must also be boolean
1325 if (element.key == byte_type)
1327 type e2 (boolean_type);
1328 ok = e2.compatible (t, this);
1331 verify_fail ("incompatible array element type");
1334 // Return T and not ELEMENT, because T might be specialized.
1340 if (PC >= current_method->code_length)
1341 verify_fail ("premature end of bytecode");
1342 return (jint) bytecode[PC++] & 0xff;
1347 jint b1 = get_byte ();
1348 jint b2 = get_byte ();
1349 return (jint) ((b1 << 8) | b2) & 0xffff;
1354 jint b1 = get_byte ();
1355 jint b2 = get_byte ();
1356 jshort s = (b1 << 8) | b2;
1362 jint b1 = get_byte ();
1363 jint b2 = get_byte ();
1364 jint b3 = get_byte ();
1365 jint b4 = get_byte ();
1366 return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
1369 int compute_jump (int offset)
1371 int npc = start_PC + offset;
1372 if (npc < 0 || npc >= current_method->code_length)
1373 verify_fail ("branch out of range", start_PC);
1377 // Add a new state to the state list at NPC.
1378 state *add_new_state (int npc, state *old_state)
1380 state *new_state = new state (old_state, current_method->max_stack,
1381 current_method->max_locals);
1382 debug_print ("== New state in add_new_state\n");
1383 new_state->print ("New", npc, current_method->max_stack,
1384 current_method->max_locals);
1385 linked<state> *nlink
1386 = (linked<state> *) _Jv_Malloc (sizeof (linked<state>));
1387 nlink->val = new_state;
1388 nlink->next = states[npc];
1389 states[npc] = nlink;
1390 new_state->set_pc (npc);
1394 // Merge the indicated state into the state at the branch target and
1395 // schedule a new PC if there is a change. NPC is the PC of the
1396 // branch target, and FROM_STATE is the state at the source of the
1397 // branch. This method returns true if the destination state
1398 // changed and requires reverification, false otherwise.
1399 void merge_into (int npc, state *from_state)
1401 // Iterate over all target states and merge our state into each,
1402 // if applicable. FIXME one improvement we could make here is
1403 // "state destruction". Merging a new state into an existing one
1404 // might cause a return_address_type to be merged to
1405 // unsuitable_type. In this case the resulting state may now be
1406 // mergeable with other states currently held in parallel at this
1407 // location. So in this situation we could pairwise compare and
1408 // reduce the number of parallel states.
1409 bool applicable = false;
1410 for (linked<state> *iter = states[npc]; iter != NULL; iter = iter->next)
1412 state *new_state = iter->val;
1413 if (new_state->state_mergeable_p (from_state,
1414 current_method->max_locals, this))
1418 debug_print ("== Merge states in merge_into\n");
1419 from_state->print ("Frm", start_PC, current_method->max_stack,
1420 current_method->max_locals);
1421 new_state->print (" To", npc, current_method->max_stack,
1422 current_method->max_locals);
1423 bool changed = new_state->merge (from_state,
1424 current_method->max_locals,
1426 new_state->print ("New", npc, current_method->max_stack,
1427 current_method->max_locals);
1430 new_state->reverify (this);
1436 // Either we don't yet have a state at NPC, or we have a
1437 // return-address type that is in conflict with all existing
1438 // state. So, we need to create a new entry.
1439 state *new_state = add_new_state (npc, from_state);
1440 // A new state added in this way must always be reverified.
1441 new_state->reverify (this);
1445 void push_jump (int offset)
1447 int npc = compute_jump (offset);
1448 // According to the JVM Spec, we need to check for uninitialized
1449 // objects here. However, this does not actually affect type
1450 // safety, and the Eclipse java compiler generates code that
1451 // violates this constraint.
1452 merge_into (npc, current_state);
1455 void push_exception_jump (type t, int pc)
1457 // According to the JVM Spec, we need to check for uninitialized
1458 // objects here. However, this does not actually affect type
1459 // safety, and the Eclipse java compiler generates code that
1460 // violates this constraint.
1461 state s (current_state, current_method->max_stack,
1462 current_method->max_locals);
1463 if (current_method->max_stack < 1)
1464 verify_fail ("stack overflow at exception handler");
1465 s.set_exception (t, current_method->max_stack);
1466 merge_into (pc, &s);
1471 state *new_state = next_verify_state;
1472 if (new_state == INVALID_STATE)
1473 verify_fail ("programmer error in pop_jump");
1474 if (new_state != NULL)
1476 next_verify_state = new_state->next;
1477 new_state->next = INVALID_STATE;
1482 void invalidate_pc ()
1484 PC = state::NO_NEXT;
1487 void note_branch_target (int pc)
1489 // Don't check `pc <= PC', because we've advanced PC after
1490 // fetching the target and we haven't yet checked the next
1492 if (pc < PC && ! (flags[pc] & FLAG_INSN_START))
1493 verify_fail ("branch not to instruction start", start_PC);
1494 flags[pc] |= FLAG_BRANCH_TARGET;
1497 void skip_padding ()
1499 while ((PC % 4) > 0)
1500 if (get_byte () != 0)
1501 verify_fail ("found nonzero padding byte");
1504 // Do the work for a `ret' instruction. INDEX is the index into the
1506 void handle_ret_insn (int index)
1508 type ret_addr = get_variable (index, return_address_type);
1509 // It would be nice if we could do this. However, the JVM Spec
1510 // doesn't say that this is what happens. It is implied that
1511 // reusing a return address is invalid, but there's no actual
1512 // prohibition against it.
1513 // set_variable (index, unsuitable_type);
1515 int npc = ret_addr.get_pc ();
1516 // We might be returning to a `jsr' that is at the end of the
1517 // bytecode. This is ok if we never return from the called
1518 // subroutine, but if we see this here it is an error.
1519 if (npc >= current_method->code_length)
1520 verify_fail ("fell off end");
1522 // According to the JVM Spec, we need to check for uninitialized
1523 // objects here. However, this does not actually affect type
1524 // safety, and the Eclipse java compiler generates code that
1525 // violates this constraint.
1526 merge_into (npc, current_state);
1530 void handle_jsr_insn (int offset)
1532 int npc = compute_jump (offset);
1534 // According to the JVM Spec, we need to check for uninitialized
1535 // objects here. However, this does not actually affect type
1536 // safety, and the Eclipse java compiler generates code that
1537 // violates this constraint.
1539 // Modify our state as appropriate for entry into a subroutine.
1540 type ret_addr (return_address_type);
1541 ret_addr.set_return_address (PC);
1542 push_type (ret_addr);
1543 merge_into (npc, current_state);
1547 jclass construct_primitive_array_type (type_val prim)
1553 k = JvPrimClass (boolean);
1556 k = JvPrimClass (char);
1559 k = JvPrimClass (float);
1562 k = JvPrimClass (double);
1565 k = JvPrimClass (byte);
1568 k = JvPrimClass (short);
1571 k = JvPrimClass (int);
1574 k = JvPrimClass (long);
1577 // These aren't used here but we call them out to avoid
1580 case unsuitable_type:
1581 case return_address_type:
1582 case continuation_type:
1583 case reference_type:
1585 case uninitialized_reference_type:
1587 verify_fail ("unknown type in construct_primitive_array_type");
1589 k = _Jv_GetArrayClass (k, NULL);
1593 // This pass computes the location of branch targets and also
1594 // instruction starts.
1595 void branch_prepass ()
1597 flags = (char *) _Jv_Malloc (current_method->code_length);
1599 for (int i = 0; i < current_method->code_length; ++i)
1603 while (PC < current_method->code_length)
1605 // Set `start_PC' early so that error checking can have the
1608 flags[PC] |= FLAG_INSN_START;
1610 java_opcode opcode = (java_opcode) bytecode[PC++];
1614 case op_aconst_null:
1750 case op_monitorenter:
1751 case op_monitorexit:
1759 case op_arraylength:
1791 case op_invokespecial:
1792 case op_invokestatic:
1793 case op_invokevirtual:
1797 case op_multianewarray:
1820 note_branch_target (compute_jump (get_short ()));
1823 case op_tableswitch:
1826 note_branch_target (compute_jump (get_int ()));
1827 jint low = get_int ();
1828 jint hi = get_int ();
1830 verify_fail ("invalid tableswitch", start_PC);
1831 for (int i = low; i <= hi; ++i)
1832 note_branch_target (compute_jump (get_int ()));
1836 case op_lookupswitch:
1839 note_branch_target (compute_jump (get_int ()));
1840 int npairs = get_int ();
1842 verify_fail ("too few pairs in lookupswitch", start_PC);
1843 while (npairs-- > 0)
1846 note_branch_target (compute_jump (get_int ()));
1851 case op_invokeinterface:
1859 opcode = (java_opcode) get_byte ();
1861 if (opcode == op_iinc)
1868 note_branch_target (compute_jump (get_int ()));
1871 // These are unused here, but we call them out explicitly
1872 // so that -Wswitch-enum doesn't complain.
1878 case op_putstatic_1:
1879 case op_putstatic_2:
1880 case op_putstatic_4:
1881 case op_putstatic_8:
1882 case op_putstatic_a:
1884 case op_getfield_2s:
1885 case op_getfield_2u:
1889 case op_getstatic_1:
1890 case op_getstatic_2s:
1891 case op_getstatic_2u:
1892 case op_getstatic_4:
1893 case op_getstatic_8:
1894 case op_getstatic_a:
1896 verify_fail ("unrecognized instruction in branch_prepass",
1900 // See if any previous branch tried to branch to the middle of
1901 // this instruction.
1902 for (int pc = start_PC + 1; pc < PC; ++pc)
1904 if ((flags[pc] & FLAG_BRANCH_TARGET))
1905 verify_fail ("branch to middle of instruction", pc);
1909 // Verify exception handlers.
1910 for (int i = 0; i < current_method->exc_count; ++i)
1912 if (! (flags[exception[i].handler_pc.i] & FLAG_INSN_START))
1913 verify_fail ("exception handler not at instruction start",
1914 exception[i].handler_pc.i);
1915 if (! (flags[exception[i].start_pc.i] & FLAG_INSN_START))
1916 verify_fail ("exception start not at instruction start",
1917 exception[i].start_pc.i);
1918 if (exception[i].end_pc.i != current_method->code_length
1919 && ! (flags[exception[i].end_pc.i] & FLAG_INSN_START))
1920 verify_fail ("exception end not at instruction start",
1921 exception[i].end_pc.i);
1923 flags[exception[i].handler_pc.i] |= FLAG_BRANCH_TARGET;
1927 void check_pool_index (int index)
1929 if (index < 0 || index >= current_class->constants.size)
1930 verify_fail ("constant pool index out of range", start_PC);
1933 type check_class_constant (int index)
1935 check_pool_index (index);
1936 _Jv_Constants *pool = ¤t_class->constants;
1937 if (pool->tags[index] == JV_CONSTANT_ResolvedClass)
1938 return type (pool->data[index].clazz, this);
1939 else if (pool->tags[index] == JV_CONSTANT_Class)
1940 return type (pool->data[index].utf8, this);
1941 verify_fail ("expected class constant", start_PC);
1944 type check_constant (int index)
1946 check_pool_index (index);
1947 _Jv_Constants *pool = ¤t_class->constants;
1948 if (pool->tags[index] == JV_CONSTANT_ResolvedString
1949 || pool->tags[index] == JV_CONSTANT_String)
1950 return type (&java::lang::String::class$, this);
1951 else if (pool->tags[index] == JV_CONSTANT_Integer)
1952 return type (int_type);
1953 else if (pool->tags[index] == JV_CONSTANT_Float)
1954 return type (float_type);
1955 verify_fail ("String, int, or float constant expected", start_PC);
1958 type check_wide_constant (int index)
1960 check_pool_index (index);
1961 _Jv_Constants *pool = ¤t_class->constants;
1962 if (pool->tags[index] == JV_CONSTANT_Long)
1963 return type (long_type);
1964 else if (pool->tags[index] == JV_CONSTANT_Double)
1965 return type (double_type);
1966 verify_fail ("long or double constant expected", start_PC);
1969 // Helper for both field and method. These are laid out the same in
1970 // the constant pool.
1971 type handle_field_or_method (int index, int expected,
1972 _Jv_Utf8Const **name,
1973 _Jv_Utf8Const **fmtype)
1975 check_pool_index (index);
1976 _Jv_Constants *pool = ¤t_class->constants;
1977 if (pool->tags[index] != expected)
1978 verify_fail ("didn't see expected constant", start_PC);
1979 // Once we know we have a Fieldref or Methodref we assume that it
1980 // is correctly laid out in the constant pool. I think the code
1981 // in defineclass.cc guarantees this.
1982 _Jv_ushort class_index, name_and_type_index;
1983 _Jv_loadIndexes (&pool->data[index],
1985 name_and_type_index);
1986 _Jv_ushort name_index, desc_index;
1987 _Jv_loadIndexes (&pool->data[name_and_type_index],
1988 name_index, desc_index);
1990 *name = pool->data[name_index].utf8;
1991 *fmtype = pool->data[desc_index].utf8;
1993 return check_class_constant (class_index);
1996 // Return field's type, compute class' type if requested.
1997 // If PUTFIELD is true, use the special 'putfield' semantics.
1998 type check_field_constant (int index, type *class_type = NULL,
1999 bool putfield = false)
2001 _Jv_Utf8Const *name, *field_type;
2002 type ct = handle_field_or_method (index,
2003 JV_CONSTANT_Fieldref,
2004 &name, &field_type);
2008 if (field_type->first() == '[' || field_type->first() == 'L')
2009 result = type (field_type, this);
2011 result = get_type_val_for_signature (field_type->first());
2013 // We have an obscure special case here: we can use `putfield' on
2014 // a field declared in this class, even if `this' has not yet been
2017 && ! current_state->this_type.isinitialized ()
2018 && current_state->this_type.pc == type::SELF
2019 && current_state->this_type.equals (ct, this)
2020 // We don't look at the signature, figuring that if it is
2021 // wrong we will fail during linking. FIXME?
2022 && _Jv_Linker::has_field_p (current_class, name))
2023 // Note that we don't actually know whether we're going to match
2024 // against 'this' or some other object of the same type. So,
2025 // here we set things up so that it doesn't matter. This relies
2026 // on knowing what our caller is up to.
2027 class_type->set_uninitialized (type::EITHER, this);
2032 type check_method_constant (int index, bool is_interface,
2033 _Jv_Utf8Const **method_name,
2034 _Jv_Utf8Const **method_signature)
2036 return handle_field_or_method (index,
2038 ? JV_CONSTANT_InterfaceMethodref
2039 : JV_CONSTANT_Methodref),
2040 method_name, method_signature);
2043 type get_one_type (char *&p)
2061 _Jv_Utf8Const *name = make_utf8_const (start, p - start);
2062 return type (name, this);
2065 // Casting to jchar here is ok since we are looking at an ASCII
2067 type_val rt = get_type_val_for_signature (jchar (v));
2069 if (arraycount == 0)
2071 // Callers of this function eventually push their arguments on
2072 // the stack. So, promote them here.
2073 return type (rt).promote ();
2076 jclass k = construct_primitive_array_type (rt);
2077 while (--arraycount > 0)
2078 k = _Jv_GetArrayClass (k, NULL);
2079 return type (k, this);
2082 void compute_argument_types (_Jv_Utf8Const *signature,
2085 char *p = signature->chars();
2092 types[i++] = get_one_type (p);
2095 type compute_return_type (_Jv_Utf8Const *signature)
2097 char *p = signature->chars();
2101 return get_one_type (p);
2104 void check_return_type (type onstack)
2106 type rt = compute_return_type (current_method->self->signature);
2107 if (! rt.compatible (onstack, this))
2108 verify_fail ("incompatible return type");
2111 // Initialize the stack for the new method. Returns true if this
2112 // method is an instance initializer.
2113 bool initialize_stack ()
2116 bool is_init = _Jv_equalUtf8Consts (current_method->self->name,
2118 bool is_clinit = _Jv_equalUtf8Consts (current_method->self->name,
2121 using namespace java::lang::reflect;
2122 if (! Modifier::isStatic (current_method->self->accflags))
2124 type kurr (current_class, this);
2127 kurr.set_uninitialized (type::SELF, this);
2131 verify_fail ("<clinit> method must be static");
2132 set_variable (0, kurr);
2133 current_state->set_this_type (kurr);
2139 verify_fail ("<init> method must be non-static");
2142 // We have to handle wide arguments specially here.
2143 int arg_count = _Jv_count_arguments (current_method->self->signature);
2144 type arg_types[arg_count];
2145 compute_argument_types (current_method->self->signature, arg_types);
2146 for (int i = 0; i < arg_count; ++i)
2148 set_variable (var, arg_types[i]);
2150 if (arg_types[i].iswide ())
2157 void verify_instructions_0 ()
2159 current_state = new state (current_method->max_stack,
2160 current_method->max_locals);
2165 // True if we are verifying an instance initializer.
2166 bool this_is_init = initialize_stack ();
2168 states = (linked<state> **) _Jv_Malloc (sizeof (linked<state> *)
2169 * current_method->code_length);
2170 for (int i = 0; i < current_method->code_length; ++i)
2173 next_verify_state = NULL;
2177 // If the PC was invalidated, get a new one from the work list.
2178 if (PC == state::NO_NEXT)
2180 state *new_state = pop_jump ();
2181 // If it is null, we're done.
2182 if (new_state == NULL)
2185 PC = new_state->get_pc ();
2186 debug_print ("== State pop from pending list\n");
2187 // Set up the current state.
2188 current_state->copy (new_state, current_method->max_stack,
2189 current_method->max_locals);
2193 // We only have to do this checking in the situation where
2194 // control flow falls through from the previous
2195 // instruction. Otherwise merging is done at the time we
2197 if (states[PC] != NULL)
2199 // We've already visited this instruction. So merge
2200 // the states together. It is simplest, but not most
2201 // efficient, to just always invalidate the PC here.
2202 merge_into (PC, current_state);
2208 // Control can't fall off the end of the bytecode. We need to
2209 // check this in both cases, not just the fall-through case,
2210 // because we don't check to see whether a `jsr' appears at
2211 // the end of the bytecode until we process a `ret'.
2212 if (PC >= current_method->code_length)
2213 verify_fail ("fell off end");
2215 // We only have to keep saved state at branch targets. If
2216 // we're at a branch target and the state here hasn't been set
2217 // yet, we set it now. You might notice that `ret' targets
2218 // won't necessarily have FLAG_BRANCH_TARGET set. This
2219 // doesn't matter, since those states will be filled in by
2221 if (states[PC] == NULL && (flags[PC] & FLAG_BRANCH_TARGET))
2222 add_new_state (PC, current_state);
2224 // Set this before handling exceptions so that debug output is
2228 // Update states for all active exception handlers. Ordinarily
2229 // there are not many exception handlers. So we simply run
2230 // through them all.
2231 for (int i = 0; i < current_method->exc_count; ++i)
2233 if (PC >= exception[i].start_pc.i && PC < exception[i].end_pc.i)
2235 type handler (&java::lang::Throwable::class$, this);
2236 if (exception[i].handler_type.i != 0)
2237 handler = check_class_constant (exception[i].handler_type.i);
2238 push_exception_jump (handler, exception[i].handler_pc.i);
2242 current_state->print (" ", PC, current_method->max_stack,
2243 current_method->max_locals);
2244 java_opcode opcode = (java_opcode) bytecode[PC++];
2250 case op_aconst_null:
2251 push_type (null_type);
2261 push_type (int_type);
2266 push_type (long_type);
2272 push_type (float_type);
2277 push_type (double_type);
2282 push_type (int_type);
2287 push_type (int_type);
2291 push_type (check_constant (get_byte ()));
2294 push_type (check_constant (get_ushort ()));
2297 push_type (check_wide_constant (get_ushort ()));
2301 push_type (get_variable (get_byte (), int_type));
2304 push_type (get_variable (get_byte (), long_type));
2307 push_type (get_variable (get_byte (), float_type));
2310 push_type (get_variable (get_byte (), double_type));
2313 push_type (get_variable (get_byte (), reference_type));
2320 push_type (get_variable (opcode - op_iload_0, int_type));
2326 push_type (get_variable (opcode - op_lload_0, long_type));
2332 push_type (get_variable (opcode - op_fload_0, float_type));
2338 push_type (get_variable (opcode - op_dload_0, double_type));
2344 push_type (get_variable (opcode - op_aload_0, reference_type));
2347 pop_type (int_type);
2348 push_type (require_array_type (pop_init_ref (reference_type),
2352 pop_type (int_type);
2353 push_type (require_array_type (pop_init_ref (reference_type),
2357 pop_type (int_type);
2358 push_type (require_array_type (pop_init_ref (reference_type),
2362 pop_type (int_type);
2363 push_type (require_array_type (pop_init_ref (reference_type),
2367 pop_type (int_type);
2368 push_type (require_array_type (pop_init_ref (reference_type),
2372 pop_type (int_type);
2373 require_array_type (pop_init_ref (reference_type), byte_type);
2374 push_type (int_type);
2377 pop_type (int_type);
2378 require_array_type (pop_init_ref (reference_type), char_type);
2379 push_type (int_type);
2382 pop_type (int_type);
2383 require_array_type (pop_init_ref (reference_type), short_type);
2384 push_type (int_type);
2387 set_variable (get_byte (), pop_type (int_type));
2390 set_variable (get_byte (), pop_type (long_type));
2393 set_variable (get_byte (), pop_type (float_type));
2396 set_variable (get_byte (), pop_type (double_type));
2399 set_variable (get_byte (), pop_ref_or_return ());
2405 set_variable (opcode - op_istore_0, pop_type (int_type));
2411 set_variable (opcode - op_lstore_0, pop_type (long_type));
2417 set_variable (opcode - op_fstore_0, pop_type (float_type));
2423 set_variable (opcode - op_dstore_0, pop_type (double_type));
2429 set_variable (opcode - op_astore_0, pop_ref_or_return ());
2432 pop_type (int_type);
2433 pop_type (int_type);
2434 require_array_type (pop_init_ref (reference_type), int_type);
2437 pop_type (long_type);
2438 pop_type (int_type);
2439 require_array_type (pop_init_ref (reference_type), long_type);
2442 pop_type (float_type);
2443 pop_type (int_type);
2444 require_array_type (pop_init_ref (reference_type), float_type);
2447 pop_type (double_type);
2448 pop_type (int_type);
2449 require_array_type (pop_init_ref (reference_type), double_type);
2452 pop_type (reference_type);
2453 pop_type (int_type);
2454 require_array_type (pop_init_ref (reference_type), reference_type);
2457 pop_type (int_type);
2458 pop_type (int_type);
2459 require_array_type (pop_init_ref (reference_type), byte_type);
2462 pop_type (int_type);
2463 pop_type (int_type);
2464 require_array_type (pop_init_ref (reference_type), char_type);
2467 pop_type (int_type);
2468 pop_type (int_type);
2469 require_array_type (pop_init_ref (reference_type), short_type);
2476 type t = pop_raw ();
2500 type t2 = pop_raw ();
2515 type t = pop_raw ();
2530 type t1 = pop_raw ();
2547 type t1 = pop_raw ();
2550 type t2 = pop_raw ();
2568 type t3 = pop_raw ();
2606 pop_type (int_type);
2607 push_type (pop_type (int_type));
2617 pop_type (long_type);
2618 push_type (pop_type (long_type));
2623 pop_type (int_type);
2624 push_type (pop_type (long_type));
2631 pop_type (float_type);
2632 push_type (pop_type (float_type));
2639 pop_type (double_type);
2640 push_type (pop_type (double_type));
2646 push_type (pop_type (int_type));
2649 push_type (pop_type (long_type));
2652 push_type (pop_type (float_type));
2655 push_type (pop_type (double_type));
2658 get_variable (get_byte (), int_type);
2662 pop_type (int_type);
2663 push_type (long_type);
2666 pop_type (int_type);
2667 push_type (float_type);
2670 pop_type (int_type);
2671 push_type (double_type);
2674 pop_type (long_type);
2675 push_type (int_type);
2678 pop_type (long_type);
2679 push_type (float_type);
2682 pop_type (long_type);
2683 push_type (double_type);
2686 pop_type (float_type);
2687 push_type (int_type);
2690 pop_type (float_type);
2691 push_type (long_type);
2694 pop_type (float_type);
2695 push_type (double_type);
2698 pop_type (double_type);
2699 push_type (int_type);
2702 pop_type (double_type);
2703 push_type (long_type);
2706 pop_type (double_type);
2707 push_type (float_type);
2710 pop_type (long_type);
2711 pop_type (long_type);
2712 push_type (int_type);
2716 pop_type (float_type);
2717 pop_type (float_type);
2718 push_type (int_type);
2722 pop_type (double_type);
2723 pop_type (double_type);
2724 push_type (int_type);
2732 pop_type (int_type);
2733 push_jump (get_short ());
2741 pop_type (int_type);
2742 pop_type (int_type);
2743 push_jump (get_short ());
2747 pop_type (reference_type);
2748 pop_type (reference_type);
2749 push_jump (get_short ());
2752 push_jump (get_short ());
2756 handle_jsr_insn (get_short ());
2759 handle_ret_insn (get_byte ());
2761 case op_tableswitch:
2763 pop_type (int_type);
2765 push_jump (get_int ());
2766 jint low = get_int ();
2767 jint high = get_int ();
2768 // Already checked LOW -vs- HIGH.
2769 for (int i = low; i <= high; ++i)
2770 push_jump (get_int ());
2775 case op_lookupswitch:
2777 pop_type (int_type);
2779 push_jump (get_int ());
2780 jint npairs = get_int ();
2781 // Already checked NPAIRS >= 0.
2783 for (int i = 0; i < npairs; ++i)
2785 jint key = get_int ();
2786 if (i > 0 && key <= lastkey)
2787 verify_fail ("lookupswitch pairs unsorted", start_PC);
2789 push_jump (get_int ());
2795 check_return_type (pop_type (int_type));
2799 check_return_type (pop_type (long_type));
2803 check_return_type (pop_type (float_type));
2807 check_return_type (pop_type (double_type));
2811 check_return_type (pop_init_ref (reference_type));
2815 // We only need to check this when the return type is
2816 // void, because all instance initializers return void.
2818 current_state->check_this_initialized (this);
2819 check_return_type (void_type);
2823 push_type (check_field_constant (get_ushort ()));
2826 pop_type (check_field_constant (get_ushort ()));
2831 type field = check_field_constant (get_ushort (), &klass);
2839 type field = check_field_constant (get_ushort (), &klass, true);
2845 case op_invokevirtual:
2846 case op_invokespecial:
2847 case op_invokestatic:
2848 case op_invokeinterface:
2850 _Jv_Utf8Const *method_name, *method_signature;
2852 = check_method_constant (get_ushort (),
2853 opcode == op_invokeinterface,
2856 // NARGS is only used when we're processing
2857 // invokeinterface. It is simplest for us to compute it
2858 // here and then verify it later.
2860 if (opcode == op_invokeinterface)
2862 nargs = get_byte ();
2863 if (get_byte () != 0)
2864 verify_fail ("invokeinterface dummy byte is wrong");
2867 bool is_init = false;
2868 if (_Jv_equalUtf8Consts (method_name, gcj::init_name))
2871 if (opcode != op_invokespecial)
2872 verify_fail ("can't invoke <init>");
2874 else if (method_name->first() == '<')
2875 verify_fail ("can't invoke method starting with `<'");
2877 // Pop arguments and check types.
2878 int arg_count = _Jv_count_arguments (method_signature);
2879 type arg_types[arg_count];
2880 compute_argument_types (method_signature, arg_types);
2881 for (int i = arg_count - 1; i >= 0; --i)
2883 // This is only used for verifying the byte for
2885 nargs -= arg_types[i].depth ();
2886 pop_init_ref (arg_types[i]);
2889 if (opcode == op_invokeinterface
2891 verify_fail ("wrong argument count for invokeinterface");
2893 if (opcode != op_invokestatic)
2895 type t = class_type;
2898 // In this case the PC doesn't matter.
2899 t.set_uninitialized (type::UNINIT, this);
2900 // FIXME: check to make sure that the <init>
2901 // call is to the right class.
2902 // It must either be super or an exact class
2905 type raw = pop_raw ();
2906 if (! t.compatible (raw, this))
2907 verify_fail ("incompatible type on stack");
2910 current_state->set_initialized (raw.get_pc (),
2911 current_method->max_locals);
2914 type rt = compute_return_type (method_signature);
2922 type t = check_class_constant (get_ushort ());
2923 if (t.isarray () || t.isinterface (this) || t.isabstract (this))
2924 verify_fail ("type is array, interface, or abstract");
2925 t.set_uninitialized (start_PC, this);
2932 int atype = get_byte ();
2933 // We intentionally have chosen constants to make this
2935 if (atype < boolean_type || atype > long_type)
2936 verify_fail ("type not primitive", start_PC);
2937 pop_type (int_type);
2938 type t (construct_primitive_array_type (type_val (atype)), this);
2943 pop_type (int_type);
2944 push_type (check_class_constant (get_ushort ()).to_array (this));
2946 case op_arraylength:
2948 type t = pop_init_ref (reference_type);
2949 if (! t.isarray () && ! t.isnull ())
2950 verify_fail ("array type expected");
2951 push_type (int_type);
2955 pop_type (type (&java::lang::Throwable::class$, this));
2959 pop_init_ref (reference_type);
2960 push_type (check_class_constant (get_ushort ()));
2963 pop_init_ref (reference_type);
2964 check_class_constant (get_ushort ());
2965 push_type (int_type);
2967 case op_monitorenter:
2968 pop_init_ref (reference_type);
2970 case op_monitorexit:
2971 pop_init_ref (reference_type);
2975 switch (get_byte ())
2978 push_type (get_variable (get_ushort (), int_type));
2981 push_type (get_variable (get_ushort (), long_type));
2984 push_type (get_variable (get_ushort (), float_type));
2987 push_type (get_variable (get_ushort (), double_type));
2990 push_type (get_variable (get_ushort (), reference_type));
2993 set_variable (get_ushort (), pop_type (int_type));
2996 set_variable (get_ushort (), pop_type (long_type));
2999 set_variable (get_ushort (), pop_type (float_type));
3002 set_variable (get_ushort (), pop_type (double_type));
3005 set_variable (get_ushort (), pop_init_ref (reference_type));
3008 handle_ret_insn (get_short ());
3011 get_variable (get_ushort (), int_type);
3015 verify_fail ("unrecognized wide instruction", start_PC);
3019 case op_multianewarray:
3021 type atype = check_class_constant (get_ushort ());
3022 int dim = get_byte ();
3024 verify_fail ("too few dimensions to multianewarray", start_PC);
3025 atype.verify_dimensions (dim, this);
3026 for (int i = 0; i < dim; ++i)
3027 pop_type (int_type);
3033 pop_type (reference_type);
3034 push_jump (get_short ());
3037 push_jump (get_int ());
3041 handle_jsr_insn (get_int ());
3044 // These are unused here, but we call them out explicitly
3045 // so that -Wswitch-enum doesn't complain.
3051 case op_putstatic_1:
3052 case op_putstatic_2:
3053 case op_putstatic_4:
3054 case op_putstatic_8:
3055 case op_putstatic_a:
3057 case op_getfield_2s:
3058 case op_getfield_2u:
3062 case op_getstatic_1:
3063 case op_getstatic_2s:
3064 case op_getstatic_2u:
3065 case op_getstatic_4:
3066 case op_getstatic_8:
3067 case op_getstatic_a:
3069 // Unrecognized opcode.
3070 verify_fail ("unrecognized instruction in verify_instructions_0",
3078 void verify_instructions ()
3081 verify_instructions_0 ();
3084 _Jv_BytecodeVerifier (_Jv_InterpMethod *m)
3086 // We just print the text as utf-8. This is just for debugging
3088 debug_print ("--------------------------------\n");
3089 debug_print ("-- Verifying method `%s'\n", m->self->name->chars());
3092 bytecode = m->bytecode ();
3093 exception = m->exceptions ();
3094 current_class = m->defining_class;
3102 ~_Jv_BytecodeVerifier ()
3107 while (utf8_list != NULL)
3109 linked<_Jv_Utf8Const> *n = utf8_list->next;
3110 _Jv_Free (utf8_list);
3114 while (isect_list != NULL)
3116 ref_intersection *next = isect_list->alloc_next;
3123 for (int i = 0; i < current_method->code_length; ++i)
3125 linked<state> *iter = states[i];
3126 while (iter != NULL)
3128 linked<state> *next = iter->next;
3140 _Jv_VerifyMethod (_Jv_InterpMethod *meth)
3142 _Jv_BytecodeVerifier v (meth);
3143 v.verify_instructions ();
3146 #endif /* INTERPRETER */