1 // defineclass.cc - defining a class from .class format.
3 /* Copyright (C) 2001 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 // Writte by Tom Tromey <tromey@redhat.com>
17 #include <java-insns.h>
18 #include <java-interp.h>
22 #include <java/lang/Class.h>
23 #include <java/lang/VerifyError.h>
24 #include <java/lang/Throwable.h>
25 #include <java/lang/reflect/Modifier.h>
26 #include <java/lang/StringBuffer.h>
30 // * read more about when classes must be loaded
31 // * there are bugs with boolean arrays?
32 // * class loader madness
33 // * Lots and lots of debugging and testing
34 // * type representation is still ugly. look for the big switches
35 // * at least one GC problem :-(
38 // This is global because __attribute__ doesn't seem to work on static
40 static void verify_fail (char *msg, jint pc = -1)
41 __attribute__ ((__noreturn__));
43 class _Jv_BytecodeVerifier
47 static const int FLAG_INSN_START = 1;
48 static const int FLAG_BRANCH_TARGET = 2;
49 static const int FLAG_JSR_TARGET = 4;
57 // The PC corresponding to the start of the current instruction.
60 // The current state of the stack, locals, etc.
63 // We store the state at branch targets, for merging. This holds
67 // We keep a linked list of all the PCs which we must reverify.
68 // The link is done using the PC values. This is the head of the
72 // We keep some flags for each instruction. The values are the
73 // FLAG_* constants defined above.
76 // We need to keep track of which instructions can call a given
77 // subroutine. FIXME: this is inefficient. We keep a linked list
78 // of all calling `jsr's at at each jsr target.
81 // The current top of the stack, in terms of slots.
83 // The current depth of the stack. This will be larger than
84 // STACKTOP when wide types are on the stack.
87 // The bytecode itself.
88 unsigned char *bytecode;
90 _Jv_InterpException *exception;
95 _Jv_InterpMethod *current_method;
97 // This enum holds a list of tags for all the different types we
98 // need to handle. Reference types are treated specially by the
104 // The values for primitive types are chosen to correspond to values
105 // specified to newarray.
115 // Used when overwriting second word of a double or long in the
116 // local variables. Also used after merging local variable states
117 // to indicate an unusable value.
122 // Everything after `reference_type' must be a reference type.
125 unresolved_reference_type,
126 uninitialized_reference_type,
127 uninitialized_unresolved_reference_type
130 // Return the type_val corresponding to a primitive signature
131 // character. For instance `I' returns `int.class'.
132 static type_val get_type_val_for_signature (jchar sig)
165 verify_fail ("invalid signature");
170 // Return the type_val corresponding to a primitive class.
171 static type_val get_type_val_for_signature (jclass k)
173 return get_type_val_for_signature ((jchar) k->method_count);
176 // This is like _Jv_IsAssignableFrom, but it works even if SOURCE or
177 // TARGET haven't been prepared.
178 static bool is_assignable_from_slow (jclass target, jclass source)
180 // This will terminate when SOURCE==Object.
183 if (source == target)
186 if (target->isPrimitive () || source->isPrimitive ())
189 // _Jv_IsAssignableFrom can handle a target which is an
190 // interface even if it hasn't been prepared.
191 if ((target->state > JV_STATE_LINKED || target->isInterface ())
192 && source->state > JV_STATE_LINKED)
193 return _Jv_IsAssignableFrom (target, source);
195 if (target->isArray ())
197 if (! source->isArray ())
199 target = target->getComponentType ();
200 source = source->getComponentType ();
202 else if (target->isInterface ())
204 for (int i = 0; i < source->interface_count; ++i)
206 // We use a recursive call because we also need to
207 // check superinterfaces.
208 if (is_assignable_from_slow (target, source->interfaces[i]))
213 else if (target == &java::lang::Object::class$)
215 else if (source->isInterface ()
216 || source == &java::lang::Object::class$)
219 source = source->getSuperclass ();
223 // This is used to keep track of which `jsr's correspond to a given
227 // PC of the instruction just after the jsr.
233 // The `type' class is used to represent a single type in the
239 // Some associated data.
242 // For a resolved reference type, this is a pointer to the class.
244 // For other reference types, this it the name of the class.
247 // This is used when constructing a new object. It is the PC of the
248 // `new' instruction which created the object. We use the special
249 // value -2 to mean that this is uninitialized, and the special
250 // value -1 for the case where the current method is itself the
254 static const int UNINIT = -2;
255 static const int SELF = -1;
257 // Basic constructor.
260 key = unsuitable_type;
265 // Make a new instance given the type tag. We assume a generic
266 // `reference_type' means Object.
271 if (key == reference_type)
272 data.klass = &java::lang::Object::class$;
276 // Make a new instance given a class.
279 key = reference_type;
284 // Make a new instance given the name of a class.
285 type (_Jv_Utf8Const *n)
287 key = unresolved_reference_type;
300 // These operators are required because libgcj can't link in
302 void *operator new[] (size_t bytes)
304 return _Jv_Malloc (bytes);
307 void operator delete[] (void *mem)
312 type& operator= (type_val k)
320 type& operator= (const type& t)
328 // Promote a numeric type.
331 if (key == boolean_type || key == char_type
332 || key == byte_type || key == short_type)
337 // If *THIS is an unresolved reference type, resolve it.
340 if (key != unresolved_reference_type
341 && key != uninitialized_unresolved_reference_type)
344 // FIXME: class loader
345 using namespace java::lang;
346 // We might see either kind of name. Sigh.
347 if (data.name->data[0] == 'L'
348 && data.name->data[data.name->length - 1] == ';')
349 data.klass = _Jv_FindClassFromSignature (data.name->data, NULL);
351 data.klass = Class::forName (_Jv_NewStringUtf8Const (data.name),
353 key = (key == unresolved_reference_type
355 : uninitialized_reference_type);
358 // Mark this type as the uninitialized result of `new'.
359 void set_uninitialized (int npc)
361 if (key == reference_type)
362 key = uninitialized_reference_type;
363 else if (key == unresolved_reference_type)
364 key = uninitialized_unresolved_reference_type;
366 verify_fail ("internal error in type::uninitialized");
370 // Mark this type as now initialized.
371 void set_initialized (int npc)
373 if (npc != UNINIT && pc == npc
374 && (key == uninitialized_reference_type
375 || key == uninitialized_unresolved_reference_type))
377 key = (key == uninitialized_reference_type
379 : unresolved_reference_type);
385 // Return true if an object of type K can be assigned to a variable
386 // of type *THIS. Handle various special cases too. Might modify
387 // *THIS or K. Note however that this does not perform numeric
389 bool compatible (type &k)
391 // Any type is compatible with the unsuitable type.
392 if (key == unsuitable_type)
395 if (key < reference_type || k.key < reference_type)
398 // The `null' type is convertible to any reference type.
399 // FIXME: is this correct for THIS?
400 if (key == null_type || k.key == null_type)
403 // Any reference type is convertible to Object. This is a special
404 // case so we don't need to unnecessarily resolve a class.
405 if (key == reference_type
406 && data.klass == &java::lang::Object::class$)
409 // An initialized type and an uninitialized type are not
411 if (isinitialized () != k.isinitialized ())
414 // Two uninitialized objects are compatible if either:
415 // * The PCs are identical, or
416 // * One PC is UNINIT.
417 if (! isinitialized ())
419 if (pc != k.pc && pc != UNINIT && k.pc != UNINIT)
423 // Two unresolved types are equal if their names are the same.
426 && _Jv_equalUtf8Consts (data.name, k.data.name))
429 // We must resolve both types and check assignability.
432 return is_assignable_from_slow (data.klass, k.data.klass);
437 return key == void_type;
442 return key == long_type || key == double_type;
445 // Return number of stack or local variable slots taken by this
449 return iswide () ? 2 : 1;
452 bool isarray () const
454 // We treat null_type as not an array. This is ok based on the
455 // current uses of this method.
456 if (key == reference_type)
457 return data.klass->isArray ();
458 else if (key == unresolved_reference_type)
459 return data.name->data[0] == '[';
466 if (key != reference_type)
468 return data.klass->isInterface ();
474 if (key != reference_type)
476 using namespace java::lang::reflect;
477 return Modifier::isAbstract (data.klass->getModifiers ());
480 // Return the element type of an array.
483 // FIXME: maybe should do string manipulation here.
485 if (key != reference_type)
486 verify_fail ("programmer error in type::element_type()");
488 jclass k = data.klass->getComponentType ();
489 if (k->isPrimitive ())
490 return type (get_type_val_for_signature (k));
494 bool isreference () const
496 return key >= reference_type;
504 bool isinitialized () const
506 return (key == reference_type
508 || key == unresolved_reference_type);
511 bool isresolved () const
513 return (key == reference_type
515 || key == uninitialized_reference_type);
518 void verify_dimensions (int ndims)
520 // The way this is written, we don't need to check isarray().
521 if (key == reference_type)
523 jclass k = data.klass;
524 while (k->isArray () && ndims > 0)
526 k = k->getComponentType ();
532 // We know KEY == unresolved_reference_type.
533 char *p = data.name->data;
534 while (*p++ == '[' && ndims-- > 0)
539 verify_fail ("array type has fewer dimensions than required");
542 // Merge OLD_TYPE into this. On error throw exception.
543 bool merge (type& old_type, bool local_semantics = false)
545 bool changed = false;
546 bool refo = old_type.isreference ();
547 bool refn = isreference ();
550 if (old_type.key == null_type)
552 else if (key == null_type)
557 else if (isinitialized () != old_type.isinitialized ())
558 verify_fail ("merging initialized and uninitialized types");
561 if (! isinitialized ())
565 else if (old_type.pc == UNINIT)
567 else if (pc != old_type.pc)
568 verify_fail ("merging different uninitialized types");
572 && ! old_type.isresolved ()
573 && _Jv_equalUtf8Consts (data.name, old_type.data.name))
575 // Types are identical.
582 jclass k = data.klass;
583 jclass oldk = old_type.data.klass;
586 while (k->isArray () && oldk->isArray ())
589 k = k->getComponentType ();
590 oldk = oldk->getComponentType ();
593 // This loop will end when we hit Object.
596 if (is_assignable_from_slow (k, oldk))
598 k = k->getSuperclass ();
604 while (arraycount > 0)
606 // FIXME: Class loader.
607 k = _Jv_GetArrayClass (k, NULL);
615 else if (refo || refn || key != old_type.key)
619 key = unsuitable_type;
623 verify_fail ("unmergeable type");
629 // This class holds all the state information we need for a given
633 // Current top of stack.
635 // Current stack depth. This is like the top of stack but it
636 // includes wide variable information.
640 // The local variables.
642 // This is used in subroutines to keep track of which local
643 // variables have been accessed.
645 // If not 0, then we are in a subroutine. The value is the PC of
646 // the subroutine's entry point. We can use 0 as an exceptional
647 // value because PC=0 can never be a subroutine.
649 // This is used to keep a linked list of all the states which
650 // require re-verification. We use the PC to keep track.
653 // INVALID marks a state which is not on the linked list of states
654 // requiring reverification.
655 static const int INVALID = -1;
656 // NO_NEXT marks the state at the end of the reverification list.
657 static const int NO_NEXT = -2;
663 local_changed = NULL;
666 state (int max_stack, int max_locals)
670 stack = new type[max_stack];
671 for (int i = 0; i < max_stack; ++i)
672 stack[i] = unsuitable_type;
673 locals = new type[max_locals];
674 local_changed = (bool *) _Jv_Malloc (sizeof (bool) * max_locals);
675 for (int i = 0; i < max_locals; ++i)
677 locals[i] = unsuitable_type;
678 local_changed[i] = false;
684 state (const state *copy, int max_stack, int max_locals)
686 stack = new type[max_stack];
687 locals = new type[max_locals];
688 local_changed = (bool *) _Jv_Malloc (sizeof (bool) * max_locals);
700 _Jv_Free (local_changed);
703 void *operator new[] (size_t bytes)
705 return _Jv_Malloc (bytes);
708 void operator delete[] (void *mem)
713 void *operator new (size_t bytes)
715 return _Jv_Malloc (bytes);
718 void operator delete (void *mem)
723 void copy (const state *copy, int max_stack, int max_locals)
725 stacktop = copy->stacktop;
726 stackdepth = copy->stackdepth;
727 subroutine = copy->subroutine;
728 for (int i = 0; i < max_stack; ++i)
729 stack[i] = copy->stack[i];
730 for (int i = 0; i < max_locals; ++i)
732 locals[i] = copy->locals[i];
733 local_changed[i] = copy->local_changed[i];
735 // Don't modify `next'.
738 // Modify this state to reflect entry to an exception handler.
739 void set_exception (type t, int max_stack)
744 for (int i = stacktop; i < max_stack; ++i)
745 stack[i] = unsuitable_type;
747 // FIXME: subroutine handling?
750 // Merge STATE into this state. Destructively modifies this state.
751 // Returns true if the new state was in fact changed. Will throw an
752 // exception if the states are not mergeable.
753 bool merge (state *state_old, bool ret_semantics,
756 bool changed = false;
758 // Merge subroutine states. *THIS and *STATE_OLD must be in the
759 // same subroutine. Also, recursive subroutine calls must be
761 if (subroutine == state_old->subroutine)
765 else if (subroutine == 0)
767 subroutine = state_old->subroutine;
771 verify_fail ("subroutines merged");
774 if (state_old->stacktop != stacktop)
775 verify_fail ("stack sizes differ");
776 for (int i = 0; i < state_old->stacktop; ++i)
778 if (stack[i].merge (state_old->stack[i]))
782 // Merge local variables.
783 for (int i = 0; i < max_locals; ++i)
785 if (! ret_semantics || local_changed[i])
787 if (locals[i].merge (state_old->locals[i], true))
794 // If we're in a subroutine, we must compute the union of
795 // all the changed local variables.
796 if (state_old->local_changed[i])
803 // Throw an exception if there is an uninitialized object on the
804 // stack or in a local variable. EXCEPTION_SEMANTICS controls
805 // whether we're using backwards-branch or exception-handing
807 void check_no_uninitialized_objects (int max_locals,
808 bool exception_semantics = false)
810 if (! exception_semantics)
812 for (int i = 0; i < stacktop; ++i)
813 if (stack[i].isreference () && ! stack[i].isinitialized ())
814 verify_fail ("uninitialized object on stack");
817 for (int i = 0; i < max_locals; ++i)
818 if (locals[i].isreference () && ! locals[i].isinitialized ())
819 verify_fail ("uninitialized object in local variable");
822 // Note that a local variable was accessed or modified.
823 void note_variable (int index)
826 local_changed[index] = true;
829 // Mark each `new'd object we know of that was allocated at PC as
831 void set_initialized (int pc, int max_locals)
833 for (int i = 0; i < stacktop; ++i)
834 stack[i].set_initialized (pc);
835 for (int i = 0; i < max_locals; ++i)
836 locals[i].set_initialized (pc);
842 if (current_state->stacktop <= 0)
843 verify_fail ("stack empty", start_PC);
844 type r = current_state->stack[--current_state->stacktop];
845 current_state->stackdepth -= r.depth ();
846 if (current_state->stackdepth < 0)
847 verify_fail ("stack empty", start_PC);
855 verify_fail ("narrow pop of wide type", start_PC);
863 verify_fail ("wide pop of narrow type", start_PC);
867 type pop_type (type match)
871 if (! match.compatible (t))
872 verify_fail ("incompatible type on stack", start_PC);
876 void push_type (type t)
878 // If T is a numeric type like short, promote it to int.
881 int depth = t.depth ();
882 if (current_state->stackdepth + depth > current_method->max_stack)
883 verify_fail ("stack overflow");
884 current_state->stack[current_state->stacktop++] = t;
885 current_state->stackdepth += depth;
888 void set_variable (int index, type t)
890 // If T is a numeric type like short, promote it to int.
893 int depth = t.depth ();
894 if (index > current_method->max_locals - depth)
895 verify_fail ("invalid local variable");
896 current_state->locals[index] = t;
897 current_state->note_variable (index);
901 current_state->locals[index + 1] = continuation_type;
902 current_state->note_variable (index + 1);
904 if (index > 0 && current_state->locals[index - 1].iswide ())
906 current_state->locals[index - 1] = unsuitable_type;
907 // There's no need to call note_variable here.
911 type get_variable (int index, type t)
913 int depth = t.depth ();
914 if (index > current_method->max_locals - depth)
915 verify_fail ("invalid local variable", start_PC);
916 if (! t.compatible (current_state->locals[index]))
917 verify_fail ("incompatible type in local variable", start_PC);
920 type t (continuation_type);
921 if (! current_state->locals[index + 1].compatible (t))
922 verify_fail ("invalid local variable", start_PC);
924 current_state->note_variable (index);
925 return current_state->locals[index];
928 // Make sure ARRAY is an array type and that its elements are
929 // compatible with type ELEMENT. Returns the actual element type.
930 type require_array_type (type array, type element)
932 if (! array.isarray ())
933 verify_fail ("array required");
935 type t = array.element_type ();
936 if (! element.compatible (t))
937 verify_fail ("incompatible array element type");
939 // Return T and not ELEMENT, because T might be specialized.
945 if (PC >= current_method->code_length)
946 verify_fail ("premature end of bytecode");
947 return (jint) bytecode[PC++] & 0xff;
952 jint b1 = get_byte ();
953 jint b2 = get_byte ();
954 return (jint) ((b1 << 8) | b2) & 0xffff;
959 jint b1 = get_byte ();
960 jint b2 = get_byte ();
961 jshort s = (b1 << 8) | b2;
967 jint b1 = get_byte ();
968 jint b2 = get_byte ();
969 jint b3 = get_byte ();
970 jint b4 = get_byte ();
971 return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
974 int compute_jump (int offset)
976 int npc = start_PC + offset;
977 if (npc < 0 || npc >= current_method->code_length)
978 verify_fail ("branch out of range");
982 // Merge the indicated state into a new state and schedule a new PC if
983 // there is a change. If RET_SEMANTICS is true, then we are merging
984 // from a `ret' instruction into the instruction after a `jsr'. This
985 // is a special case with its own modified semantics.
986 void push_jump_merge (int npc, state *nstate, bool ret_semantics = false)
989 if (states[npc] == NULL)
991 // FIXME: what if we reach this code from a `ret'?
993 states[npc] = new state (nstate, current_method->max_stack,
994 current_method->max_locals);
997 changed = nstate->merge (states[npc], ret_semantics,
998 current_method->max_stack);
1000 if (changed && states[npc]->next == state::INVALID)
1002 // The merge changed the state, and the new PC isn't yet on our
1003 // list of PCs to re-verify.
1004 states[npc]->next = next_verify_pc;
1005 next_verify_pc = npc;
1009 void push_jump (int offset)
1011 int npc = compute_jump (offset);
1013 current_state->check_no_uninitialized_objects (current_method->max_stack);
1014 push_jump_merge (npc, current_state);
1017 void push_exception_jump (type t, int pc)
1019 current_state->check_no_uninitialized_objects (current_method->max_stack,
1021 state s (current_state, current_method->max_stack,
1022 current_method->max_locals);
1023 s.set_exception (t, current_method->max_stack);
1024 push_jump_merge (pc, &s);
1029 int npc = next_verify_pc;
1030 if (npc != state::NO_NEXT)
1032 next_verify_pc = states[npc]->next;
1033 states[npc]->next = state::INVALID;
1038 void invalidate_pc ()
1040 PC = state::NO_NEXT;
1043 void note_branch_target (int pc, bool is_jsr_target = false)
1045 if (pc <= PC && ! (flags[pc] & FLAG_INSN_START))
1046 verify_fail ("branch not to instruction start");
1047 flags[pc] |= FLAG_BRANCH_TARGET;
1050 // Record the jsr which called this instruction.
1051 subr_info *info = (subr_info *) _Jv_Malloc (sizeof (subr_info));
1053 info->next = jsr_ptrs[pc];
1054 jsr_ptrs[pc] = info;
1055 flags[pc] |= FLAG_JSR_TARGET;
1059 void skip_padding ()
1061 while ((PC % 4) > 0)
1062 if (get_byte () != 0)
1063 verify_fail ("found nonzero padding byte");
1066 // Return the subroutine to which the instruction at PC belongs.
1067 int get_subroutine (int pc)
1069 if (states[pc] == NULL)
1071 return states[pc]->subroutine;
1074 // Do the work for a `ret' instruction. INDEX is the index into the
1076 void handle_ret_insn (int index)
1078 get_variable (index, return_address_type);
1080 int csub = current_state->subroutine;
1082 verify_fail ("no subroutine");
1084 for (subr_info *subr = jsr_ptrs[csub]; subr != NULL; subr = subr->next)
1086 // Temporarily modify the current state so it looks like we're
1087 // in the enclosing context.
1088 current_state->subroutine = get_subroutine (subr->pc);
1090 current_state->check_no_uninitialized_objects (current_method->max_stack);
1091 push_jump_merge (subr->pc, current_state, true);
1094 current_state->subroutine = csub;
1098 // We're in the subroutine SUB, calling a subroutine at DEST. Make
1099 // sure this subroutine isn't already on the stack.
1100 void check_nonrecursive_call (int sub, int dest)
1105 verify_fail ("recursive subroutine call");
1106 for (subr_info *info = jsr_ptrs[sub]; info != NULL; info = info->next)
1107 check_nonrecursive_call (get_subroutine (info->pc), dest);
1110 void handle_jsr_insn (int offset)
1112 int npc = compute_jump (offset);
1115 current_state->check_no_uninitialized_objects (current_method->max_stack);
1116 check_nonrecursive_call (current_state->subroutine, npc);
1118 // Temporarily modify the current state so that it looks like we are
1119 // in the subroutine.
1120 push_type (return_address_type);
1121 int save = current_state->subroutine;
1122 current_state->subroutine = npc;
1124 // Merge into the subroutine.
1125 push_jump_merge (npc, current_state);
1127 // Undo our modifications.
1128 current_state->subroutine = save;
1129 pop_type (return_address_type);
1132 jclass construct_primitive_array_type (type_val prim)
1138 k = JvPrimClass (boolean);
1141 k = JvPrimClass (char);
1144 k = JvPrimClass (float);
1147 k = JvPrimClass (double);
1150 k = JvPrimClass (byte);
1153 k = JvPrimClass (short);
1156 k = JvPrimClass (int);
1159 k = JvPrimClass (long);
1162 verify_fail ("unknown type in construct_primitive_array_type");
1164 k = _Jv_GetArrayClass (k, NULL);
1168 // This pass computes the location of branch targets and also
1169 // instruction starts.
1170 void branch_prepass ()
1172 flags = (char *) _Jv_Malloc (current_method->code_length);
1173 jsr_ptrs = (subr_info **) _Jv_Malloc (sizeof (subr_info *)
1174 * current_method->code_length);
1176 for (int i = 0; i < current_method->code_length; ++i)
1182 bool last_was_jsr = false;
1185 while (PC < current_method->code_length)
1187 flags[PC] |= FLAG_INSN_START;
1189 // If the previous instruction was a jsr, then the next
1190 // instruction is a branch target -- the branch being the
1191 // corresponding `ret'.
1193 note_branch_target (PC);
1194 last_was_jsr = false;
1197 unsigned char opcode = bytecode[PC++];
1201 case op_aconst_null:
1338 case op_monitorenter:
1339 case op_monitorexit:
1362 case op_arraylength:
1378 case op_invokespecial:
1379 case op_invokestatic:
1380 case op_invokevirtual:
1384 case op_multianewarray:
1390 last_was_jsr = true;
1409 note_branch_target (compute_jump (get_short ()), last_was_jsr);
1412 case op_tableswitch:
1415 note_branch_target (compute_jump (get_int ()));
1416 jint low = get_int ();
1417 jint hi = get_int ();
1419 verify_fail ("invalid tableswitch", start_PC);
1420 for (int i = low; i <= hi; ++i)
1421 note_branch_target (compute_jump (get_int ()));
1425 case op_lookupswitch:
1428 note_branch_target (compute_jump (get_int ()));
1429 int npairs = get_int ();
1431 verify_fail ("too few pairs in lookupswitch", start_PC);
1432 while (npairs-- > 0)
1435 note_branch_target (compute_jump (get_int ()));
1440 case op_invokeinterface:
1448 opcode = get_byte ();
1450 if (opcode == (unsigned char) op_iinc)
1456 last_was_jsr = true;
1459 note_branch_target (compute_jump (get_int ()), last_was_jsr);
1463 verify_fail ("unrecognized instruction in branch_prepass",
1467 // See if any previous branch tried to branch to the middle of
1468 // this instruction.
1469 for (int pc = start_PC + 1; pc < PC; ++pc)
1471 if ((flags[pc] & FLAG_BRANCH_TARGET))
1472 verify_fail ("branch to middle of instruction", pc);
1476 // Verify exception handlers.
1477 for (int i = 0; i < current_method->exc_count; ++i)
1479 if (! (flags[exception[i].handler_pc] & FLAG_INSN_START))
1480 verify_fail ("exception handler not at instruction start",
1481 exception[i].handler_pc);
1482 if (exception[i].start_pc > exception[i].end_pc)
1483 verify_fail ("exception range inverted");
1484 if (! (flags[exception[i].start_pc] & FLAG_INSN_START))
1485 verify_fail ("exception start not at instruction start",
1486 exception[i].start_pc);
1487 else if (! (flags[exception[i].end_pc] & FLAG_INSN_START))
1488 verify_fail ("exception end not at instruction start",
1489 exception[i].end_pc);
1491 flags[exception[i].handler_pc] |= FLAG_BRANCH_TARGET;
1495 void check_pool_index (int index)
1497 if (index < 0 || index >= current_class->constants.size)
1498 verify_fail ("constant pool index out of range", start_PC);
1501 type check_class_constant (int index)
1503 check_pool_index (index);
1504 _Jv_Constants *pool = ¤t_class->constants;
1505 if (pool->tags[index] == JV_CONSTANT_ResolvedClass)
1506 return type (pool->data[index].clazz);
1507 else if (pool->tags[index] == JV_CONSTANT_Class)
1508 return type (pool->data[index].utf8);
1509 verify_fail ("expected class constant", start_PC);
1512 type check_constant (int index)
1514 check_pool_index (index);
1515 _Jv_Constants *pool = ¤t_class->constants;
1516 if (pool->tags[index] == JV_CONSTANT_ResolvedString
1517 || pool->tags[index] == JV_CONSTANT_String)
1518 return type (&java::lang::String::class$);
1519 else if (pool->tags[index] == JV_CONSTANT_Integer)
1520 return type (int_type);
1521 else if (pool->tags[index] == JV_CONSTANT_Float)
1522 return type (float_type);
1523 verify_fail ("String, int, or float constant expected", start_PC);
1526 type check_wide_constant (int index)
1528 check_pool_index (index);
1529 _Jv_Constants *pool = ¤t_class->constants;
1530 if (pool->tags[index] == JV_CONSTANT_Long)
1531 return type (long_type);
1532 else if (pool->tags[index] == JV_CONSTANT_Double)
1533 return type (double_type);
1534 verify_fail ("long or double constant expected", start_PC);
1537 // Helper for both field and method. These are laid out the same in
1538 // the constant pool.
1539 type handle_field_or_method (int index, int expected,
1540 _Jv_Utf8Const **name,
1541 _Jv_Utf8Const **fmtype)
1543 check_pool_index (index);
1544 _Jv_Constants *pool = ¤t_class->constants;
1545 if (pool->tags[index] != expected)
1546 verify_fail ("didn't see expected constant", start_PC);
1547 // Once we know we have a Fieldref or Methodref we assume that it
1548 // is correctly laid out in the constant pool. I think the code
1549 // in defineclass.cc guarantees this.
1550 _Jv_ushort class_index, name_and_type_index;
1551 _Jv_loadIndexes (&pool->data[index],
1553 name_and_type_index);
1554 _Jv_ushort name_index, desc_index;
1555 _Jv_loadIndexes (&pool->data[name_and_type_index],
1556 name_index, desc_index);
1558 *name = pool->data[name_index].utf8;
1559 *fmtype = pool->data[desc_index].utf8;
1561 return check_class_constant (class_index);
1564 // Return field's type, compute class' type if requested.
1565 type check_field_constant (int index, type *class_type = NULL)
1567 _Jv_Utf8Const *name, *field_type;
1568 type ct = handle_field_or_method (index,
1569 JV_CONSTANT_Fieldref,
1570 &name, &field_type);
1573 if (field_type->data[0] == '[' || field_type->data[0] == 'L')
1574 return type (field_type);
1575 return get_type_val_for_signature (field_type->data[0]);
1578 type check_method_constant (int index, bool is_interface,
1579 _Jv_Utf8Const **method_name,
1580 _Jv_Utf8Const **method_signature)
1582 return handle_field_or_method (index,
1584 ? JV_CONSTANT_InterfaceMethodref
1585 : JV_CONSTANT_Methodref),
1586 method_name, method_signature);
1589 type get_one_type (char *&p)
1607 // FIXME! This will get collected!
1608 _Jv_Utf8Const *name = _Jv_makeUtf8Const (start, p - start);
1612 // Casting to jchar here is ok since we are looking at an ASCII
1614 type_val rt = get_type_val_for_signature (jchar (v));
1616 if (arraycount == 0)
1618 // Callers of this function eventually push their arguments on
1619 // the stack. So, promote them here.
1620 return type (rt).promote ();
1623 jclass k = construct_primitive_array_type (rt);
1624 while (--arraycount > 0)
1625 k = _Jv_GetArrayClass (k, NULL);
1629 void compute_argument_types (_Jv_Utf8Const *signature,
1632 char *p = signature->data;
1638 types[i++] = get_one_type (p);
1641 type compute_return_type (_Jv_Utf8Const *signature)
1643 char *p = signature->data;
1647 return get_one_type (p);
1650 void check_return_type (type onstack)
1652 type rt = compute_return_type (current_method->self->signature);
1653 if (! rt.compatible (onstack))
1654 verify_fail ("incompatible return type", start_PC);
1657 void verify_instructions_0 ()
1659 current_state = new state (current_method->max_stack,
1660 current_method->max_locals);
1668 using namespace java::lang::reflect;
1669 if (! Modifier::isStatic (current_method->self->accflags))
1671 type kurr (current_class);
1672 if (_Jv_equalUtf8Consts (current_method->self->name, gcj::init_name))
1673 kurr.set_uninitialized (type::SELF);
1674 set_variable (0, kurr);
1678 // We have to handle wide arguments specially here.
1679 int arg_count = _Jv_count_arguments (current_method->self->signature);
1680 type arg_types[arg_count];
1681 compute_argument_types (current_method->self->signature, arg_types);
1682 for (int i = 0; i < arg_count; ++i)
1684 set_variable (var, arg_types[i]);
1686 if (arg_types[i].iswide ())
1691 states = (state **) _Jv_Malloc (sizeof (state *)
1692 * current_method->code_length);
1693 for (int i = 0; i < current_method->code_length; ++i)
1696 next_verify_pc = state::NO_NEXT;
1700 // If the PC was invalidated, get a new one from the work list.
1701 if (PC == state::NO_NEXT)
1704 if (PC == state::INVALID)
1705 verify_fail ("saw state::INVALID", start_PC);
1706 if (PC == state::NO_NEXT)
1708 // Set up the current state.
1709 *current_state = *states[PC];
1712 // Control can't fall off the end of the bytecode.
1713 if (PC >= current_method->code_length)
1714 verify_fail ("fell off end");
1716 if (states[PC] != NULL)
1718 // We've already visited this instruction. So merge the
1719 // states together. If this yields no change then we don't
1720 // have to re-verify.
1721 if (! current_state->merge (states[PC], false,
1722 current_method->max_stack))
1727 // Save a copy of it for later.
1728 states[PC]->copy (current_state, current_method->max_stack,
1729 current_method->max_locals);
1731 else if ((flags[PC] & FLAG_BRANCH_TARGET))
1733 // We only have to keep saved state at branch targets.
1734 states[PC] = new state (current_state, current_method->max_stack,
1735 current_method->max_locals);
1738 // Update states for all active exception handlers. Ordinarily
1739 // there are not many exception handlers. So we simply run
1740 // through them all.
1741 for (int i = 0; i < current_method->exc_count; ++i)
1743 if (PC >= exception[i].start_pc && PC < exception[i].end_pc)
1745 type handler = reference_type;
1746 if (exception[i].handler_type != 0)
1747 handler = check_class_constant (exception[i].handler_type);
1748 push_exception_jump (handler, exception[i].handler_pc);
1753 unsigned char opcode = bytecode[PC++];
1759 case op_aconst_null:
1760 push_type (null_type);
1770 push_type (int_type);
1775 push_type (long_type);
1781 push_type (float_type);
1786 push_type (double_type);
1791 push_type (int_type);
1796 push_type (int_type);
1800 push_type (check_constant (get_byte ()));
1803 push_type (check_constant (get_ushort ()));
1806 push_type (check_wide_constant (get_ushort ()));
1810 push_type (get_variable (get_byte (), int_type));
1813 push_type (get_variable (get_byte (), long_type));
1816 push_type (get_variable (get_byte (), float_type));
1819 push_type (get_variable (get_byte (), double_type));
1822 push_type (get_variable (get_byte (), reference_type));
1829 push_type (get_variable (opcode - op_iload_0, int_type));
1835 push_type (get_variable (opcode - op_lload_0, long_type));
1841 push_type (get_variable (opcode - op_fload_0, float_type));
1847 push_type (get_variable (opcode - op_dload_0, double_type));
1853 push_type (get_variable (opcode - op_aload_0, reference_type));
1856 pop_type (int_type);
1857 push_type (require_array_type (pop_type (reference_type),
1861 pop_type (int_type);
1862 push_type (require_array_type (pop_type (reference_type),
1866 pop_type (int_type);
1867 push_type (require_array_type (pop_type (reference_type),
1871 pop_type (int_type);
1872 push_type (require_array_type (pop_type (reference_type),
1876 pop_type (int_type);
1877 push_type (require_array_type (pop_type (reference_type),
1881 pop_type (int_type);
1882 require_array_type (pop_type (reference_type), byte_type);
1883 push_type (int_type);
1886 pop_type (int_type);
1887 require_array_type (pop_type (reference_type), char_type);
1888 push_type (int_type);
1891 pop_type (int_type);
1892 require_array_type (pop_type (reference_type), short_type);
1893 push_type (int_type);
1896 set_variable (get_byte (), pop_type (int_type));
1899 set_variable (get_byte (), pop_type (long_type));
1902 set_variable (get_byte (), pop_type (float_type));
1905 set_variable (get_byte (), pop_type (double_type));
1908 set_variable (get_byte (), pop_type (reference_type));
1914 set_variable (opcode - op_istore_0, pop_type (int_type));
1920 set_variable (opcode - op_lstore_0, pop_type (long_type));
1926 set_variable (opcode - op_fstore_0, pop_type (float_type));
1932 set_variable (opcode - op_dstore_0, pop_type (double_type));
1938 set_variable (opcode - op_astore_0, pop_type (reference_type));
1941 pop_type (int_type);
1942 pop_type (int_type);
1943 require_array_type (pop_type (reference_type), int_type);
1946 pop_type (long_type);
1947 pop_type (int_type);
1948 require_array_type (pop_type (reference_type), long_type);
1951 pop_type (float_type);
1952 pop_type (int_type);
1953 require_array_type (pop_type (reference_type), float_type);
1956 pop_type (double_type);
1957 pop_type (int_type);
1958 require_array_type (pop_type (reference_type), double_type);
1961 pop_type (reference_type);
1962 pop_type (int_type);
1963 require_array_type (pop_type (reference_type), reference_type);
1966 pop_type (int_type);
1967 pop_type (int_type);
1968 require_array_type (pop_type (reference_type), byte_type);
1971 pop_type (int_type);
1972 pop_type (int_type);
1973 require_array_type (pop_type (reference_type), char_type);
1976 pop_type (int_type);
1977 pop_type (int_type);
1978 require_array_type (pop_type (reference_type), short_type);
2005 type t2 = pop_raw ();
2020 type t = pop_raw ();
2033 type t1 = pop_raw ();
2051 type t1 = pop_raw ();
2054 type t2 = pop_raw ();
2072 type t3 = pop_raw ();
2110 pop_type (int_type);
2111 push_type (pop_type (int_type));
2124 pop_type (long_type);
2125 push_type (pop_type (long_type));
2132 pop_type (float_type);
2133 push_type (pop_type (float_type));
2140 pop_type (double_type);
2141 push_type (pop_type (double_type));
2147 push_type (pop_type (int_type));
2150 push_type (pop_type (long_type));
2153 push_type (pop_type (float_type));
2156 push_type (pop_type (double_type));
2159 get_variable (get_byte (), int_type);
2163 pop_type (int_type);
2164 push_type (long_type);
2167 pop_type (int_type);
2168 push_type (float_type);
2171 pop_type (int_type);
2172 push_type (double_type);
2175 pop_type (long_type);
2176 push_type (int_type);
2179 pop_type (long_type);
2180 push_type (float_type);
2183 pop_type (long_type);
2184 push_type (double_type);
2187 pop_type (float_type);
2188 push_type (int_type);
2191 pop_type (float_type);
2192 push_type (long_type);
2195 pop_type (float_type);
2196 push_type (double_type);
2199 pop_type (double_type);
2200 push_type (int_type);
2203 pop_type (double_type);
2204 push_type (long_type);
2207 pop_type (double_type);
2208 push_type (float_type);
2211 pop_type (long_type);
2212 pop_type (long_type);
2213 push_type (int_type);
2217 pop_type (float_type);
2218 pop_type (float_type);
2219 push_type (int_type);
2223 pop_type (double_type);
2224 pop_type (double_type);
2225 push_type (int_type);
2233 pop_type (int_type);
2234 push_jump (get_short ());
2242 pop_type (int_type);
2243 pop_type (int_type);
2244 push_jump (get_short ());
2248 pop_type (reference_type);
2249 pop_type (reference_type);
2250 push_jump (get_short ());
2253 push_jump (get_short ());
2257 handle_jsr_insn (get_short ());
2260 handle_ret_insn (get_byte ());
2262 case op_tableswitch:
2264 pop_type (int_type);
2266 push_jump (get_int ());
2267 jint low = get_int ();
2268 jint high = get_int ();
2269 // Already checked LOW -vs- HIGH.
2270 for (int i = low; i <= high; ++i)
2271 push_jump (get_int ());
2276 case op_lookupswitch:
2278 pop_type (int_type);
2280 push_jump (get_int ());
2281 jint npairs = get_int ();
2282 // Already checked NPAIRS >= 0.
2284 for (int i = 0; i < npairs; ++i)
2286 jint key = get_int ();
2287 if (i > 0 && key <= lastkey)
2288 verify_fail ("lookupswitch pairs unsorted", start_PC);
2290 push_jump (get_int ());
2296 check_return_type (pop_type (int_type));
2300 check_return_type (pop_type (long_type));
2304 check_return_type (pop_type (float_type));
2308 check_return_type (pop_type (double_type));
2312 check_return_type (pop_type (reference_type));
2316 check_return_type (void_type);
2320 push_type (check_field_constant (get_ushort ()));
2323 pop_type (check_field_constant (get_ushort ()));
2328 type field = check_field_constant (get_ushort (), &klass);
2336 type field = check_field_constant (get_ushort (), &klass);
2342 case op_invokevirtual:
2343 case op_invokespecial:
2344 case op_invokestatic:
2345 case op_invokeinterface:
2347 _Jv_Utf8Const *method_name, *method_signature;
2349 = check_method_constant (get_ushort (),
2350 opcode == (unsigned char) op_invokeinterface,
2353 int arg_count = _Jv_count_arguments (method_signature);
2354 if (opcode == (unsigned char) op_invokeinterface)
2356 int nargs = get_byte ();
2358 verify_fail ("too few arguments to invokeinterface",
2360 if (get_byte () != 0)
2361 verify_fail ("invokeinterface dummy byte is wrong",
2363 if (nargs - 1 != arg_count)
2364 verify_fail ("wrong argument count for invokeinterface",
2368 bool is_init = false;
2369 if (_Jv_equalUtf8Consts (method_name, gcj::init_name))
2372 if (opcode != (unsigned char) op_invokespecial)
2373 verify_fail ("can't invoke <init>", start_PC);
2375 else if (method_name->data[0] == '<')
2376 verify_fail ("can't invoke method starting with `<'",
2379 // Pop arguments and check types.
2380 type arg_types[arg_count];
2381 compute_argument_types (method_signature, arg_types);
2382 for (int i = arg_count - 1; i >= 0; --i)
2383 pop_type (arg_types[i]);
2385 if (opcode != (unsigned char) op_invokestatic)
2387 type t = class_type;
2390 // In this case the PC doesn't matter.
2391 t.set_uninitialized (type::UNINIT);
2395 current_state->set_initialized (t.get_pc (),
2396 current_method->max_locals);
2399 type rt = compute_return_type (method_signature);
2407 type t = check_class_constant (get_ushort ());
2408 if (t.isarray () || t.isinterface () || t.isabstract ())
2409 verify_fail ("type is array, interface, or abstract",
2411 t.set_uninitialized (start_PC);
2418 int atype = get_byte ();
2419 // We intentionally have chosen constants to make this
2421 if (atype < boolean_type || atype > long_type)
2422 verify_fail ("type not primitive", start_PC);
2423 pop_type (int_type);
2424 push_type (construct_primitive_array_type (type_val (atype)));
2428 pop_type (int_type);
2429 push_type (check_class_constant (get_ushort ()));
2431 case op_arraylength:
2433 type t = pop_type (reference_type);
2435 verify_fail ("array type expected", start_PC);
2436 push_type (int_type);
2440 pop_type (type (&java::lang::Throwable::class$));
2444 pop_type (reference_type);
2445 push_type (check_class_constant (get_ushort ()));
2448 pop_type (reference_type);
2449 check_class_constant (get_ushort ());
2450 push_type (int_type);
2452 case op_monitorenter:
2453 pop_type (reference_type);
2455 case op_monitorexit:
2456 pop_type (reference_type);
2460 switch (get_byte ())
2463 push_type (get_variable (get_ushort (), int_type));
2466 push_type (get_variable (get_ushort (), long_type));
2469 push_type (get_variable (get_ushort (), float_type));
2472 push_type (get_variable (get_ushort (), double_type));
2475 push_type (get_variable (get_ushort (), reference_type));
2478 set_variable (get_ushort (), pop_type (int_type));
2481 set_variable (get_ushort (), pop_type (long_type));
2484 set_variable (get_ushort (), pop_type (float_type));
2487 set_variable (get_ushort (), pop_type (double_type));
2490 set_variable (get_ushort (), pop_type (reference_type));
2493 handle_ret_insn (get_short ());
2496 get_variable (get_ushort (), int_type);
2500 verify_fail ("unrecognized wide instruction", start_PC);
2504 case op_multianewarray:
2506 type atype = check_class_constant (get_ushort ());
2507 int dim = get_byte ();
2509 verify_fail ("too few dimensions to multianewarray", start_PC);
2510 atype.verify_dimensions (dim);
2511 for (int i = 0; i < dim; ++i)
2512 pop_type (int_type);
2518 pop_type (reference_type);
2519 push_jump (get_short ());
2522 push_jump (get_int ());
2526 handle_jsr_insn (get_int ());
2530 // Unrecognized opcode.
2531 verify_fail ("unrecognized instruction in verify_instructions_0",
2539 void verify_instructions ()
2542 verify_instructions_0 ();
2545 _Jv_BytecodeVerifier (_Jv_InterpMethod *m)
2548 bytecode = m->bytecode ();
2549 exception = m->exceptions ();
2550 current_class = m->defining_class;
2557 ~_Jv_BytecodeVerifier ()
2564 _Jv_Free (jsr_ptrs);
2569 _Jv_VerifyMethod (_Jv_InterpMethod *meth)
2571 _Jv_BytecodeVerifier v (meth);
2572 v.verify_instructions ();
2575 // FIXME: add more info, like PC, when required.
2577 verify_fail (char *s, jint pc)
2579 using namespace java::lang;
2580 StringBuffer *buf = new StringBuffer ();
2582 buf->append (JvNewStringLatin1 ("verification failed"));
2585 buf->append (JvNewStringLatin1 (" at PC "));
2588 buf->append (JvNewStringLatin1 (": "));
2589 buf->append (JvNewStringLatin1 (s));
2590 throw new java::lang::VerifyError (buf->toString ());
2593 #endif /* INTERPRETER */