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.
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
:
1980 verify_fail ("unrecognized instruction in branch_prepass",
1984 // See if any previous branch tried to branch to the middle of
1985 // this instruction.
1986 for (int pc
= start_PC
+ 1; pc
< PC
; ++pc
)
1988 if ((flags
[pc
] & FLAG_BRANCH_TARGET
))
1989 verify_fail ("branch to middle of instruction", pc
);
1993 // Verify exception handlers.
1994 for (int i
= 0; i
< current_method
->exc_count
; ++i
)
1996 if (! (flags
[exception
[i
].handler_pc
.i
] & FLAG_INSN_START
))
1997 verify_fail ("exception handler not at instruction start",
1998 exception
[i
].handler_pc
.i
);
1999 if (! (flags
[exception
[i
].start_pc
.i
] & FLAG_INSN_START
))
2000 verify_fail ("exception start not at instruction start",
2001 exception
[i
].start_pc
.i
);
2002 if (exception
[i
].end_pc
.i
!= current_method
->code_length
2003 && ! (flags
[exception
[i
].end_pc
.i
] & FLAG_INSN_START
))
2004 verify_fail ("exception end not at instruction start",
2005 exception
[i
].end_pc
.i
);
2007 flags
[exception
[i
].handler_pc
.i
] |= FLAG_BRANCH_TARGET
;
2011 void check_pool_index (int index
)
2013 if (index
< 0 || index
>= current_class
->constants
.size
)
2014 verify_fail ("constant pool index out of range", start_PC
);
2017 type
check_class_constant (int index
)
2019 check_pool_index (index
);
2020 _Jv_Constants
*pool
= ¤t_class
->constants
;
2021 if (pool
->tags
[index
] == JV_CONSTANT_ResolvedClass
)
2022 return type (pool
->data
[index
].clazz
, this);
2023 else if (pool
->tags
[index
] == JV_CONSTANT_Class
)
2024 return type (pool
->data
[index
].utf8
, this);
2025 verify_fail ("expected class constant", start_PC
);
2028 type
check_constant (int index
)
2030 check_pool_index (index
);
2031 _Jv_Constants
*pool
= ¤t_class
->constants
;
2032 int tag
= pool
->tags
[index
];
2033 if (tag
== JV_CONSTANT_ResolvedString
|| tag
== JV_CONSTANT_String
)
2034 return type (&java::lang::String::class$
, this);
2035 else if (tag
== JV_CONSTANT_Integer
)
2036 return type (int_type
);
2037 else if (tag
== JV_CONSTANT_Float
)
2038 return type (float_type
);
2039 else if (current_method
->is_15
2040 && (tag
== JV_CONSTANT_ResolvedClass
|| tag
== JV_CONSTANT_Class
))
2041 return type (&java::lang::Class::class$
, this);
2042 verify_fail ("String, int, or float constant expected", start_PC
);
2045 type
check_wide_constant (int index
)
2047 check_pool_index (index
);
2048 _Jv_Constants
*pool
= ¤t_class
->constants
;
2049 if (pool
->tags
[index
] == JV_CONSTANT_Long
)
2050 return type (long_type
);
2051 else if (pool
->tags
[index
] == JV_CONSTANT_Double
)
2052 return type (double_type
);
2053 verify_fail ("long or double constant expected", start_PC
);
2056 // Helper for both field and method. These are laid out the same in
2057 // the constant pool.
2058 type
handle_field_or_method (int index
, int expected
,
2059 _Jv_Utf8Const
**name
,
2060 _Jv_Utf8Const
**fmtype
)
2062 check_pool_index (index
);
2063 _Jv_Constants
*pool
= ¤t_class
->constants
;
2064 if (pool
->tags
[index
] != expected
)
2065 verify_fail ("didn't see expected constant", start_PC
);
2066 // Once we know we have a Fieldref or Methodref we assume that it
2067 // is correctly laid out in the constant pool. I think the code
2068 // in defineclass.cc guarantees this.
2069 _Jv_ushort class_index
, name_and_type_index
;
2070 _Jv_loadIndexes (&pool
->data
[index
],
2072 name_and_type_index
);
2073 _Jv_ushort name_index
, desc_index
;
2074 _Jv_loadIndexes (&pool
->data
[name_and_type_index
],
2075 name_index
, desc_index
);
2077 *name
= pool
->data
[name_index
].utf8
;
2078 *fmtype
= pool
->data
[desc_index
].utf8
;
2080 return check_class_constant (class_index
);
2083 // Return field's type, compute class' type if requested.
2084 // If PUTFIELD is true, use the special 'putfield' semantics.
2085 type
check_field_constant (int index
, type
*class_type
= NULL
,
2086 bool putfield
= false)
2088 _Jv_Utf8Const
*name
, *field_type
;
2089 type ct
= handle_field_or_method (index
,
2090 JV_CONSTANT_Fieldref
,
2091 &name
, &field_type
);
2095 if (field_type
->first() == '[' || field_type
->first() == 'L')
2096 result
= type (field_type
, this);
2098 result
= get_type_val_for_signature (field_type
->first());
2100 // We have an obscure special case here: we can use `putfield' on
2101 // a field declared in this class, even if `this' has not yet been
2104 && ! current_state
->this_type
.isinitialized ()
2105 && current_state
->this_type
.pc
== type::SELF
2106 && current_state
->this_type
.equals (ct
, this)
2107 // We don't look at the signature, figuring that if it is
2108 // wrong we will fail during linking. FIXME?
2109 && _Jv_Linker::has_field_p (current_class
, name
))
2110 // Note that we don't actually know whether we're going to match
2111 // against 'this' or some other object of the same type. So,
2112 // here we set things up so that it doesn't matter. This relies
2113 // on knowing what our caller is up to.
2114 class_type
->set_uninitialized (type::EITHER
, this);
2119 type
check_method_constant (int index
, bool is_interface
,
2120 _Jv_Utf8Const
**method_name
,
2121 _Jv_Utf8Const
**method_signature
)
2123 return handle_field_or_method (index
,
2125 ? JV_CONSTANT_InterfaceMethodref
2126 : JV_CONSTANT_Methodref
),
2127 method_name
, method_signature
);
2130 type
get_one_type (char *&p
)
2148 _Jv_Utf8Const
*name
= make_utf8_const (start
, p
- start
);
2149 return type (name
, this);
2152 // Casting to jchar here is ok since we are looking at an ASCII
2154 type_val rt
= get_type_val_for_signature (jchar (v
));
2156 if (arraycount
== 0)
2158 // Callers of this function eventually push their arguments on
2159 // the stack. So, promote them here.
2160 return type (rt
).promote ();
2163 jclass k
= construct_primitive_array_type (rt
);
2164 while (--arraycount
> 0)
2165 k
= _Jv_GetArrayClass (k
, NULL
);
2166 return type (k
, this);
2169 void compute_argument_types (_Jv_Utf8Const
*signature
,
2172 char *p
= signature
->chars();
2179 types
[i
++] = get_one_type (p
);
2182 type
compute_return_type (_Jv_Utf8Const
*signature
)
2184 char *p
= signature
->chars();
2188 return get_one_type (p
);
2191 void check_return_type (type onstack
)
2193 type rt
= compute_return_type (current_method
->self
->signature
);
2194 if (! rt
.compatible (onstack
, this))
2195 verify_fail ("incompatible return type");
2198 // Initialize the stack for the new method. Returns true if this
2199 // method is an instance initializer.
2200 bool initialize_stack ()
2203 bool is_init
= _Jv_equalUtf8Consts (current_method
->self
->name
,
2205 bool is_clinit
= _Jv_equalUtf8Consts (current_method
->self
->name
,
2208 using namespace java::lang::reflect
;
2209 if (! Modifier::isStatic (current_method
->self
->accflags
))
2211 type
kurr (current_class
, this);
2214 kurr
.set_uninitialized (type::SELF
, this);
2218 verify_fail ("<clinit> method must be static");
2219 set_variable (0, kurr
);
2220 current_state
->set_this_type (kurr
);
2226 verify_fail ("<init> method must be non-static");
2229 // We have to handle wide arguments specially here.
2230 int arg_count
= _Jv_count_arguments (current_method
->self
->signature
);
2231 type arg_types
[arg_count
];
2232 compute_argument_types (current_method
->self
->signature
, arg_types
);
2233 for (int i
= 0; i
< arg_count
; ++i
)
2235 set_variable (var
, arg_types
[i
]);
2237 if (arg_types
[i
].iswide ())
2244 void verify_instructions_0 ()
2246 current_state
= new state (current_method
->max_stack
,
2247 current_method
->max_locals
);
2252 // True if we are verifying an instance initializer.
2253 bool this_is_init
= initialize_stack ();
2255 states
= (linked
<state
> **) _Jv_Malloc (sizeof (linked
<state
> *)
2256 * current_method
->code_length
);
2257 for (int i
= 0; i
< current_method
->code_length
; ++i
)
2260 next_verify_state
= NULL
;
2264 // If the PC was invalidated, get a new one from the work list.
2265 if (PC
== state::NO_NEXT
)
2267 state
*new_state
= pop_jump ();
2268 // If it is null, we're done.
2269 if (new_state
== NULL
)
2272 PC
= new_state
->get_pc ();
2273 debug_print ("== State pop from pending list\n");
2274 // Set up the current state.
2275 current_state
->copy (new_state
, current_method
->max_stack
,
2276 current_method
->max_locals
);
2280 // We only have to do this checking in the situation where
2281 // control flow falls through from the previous
2282 // instruction. Otherwise merging is done at the time we
2283 // push the branch. Note that we'll catch the
2284 // off-the-end problem just below.
2285 if (PC
< current_method
->code_length
&& states
[PC
] != NULL
)
2287 // We've already visited this instruction. So merge
2288 // the states together. It is simplest, but not most
2289 // efficient, to just always invalidate the PC here.
2290 merge_into (PC
, current_state
);
2296 // Control can't fall off the end of the bytecode. We need to
2297 // check this in both cases, not just the fall-through case,
2298 // because we don't check to see whether a `jsr' appears at
2299 // the end of the bytecode until we process a `ret'.
2300 if (PC
>= current_method
->code_length
)
2301 verify_fail ("fell off end");
2303 // We only have to keep saved state at branch targets. If
2304 // we're at a branch target and the state here hasn't been set
2305 // yet, we set it now. You might notice that `ret' targets
2306 // won't necessarily have FLAG_BRANCH_TARGET set. This
2307 // doesn't matter, since those states will be filled in by
2309 if (states
[PC
] == NULL
&& (flags
[PC
] & FLAG_BRANCH_TARGET
))
2310 add_new_state (PC
, current_state
);
2312 // Set this before handling exceptions so that debug output is
2316 // Update states for all active exception handlers. Ordinarily
2317 // there are not many exception handlers. So we simply run
2318 // through them all.
2319 for (int i
= 0; i
< current_method
->exc_count
; ++i
)
2321 if (PC
>= exception
[i
].start_pc
.i
&& PC
< exception
[i
].end_pc
.i
)
2323 type
handler (&java::lang::Throwable::class$
, this);
2324 if (exception
[i
].handler_type
.i
!= 0)
2325 handler
= check_class_constant (exception
[i
].handler_type
.i
);
2326 push_exception_jump (handler
, exception
[i
].handler_pc
.i
);
2330 current_state
->print (" ", PC
, current_method
->max_stack
,
2331 current_method
->max_locals
);
2332 java_opcode opcode
= (java_opcode
) bytecode
[PC
++];
2338 case op_aconst_null
:
2339 push_type (null_type
);
2349 push_type (int_type
);
2354 push_type (long_type
);
2360 push_type (float_type
);
2365 push_type (double_type
);
2370 push_type (int_type
);
2375 push_type (int_type
);
2379 push_type (check_constant (get_byte ()));
2382 push_type (check_constant (get_ushort ()));
2385 push_type (check_wide_constant (get_ushort ()));
2389 push_type (get_variable (get_byte (), int_type
));
2392 push_type (get_variable (get_byte (), long_type
));
2395 push_type (get_variable (get_byte (), float_type
));
2398 push_type (get_variable (get_byte (), double_type
));
2401 push_type (get_variable (get_byte (), reference_type
));
2408 push_type (get_variable (opcode
- op_iload_0
, int_type
));
2414 push_type (get_variable (opcode
- op_lload_0
, long_type
));
2420 push_type (get_variable (opcode
- op_fload_0
, float_type
));
2426 push_type (get_variable (opcode
- op_dload_0
, double_type
));
2432 push_type (get_variable (opcode
- op_aload_0
, reference_type
));
2435 pop_type (int_type
);
2436 push_type (require_array_type (pop_init_ref (reference_type
),
2440 pop_type (int_type
);
2441 push_type (require_array_type (pop_init_ref (reference_type
),
2445 pop_type (int_type
);
2446 push_type (require_array_type (pop_init_ref (reference_type
),
2450 pop_type (int_type
);
2451 push_type (require_array_type (pop_init_ref (reference_type
),
2455 pop_type (int_type
);
2456 push_type (require_array_type (pop_init_ref (reference_type
),
2460 pop_type (int_type
);
2461 require_array_type (pop_init_ref (reference_type
), byte_type
);
2462 push_type (int_type
);
2465 pop_type (int_type
);
2466 require_array_type (pop_init_ref (reference_type
), char_type
);
2467 push_type (int_type
);
2470 pop_type (int_type
);
2471 require_array_type (pop_init_ref (reference_type
), short_type
);
2472 push_type (int_type
);
2475 set_variable (get_byte (), pop_type (int_type
));
2478 set_variable (get_byte (), pop_type (long_type
));
2481 set_variable (get_byte (), pop_type (float_type
));
2484 set_variable (get_byte (), pop_type (double_type
));
2487 set_variable (get_byte (), pop_ref_or_return ());
2493 set_variable (opcode
- op_istore_0
, pop_type (int_type
));
2499 set_variable (opcode
- op_lstore_0
, pop_type (long_type
));
2505 set_variable (opcode
- op_fstore_0
, pop_type (float_type
));
2511 set_variable (opcode
- op_dstore_0
, pop_type (double_type
));
2517 set_variable (opcode
- op_astore_0
, pop_ref_or_return ());
2520 pop_type (int_type
);
2521 pop_type (int_type
);
2522 require_array_type (pop_init_ref (reference_type
), int_type
);
2525 pop_type (long_type
);
2526 pop_type (int_type
);
2527 require_array_type (pop_init_ref (reference_type
), long_type
);
2530 pop_type (float_type
);
2531 pop_type (int_type
);
2532 require_array_type (pop_init_ref (reference_type
), float_type
);
2535 pop_type (double_type
);
2536 pop_type (int_type
);
2537 require_array_type (pop_init_ref (reference_type
), double_type
);
2540 pop_type (reference_type
);
2541 pop_type (int_type
);
2542 require_array_type (pop_init_ref (reference_type
), reference_type
);
2545 pop_type (int_type
);
2546 pop_type (int_type
);
2547 require_array_type (pop_init_ref (reference_type
), byte_type
);
2550 pop_type (int_type
);
2551 pop_type (int_type
);
2552 require_array_type (pop_init_ref (reference_type
), char_type
);
2555 pop_type (int_type
);
2556 pop_type (int_type
);
2557 require_array_type (pop_init_ref (reference_type
), short_type
);
2564 type t
= pop_raw ();
2588 type t2
= pop_raw ();
2603 type t
= pop_raw ();
2618 type t1
= pop_raw ();
2635 type t1
= pop_raw ();
2638 type t2
= pop_raw ();
2656 type t3
= pop_raw ();
2694 pop_type (int_type
);
2695 push_type (pop_type (int_type
));
2705 pop_type (long_type
);
2706 push_type (pop_type (long_type
));
2711 pop_type (int_type
);
2712 push_type (pop_type (long_type
));
2719 pop_type (float_type
);
2720 push_type (pop_type (float_type
));
2727 pop_type (double_type
);
2728 push_type (pop_type (double_type
));
2734 push_type (pop_type (int_type
));
2737 push_type (pop_type (long_type
));
2740 push_type (pop_type (float_type
));
2743 push_type (pop_type (double_type
));
2746 get_variable (get_byte (), int_type
);
2750 pop_type (int_type
);
2751 push_type (long_type
);
2754 pop_type (int_type
);
2755 push_type (float_type
);
2758 pop_type (int_type
);
2759 push_type (double_type
);
2762 pop_type (long_type
);
2763 push_type (int_type
);
2766 pop_type (long_type
);
2767 push_type (float_type
);
2770 pop_type (long_type
);
2771 push_type (double_type
);
2774 pop_type (float_type
);
2775 push_type (int_type
);
2778 pop_type (float_type
);
2779 push_type (long_type
);
2782 pop_type (float_type
);
2783 push_type (double_type
);
2786 pop_type (double_type
);
2787 push_type (int_type
);
2790 pop_type (double_type
);
2791 push_type (long_type
);
2794 pop_type (double_type
);
2795 push_type (float_type
);
2798 pop_type (long_type
);
2799 pop_type (long_type
);
2800 push_type (int_type
);
2804 pop_type (float_type
);
2805 pop_type (float_type
);
2806 push_type (int_type
);
2810 pop_type (double_type
);
2811 pop_type (double_type
);
2812 push_type (int_type
);
2820 pop_type (int_type
);
2821 push_jump (get_short ());
2829 pop_type (int_type
);
2830 pop_type (int_type
);
2831 push_jump (get_short ());
2835 pop_type (reference_type
);
2836 pop_type (reference_type
);
2837 push_jump (get_short ());
2840 push_jump (get_short ());
2844 handle_jsr_insn (get_short ());
2847 handle_ret_insn (get_byte ());
2849 case op_tableswitch
:
2851 pop_type (int_type
);
2853 push_jump (get_int ());
2854 jint low
= get_int ();
2855 jint high
= get_int ();
2856 // Already checked LOW -vs- HIGH.
2857 for (int i
= low
; i
<= high
; ++i
)
2858 push_jump (get_int ());
2863 case op_lookupswitch
:
2865 pop_type (int_type
);
2867 push_jump (get_int ());
2868 jint npairs
= get_int ();
2869 // Already checked NPAIRS >= 0.
2871 for (int i
= 0; i
< npairs
; ++i
)
2873 jint key
= get_int ();
2874 if (i
> 0 && key
<= lastkey
)
2875 verify_fail ("lookupswitch pairs unsorted", start_PC
);
2877 push_jump (get_int ());
2883 check_return_type (pop_type (int_type
));
2887 check_return_type (pop_type (long_type
));
2891 check_return_type (pop_type (float_type
));
2895 check_return_type (pop_type (double_type
));
2899 check_return_type (pop_init_ref (reference_type
));
2903 // We only need to check this when the return type is
2904 // void, because all instance initializers return void.
2906 current_state
->check_this_initialized (this);
2907 check_return_type (void_type
);
2911 push_type (check_field_constant (get_ushort ()));
2914 pop_type (check_field_constant (get_ushort ()));
2919 type field
= check_field_constant (get_ushort (), &klass
);
2927 type field
= check_field_constant (get_ushort (), &klass
, true);
2933 case op_invokevirtual
:
2934 case op_invokespecial
:
2935 case op_invokestatic
:
2936 case op_invokeinterface
:
2938 _Jv_Utf8Const
*method_name
, *method_signature
;
2940 = check_method_constant (get_ushort (),
2941 opcode
== op_invokeinterface
,
2944 // NARGS is only used when we're processing
2945 // invokeinterface. It is simplest for us to compute it
2946 // here and then verify it later.
2948 if (opcode
== op_invokeinterface
)
2950 nargs
= get_byte ();
2951 if (get_byte () != 0)
2952 verify_fail ("invokeinterface dummy byte is wrong");
2955 bool is_init
= false;
2956 if (_Jv_equalUtf8Consts (method_name
, gcj::init_name
))
2959 if (opcode
!= op_invokespecial
)
2960 verify_fail ("can't invoke <init>");
2962 else if (method_name
->first() == '<')
2963 verify_fail ("can't invoke method starting with `<'");
2965 // Pop arguments and check types.
2966 int arg_count
= _Jv_count_arguments (method_signature
);
2967 type arg_types
[arg_count
];
2968 compute_argument_types (method_signature
, arg_types
);
2969 for (int i
= arg_count
- 1; i
>= 0; --i
)
2971 // This is only used for verifying the byte for
2973 nargs
-= arg_types
[i
].depth ();
2974 pop_init_ref (arg_types
[i
]);
2977 if (opcode
== op_invokeinterface
2979 verify_fail ("wrong argument count for invokeinterface");
2981 if (opcode
!= op_invokestatic
)
2983 type t
= class_type
;
2986 // In this case the PC doesn't matter.
2987 t
.set_uninitialized (type::UNINIT
, this);
2988 // FIXME: check to make sure that the <init>
2989 // call is to the right class.
2990 // It must either be super or an exact class
2993 type raw
= pop_raw ();
2994 if (! t
.compatible (raw
, this))
2995 verify_fail ("incompatible type on stack");
2998 current_state
->set_initialized (raw
.get_pc (),
2999 current_method
->max_locals
);
3002 type rt
= compute_return_type (method_signature
);
3010 type t
= check_class_constant (get_ushort ());
3012 verify_fail ("type is array");
3013 t
.set_uninitialized (start_PC
, this);
3020 int atype
= get_byte ();
3021 // We intentionally have chosen constants to make this
3023 if (atype
< boolean_type
|| atype
> long_type
)
3024 verify_fail ("type not primitive", start_PC
);
3025 pop_type (int_type
);
3026 type
t (construct_primitive_array_type (type_val (atype
)), this);
3031 pop_type (int_type
);
3032 push_type (check_class_constant (get_ushort ()).to_array (this));
3034 case op_arraylength
:
3036 type t
= pop_init_ref (reference_type
);
3037 if (! t
.isarray () && ! t
.isnull ())
3038 verify_fail ("array type expected");
3039 push_type (int_type
);
3043 pop_type (type (&java::lang::Throwable::class$
, this));
3047 pop_init_ref (reference_type
);
3048 push_type (check_class_constant (get_ushort ()));
3051 pop_init_ref (reference_type
);
3052 check_class_constant (get_ushort ());
3053 push_type (int_type
);
3055 case op_monitorenter
:
3056 pop_init_ref (reference_type
);
3058 case op_monitorexit
:
3059 pop_init_ref (reference_type
);
3063 switch (get_byte ())
3066 push_type (get_variable (get_ushort (), int_type
));
3069 push_type (get_variable (get_ushort (), long_type
));
3072 push_type (get_variable (get_ushort (), float_type
));
3075 push_type (get_variable (get_ushort (), double_type
));
3078 push_type (get_variable (get_ushort (), reference_type
));
3081 set_variable (get_ushort (), pop_type (int_type
));
3084 set_variable (get_ushort (), pop_type (long_type
));
3087 set_variable (get_ushort (), pop_type (float_type
));
3090 set_variable (get_ushort (), pop_type (double_type
));
3093 set_variable (get_ushort (), pop_init_ref (reference_type
));
3096 handle_ret_insn (get_short ());
3099 get_variable (get_ushort (), int_type
);
3103 verify_fail ("unrecognized wide instruction", start_PC
);
3107 case op_multianewarray
:
3109 type atype
= check_class_constant (get_ushort ());
3110 int dim
= get_byte ();
3112 verify_fail ("too few dimensions to multianewarray", start_PC
);
3113 atype
.verify_dimensions (dim
, this);
3114 for (int i
= 0; i
< dim
; ++i
)
3115 pop_type (int_type
);
3121 pop_type (reference_type
);
3122 push_jump (get_short ());
3125 push_jump (get_int ());
3129 handle_jsr_insn (get_int ());
3132 // These are unused here, but we call them out explicitly
3133 // so that -Wswitch-enum doesn't complain.
3139 case op_putstatic_1
:
3140 case op_putstatic_2
:
3141 case op_putstatic_4
:
3142 case op_putstatic_8
:
3143 case op_putstatic_a
:
3145 case op_getfield_2s
:
3146 case op_getfield_2u
:
3150 case op_getstatic_1
:
3151 case op_getstatic_2s
:
3152 case op_getstatic_2u
:
3153 case op_getstatic_4
:
3154 case op_getstatic_8
:
3155 case op_getstatic_a
:
3157 // Unrecognized opcode.
3158 verify_fail ("unrecognized instruction in verify_instructions_0",
3166 void verify_instructions ()
3169 verify_instructions_0 ();
3172 _Jv_BytecodeVerifier (_Jv_InterpMethod
*m
)
3174 // We just print the text as utf-8. This is just for debugging
3176 debug_print ("--------------------------------\n");
3177 debug_print ("-- Verifying method `%s'\n", m
->self
->name
->chars());
3180 bytecode
= m
->bytecode ();
3181 exception
= m
->exceptions ();
3182 current_class
= m
->defining_class
;
3190 ~_Jv_BytecodeVerifier ()
3195 while (utf8_list
!= NULL
)
3197 linked
<_Jv_Utf8Const
> *n
= utf8_list
->next
;
3198 _Jv_Free (utf8_list
);
3202 while (isect_list
!= NULL
)
3204 ref_intersection
*next
= isect_list
->alloc_next
;
3211 for (int i
= 0; i
< current_method
->code_length
; ++i
)
3213 linked
<state
> *iter
= states
[i
];
3214 while (iter
!= NULL
)
3216 linked
<state
> *next
= iter
->next
;
3228 _Jv_VerifyMethod (_Jv_InterpMethod
*meth
)
3230 _Jv_BytecodeVerifier
v (meth
);
3231 v
.verify_instructions ();
3234 #endif /* INTERPRETER */