1 // verify.cc - verify bytecode
3 /* Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006 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.
21 #include <java-insns.h>
22 #include <java-interp.h>
24 // On Solaris 10/x86, <signal.h> indirectly includes <ia32/sys/reg.h>, which
25 // defines PC since g++ predefines __EXTENSIONS__. Undef here to avoid clash
26 // with PC member of class _Jv_BytecodeVerifier below.
31 #include <java/lang/Class.h>
32 #include <java/lang/VerifyError.h>
33 #include <java/lang/Throwable.h>
34 #include <java/lang/reflect/Modifier.h>
35 #include <java/lang/StringBuffer.h>
36 #include <java/lang/NoClassDefFoundError.h>
40 #endif /* VERIFY_DEBUG */
43 // This is used to mark states which are not scheduled for
45 #define INVALID_STATE ((state *) -1)
47 static void debug_print (const char *fmt
, ...)
48 __attribute__ ((format (printf
, 1, 2)));
51 debug_print (MAYBE_UNUSED
const char *fmt
, ...)
56 vfprintf (stderr
, fmt
, ap
);
58 #endif /* VERIFY_DEBUG */
61 // This started as a fairly ordinary verifier, and for the most part
62 // it remains so. It works in the obvious way, by modeling the effect
63 // of each opcode as it is encountered. For most opcodes, this is a
64 // straightforward operation.
66 // This verifier does not do type merging. It used to, but this
67 // results in difficulty verifying some relatively simple code
68 // involving interfaces, and it pushed some verification work into the
71 // Instead of merging reference types, when we reach a point where two
72 // flows of control merge, we simply keep the union of reference types
73 // from each branch. Then, when we need to verify a fact about a
74 // reference on the stack (e.g., that it is compatible with the
75 // argument type of a method), we check to ensure that all possible
76 // types satisfy the requirement.
78 // Another area this verifier differs from the norm is in its handling
79 // of subroutines. The JVM specification has some confusing things to
80 // say about subroutines. For instance, it makes claims about not
81 // allowing subroutines to merge and it rejects recursive subroutines.
82 // For the most part these are red herrings; we used to try to follow
83 // these things but they lead to problems. For example, the notion of
84 // "being in a subroutine" is not well-defined: is an exception
85 // handler in a subroutine? If you never execute the `ret' but
86 // instead `goto 1' do you remain in the subroutine?
88 // For clarity on what is really required for type safety, read
89 // "Simple Verification Technique for Complex Java Bytecode
90 // Subroutines" by Alessandro Coglio. Among other things this paper
91 // shows that recursive subroutines are not harmful to type safety.
92 // We implement something similar to what he proposes. Note that this
93 // means that this verifier will accept code that is rejected by some
96 // For those not wanting to read the paper, the basic observation is
97 // that we can maintain split states in subroutines. We maintain one
98 // state for each calling `jsr'. In other words, we re-verify a
99 // subroutine once for each caller, using the exact types held by the
100 // callers (as opposed to the old approach of merging types and
101 // keeping a bitmap registering what did or did not change). This
102 // approach lets us continue to verify correctly even when a
103 // subroutine is exited via `goto' or `athrow' and not `ret'.
105 // In some other areas the JVM specification is (mildly) incorrect,
106 // so we diverge. For instance, you cannot
107 // violate type safety by allocating an object with `new' and then
108 // failing to initialize it, no matter how one branches or where one
109 // stores the uninitialized reference. See "Improving the official
110 // specification of Java bytecode verification" by Alessandro Coglio.
112 // Note that there's no real point in enforcing that padding bytes or
113 // the mystery byte of invokeinterface must be 0, but we do that
116 // The verifier is currently neither completely lazy nor eager when it
117 // comes to loading classes. It tries to represent types by name when
118 // possible, and then loads them when it needs to verify a fact about
119 // the type. Checking types by name is valid because we only use
120 // names which come from the current class' constant pool. Since all
121 // such names are looked up using the same class loader, there is no
122 // danger that we might be fooled into comparing different types with
125 // In the future we plan to allow for a completely lazy mode of
126 // operation, where the verifier will construct a list of type
127 // assertions to be checked later.
129 // Some test cases for the verifier live in the "verify" module of the
130 // Mauve test suite. However, some of these are presently
131 // (2004-01-20) believed to be incorrect. (More precisely the notion
132 // of "correct" is not well-defined, and this verifier differs from
133 // others while remaining type-safe.) Some other tests live in the
134 // libgcj test suite.
135 class _Jv_BytecodeVerifier
139 static const int FLAG_INSN_START
= 1;
140 static const int FLAG_BRANCH_TARGET
= 2;
145 struct ref_intersection
;
156 // The PC corresponding to the start of the current instruction.
159 // The current state of the stack, locals, etc.
160 state
*current_state
;
162 // At each branch target we keep a linked list of all the states we
163 // can process at that point. We'll only have multiple states at a
164 // given PC if they both have different return-address types in the
165 // same stack or local slot. This array is indexed by PC and holds
166 // the list of all such states.
167 linked
<state
> **states
;
169 // We keep a linked list of all the states which we must reverify.
170 // This is the head of the list.
171 state
*next_verify_state
;
173 // We keep some flags for each instruction. The values are the
174 // FLAG_* constants defined above. This is an array indexed by PC.
177 // The bytecode itself.
178 unsigned char *bytecode
;
180 _Jv_InterpException
*exception
;
183 jclass current_class
;
185 _Jv_InterpMethod
*current_method
;
187 // A linked list of utf8 objects we allocate.
188 linked
<_Jv_Utf8Const
> *utf8_list
;
190 // A linked list of all ref_intersection objects we allocate.
191 ref_intersection
*isect_list
;
193 // Create a new Utf-8 constant and return it. We do this to avoid
194 // having our Utf-8 constants prematurely collected.
195 _Jv_Utf8Const
*make_utf8_const (char *s
, int len
)
197 linked
<_Jv_Utf8Const
> *lu
= (linked
<_Jv_Utf8Const
> *)
198 _Jv_Malloc (sizeof (linked
<_Jv_Utf8Const
>)
199 + _Jv_Utf8Const::space_needed(s
, len
));
200 _Jv_Utf8Const
*r
= (_Jv_Utf8Const
*) (lu
+ 1);
203 lu
->next
= utf8_list
;
209 __attribute__ ((__noreturn__
)) void verify_fail (const char *s
, jint pc
= -1)
211 using namespace java::lang
;
212 StringBuffer
*buf
= new StringBuffer ();
214 buf
->append (JvNewStringLatin1 ("verification failed"));
219 buf
->append (JvNewStringLatin1 (" at PC "));
223 _Jv_InterpMethod
*method
= current_method
;
224 buf
->append (JvNewStringLatin1 (" in "));
225 buf
->append (current_class
->getName());
226 buf
->append ((jchar
) ':');
227 buf
->append (method
->get_method()->name
->toString());
228 buf
->append ((jchar
) '(');
229 buf
->append (method
->get_method()->signature
->toString());
230 buf
->append ((jchar
) ')');
232 buf
->append (JvNewStringLatin1 (": "));
233 buf
->append (JvNewStringLatin1 (s
));
234 throw new java::lang::VerifyError (buf
->toString ());
237 // This enum holds a list of tags for all the different types we
238 // need to handle. Reference types are treated specially by the
244 // The values for primitive types are chosen to correspond to values
245 // specified to newarray.
255 // Used when overwriting second word of a double or long in the
256 // local variables. Also used after merging local variable states
257 // to indicate an unusable value.
260 // This is the second word of a two-word value, i.e., a double or
264 // Everything after `reference_type' must be a reference type.
267 uninitialized_reference_type
270 // This represents a merged class type. Some verifiers (including
271 // earlier versions of this one) will compute the intersection of
272 // two class types when merging states. However, this loses
273 // critical information about interfaces implemented by the various
274 // classes. So instead we keep track of all the actual classes that
276 struct ref_intersection
278 // Whether or not this type has been resolved.
284 // For a resolved reference type, this is a pointer to the class.
286 // For other reference types, this it the name of the class.
290 // Link to the next reference in the intersection.
291 ref_intersection
*ref_next
;
293 // This is used to keep track of all the allocated
294 // ref_intersection objects, so we can free them.
295 // FIXME: we should allocate these in chunks.
296 ref_intersection
*alloc_next
;
298 ref_intersection (jclass klass
, _Jv_BytecodeVerifier
*verifier
)
303 alloc_next
= verifier
->isect_list
;
304 verifier
->isect_list
= this;
307 ref_intersection (_Jv_Utf8Const
*name
, _Jv_BytecodeVerifier
*verifier
)
312 alloc_next
= verifier
->isect_list
;
313 verifier
->isect_list
= this;
316 ref_intersection (ref_intersection
*dup
, ref_intersection
*tail
,
317 _Jv_BytecodeVerifier
*verifier
)
320 is_resolved
= dup
->is_resolved
;
322 alloc_next
= verifier
->isect_list
;
323 verifier
->isect_list
= this;
326 bool equals (ref_intersection
*other
, _Jv_BytecodeVerifier
*verifier
)
328 if (! is_resolved
&& ! other
->is_resolved
329 && _Jv_equalUtf8Classnames (data
.name
, other
->data
.name
))
333 if (! other
->is_resolved
)
334 other
->resolve (verifier
);
335 return data
.klass
== other
->data
.klass
;
338 // Merge THIS type into OTHER, returning the result. This will
339 // return OTHER if all the classes in THIS already appear in
341 ref_intersection
*merge (ref_intersection
*other
,
342 _Jv_BytecodeVerifier
*verifier
)
344 ref_intersection
*tail
= other
;
345 for (ref_intersection
*self
= this; self
!= NULL
; self
= self
->ref_next
)
348 for (ref_intersection
*iter
= other
; iter
!= NULL
;
349 iter
= iter
->ref_next
)
351 if (iter
->equals (self
, verifier
))
359 tail
= new ref_intersection (self
, tail
, verifier
);
364 void resolve (_Jv_BytecodeVerifier
*verifier
)
369 // This is useful if you want to see which classes have to be resolved
370 // while doing the class verification.
371 debug_print("resolving class: %s\n", data
.name
->chars());
373 using namespace java::lang
;
374 java::lang::ClassLoader
*loader
375 = verifier
->current_class
->getClassLoaderInternal();
377 // Due to special handling in to_array() array classes will always
378 // be of the "L ... ;" kind. The separator char ('.' or '/' may vary
380 if (data
.name
->limit()[-1] == ';')
382 data
.klass
= _Jv_FindClassFromSignature (data
.name
->chars(), loader
);
383 if (data
.klass
== NULL
)
384 throw new java::lang::NoClassDefFoundError(data
.name
->toString());
387 data
.klass
= Class::forName (_Jv_NewStringUtf8Const (data
.name
),
392 // See if an object of type OTHER can be assigned to an object of
393 // type *THIS. This might resolve classes in one chain or the
395 bool compatible (ref_intersection
*other
,
396 _Jv_BytecodeVerifier
*verifier
)
398 ref_intersection
*self
= this;
400 for (; self
!= NULL
; self
= self
->ref_next
)
402 ref_intersection
*other_iter
= other
;
404 for (; other_iter
!= NULL
; other_iter
= other_iter
->ref_next
)
406 // Avoid resolving if possible.
407 if (! self
->is_resolved
408 && ! other_iter
->is_resolved
409 && _Jv_equalUtf8Classnames (self
->data
.name
,
410 other_iter
->data
.name
))
413 if (! self
->is_resolved
)
414 self
->resolve(verifier
);
416 // If the LHS of the expression is of type
417 // java.lang.Object, assignment will succeed, no matter
418 // what the type of the RHS is. Using this short-cut we
419 // don't need to resolve the class of the RHS at
420 // verification time.
421 if (self
->data
.klass
== &java::lang::Object::class$
)
424 if (! other_iter
->is_resolved
)
425 other_iter
->resolve(verifier
);
427 if (! is_assignable_from_slow (self
->data
.klass
,
428 other_iter
->data
.klass
))
438 // assert (ref_next == NULL);
440 return data
.klass
->isArray ();
442 return data
.name
->first() == '[';
445 bool isinterface (_Jv_BytecodeVerifier
*verifier
)
447 // assert (ref_next == NULL);
450 return data
.klass
->isInterface ();
453 bool isabstract (_Jv_BytecodeVerifier
*verifier
)
455 // assert (ref_next == NULL);
458 using namespace java::lang::reflect
;
459 return Modifier::isAbstract (data
.klass
->getModifiers ());
462 jclass
getclass (_Jv_BytecodeVerifier
*verifier
)
469 int count_dimensions ()
474 jclass k
= data
.klass
;
475 while (k
->isArray ())
477 k
= k
->getComponentType ();
483 char *p
= data
.name
->chars();
490 void *operator new (size_t bytes
)
492 return _Jv_Malloc (bytes
);
495 void operator delete (void *mem
)
501 // Return the type_val corresponding to a primitive signature
502 // character. For instance `I' returns `int.class'.
503 type_val
get_type_val_for_signature (jchar sig
)
536 verify_fail ("invalid signature");
541 // Return the type_val corresponding to a primitive class.
542 type_val
get_type_val_for_signature (jclass k
)
544 return get_type_val_for_signature ((jchar
) k
->method_count
);
547 // This is like _Jv_IsAssignableFrom, but it works even if SOURCE or
548 // TARGET haven't been prepared.
549 static bool is_assignable_from_slow (jclass target
, jclass source
)
551 // First, strip arrays.
552 while (target
->isArray ())
554 // If target is array, source must be as well.
555 if (! source
->isArray ())
557 target
= target
->getComponentType ();
558 source
= source
->getComponentType ();
562 if (target
== &java::lang::Object::class$
)
567 if (source
== target
)
570 if (target
->isPrimitive () || source
->isPrimitive ())
573 if (target
->isInterface ())
575 for (int i
= 0; i
< source
->interface_count
; ++i
)
577 // We use a recursive call because we also need to
578 // check superinterfaces.
579 if (is_assignable_from_slow (target
, source
->getInterface (i
)))
583 source
= source
->getSuperclass ();
585 while (source
!= NULL
);
590 // The `type' class is used to represent a single type in the
597 // For reference types, the representation of the type.
598 ref_intersection
*klass
;
600 // This is used in two situations.
602 // First, when constructing a new object, it is the PC of the
603 // `new' instruction which created the object. We use the special
604 // value UNINIT to mean that this is uninitialized. The special
605 // value SELF is used for the case where the current method is
606 // itself the <init> method. the special value EITHER is used
607 // when we may optionally allow either an uninitialized or
608 // initialized reference to match.
610 // Second, when the key is return_address_type, this holds the PC
611 // of the instruction following the `jsr'.
614 static const int UNINIT
= -2;
615 static const int SELF
= -1;
616 static const int EITHER
= -3;
618 // Basic constructor.
621 key
= unsuitable_type
;
626 // Make a new instance given the type tag. We assume a generic
627 // `reference_type' means Object.
631 // For reference_type, if KLASS==NULL then that means we are
632 // looking for a generic object of any kind, including an
633 // uninitialized reference.
638 // Make a new instance given a class.
639 type (jclass k
, _Jv_BytecodeVerifier
*verifier
)
641 key
= reference_type
;
642 klass
= new ref_intersection (k
, verifier
);
646 // Make a new instance given the name of a class.
647 type (_Jv_Utf8Const
*n
, _Jv_BytecodeVerifier
*verifier
)
649 key
= reference_type
;
650 klass
= new ref_intersection (n
, verifier
);
662 // These operators are required because libgcj can't link in
664 void *operator new[] (size_t bytes
)
666 return _Jv_Malloc (bytes
);
669 void operator delete[] (void *mem
)
674 type
& operator= (type_val k
)
682 type
& operator= (const type
& t
)
690 // Promote a numeric type.
693 if (key
== boolean_type
|| key
== char_type
694 || key
== byte_type
|| key
== short_type
)
699 // Mark this type as the uninitialized result of `new'.
700 void set_uninitialized (int npc
, _Jv_BytecodeVerifier
*verifier
)
702 if (key
== reference_type
)
703 key
= uninitialized_reference_type
;
705 verifier
->verify_fail ("internal error in type::uninitialized");
709 // Mark this type as now initialized.
710 void set_initialized (int npc
)
712 if (npc
!= UNINIT
&& pc
== npc
&& key
== uninitialized_reference_type
)
714 key
= reference_type
;
719 // Mark this type as a particular return address.
720 void set_return_address (int npc
)
725 // Return true if this type and type OTHER are considered
726 // mergeable for the purposes of state merging. This is related
727 // to subroutine handling. For this purpose two types are
728 // considered unmergeable if they are both return-addresses but
729 // have different PCs.
730 bool state_mergeable_p (const type
&other
) const
732 return (key
!= return_address_type
733 || other
.key
!= return_address_type
737 // Return true if an object of type K can be assigned to a variable
738 // of type *THIS. Handle various special cases too. Might modify
739 // *THIS or K. Note however that this does not perform numeric
741 bool compatible (type
&k
, _Jv_BytecodeVerifier
*verifier
)
743 // Any type is compatible with the unsuitable type.
744 if (key
== unsuitable_type
)
747 if (key
< reference_type
|| k
.key
< reference_type
)
750 // The `null' type is convertible to any initialized reference
752 if (key
== null_type
)
753 return k
.key
!= uninitialized_reference_type
;
754 if (k
.key
== null_type
)
755 return key
!= uninitialized_reference_type
;
757 // A special case for a generic reference.
761 verifier
->verify_fail ("programmer error in type::compatible");
763 // Handle the special 'EITHER' case, which is only used in a
764 // special case of 'putfield'. Note that we only need to handle
765 // this on the LHS of a check.
766 if (! isinitialized () && pc
== EITHER
)
768 // If the RHS is uninitialized, it must be an uninitialized
770 if (! k
.isinitialized () && k
.pc
!= SELF
)
773 else if (isinitialized () != k
.isinitialized ())
775 // An initialized type and an uninitialized type are not
776 // otherwise compatible.
781 // Two uninitialized objects are compatible if either:
782 // * The PCs are identical, or
783 // * One PC is UNINIT.
784 if (! isinitialized ())
786 if (pc
!= k
.pc
&& pc
!= UNINIT
&& k
.pc
!= UNINIT
)
791 return klass
->compatible(k
.klass
, verifier
);
794 bool equals (const type
&other
, _Jv_BytecodeVerifier
*vfy
)
796 // Only works for reference types.
797 if ((key
!= reference_type
798 && key
!= uninitialized_reference_type
)
799 || (other
.key
!= reference_type
800 && other
.key
!= uninitialized_reference_type
))
802 // Only for single-valued types.
803 if (klass
->ref_next
|| other
.klass
->ref_next
)
805 return klass
->equals (other
.klass
, vfy
);
810 return key
== void_type
;
815 return key
== long_type
|| key
== double_type
;
818 // Return number of stack or local variable slots taken by this
822 return iswide () ? 2 : 1;
825 bool isarray () const
827 // We treat null_type as not an array. This is ok based on the
828 // current uses of this method.
829 if (key
== reference_type
)
830 return klass
->isarray ();
836 return key
== null_type
;
839 bool isinterface (_Jv_BytecodeVerifier
*verifier
)
841 if (key
!= reference_type
)
843 return klass
->isinterface (verifier
);
846 bool isabstract (_Jv_BytecodeVerifier
*verifier
)
848 if (key
!= reference_type
)
850 return klass
->isabstract (verifier
);
853 // Return the element type of an array.
854 type
element_type (_Jv_BytecodeVerifier
*verifier
)
856 if (key
!= reference_type
)
857 verifier
->verify_fail ("programmer error in type::element_type()", -1);
859 jclass k
= klass
->getclass (verifier
)->getComponentType ();
860 if (k
->isPrimitive ())
861 return type (verifier
->get_type_val_for_signature (k
));
862 return type (k
, verifier
);
865 // Return the array type corresponding to an initialized
866 // reference. We could expand this to work for other kinds of
867 // types, but currently we don't need to.
868 type
to_array (_Jv_BytecodeVerifier
*verifier
)
870 if (key
!= reference_type
)
871 verifier
->verify_fail ("internal error in type::to_array()");
873 // In case the class is already resolved we can simply ask the runtime
874 // to give us the array version.
875 // If it is not resolved we prepend "[" to the classname to make the
876 // array usage verification more lazy. In other words: makes new Foo[300]
877 // pass the verifier if Foo.class is missing.
878 if (klass
->is_resolved
)
880 jclass k
= klass
->getclass (verifier
);
882 return type (_Jv_GetArrayClass (k
, k
->getClassLoaderInternal()),
887 int len
= klass
->data
.name
->len();
889 // If the classname is given in the Lp1/p2/cn; format we only need
890 // to add a leading '['. The same procedure has to be done for
891 // primitive arrays (ie. provided "[I", the result should be "[[I".
892 // If the classname is given as p1.p2.cn we have to embed it into
894 if (klass
->data
.name
->limit()[-1] == ';' ||
895 _Jv_isPrimitiveOrDerived(klass
->data
.name
))
897 // Reserves space for leading '[' and trailing '\0' .
898 char arrayName
[len
+ 2];
901 strcpy(&arrayName
[1], klass
->data
.name
->chars());
904 // This is only needed when we want to print the string to the
905 // screen while debugging.
906 arrayName
[len
+ 1] = '\0';
908 debug_print("len: %d - old: '%s' - new: '%s'\n", len
, klass
->data
.name
->chars(), arrayName
);
911 return type (verifier
->make_utf8_const( arrayName
, len
+ 1 ),
916 // Reserves space for leading "[L" and trailing ';' and '\0' .
917 char arrayName
[len
+ 4];
921 strcpy(&arrayName
[2], klass
->data
.name
->chars());
922 arrayName
[len
+ 2] = ';';
925 // This is only needed when we want to print the string to the
926 // screen while debugging.
927 arrayName
[len
+ 3] = '\0';
929 debug_print("len: %d - old: '%s' - new: '%s'\n", len
, klass
->data
.name
->chars(), arrayName
);
932 return type (verifier
->make_utf8_const( arrayName
, len
+ 3 ),
939 bool isreference () const
941 return key
>= reference_type
;
949 bool isinitialized () const
951 return key
== reference_type
|| key
== null_type
;
954 bool isresolved () const
956 return (key
== reference_type
958 || key
== uninitialized_reference_type
);
961 void verify_dimensions (int ndims
, _Jv_BytecodeVerifier
*verifier
)
963 // The way this is written, we don't need to check isarray().
964 if (key
!= reference_type
)
965 verifier
->verify_fail ("internal error in verify_dimensions:"
966 " not a reference type");
968 if (klass
->count_dimensions () < ndims
)
969 verifier
->verify_fail ("array type has fewer dimensions"
973 // Merge OLD_TYPE into this. On error throw exception. Return
974 // true if the merge caused a type change.
975 bool merge (type
& old_type
, bool local_semantics
,
976 _Jv_BytecodeVerifier
*verifier
)
978 bool changed
= false;
979 bool refo
= old_type
.isreference ();
980 bool refn
= isreference ();
983 if (old_type
.key
== null_type
)
985 else if (key
== null_type
)
990 else if (isinitialized () != old_type
.isinitialized ())
991 verifier
->verify_fail ("merging initialized and uninitialized types");
994 if (! isinitialized ())
998 else if (old_type
.pc
== UNINIT
)
1000 else if (pc
!= old_type
.pc
)
1001 verifier
->verify_fail ("merging different uninitialized types");
1004 ref_intersection
*merged
= old_type
.klass
->merge (klass
,
1006 if (merged
!= klass
)
1013 else if (refo
|| refn
|| key
!= old_type
.key
)
1015 if (local_semantics
)
1017 // If we already have an `unsuitable' type, then we
1018 // don't need to change again.
1019 if (key
!= unsuitable_type
)
1021 key
= unsuitable_type
;
1026 verifier
->verify_fail ("unmergeable type");
1032 void print (void) const
1037 case boolean_type
: c
= 'Z'; break;
1038 case byte_type
: c
= 'B'; break;
1039 case char_type
: c
= 'C'; break;
1040 case short_type
: c
= 'S'; break;
1041 case int_type
: c
= 'I'; break;
1042 case long_type
: c
= 'J'; break;
1043 case float_type
: c
= 'F'; break;
1044 case double_type
: c
= 'D'; break;
1045 case void_type
: c
= 'V'; break;
1046 case unsuitable_type
: c
= '-'; break;
1047 case return_address_type
: c
= 'r'; break;
1048 case continuation_type
: c
= '+'; break;
1049 case reference_type
: c
= 'L'; break;
1050 case null_type
: c
= '@'; break;
1051 case uninitialized_reference_type
: c
= 'U'; break;
1053 debug_print ("%c", c
);
1055 #endif /* VERIFY_DEBUG */
1058 // This class holds all the state information we need for a given
1062 // The current top of the stack, in terms of slots.
1064 // The current depth of the stack. This will be larger than
1065 // STACKTOP when wide types are on the stack.
1069 // The local variables.
1071 // We keep track of the type of `this' specially. This is used to
1072 // ensure that an instance initializer invokes another initializer
1073 // on `this' before returning. We must keep track of this
1074 // specially because otherwise we might be confused by code which
1075 // assigns to locals[0] (overwriting `this') and then returns
1076 // without really initializing.
1079 // The PC for this state. This is only valid on states which are
1080 // permanently attached to a given PC. For an object like
1081 // `current_state', which is used transiently, this has no
1084 // We keep a linked list of all states requiring reverification.
1085 // If this is the special value INVALID_STATE then this state is
1086 // not on the list. NULL marks the end of the linked list.
1089 // NO_NEXT is the PC value meaning that a new state must be
1090 // acquired from the verification list.
1091 static const int NO_NEXT
= -1;
1098 next
= INVALID_STATE
;
1101 state (int max_stack
, int max_locals
)
1106 stack
= new type
[max_stack
];
1107 for (int i
= 0; i
< max_stack
; ++i
)
1108 stack
[i
] = unsuitable_type
;
1109 locals
= new type
[max_locals
];
1110 for (int i
= 0; i
< max_locals
; ++i
)
1111 locals
[i
] = unsuitable_type
;
1113 next
= INVALID_STATE
;
1116 state (const state
*orig
, int max_stack
, int max_locals
)
1118 stack
= new type
[max_stack
];
1119 locals
= new type
[max_locals
];
1120 copy (orig
, max_stack
, max_locals
);
1122 next
= INVALID_STATE
;
1133 void *operator new[] (size_t bytes
)
1135 return _Jv_Malloc (bytes
);
1138 void operator delete[] (void *mem
)
1143 void *operator new (size_t bytes
)
1145 return _Jv_Malloc (bytes
);
1148 void operator delete (void *mem
)
1153 void copy (const state
*copy
, int max_stack
, int max_locals
)
1155 stacktop
= copy
->stacktop
;
1156 stackdepth
= copy
->stackdepth
;
1157 for (int i
= 0; i
< max_stack
; ++i
)
1158 stack
[i
] = copy
->stack
[i
];
1159 for (int i
= 0; i
< max_locals
; ++i
)
1160 locals
[i
] = copy
->locals
[i
];
1162 this_type
= copy
->this_type
;
1163 // Don't modify `next' or `pc'.
1166 // Modify this state to reflect entry to an exception handler.
1167 void set_exception (type t
, int max_stack
)
1172 for (int i
= stacktop
; i
< max_stack
; ++i
)
1173 stack
[i
] = unsuitable_type
;
1176 inline int get_pc () const
1181 void set_pc (int npc
)
1186 // Merge STATE_OLD into this state. Destructively modifies this
1187 // state. Returns true if the new state was in fact changed.
1188 // Will throw an exception if the states are not mergeable.
1189 bool merge (state
*state_old
, int max_locals
,
1190 _Jv_BytecodeVerifier
*verifier
)
1192 bool changed
= false;
1194 // Special handling for `this'. If one or the other is
1195 // uninitialized, then the merge is uninitialized.
1196 if (this_type
.isinitialized ())
1197 this_type
= state_old
->this_type
;
1200 if (state_old
->stacktop
!= stacktop
) // FIXME stackdepth instead?
1201 verifier
->verify_fail ("stack sizes differ");
1202 for (int i
= 0; i
< state_old
->stacktop
; ++i
)
1204 if (stack
[i
].merge (state_old
->stack
[i
], false, verifier
))
1208 // Merge local variables.
1209 for (int i
= 0; i
< max_locals
; ++i
)
1211 if (locals
[i
].merge (state_old
->locals
[i
], true, verifier
))
1218 // Ensure that `this' has been initialized.
1219 void check_this_initialized (_Jv_BytecodeVerifier
*verifier
)
1221 if (this_type
.isreference () && ! this_type
.isinitialized ())
1222 verifier
->verify_fail ("`this' is uninitialized");
1225 // Set type of `this'.
1226 void set_this_type (const type
&k
)
1231 // Mark each `new'd object we know of that was allocated at PC as
1233 void set_initialized (int pc
, int max_locals
)
1235 for (int i
= 0; i
< stacktop
; ++i
)
1236 stack
[i
].set_initialized (pc
);
1237 for (int i
= 0; i
< max_locals
; ++i
)
1238 locals
[i
].set_initialized (pc
);
1239 this_type
.set_initialized (pc
);
1242 // This tests to see whether two states can be considered "merge
1243 // compatible". If both states have a return-address in the same
1244 // slot, and the return addresses are different, then they are not
1245 // compatible and we must not try to merge them.
1246 bool state_mergeable_p (state
*other
, int max_locals
,
1247 _Jv_BytecodeVerifier
*verifier
)
1249 // This is tricky: if the stack sizes differ, then not only are
1250 // these not mergeable, but in fact we should give an error, as
1251 // we've found two execution paths that reach a branch target
1252 // with different stack depths. FIXME stackdepth instead?
1253 if (stacktop
!= other
->stacktop
)
1254 verifier
->verify_fail ("stack sizes differ");
1256 for (int i
= 0; i
< stacktop
; ++i
)
1257 if (! stack
[i
].state_mergeable_p (other
->stack
[i
]))
1259 for (int i
= 0; i
< max_locals
; ++i
)
1260 if (! locals
[i
].state_mergeable_p (other
->locals
[i
]))
1265 void reverify (_Jv_BytecodeVerifier
*verifier
)
1267 if (next
== INVALID_STATE
)
1269 next
= verifier
->next_verify_state
;
1270 verifier
->next_verify_state
= this;
1275 void print (const char *leader
, int pc
,
1276 int max_stack
, int max_locals
) const
1278 debug_print ("%s [%4d]: [stack] ", leader
, pc
);
1280 for (i
= 0; i
< stacktop
; ++i
)
1282 for (; i
< max_stack
; ++i
)
1284 debug_print (" [local] ");
1285 for (i
= 0; i
< max_locals
; ++i
)
1287 debug_print (" | %p\n", this);
1290 inline void print (const char *, int, int, int) const
1293 #endif /* VERIFY_DEBUG */
1298 if (current_state
->stacktop
<= 0)
1299 verify_fail ("stack empty");
1300 type r
= current_state
->stack
[--current_state
->stacktop
];
1301 current_state
->stackdepth
-= r
.depth ();
1302 if (current_state
->stackdepth
< 0)
1303 verify_fail ("stack empty", start_PC
);
1309 type r
= pop_raw ();
1311 verify_fail ("narrow pop of wide type");
1315 type
pop_type (type match
)
1318 type t
= pop_raw ();
1319 if (! match
.compatible (t
, this))
1320 verify_fail ("incompatible type on stack");
1324 // Pop a reference which is guaranteed to be initialized. MATCH
1325 // doesn't have to be a reference type; in this case this acts like
1327 type
pop_init_ref (type match
)
1329 type t
= pop_raw ();
1330 if (t
.isreference () && ! t
.isinitialized ())
1331 verify_fail ("initialized reference required");
1332 else if (! match
.compatible (t
, this))
1333 verify_fail ("incompatible type on stack");
1337 // Pop a reference type or a return address.
1338 type
pop_ref_or_return ()
1340 type t
= pop_raw ();
1341 if (! t
.isreference () && t
.key
!= return_address_type
)
1342 verify_fail ("expected reference or return address on stack");
1346 void push_type (type t
)
1348 // If T is a numeric type like short, promote it to int.
1351 int depth
= t
.depth ();
1352 if (current_state
->stackdepth
+ depth
> current_method
->max_stack
)
1353 verify_fail ("stack overflow");
1354 current_state
->stack
[current_state
->stacktop
++] = t
;
1355 current_state
->stackdepth
+= depth
;
1358 void set_variable (int index
, type t
)
1360 // If T is a numeric type like short, promote it to int.
1363 int depth
= t
.depth ();
1364 if (index
> current_method
->max_locals
- depth
)
1365 verify_fail ("invalid local variable");
1366 current_state
->locals
[index
] = t
;
1369 current_state
->locals
[index
+ 1] = continuation_type
;
1370 if (index
> 0 && current_state
->locals
[index
- 1].iswide ())
1371 current_state
->locals
[index
- 1] = unsuitable_type
;
1374 type
get_variable (int index
, type t
)
1376 int depth
= t
.depth ();
1377 if (index
> current_method
->max_locals
- depth
)
1378 verify_fail ("invalid local variable");
1379 if (! t
.compatible (current_state
->locals
[index
], this))
1380 verify_fail ("incompatible type in local variable");
1383 type
t (continuation_type
);
1384 if (! current_state
->locals
[index
+ 1].compatible (t
, this))
1385 verify_fail ("invalid local variable");
1387 return current_state
->locals
[index
];
1390 // Make sure ARRAY is an array type and that its elements are
1391 // compatible with type ELEMENT. Returns the actual element type.
1392 type
require_array_type (type array
, type element
)
1394 // An odd case. Here we just pretend that everything went ok. If
1395 // the requested element type is some kind of reference, return
1396 // the null type instead.
1397 if (array
.isnull ())
1398 return element
.isreference () ? type (null_type
) : element
;
1400 if (! array
.isarray ())
1401 verify_fail ("array required");
1403 type t
= array
.element_type (this);
1404 if (! element
.compatible (t
, this))
1406 // Special case for byte arrays, which must also be boolean
1409 if (element
.key
== byte_type
)
1411 type
e2 (boolean_type
);
1412 ok
= e2
.compatible (t
, this);
1415 verify_fail ("incompatible array element type");
1418 // Return T and not ELEMENT, because T might be specialized.
1424 if (PC
>= current_method
->code_length
)
1425 verify_fail ("premature end of bytecode");
1426 return (jint
) bytecode
[PC
++] & 0xff;
1431 jint b1
= get_byte ();
1432 jint b2
= get_byte ();
1433 return (jint
) ((b1
<< 8) | b2
) & 0xffff;
1438 jint b1
= get_byte ();
1439 jint b2
= get_byte ();
1440 jshort s
= (b1
<< 8) | b2
;
1446 jint b1
= get_byte ();
1447 jint b2
= get_byte ();
1448 jint b3
= get_byte ();
1449 jint b4
= get_byte ();
1450 return (b1
<< 24) | (b2
<< 16) | (b3
<< 8) | b4
;
1453 int compute_jump (int offset
)
1455 int npc
= start_PC
+ offset
;
1456 if (npc
< 0 || npc
>= current_method
->code_length
)
1457 verify_fail ("branch out of range", start_PC
);
1461 // Add a new state to the state list at NPC.
1462 state
*add_new_state (int npc
, state
*old_state
)
1464 state
*new_state
= new state (old_state
, current_method
->max_stack
,
1465 current_method
->max_locals
);
1466 debug_print ("== New state in add_new_state\n");
1467 new_state
->print ("New", npc
, current_method
->max_stack
,
1468 current_method
->max_locals
);
1469 linked
<state
> *nlink
1470 = (linked
<state
> *) _Jv_Malloc (sizeof (linked
<state
>));
1471 nlink
->val
= new_state
;
1472 nlink
->next
= states
[npc
];
1473 states
[npc
] = nlink
;
1474 new_state
->set_pc (npc
);
1478 // Merge the indicated state into the state at the branch target and
1479 // schedule a new PC if there is a change. NPC is the PC of the
1480 // branch target, and FROM_STATE is the state at the source of the
1481 // branch. This method returns true if the destination state
1482 // changed and requires reverification, false otherwise.
1483 void merge_into (int npc
, state
*from_state
)
1485 // Iterate over all target states and merge our state into each,
1486 // if applicable. FIXME one improvement we could make here is
1487 // "state destruction". Merging a new state into an existing one
1488 // might cause a return_address_type to be merged to
1489 // unsuitable_type. In this case the resulting state may now be
1490 // mergeable with other states currently held in parallel at this
1491 // location. So in this situation we could pairwise compare and
1492 // reduce the number of parallel states.
1493 bool applicable
= false;
1494 for (linked
<state
> *iter
= states
[npc
]; iter
!= NULL
; iter
= iter
->next
)
1496 state
*new_state
= iter
->val
;
1497 if (new_state
->state_mergeable_p (from_state
,
1498 current_method
->max_locals
, this))
1502 debug_print ("== Merge states in merge_into\n");
1503 from_state
->print ("Frm", start_PC
, current_method
->max_stack
,
1504 current_method
->max_locals
);
1505 new_state
->print (" To", npc
, current_method
->max_stack
,
1506 current_method
->max_locals
);
1507 bool changed
= new_state
->merge (from_state
,
1508 current_method
->max_locals
,
1510 new_state
->print ("New", npc
, current_method
->max_stack
,
1511 current_method
->max_locals
);
1514 new_state
->reverify (this);
1520 // Either we don't yet have a state at NPC, or we have a
1521 // return-address type that is in conflict with all existing
1522 // state. So, we need to create a new entry.
1523 state
*new_state
= add_new_state (npc
, from_state
);
1524 // A new state added in this way must always be reverified.
1525 new_state
->reverify (this);
1529 void push_jump (int offset
)
1531 int npc
= compute_jump (offset
);
1532 // According to the JVM Spec, we need to check for uninitialized
1533 // objects here. However, this does not actually affect type
1534 // safety, and the Eclipse java compiler generates code that
1535 // violates this constraint.
1536 merge_into (npc
, current_state
);
1539 void push_exception_jump (type t
, int pc
)
1541 // According to the JVM Spec, we need to check for uninitialized
1542 // objects here. However, this does not actually affect type
1543 // safety, and the Eclipse java compiler generates code that
1544 // violates this constraint.
1545 state
s (current_state
, current_method
->max_stack
,
1546 current_method
->max_locals
);
1547 if (current_method
->max_stack
< 1)
1548 verify_fail ("stack overflow at exception handler");
1549 s
.set_exception (t
, current_method
->max_stack
);
1550 merge_into (pc
, &s
);
1555 state
*new_state
= next_verify_state
;
1556 if (new_state
== INVALID_STATE
)
1557 verify_fail ("programmer error in pop_jump");
1558 if (new_state
!= NULL
)
1560 next_verify_state
= new_state
->next
;
1561 new_state
->next
= INVALID_STATE
;
1566 void invalidate_pc ()
1568 PC
= state::NO_NEXT
;
1571 void note_branch_target (int pc
)
1573 // Don't check `pc <= PC', because we've advanced PC after
1574 // fetching the target and we haven't yet checked the next
1576 if (pc
< PC
&& ! (flags
[pc
] & FLAG_INSN_START
))
1577 verify_fail ("branch not to instruction start", start_PC
);
1578 flags
[pc
] |= FLAG_BRANCH_TARGET
;
1581 void skip_padding ()
1583 while ((PC
% 4) > 0)
1584 if (get_byte () != 0)
1585 verify_fail ("found nonzero padding byte");
1588 // Do the work for a `ret' instruction. INDEX is the index into the
1590 void handle_ret_insn (int index
)
1592 type ret_addr
= get_variable (index
, return_address_type
);
1593 // It would be nice if we could do this. However, the JVM Spec
1594 // doesn't say that this is what happens. It is implied that
1595 // reusing a return address is invalid, but there's no actual
1596 // prohibition against it.
1597 // set_variable (index, unsuitable_type);
1599 int npc
= ret_addr
.get_pc ();
1600 // We might be returning to a `jsr' that is at the end of the
1601 // bytecode. This is ok if we never return from the called
1602 // subroutine, but if we see this here it is an error.
1603 if (npc
>= current_method
->code_length
)
1604 verify_fail ("fell off end");
1606 // According to the JVM Spec, we need to check for uninitialized
1607 // objects here. However, this does not actually affect type
1608 // safety, and the Eclipse java compiler generates code that
1609 // violates this constraint.
1610 merge_into (npc
, current_state
);
1614 void handle_jsr_insn (int offset
)
1616 int npc
= compute_jump (offset
);
1618 // According to the JVM Spec, we need to check for uninitialized
1619 // objects here. However, this does not actually affect type
1620 // safety, and the Eclipse java compiler generates code that
1621 // violates this constraint.
1623 // Modify our state as appropriate for entry into a subroutine.
1624 type
ret_addr (return_address_type
);
1625 ret_addr
.set_return_address (PC
);
1626 push_type (ret_addr
);
1627 merge_into (npc
, current_state
);
1631 jclass
construct_primitive_array_type (type_val prim
)
1637 k
= JvPrimClass (boolean
);
1640 k
= JvPrimClass (char);
1643 k
= JvPrimClass (float);
1646 k
= JvPrimClass (double);
1649 k
= JvPrimClass (byte
);
1652 k
= JvPrimClass (short);
1655 k
= JvPrimClass (int);
1658 k
= JvPrimClass (long);
1661 // These aren't used here but we call them out to avoid
1664 case unsuitable_type
:
1665 case return_address_type
:
1666 case continuation_type
:
1667 case reference_type
:
1669 case uninitialized_reference_type
:
1671 verify_fail ("unknown type in construct_primitive_array_type");
1673 k
= _Jv_GetArrayClass (k
, NULL
);
1677 // This pass computes the location of branch targets and also
1678 // instruction starts.
1679 void branch_prepass ()
1681 flags
= (char *) _Jv_Malloc (current_method
->code_length
);
1683 for (int i
= 0; i
< current_method
->code_length
; ++i
)
1687 while (PC
< current_method
->code_length
)
1689 // Set `start_PC' early so that error checking can have the
1692 flags
[PC
] |= FLAG_INSN_START
;
1694 java_opcode opcode
= (java_opcode
) bytecode
[PC
++];
1698 case op_aconst_null
:
1834 case op_monitorenter
:
1835 case op_monitorexit
:
1843 case op_arraylength
:
1875 case op_invokespecial
:
1876 case op_invokestatic
:
1877 case op_invokevirtual
:
1881 case op_multianewarray
:
1904 note_branch_target (compute_jump (get_short ()));
1907 case op_tableswitch
:
1910 note_branch_target (compute_jump (get_int ()));
1911 jint low
= get_int ();
1912 jint hi
= get_int ();
1914 verify_fail ("invalid tableswitch", start_PC
);
1915 for (int i
= low
; i
<= hi
; ++i
)
1916 note_branch_target (compute_jump (get_int ()));
1920 case op_lookupswitch
:
1923 note_branch_target (compute_jump (get_int ()));
1924 int npairs
= get_int ();
1926 verify_fail ("too few pairs in lookupswitch", start_PC
);
1927 while (npairs
-- > 0)
1930 note_branch_target (compute_jump (get_int ()));
1935 case op_invokeinterface
:
1943 opcode
= (java_opcode
) get_byte ();
1945 if (opcode
== op_iinc
)
1952 note_branch_target (compute_jump (get_int ()));
1955 // These are unused here, but we call them out explicitly
1956 // so that -Wswitch-enum doesn't complain.
1962 case op_putstatic_1
:
1963 case op_putstatic_2
:
1964 case op_putstatic_4
:
1965 case op_putstatic_8
:
1966 case op_putstatic_a
:
1968 case op_getfield_2s
:
1969 case op_getfield_2u
:
1973 case op_getstatic_1
:
1974 case op_getstatic_2s
:
1975 case op_getstatic_2u
:
1976 case op_getstatic_4
:
1977 case op_getstatic_8
:
1978 case op_getstatic_a
:
1981 verify_fail ("unrecognized instruction in branch_prepass",
1985 // See if any previous branch tried to branch to the middle of
1986 // this instruction.
1987 for (int pc
= start_PC
+ 1; pc
< PC
; ++pc
)
1989 if ((flags
[pc
] & FLAG_BRANCH_TARGET
))
1990 verify_fail ("branch to middle of instruction", pc
);
1994 // Verify exception handlers.
1995 for (int i
= 0; i
< current_method
->exc_count
; ++i
)
1997 if (! (flags
[exception
[i
].handler_pc
.i
] & FLAG_INSN_START
))
1998 verify_fail ("exception handler not at instruction start",
1999 exception
[i
].handler_pc
.i
);
2000 if (! (flags
[exception
[i
].start_pc
.i
] & FLAG_INSN_START
))
2001 verify_fail ("exception start not at instruction start",
2002 exception
[i
].start_pc
.i
);
2003 if (exception
[i
].end_pc
.i
!= current_method
->code_length
2004 && ! (flags
[exception
[i
].end_pc
.i
] & FLAG_INSN_START
))
2005 verify_fail ("exception end not at instruction start",
2006 exception
[i
].end_pc
.i
);
2008 flags
[exception
[i
].handler_pc
.i
] |= FLAG_BRANCH_TARGET
;
2012 void check_pool_index (int index
)
2014 if (index
< 0 || index
>= current_class
->constants
.size
)
2015 verify_fail ("constant pool index out of range", start_PC
);
2018 type
check_class_constant (int index
)
2020 check_pool_index (index
);
2021 _Jv_Constants
*pool
= ¤t_class
->constants
;
2022 if (pool
->tags
[index
] == JV_CONSTANT_ResolvedClass
)
2023 return type (pool
->data
[index
].clazz
, this);
2024 else if (pool
->tags
[index
] == JV_CONSTANT_Class
)
2025 return type (pool
->data
[index
].utf8
, this);
2026 verify_fail ("expected class constant", start_PC
);
2029 type
check_constant (int index
)
2031 check_pool_index (index
);
2032 _Jv_Constants
*pool
= ¤t_class
->constants
;
2033 int tag
= pool
->tags
[index
];
2034 if (tag
== JV_CONSTANT_ResolvedString
|| tag
== JV_CONSTANT_String
)
2035 return type (&java::lang::String::class$
, this);
2036 else if (tag
== JV_CONSTANT_Integer
)
2037 return type (int_type
);
2038 else if (tag
== JV_CONSTANT_Float
)
2039 return type (float_type
);
2040 else if (current_method
->is_15
2041 && (tag
== JV_CONSTANT_ResolvedClass
|| tag
== JV_CONSTANT_Class
))
2042 return type (&java::lang::Class::class$
, this);
2043 verify_fail ("String, int, or float constant expected", start_PC
);
2046 type
check_wide_constant (int index
)
2048 check_pool_index (index
);
2049 _Jv_Constants
*pool
= ¤t_class
->constants
;
2050 if (pool
->tags
[index
] == JV_CONSTANT_Long
)
2051 return type (long_type
);
2052 else if (pool
->tags
[index
] == JV_CONSTANT_Double
)
2053 return type (double_type
);
2054 verify_fail ("long or double constant expected", start_PC
);
2057 // Helper for both field and method. These are laid out the same in
2058 // the constant pool.
2059 type
handle_field_or_method (int index
, int expected
,
2060 _Jv_Utf8Const
**name
,
2061 _Jv_Utf8Const
**fmtype
)
2063 check_pool_index (index
);
2064 _Jv_Constants
*pool
= ¤t_class
->constants
;
2065 if (pool
->tags
[index
] != expected
)
2066 verify_fail ("didn't see expected constant", start_PC
);
2067 // Once we know we have a Fieldref or Methodref we assume that it
2068 // is correctly laid out in the constant pool. I think the code
2069 // in defineclass.cc guarantees this.
2070 _Jv_ushort class_index
, name_and_type_index
;
2071 _Jv_loadIndexes (&pool
->data
[index
],
2073 name_and_type_index
);
2074 _Jv_ushort name_index
, desc_index
;
2075 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
2076 name_index
, desc_index
);
2078 *name
= pool
->data
[name_index
].utf8
;
2079 *fmtype
= pool
->data
[desc_index
].utf8
;
2081 return check_class_constant (class_index
);
2084 // Return field's type, compute class' type if requested.
2085 // If PUTFIELD is true, use the special 'putfield' semantics.
2086 type
check_field_constant (int index
, type
*class_type
= NULL
,
2087 bool putfield
= false)
2089 _Jv_Utf8Const
*name
, *field_type
;
2090 type ct
= handle_field_or_method (index
,
2091 JV_CONSTANT_Fieldref
,
2092 &name
, &field_type
);
2096 if (field_type
->first() == '[' || field_type
->first() == 'L')
2097 result
= type (field_type
, this);
2099 result
= get_type_val_for_signature (field_type
->first());
2101 // We have an obscure special case here: we can use `putfield' on
2102 // a field declared in this class, even if `this' has not yet been
2105 && ! current_state
->this_type
.isinitialized ()
2106 && current_state
->this_type
.pc
== type::SELF
2107 && current_state
->this_type
.equals (ct
, this)
2108 // We don't look at the signature, figuring that if it is
2109 // wrong we will fail during linking. FIXME?
2110 && _Jv_Linker::has_field_p (current_class
, name
))
2111 // Note that we don't actually know whether we're going to match
2112 // against 'this' or some other object of the same type. So,
2113 // here we set things up so that it doesn't matter. This relies
2114 // on knowing what our caller is up to.
2115 class_type
->set_uninitialized (type::EITHER
, this);
2120 type
check_method_constant (int index
, bool is_interface
,
2121 _Jv_Utf8Const
**method_name
,
2122 _Jv_Utf8Const
**method_signature
)
2124 return handle_field_or_method (index
,
2126 ? JV_CONSTANT_InterfaceMethodref
2127 : JV_CONSTANT_Methodref
),
2128 method_name
, method_signature
);
2131 type
get_one_type (char *&p
)
2149 _Jv_Utf8Const
*name
= make_utf8_const (start
, p
- start
);
2150 return type (name
, this);
2153 // Casting to jchar here is ok since we are looking at an ASCII
2155 type_val rt
= get_type_val_for_signature (jchar (v
));
2157 if (arraycount
== 0)
2159 // Callers of this function eventually push their arguments on
2160 // the stack. So, promote them here.
2161 return type (rt
).promote ();
2164 jclass k
= construct_primitive_array_type (rt
);
2165 while (--arraycount
> 0)
2166 k
= _Jv_GetArrayClass (k
, NULL
);
2167 return type (k
, this);
2170 void compute_argument_types (_Jv_Utf8Const
*signature
,
2173 char *p
= signature
->chars();
2180 types
[i
++] = get_one_type (p
);
2183 type
compute_return_type (_Jv_Utf8Const
*signature
)
2185 char *p
= signature
->chars();
2189 return get_one_type (p
);
2192 void check_return_type (type onstack
)
2194 type rt
= compute_return_type (current_method
->self
->signature
);
2195 if (! rt
.compatible (onstack
, this))
2196 verify_fail ("incompatible return type");
2199 // Initialize the stack for the new method. Returns true if this
2200 // method is an instance initializer.
2201 bool initialize_stack ()
2204 bool is_init
= _Jv_equalUtf8Consts (current_method
->self
->name
,
2206 bool is_clinit
= _Jv_equalUtf8Consts (current_method
->self
->name
,
2209 using namespace java::lang::reflect
;
2210 if (! Modifier::isStatic (current_method
->self
->accflags
))
2212 type
kurr (current_class
, this);
2215 kurr
.set_uninitialized (type::SELF
, this);
2219 verify_fail ("<clinit> method must be static");
2220 set_variable (0, kurr
);
2221 current_state
->set_this_type (kurr
);
2227 verify_fail ("<init> method must be non-static");
2230 // We have to handle wide arguments specially here.
2231 int arg_count
= _Jv_count_arguments (current_method
->self
->signature
);
2232 type arg_types
[arg_count
];
2233 compute_argument_types (current_method
->self
->signature
, arg_types
);
2234 for (int i
= 0; i
< arg_count
; ++i
)
2236 set_variable (var
, arg_types
[i
]);
2238 if (arg_types
[i
].iswide ())
2245 void verify_instructions_0 ()
2247 current_state
= new state (current_method
->max_stack
,
2248 current_method
->max_locals
);
2253 // True if we are verifying an instance initializer.
2254 bool this_is_init
= initialize_stack ();
2256 states
= (linked
<state
> **) _Jv_Malloc (sizeof (linked
<state
> *)
2257 * current_method
->code_length
);
2258 for (int i
= 0; i
< current_method
->code_length
; ++i
)
2261 next_verify_state
= NULL
;
2265 // If the PC was invalidated, get a new one from the work list.
2266 if (PC
== state::NO_NEXT
)
2268 state
*new_state
= pop_jump ();
2269 // If it is null, we're done.
2270 if (new_state
== NULL
)
2273 PC
= new_state
->get_pc ();
2274 debug_print ("== State pop from pending list\n");
2275 // Set up the current state.
2276 current_state
->copy (new_state
, current_method
->max_stack
,
2277 current_method
->max_locals
);
2281 // We only have to do this checking in the situation where
2282 // control flow falls through from the previous
2283 // instruction. Otherwise merging is done at the time we
2284 // push the branch. Note that we'll catch the
2285 // off-the-end problem just below.
2286 if (PC
< current_method
->code_length
&& states
[PC
] != NULL
)
2288 // We've already visited this instruction. So merge
2289 // the states together. It is simplest, but not most
2290 // efficient, to just always invalidate the PC here.
2291 merge_into (PC
, current_state
);
2297 // Control can't fall off the end of the bytecode. We need to
2298 // check this in both cases, not just the fall-through case,
2299 // because we don't check to see whether a `jsr' appears at
2300 // the end of the bytecode until we process a `ret'.
2301 if (PC
>= current_method
->code_length
)
2302 verify_fail ("fell off end");
2304 // We only have to keep saved state at branch targets. If
2305 // we're at a branch target and the state here hasn't been set
2306 // yet, we set it now. You might notice that `ret' targets
2307 // won't necessarily have FLAG_BRANCH_TARGET set. This
2308 // doesn't matter, since those states will be filled in by
2310 if (states
[PC
] == NULL
&& (flags
[PC
] & FLAG_BRANCH_TARGET
))
2311 add_new_state (PC
, current_state
);
2313 // Set this before handling exceptions so that debug output is
2317 // Update states for all active exception handlers. Ordinarily
2318 // there are not many exception handlers. So we simply run
2319 // through them all.
2320 for (int i
= 0; i
< current_method
->exc_count
; ++i
)
2322 if (PC
>= exception
[i
].start_pc
.i
&& PC
< exception
[i
].end_pc
.i
)
2324 type
handler (&java::lang::Throwable::class$
, this);
2325 if (exception
[i
].handler_type
.i
!= 0)
2326 handler
= check_class_constant (exception
[i
].handler_type
.i
);
2327 push_exception_jump (handler
, exception
[i
].handler_pc
.i
);
2331 current_state
->print (" ", PC
, current_method
->max_stack
,
2332 current_method
->max_locals
);
2333 java_opcode opcode
= (java_opcode
) bytecode
[PC
++];
2339 case op_aconst_null
:
2340 push_type (null_type
);
2350 push_type (int_type
);
2355 push_type (long_type
);
2361 push_type (float_type
);
2366 push_type (double_type
);
2371 push_type (int_type
);
2376 push_type (int_type
);
2380 push_type (check_constant (get_byte ()));
2383 push_type (check_constant (get_ushort ()));
2386 push_type (check_wide_constant (get_ushort ()));
2390 push_type (get_variable (get_byte (), int_type
));
2393 push_type (get_variable (get_byte (), long_type
));
2396 push_type (get_variable (get_byte (), float_type
));
2399 push_type (get_variable (get_byte (), double_type
));
2402 push_type (get_variable (get_byte (), reference_type
));
2409 push_type (get_variable (opcode
- op_iload_0
, int_type
));
2415 push_type (get_variable (opcode
- op_lload_0
, long_type
));
2421 push_type (get_variable (opcode
- op_fload_0
, float_type
));
2427 push_type (get_variable (opcode
- op_dload_0
, double_type
));
2433 push_type (get_variable (opcode
- op_aload_0
, reference_type
));
2436 pop_type (int_type
);
2437 push_type (require_array_type (pop_init_ref (reference_type
),
2441 pop_type (int_type
);
2442 push_type (require_array_type (pop_init_ref (reference_type
),
2446 pop_type (int_type
);
2447 push_type (require_array_type (pop_init_ref (reference_type
),
2451 pop_type (int_type
);
2452 push_type (require_array_type (pop_init_ref (reference_type
),
2456 pop_type (int_type
);
2457 push_type (require_array_type (pop_init_ref (reference_type
),
2461 pop_type (int_type
);
2462 require_array_type (pop_init_ref (reference_type
), byte_type
);
2463 push_type (int_type
);
2466 pop_type (int_type
);
2467 require_array_type (pop_init_ref (reference_type
), char_type
);
2468 push_type (int_type
);
2471 pop_type (int_type
);
2472 require_array_type (pop_init_ref (reference_type
), short_type
);
2473 push_type (int_type
);
2476 set_variable (get_byte (), pop_type (int_type
));
2479 set_variable (get_byte (), pop_type (long_type
));
2482 set_variable (get_byte (), pop_type (float_type
));
2485 set_variable (get_byte (), pop_type (double_type
));
2488 set_variable (get_byte (), pop_ref_or_return ());
2494 set_variable (opcode
- op_istore_0
, pop_type (int_type
));
2500 set_variable (opcode
- op_lstore_0
, pop_type (long_type
));
2506 set_variable (opcode
- op_fstore_0
, pop_type (float_type
));
2512 set_variable (opcode
- op_dstore_0
, pop_type (double_type
));
2518 set_variable (opcode
- op_astore_0
, pop_ref_or_return ());
2521 pop_type (int_type
);
2522 pop_type (int_type
);
2523 require_array_type (pop_init_ref (reference_type
), int_type
);
2526 pop_type (long_type
);
2527 pop_type (int_type
);
2528 require_array_type (pop_init_ref (reference_type
), long_type
);
2531 pop_type (float_type
);
2532 pop_type (int_type
);
2533 require_array_type (pop_init_ref (reference_type
), float_type
);
2536 pop_type (double_type
);
2537 pop_type (int_type
);
2538 require_array_type (pop_init_ref (reference_type
), double_type
);
2541 pop_type (reference_type
);
2542 pop_type (int_type
);
2543 require_array_type (pop_init_ref (reference_type
), reference_type
);
2546 pop_type (int_type
);
2547 pop_type (int_type
);
2548 require_array_type (pop_init_ref (reference_type
), byte_type
);
2551 pop_type (int_type
);
2552 pop_type (int_type
);
2553 require_array_type (pop_init_ref (reference_type
), char_type
);
2556 pop_type (int_type
);
2557 pop_type (int_type
);
2558 require_array_type (pop_init_ref (reference_type
), short_type
);
2565 type t
= pop_raw ();
2589 type t2
= pop_raw ();
2604 type t
= pop_raw ();
2619 type t1
= pop_raw ();
2636 type t1
= pop_raw ();
2639 type t2
= pop_raw ();
2657 type t3
= pop_raw ();
2695 pop_type (int_type
);
2696 push_type (pop_type (int_type
));
2706 pop_type (long_type
);
2707 push_type (pop_type (long_type
));
2712 pop_type (int_type
);
2713 push_type (pop_type (long_type
));
2720 pop_type (float_type
);
2721 push_type (pop_type (float_type
));
2728 pop_type (double_type
);
2729 push_type (pop_type (double_type
));
2735 push_type (pop_type (int_type
));
2738 push_type (pop_type (long_type
));
2741 push_type (pop_type (float_type
));
2744 push_type (pop_type (double_type
));
2747 get_variable (get_byte (), int_type
);
2751 pop_type (int_type
);
2752 push_type (long_type
);
2755 pop_type (int_type
);
2756 push_type (float_type
);
2759 pop_type (int_type
);
2760 push_type (double_type
);
2763 pop_type (long_type
);
2764 push_type (int_type
);
2767 pop_type (long_type
);
2768 push_type (float_type
);
2771 pop_type (long_type
);
2772 push_type (double_type
);
2775 pop_type (float_type
);
2776 push_type (int_type
);
2779 pop_type (float_type
);
2780 push_type (long_type
);
2783 pop_type (float_type
);
2784 push_type (double_type
);
2787 pop_type (double_type
);
2788 push_type (int_type
);
2791 pop_type (double_type
);
2792 push_type (long_type
);
2795 pop_type (double_type
);
2796 push_type (float_type
);
2799 pop_type (long_type
);
2800 pop_type (long_type
);
2801 push_type (int_type
);
2805 pop_type (float_type
);
2806 pop_type (float_type
);
2807 push_type (int_type
);
2811 pop_type (double_type
);
2812 pop_type (double_type
);
2813 push_type (int_type
);
2821 pop_type (int_type
);
2822 push_jump (get_short ());
2830 pop_type (int_type
);
2831 pop_type (int_type
);
2832 push_jump (get_short ());
2836 pop_type (reference_type
);
2837 pop_type (reference_type
);
2838 push_jump (get_short ());
2841 push_jump (get_short ());
2845 handle_jsr_insn (get_short ());
2848 handle_ret_insn (get_byte ());
2850 case op_tableswitch
:
2852 pop_type (int_type
);
2854 push_jump (get_int ());
2855 jint low
= get_int ();
2856 jint high
= get_int ();
2857 // Already checked LOW -vs- HIGH.
2858 for (int i
= low
; i
<= high
; ++i
)
2859 push_jump (get_int ());
2864 case op_lookupswitch
:
2866 pop_type (int_type
);
2868 push_jump (get_int ());
2869 jint npairs
= get_int ();
2870 // Already checked NPAIRS >= 0.
2872 for (int i
= 0; i
< npairs
; ++i
)
2874 jint key
= get_int ();
2875 if (i
> 0 && key
<= lastkey
)
2876 verify_fail ("lookupswitch pairs unsorted", start_PC
);
2878 push_jump (get_int ());
2884 check_return_type (pop_type (int_type
));
2888 check_return_type (pop_type (long_type
));
2892 check_return_type (pop_type (float_type
));
2896 check_return_type (pop_type (double_type
));
2900 check_return_type (pop_init_ref (reference_type
));
2904 // We only need to check this when the return type is
2905 // void, because all instance initializers return void.
2907 current_state
->check_this_initialized (this);
2908 check_return_type (void_type
);
2912 push_type (check_field_constant (get_ushort ()));
2915 pop_type (check_field_constant (get_ushort ()));
2920 type field
= check_field_constant (get_ushort (), &klass
);
2928 type field
= check_field_constant (get_ushort (), &klass
, true);
2934 case op_invokevirtual
:
2935 case op_invokespecial
:
2936 case op_invokestatic
:
2937 case op_invokeinterface
:
2939 _Jv_Utf8Const
*method_name
, *method_signature
;
2941 = check_method_constant (get_ushort (),
2942 opcode
== op_invokeinterface
,
2945 // NARGS is only used when we're processing
2946 // invokeinterface. It is simplest for us to compute it
2947 // here and then verify it later.
2949 if (opcode
== op_invokeinterface
)
2951 nargs
= get_byte ();
2952 if (get_byte () != 0)
2953 verify_fail ("invokeinterface dummy byte is wrong");
2956 bool is_init
= false;
2957 if (_Jv_equalUtf8Consts (method_name
, gcj::init_name
))
2960 if (opcode
!= op_invokespecial
)
2961 verify_fail ("can't invoke <init>");
2963 else if (method_name
->first() == '<')
2964 verify_fail ("can't invoke method starting with `<'");
2966 // Pop arguments and check types.
2967 int arg_count
= _Jv_count_arguments (method_signature
);
2968 type arg_types
[arg_count
];
2969 compute_argument_types (method_signature
, arg_types
);
2970 for (int i
= arg_count
- 1; i
>= 0; --i
)
2972 // This is only used for verifying the byte for
2974 nargs
-= arg_types
[i
].depth ();
2975 pop_init_ref (arg_types
[i
]);
2978 if (opcode
== op_invokeinterface
2980 verify_fail ("wrong argument count for invokeinterface");
2982 if (opcode
!= op_invokestatic
)
2984 type t
= class_type
;
2987 // In this case the PC doesn't matter.
2988 t
.set_uninitialized (type::UNINIT
, this);
2989 // FIXME: check to make sure that the <init>
2990 // call is to the right class.
2991 // It must either be super or an exact class
2994 type raw
= pop_raw ();
2995 if (! t
.compatible (raw
, this))
2996 verify_fail ("incompatible type on stack");
2999 current_state
->set_initialized (raw
.get_pc (),
3000 current_method
->max_locals
);
3003 type rt
= compute_return_type (method_signature
);
3011 type t
= check_class_constant (get_ushort ());
3013 verify_fail ("type is array");
3014 t
.set_uninitialized (start_PC
, this);
3021 int atype
= get_byte ();
3022 // We intentionally have chosen constants to make this
3024 if (atype
< boolean_type
|| atype
> long_type
)
3025 verify_fail ("type not primitive", start_PC
);
3026 pop_type (int_type
);
3027 type
t (construct_primitive_array_type (type_val (atype
)), this);
3032 pop_type (int_type
);
3033 push_type (check_class_constant (get_ushort ()).to_array (this));
3035 case op_arraylength
:
3037 type t
= pop_init_ref (reference_type
);
3038 if (! t
.isarray () && ! t
.isnull ())
3039 verify_fail ("array type expected");
3040 push_type (int_type
);
3044 pop_type (type (&java::lang::Throwable::class$
, this));
3048 pop_init_ref (reference_type
);
3049 push_type (check_class_constant (get_ushort ()));
3052 pop_init_ref (reference_type
);
3053 check_class_constant (get_ushort ());
3054 push_type (int_type
);
3056 case op_monitorenter
:
3057 pop_init_ref (reference_type
);
3059 case op_monitorexit
:
3060 pop_init_ref (reference_type
);
3064 switch (get_byte ())
3067 push_type (get_variable (get_ushort (), int_type
));
3070 push_type (get_variable (get_ushort (), long_type
));
3073 push_type (get_variable (get_ushort (), float_type
));
3076 push_type (get_variable (get_ushort (), double_type
));
3079 push_type (get_variable (get_ushort (), reference_type
));
3082 set_variable (get_ushort (), pop_type (int_type
));
3085 set_variable (get_ushort (), pop_type (long_type
));
3088 set_variable (get_ushort (), pop_type (float_type
));
3091 set_variable (get_ushort (), pop_type (double_type
));
3094 set_variable (get_ushort (), pop_init_ref (reference_type
));
3097 handle_ret_insn (get_short ());
3100 get_variable (get_ushort (), int_type
);
3104 verify_fail ("unrecognized wide instruction", start_PC
);
3108 case op_multianewarray
:
3110 type atype
= check_class_constant (get_ushort ());
3111 int dim
= get_byte ();
3113 verify_fail ("too few dimensions to multianewarray", start_PC
);
3114 atype
.verify_dimensions (dim
, this);
3115 for (int i
= 0; i
< dim
; ++i
)
3116 pop_type (int_type
);
3122 pop_type (reference_type
);
3123 push_jump (get_short ());
3126 push_jump (get_int ());
3130 handle_jsr_insn (get_int ());
3133 // These are unused here, but we call them out explicitly
3134 // so that -Wswitch-enum doesn't complain.
3140 case op_putstatic_1
:
3141 case op_putstatic_2
:
3142 case op_putstatic_4
:
3143 case op_putstatic_8
:
3144 case op_putstatic_a
:
3146 case op_getfield_2s
:
3147 case op_getfield_2u
:
3151 case op_getstatic_1
:
3152 case op_getstatic_2s
:
3153 case op_getstatic_2u
:
3154 case op_getstatic_4
:
3155 case op_getstatic_8
:
3156 case op_getstatic_a
:
3159 // Unrecognized opcode.
3160 verify_fail ("unrecognized instruction in verify_instructions_0",
3168 void verify_instructions ()
3171 verify_instructions_0 ();
3174 _Jv_BytecodeVerifier (_Jv_InterpMethod
*m
)
3176 // We just print the text as utf-8. This is just for debugging
3178 debug_print ("--------------------------------\n");
3179 debug_print ("-- Verifying method `%s'\n", m
->self
->name
->chars());
3182 bytecode
= m
->bytecode ();
3183 exception
= m
->exceptions ();
3184 current_class
= m
->defining_class
;
3192 ~_Jv_BytecodeVerifier ()
3197 while (utf8_list
!= NULL
)
3199 linked
<_Jv_Utf8Const
> *n
= utf8_list
->next
;
3200 _Jv_Free (utf8_list
);
3204 while (isect_list
!= NULL
)
3206 ref_intersection
*next
= isect_list
->alloc_next
;
3213 for (int i
= 0; i
< current_method
->code_length
; ++i
)
3215 linked
<state
> *iter
= states
[i
];
3216 while (iter
!= NULL
)
3218 linked
<state
> *next
= iter
->next
;
3230 _Jv_VerifyMethod (_Jv_InterpMethod
*meth
)
3232 _Jv_BytecodeVerifier
v (meth
);
3233 v
.verify_instructions ();
3236 #endif /* INTERPRETER */