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)
162 verify_fail ("invalid signature");
167 // Return the type_val corresponding to a primitive class.
168 static type_val get_type_val_for_signature (jclass k)
170 return get_type_val_for_signature ((jchar) k->method_count);
173 // This is like _Jv_IsAssignableFrom, but it works even if SOURCE or
174 // TARGET haven't been prepared.
175 static bool is_assignable_from_slow (jclass target, jclass source)
177 // This will terminate when SOURCE==Object.
180 if (source == target)
183 if (target->isPrimitive () || source->isPrimitive ())
186 // _Jv_IsAssignableFrom can handle a target which is an
187 // interface even if it hasn't been prepared.
188 if ((target->state > JV_STATE_LINKED || target->isInterface ())
189 && source->state > JV_STATE_LINKED)
190 return _Jv_IsAssignableFrom (target, source);
192 if (target->isArray ())
194 if (! source->isArray ())
196 target = target->getComponentType ();
197 source = source->getComponentType ();
199 else if (target->isInterface ())
201 for (int i = 0; i < source->interface_count; ++i)
203 // We use a recursive call because we also need to
204 // check superinterfaces.
205 if (is_assignable_from_slow (target, source->interfaces[i]))
210 else if (target == &java::lang::Object::class$)
212 else if (source->isInterface ()
213 || source == &java::lang::Object::class$)
216 source = source->getSuperclass ();
220 // This is used to keep track of which `jsr's correspond to a given
224 // PC of the instruction just after the jsr.
230 // The `type' class is used to represent a single type in the
236 // Some associated data.
239 // For a resolved reference type, this is a pointer to the class.
241 // For other reference types, this it the name of the class.
244 // This is used when constructing a new object. It is the PC of the
245 // `new' instruction which created the object. We use the special
246 // value -2 to mean that this is uninitialized, and the special
247 // value -1 for the case where the current method is itself the
251 static const int UNINIT = -2;
252 static const int SELF = -1;
254 // Basic constructor.
257 key = unsuitable_type;
262 // Make a new instance given the type tag. We assume a generic
263 // `reference_type' means Object.
268 if (key == reference_type)
269 data.klass = &java::lang::Object::class$;
273 // Make a new instance given a class.
276 key = reference_type;
281 // Make a new instance given the name of a class.
282 type (_Jv_Utf8Const *n)
284 key = unresolved_reference_type;
297 // These operators are required because libgcj can't link in
299 void *operator new[] (size_t bytes)
301 return _Jv_Malloc (bytes);
304 void operator delete[] (void *mem)
309 type& operator= (type_val k)
317 type& operator= (const type& t)
325 // Promote a numeric type.
328 if (key == boolean_type || key == char_type
329 || key == byte_type || key == short_type)
334 // If *THIS is an unresolved reference type, resolve it.
337 if (key != unresolved_reference_type
338 && key != uninitialized_unresolved_reference_type)
341 // FIXME: class loader
342 using namespace java::lang;
343 // We might see either kind of name. Sigh.
344 if (data.name->data[0] == 'L'
345 && data.name->data[data.name->length - 1] == ';')
346 data.klass = _Jv_FindClassFromSignature (data.name->data, NULL);
348 data.klass = Class::forName (_Jv_NewStringUtf8Const (data.name),
350 key = (key == unresolved_reference_type
352 : uninitialized_reference_type);
355 // Mark this type as the uninitialized result of `new'.
356 void set_uninitialized (int npc)
358 if (key == reference_type)
359 key = uninitialized_reference_type;
360 else if (key == unresolved_reference_type)
361 key = uninitialized_unresolved_reference_type;
363 verify_fail ("internal error in type::uninitialized");
367 // Mark this type as now initialized.
368 void set_initialized (int npc)
370 if (npc != UNINIT && pc == npc
371 && (key == uninitialized_reference_type
372 || key == uninitialized_unresolved_reference_type))
374 key = (key == uninitialized_reference_type
376 : unresolved_reference_type);
382 // Return true if an object of type K can be assigned to a variable
383 // of type *THIS. Handle various special cases too. Might modify
384 // *THIS or K. Note however that this does not perform numeric
386 bool compatible (type &k)
388 // Any type is compatible with the unsuitable type.
389 if (key == unsuitable_type)
392 if (key < reference_type || k.key < reference_type)
395 // The `null' type is convertible to any reference type.
396 // FIXME: is this correct for THIS?
397 if (key == null_type || k.key == null_type)
400 // Any reference type is convertible to Object. This is a special
401 // case so we don't need to unnecessarily resolve a class.
402 if (key == reference_type
403 && data.klass == &java::lang::Object::class$)
406 // An initialized type and an uninitialized type are not
408 if (isinitialized () != k.isinitialized ())
411 // Two uninitialized objects are compatible if either:
412 // * The PCs are identical, or
413 // * One PC is UNINIT.
414 if (! isinitialized ())
416 if (pc != k.pc && pc != UNINIT && k.pc != UNINIT)
420 // Two unresolved types are equal if their names are the same.
423 && _Jv_equalUtf8Consts (data.name, k.data.name))
426 // We must resolve both types and check assignability.
429 return is_assignable_from_slow (data.klass, k.data.klass);
434 return key == void_type;
439 return key == long_type || key == double_type;
442 // Return number of stack or local variable slots taken by this
446 return iswide () ? 2 : 1;
449 bool isarray () const
451 // We treat null_type as not an array. This is ok based on the
452 // current uses of this method.
453 if (key == reference_type)
454 return data.klass->isArray ();
455 else if (key == unresolved_reference_type)
456 return data.name->data[0] == '[';
463 if (key != reference_type)
465 return data.klass->isInterface ();
471 if (key != reference_type)
473 using namespace java::lang::reflect;
474 return Modifier::isAbstract (data.klass->getModifiers ());
477 // Return the element type of an array.
480 // FIXME: maybe should do string manipulation here.
482 if (key != reference_type)
483 verify_fail ("programmer error in type::element_type()");
485 jclass k = data.klass->getComponentType ();
486 if (k->isPrimitive ())
487 return type (get_type_val_for_signature (k));
491 bool isreference () const
493 return key >= reference_type;
501 bool isinitialized () const
503 return (key == reference_type
505 || key == unresolved_reference_type);
508 bool isresolved () const
510 return (key == reference_type
512 || key == uninitialized_reference_type);
515 void verify_dimensions (int ndims)
517 // The way this is written, we don't need to check isarray().
518 if (key == reference_type)
520 jclass k = data.klass;
521 while (k->isArray () && ndims > 0)
523 k = k->getComponentType ();
529 // We know KEY == unresolved_reference_type.
530 char *p = data.name->data;
531 while (*p++ == '[' && ndims-- > 0)
536 verify_fail ("array type has fewer dimensions than required");
539 // Merge OLD_TYPE into this. On error throw exception.
540 bool merge (type& old_type, bool local_semantics = false)
542 bool changed = false;
543 bool refo = old_type.isreference ();
544 bool refn = isreference ();
547 if (old_type.key == null_type)
549 else if (key == null_type)
554 else if (isinitialized () != old_type.isinitialized ())
555 verify_fail ("merging initialized and uninitialized types");
558 if (! isinitialized ())
562 else if (old_type.pc == UNINIT)
564 else if (pc != old_type.pc)
565 verify_fail ("merging different uninitialized types");
569 && ! old_type.isresolved ()
570 && _Jv_equalUtf8Consts (data.name, old_type.data.name))
572 // Types are identical.
579 jclass k = data.klass;
580 jclass oldk = old_type.data.klass;
583 while (k->isArray () && oldk->isArray ())
586 k = k->getComponentType ();
587 oldk = oldk->getComponentType ();
590 // This loop will end when we hit Object.
593 if (is_assignable_from_slow (k, oldk))
595 k = k->getSuperclass ();
601 while (arraycount > 0)
603 // FIXME: Class loader.
604 k = _Jv_GetArrayClass (k, NULL);
612 else if (refo || refn || key != old_type.key)
616 key = unsuitable_type;
620 verify_fail ("unmergeable type");
626 // This class holds all the state information we need for a given
630 // Current top of stack.
632 // Current stack depth. This is like the top of stack but it
633 // includes wide variable information.
637 // The local variables.
639 // This is used in subroutines to keep track of which local
640 // variables have been accessed.
642 // If not 0, then we are in a subroutine. The value is the PC of
643 // the subroutine's entry point. We can use 0 as an exceptional
644 // value because PC=0 can never be a subroutine.
646 // This is used to keep a linked list of all the states which
647 // require re-verification. We use the PC to keep track.
650 // INVALID marks a state which is not on the linked list of states
651 // requiring reverification.
652 static const int INVALID = -1;
653 // NO_NEXT marks the state at the end of the reverification list.
654 static const int NO_NEXT = -2;
660 local_changed = NULL;
663 state (int max_stack, int max_locals)
667 stack = new type[max_stack];
668 for (int i = 0; i < max_stack; ++i)
669 stack[i] = unsuitable_type;
670 locals = new type[max_locals];
671 local_changed = (bool *) _Jv_Malloc (sizeof (bool) * max_locals);
672 for (int i = 0; i < max_locals; ++i)
674 locals[i] = unsuitable_type;
675 local_changed[i] = false;
681 state (const state *copy, int max_stack, int max_locals)
683 stack = new type[max_stack];
684 locals = new type[max_locals];
685 local_changed = (bool *) _Jv_Malloc (sizeof (bool) * max_locals);
697 _Jv_Free (local_changed);
700 void *operator new[] (size_t bytes)
702 return _Jv_Malloc (bytes);
705 void operator delete[] (void *mem)
710 void *operator new (size_t bytes)
712 return _Jv_Malloc (bytes);
715 void operator delete (void *mem)
720 void copy (const state *copy, int max_stack, int max_locals)
722 stacktop = copy->stacktop;
723 stackdepth = copy->stackdepth;
724 subroutine = copy->subroutine;
725 for (int i = 0; i < max_stack; ++i)
726 stack[i] = copy->stack[i];
727 for (int i = 0; i < max_locals; ++i)
729 locals[i] = copy->locals[i];
730 local_changed[i] = copy->local_changed[i];
732 // Don't modify `next'.
735 // Modify this state to reflect entry to an exception handler.
736 void set_exception (type t, int max_stack)
741 for (int i = stacktop; i < max_stack; ++i)
742 stack[i] = unsuitable_type;
744 // FIXME: subroutine handling?
747 // Merge STATE into this state. Destructively modifies this state.
748 // Returns true if the new state was in fact changed. Will throw an
749 // exception if the states are not mergeable.
750 bool merge (state *state_old, bool ret_semantics,
753 bool changed = false;
755 // Merge subroutine states. *THIS and *STATE_OLD must be in the
756 // same subroutine. Also, recursive subroutine calls must be
758 if (subroutine == state_old->subroutine)
762 else if (subroutine == 0)
764 subroutine = state_old->subroutine;
768 verify_fail ("subroutines merged");
771 if (state_old->stacktop != stacktop)
772 verify_fail ("stack sizes differ");
773 for (int i = 0; i < state_old->stacktop; ++i)
775 if (stack[i].merge (state_old->stack[i]))
779 // Merge local variables.
780 for (int i = 0; i < max_locals; ++i)
782 if (! ret_semantics || local_changed[i])
784 if (locals[i].merge (state_old->locals[i], true))
791 // If we're in a subroutine, we must compute the union of
792 // all the changed local variables.
793 if (state_old->local_changed[i])
800 // Throw an exception if there is an uninitialized object on the
801 // stack or in a local variable. EXCEPTION_SEMANTICS controls
802 // whether we're using backwards-branch or exception-handing
804 void check_no_uninitialized_objects (int max_locals,
805 bool exception_semantics = false)
807 if (! exception_semantics)
809 for (int i = 0; i < stacktop; ++i)
810 if (stack[i].isreference () && ! stack[i].isinitialized ())
811 verify_fail ("uninitialized object on stack");
814 for (int i = 0; i < max_locals; ++i)
815 if (locals[i].isreference () && ! locals[i].isinitialized ())
816 verify_fail ("uninitialized object in local variable");
819 // Note that a local variable was accessed or modified.
820 void note_variable (int index)
823 local_changed[index] = true;
826 // Mark each `new'd object we know of that was allocated at PC as
828 void set_initialized (int pc, int max_locals)
830 for (int i = 0; i < stacktop; ++i)
831 stack[i].set_initialized (pc);
832 for (int i = 0; i < max_locals; ++i)
833 locals[i].set_initialized (pc);
839 if (current_state->stacktop <= 0)
840 verify_fail ("stack empty", start_PC);
841 type r = current_state->stack[--current_state->stacktop];
842 current_state->stackdepth -= r.depth ();
843 if (current_state->stackdepth < 0)
844 verify_fail ("stack empty", start_PC);
852 verify_fail ("narrow pop of wide type", start_PC);
860 verify_fail ("wide pop of narrow type", start_PC);
864 type pop_type (type match)
868 if (! match.compatible (t))
869 verify_fail ("incompatible type on stack", start_PC);
873 void push_type (type t)
875 // If T is a numeric type like short, promote it to int.
878 int depth = t.depth ();
879 if (current_state->stackdepth + depth > current_method->max_stack)
880 verify_fail ("stack overflow");
881 current_state->stack[current_state->stacktop++] = t;
882 current_state->stackdepth += depth;
885 void set_variable (int index, type t)
887 // If T is a numeric type like short, promote it to int.
890 int depth = t.depth ();
891 if (index > current_method->max_locals - depth)
892 verify_fail ("invalid local variable");
893 current_state->locals[index] = t;
894 current_state->note_variable (index);
898 current_state->locals[index + 1] = continuation_type;
899 current_state->note_variable (index + 1);
901 if (index > 0 && current_state->locals[index - 1].iswide ())
903 current_state->locals[index - 1] = unsuitable_type;
904 // There's no need to call note_variable here.
908 type get_variable (int index, type t)
910 int depth = t.depth ();
911 if (index > current_method->max_locals - depth)
912 verify_fail ("invalid local variable", start_PC);
913 if (! t.compatible (current_state->locals[index]))
914 verify_fail ("incompatible type in local variable", start_PC);
917 type t (continuation_type);
918 if (! current_state->locals[index + 1].compatible (t))
919 verify_fail ("invalid local variable", start_PC);
921 current_state->note_variable (index);
922 return current_state->locals[index];
925 // Make sure ARRAY is an array type and that its elements are
926 // compatible with type ELEMENT. Returns the actual element type.
927 type require_array_type (type array, type element)
929 if (! array.isarray ())
930 verify_fail ("array required");
932 type t = array.element_type ();
933 if (! element.compatible (t))
934 verify_fail ("incompatible array element type");
936 // Return T and not ELEMENT, because T might be specialized.
942 if (PC >= current_method->code_length)
943 verify_fail ("premature end of bytecode");
944 return (jint) bytecode[PC++] & 0xff;
949 jint b1 = get_byte ();
950 jint b2 = get_byte ();
951 return (jint) ((b1 << 8) | b2) & 0xffff;
956 jint b1 = get_byte ();
957 jint b2 = get_byte ();
958 jshort s = (b1 << 8) | b2;
964 jint b1 = get_byte ();
965 jint b2 = get_byte ();
966 jint b3 = get_byte ();
967 jint b4 = get_byte ();
968 return (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
971 int compute_jump (int offset)
973 int npc = start_PC + offset;
974 if (npc < 0 || npc >= current_method->code_length)
975 verify_fail ("branch out of range");
979 // Merge the indicated state into a new state and schedule a new PC if
980 // there is a change. If RET_SEMANTICS is true, then we are merging
981 // from a `ret' instruction into the instruction after a `jsr'. This
982 // is a special case with its own modified semantics.
983 void push_jump_merge (int npc, state *nstate, bool ret_semantics = false)
986 if (states[npc] == NULL)
988 // FIXME: what if we reach this code from a `ret'?
990 states[npc] = new state (nstate, current_method->max_stack,
991 current_method->max_locals);
994 changed = nstate->merge (states[npc], ret_semantics,
995 current_method->max_stack);
997 if (changed && states[npc]->next == state::INVALID)
999 // The merge changed the state, and the new PC isn't yet on our
1000 // list of PCs to re-verify.
1001 states[npc]->next = next_verify_pc;
1002 next_verify_pc = npc;
1006 void push_jump (int offset)
1008 int npc = compute_jump (offset);
1010 current_state->check_no_uninitialized_objects (current_method->max_stack);
1011 push_jump_merge (npc, current_state);
1014 void push_exception_jump (type t, int pc)
1016 current_state->check_no_uninitialized_objects (current_method->max_stack,
1018 state s (current_state, current_method->max_stack,
1019 current_method->max_locals);
1020 s.set_exception (t, current_method->max_stack);
1021 push_jump_merge (pc, &s);
1026 int npc = next_verify_pc;
1027 if (npc != state::NO_NEXT)
1029 next_verify_pc = states[npc]->next;
1030 states[npc]->next = state::INVALID;
1035 void invalidate_pc ()
1037 PC = state::NO_NEXT;
1040 void note_branch_target (int pc, bool is_jsr_target = false)
1042 if (pc <= PC && ! (flags[pc] & FLAG_INSN_START))
1043 verify_fail ("branch not to instruction start");
1044 flags[pc] |= FLAG_BRANCH_TARGET;
1047 // Record the jsr which called this instruction.
1048 subr_info *info = (subr_info *) _Jv_Malloc (sizeof (subr_info));
1050 info->next = jsr_ptrs[pc];
1051 jsr_ptrs[pc] = info;
1052 flags[pc] |= FLAG_JSR_TARGET;
1056 void skip_padding ()
1058 while ((PC % 4) > 0)
1059 if (get_byte () != 0)
1060 verify_fail ("found nonzero padding byte");
1063 // Return the subroutine to which the instruction at PC belongs.
1064 int get_subroutine (int pc)
1066 if (states[pc] == NULL)
1068 return states[pc]->subroutine;
1071 // Do the work for a `ret' instruction. INDEX is the index into the
1073 void handle_ret_insn (int index)
1075 get_variable (index, return_address_type);
1077 int csub = current_state->subroutine;
1079 verify_fail ("no subroutine");
1081 for (subr_info *subr = jsr_ptrs[csub]; subr != NULL; subr = subr->next)
1083 // Temporarily modify the current state so it looks like we're
1084 // in the enclosing context.
1085 current_state->subroutine = get_subroutine (subr->pc);
1087 current_state->check_no_uninitialized_objects (current_method->max_stack);
1088 push_jump_merge (subr->pc, current_state, true);
1091 current_state->subroutine = csub;
1095 // We're in the subroutine SUB, calling a subroutine at DEST. Make
1096 // sure this subroutine isn't already on the stack.
1097 void check_nonrecursive_call (int sub, int dest)
1102 verify_fail ("recursive subroutine call");
1103 for (subr_info *info = jsr_ptrs[sub]; info != NULL; info = info->next)
1104 check_nonrecursive_call (get_subroutine (info->pc), dest);
1107 void handle_jsr_insn (int offset)
1109 int npc = compute_jump (offset);
1112 current_state->check_no_uninitialized_objects (current_method->max_stack);
1113 check_nonrecursive_call (current_state->subroutine, npc);
1115 // Temporarily modify the current state so that it looks like we are
1116 // in the subroutine.
1117 push_type (return_address_type);
1118 int save = current_state->subroutine;
1119 current_state->subroutine = npc;
1121 // Merge into the subroutine.
1122 push_jump_merge (npc, current_state);
1124 // Undo our modifications.
1125 current_state->subroutine = save;
1126 pop_type (return_address_type);
1129 jclass construct_primitive_array_type (type_val prim)
1135 k = JvPrimClass (boolean);
1138 k = JvPrimClass (char);
1141 k = JvPrimClass (float);
1144 k = JvPrimClass (double);
1147 k = JvPrimClass (byte);
1150 k = JvPrimClass (short);
1153 k = JvPrimClass (int);
1156 k = JvPrimClass (long);
1159 verify_fail ("unknown type in construct_primitive_array_type");
1161 k = _Jv_GetArrayClass (k, NULL);
1165 // This pass computes the location of branch targets and also
1166 // instruction starts.
1167 void branch_prepass ()
1169 flags = (char *) _Jv_Malloc (current_method->code_length);
1170 jsr_ptrs = (subr_info **) _Jv_Malloc (sizeof (subr_info *)
1171 * current_method->code_length);
1173 for (int i = 0; i < current_method->code_length; ++i)
1179 bool last_was_jsr = false;
1182 while (PC < current_method->code_length)
1184 flags[PC] |= FLAG_INSN_START;
1186 // If the previous instruction was a jsr, then the next
1187 // instruction is a branch target -- the branch being the
1188 // corresponding `ret'.
1190 note_branch_target (PC);
1191 last_was_jsr = false;
1194 unsigned char opcode = bytecode[PC++];
1198 case op_aconst_null:
1335 case op_monitorenter:
1336 case op_monitorexit:
1359 case op_arraylength:
1375 case op_invokespecial:
1376 case op_invokestatic:
1377 case op_invokevirtual:
1381 case op_multianewarray:
1387 last_was_jsr = true;
1406 note_branch_target (compute_jump (get_short ()), last_was_jsr);
1409 case op_tableswitch:
1412 note_branch_target (compute_jump (get_int ()));
1413 jint low = get_int ();
1414 jint hi = get_int ();
1416 verify_fail ("invalid tableswitch", start_PC);
1417 for (int i = low; i <= hi; ++i)
1418 note_branch_target (compute_jump (get_int ()));
1422 case op_lookupswitch:
1425 note_branch_target (compute_jump (get_int ()));
1426 int npairs = get_int ();
1428 verify_fail ("too few pairs in lookupswitch", start_PC);
1429 while (npairs-- > 0)
1432 note_branch_target (compute_jump (get_int ()));
1437 case op_invokeinterface:
1445 opcode = get_byte ();
1447 if (opcode == (unsigned char) op_iinc)
1453 last_was_jsr = true;
1456 note_branch_target (compute_jump (get_int ()), last_was_jsr);
1460 verify_fail ("unrecognized instruction in branch_prepass",
1464 // See if any previous branch tried to branch to the middle of
1465 // this instruction.
1466 for (int pc = start_PC + 1; pc < PC; ++pc)
1468 if ((flags[pc] & FLAG_BRANCH_TARGET))
1469 verify_fail ("branch to middle of instruction", pc);
1473 // Verify exception handlers.
1474 for (int i = 0; i < current_method->exc_count; ++i)
1476 if (! (flags[exception[i].handler_pc] & FLAG_INSN_START))
1477 verify_fail ("exception handler not at instruction start",
1478 exception[i].handler_pc);
1479 if (exception[i].start_pc > exception[i].end_pc)
1480 verify_fail ("exception range inverted");
1481 if (! (flags[exception[i].start_pc] & FLAG_INSN_START))
1482 verify_fail ("exception start not at instruction start",
1483 exception[i].start_pc);
1484 else if (! (flags[exception[i].end_pc] & FLAG_INSN_START))
1485 verify_fail ("exception end not at instruction start",
1486 exception[i].end_pc);
1488 flags[exception[i].handler_pc] |= FLAG_BRANCH_TARGET;
1492 void check_pool_index (int index)
1494 if (index < 0 || index >= current_class->constants.size)
1495 verify_fail ("constant pool index out of range", start_PC);
1498 type check_class_constant (int index)
1500 check_pool_index (index);
1501 _Jv_Constants *pool = ¤t_class->constants;
1502 if (pool->tags[index] == JV_CONSTANT_ResolvedClass)
1503 return type (pool->data[index].clazz);
1504 else if (pool->tags[index] == JV_CONSTANT_Class)
1505 return type (pool->data[index].utf8);
1506 verify_fail ("expected class constant", start_PC);
1509 type check_constant (int index)
1511 check_pool_index (index);
1512 _Jv_Constants *pool = ¤t_class->constants;
1513 if (pool->tags[index] == JV_CONSTANT_ResolvedString
1514 || pool->tags[index] == JV_CONSTANT_String)
1515 return type (&java::lang::String::class$);
1516 else if (pool->tags[index] == JV_CONSTANT_Integer)
1517 return type (int_type);
1518 else if (pool->tags[index] == JV_CONSTANT_Float)
1519 return type (float_type);
1520 verify_fail ("String, int, or float constant expected", start_PC);
1523 type check_wide_constant (int index)
1525 check_pool_index (index);
1526 _Jv_Constants *pool = ¤t_class->constants;
1527 if (pool->tags[index] == JV_CONSTANT_Long)
1528 return type (long_type);
1529 else if (pool->tags[index] == JV_CONSTANT_Double)
1530 return type (double_type);
1531 verify_fail ("long or double constant expected", start_PC);
1534 // Helper for both field and method. These are laid out the same in
1535 // the constant pool.
1536 type handle_field_or_method (int index, int expected,
1537 _Jv_Utf8Const **name,
1538 _Jv_Utf8Const **fmtype)
1540 check_pool_index (index);
1541 _Jv_Constants *pool = ¤t_class->constants;
1542 if (pool->tags[index] != expected)
1543 verify_fail ("didn't see expected constant", start_PC);
1544 // Once we know we have a Fieldref or Methodref we assume that it
1545 // is correctly laid out in the constant pool. I think the code
1546 // in defineclass.cc guarantees this.
1547 _Jv_ushort class_index, name_and_type_index;
1548 _Jv_loadIndexes (&pool->data[index],
1550 name_and_type_index);
1551 _Jv_ushort name_index, desc_index;
1552 _Jv_loadIndexes (&pool->data[name_and_type_index],
1553 name_index, desc_index);
1555 *name = pool->data[name_index].utf8;
1556 *fmtype = pool->data[desc_index].utf8;
1558 return check_class_constant (class_index);
1561 // Return field's type, compute class' type if requested.
1562 type check_field_constant (int index, type *class_type = NULL)
1564 _Jv_Utf8Const *name, *field_type;
1565 type ct = handle_field_or_method (index,
1566 JV_CONSTANT_Fieldref,
1567 &name, &field_type);
1570 if (field_type->data[0] == '[' || field_type->data[0] == 'L')
1571 return type (field_type);
1572 return get_type_val_for_signature (field_type->data[0]);
1575 type check_method_constant (int index, bool is_interface,
1576 _Jv_Utf8Const **method_name,
1577 _Jv_Utf8Const **method_signature)
1579 return handle_field_or_method (index,
1581 ? JV_CONSTANT_InterfaceMethodref
1582 : JV_CONSTANT_Methodref),
1583 method_name, method_signature);
1586 type get_one_type (char *&p)
1604 // FIXME! This will get collected!
1605 _Jv_Utf8Const *name = _Jv_makeUtf8Const (start, p - start);
1609 // Casting to jchar here is ok since we are looking at an ASCII
1611 type_val rt = get_type_val_for_signature (jchar (v));
1613 if (arraycount == 0)
1615 // Callers of this function eventually push their arguments on
1616 // the stack. So, promote them here.
1617 return type (rt).promote ();
1620 jclass k = construct_primitive_array_type (rt);
1621 while (--arraycount > 0)
1622 k = _Jv_GetArrayClass (k, NULL);
1626 void compute_argument_types (_Jv_Utf8Const *signature,
1629 char *p = signature->data;
1635 types[i++] = get_one_type (p);
1638 type compute_return_type (_Jv_Utf8Const *signature)
1640 char *p = signature->data;
1644 return get_one_type (p);
1647 void check_return_type (type onstack)
1649 type rt = compute_return_type (current_method->self->signature);
1650 if (! rt.compatible (onstack))
1651 verify_fail ("incompatible return type", start_PC);
1654 void verify_instructions_0 ()
1656 current_state = new state (current_method->max_stack,
1657 current_method->max_locals);
1665 using namespace java::lang::reflect;
1666 if (! Modifier::isStatic (current_method->self->accflags))
1668 type kurr (current_class);
1669 if (_Jv_equalUtf8Consts (current_method->self->name, gcj::init_name))
1670 kurr.set_uninitialized (type::SELF);
1671 set_variable (0, kurr);
1675 // We have to handle wide arguments specially here.
1676 int arg_count = _Jv_count_arguments (current_method->self->signature);
1677 type arg_types[arg_count];
1678 compute_argument_types (current_method->self->signature, arg_types);
1679 for (int i = 0; i < arg_count; ++i)
1681 set_variable (var, arg_types[i]);
1683 if (arg_types[i].iswide ())
1688 states = (state **) _Jv_Malloc (sizeof (state *)
1689 * current_method->code_length);
1690 for (int i = 0; i < current_method->code_length; ++i)
1693 next_verify_pc = state::NO_NEXT;
1697 // If the PC was invalidated, get a new one from the work list.
1698 if (PC == state::NO_NEXT)
1701 if (PC == state::INVALID)
1702 verify_fail ("saw state::INVALID", start_PC);
1703 if (PC == state::NO_NEXT)
1705 // Set up the current state.
1706 *current_state = *states[PC];
1709 // Control can't fall off the end of the bytecode.
1710 if (PC >= current_method->code_length)
1711 verify_fail ("fell off end");
1713 if (states[PC] != NULL)
1715 // We've already visited this instruction. So merge the
1716 // states together. If this yields no change then we don't
1717 // have to re-verify.
1718 if (! current_state->merge (states[PC], false,
1719 current_method->max_stack))
1724 // Save a copy of it for later.
1725 states[PC]->copy (current_state, current_method->max_stack,
1726 current_method->max_locals);
1728 else if ((flags[PC] & FLAG_BRANCH_TARGET))
1730 // We only have to keep saved state at branch targets.
1731 states[PC] = new state (current_state, current_method->max_stack,
1732 current_method->max_locals);
1735 // Update states for all active exception handlers. Ordinarily
1736 // there are not many exception handlers. So we simply run
1737 // through them all.
1738 for (int i = 0; i < current_method->exc_count; ++i)
1740 if (PC >= exception[i].start_pc && PC < exception[i].end_pc)
1742 type handler = reference_type;
1743 if (exception[i].handler_type != 0)
1744 handler = check_class_constant (exception[i].handler_type);
1745 push_exception_jump (handler, exception[i].handler_pc);
1750 unsigned char opcode = bytecode[PC++];
1756 case op_aconst_null:
1757 push_type (null_type);
1767 push_type (int_type);
1772 push_type (long_type);
1778 push_type (float_type);
1783 push_type (double_type);
1788 push_type (int_type);
1793 push_type (int_type);
1797 push_type (check_constant (get_byte ()));
1800 push_type (check_constant (get_ushort ()));
1803 push_type (check_wide_constant (get_ushort ()));
1807 push_type (get_variable (get_byte (), int_type));
1810 push_type (get_variable (get_byte (), long_type));
1813 push_type (get_variable (get_byte (), float_type));
1816 push_type (get_variable (get_byte (), double_type));
1819 push_type (get_variable (get_byte (), reference_type));
1826 push_type (get_variable (opcode - op_iload_0, int_type));
1832 push_type (get_variable (opcode - op_lload_0, long_type));
1838 push_type (get_variable (opcode - op_fload_0, float_type));
1844 push_type (get_variable (opcode - op_dload_0, double_type));
1850 push_type (get_variable (opcode - op_aload_0, reference_type));
1853 pop_type (int_type);
1854 push_type (require_array_type (pop_type (reference_type),
1858 pop_type (int_type);
1859 push_type (require_array_type (pop_type (reference_type),
1863 pop_type (int_type);
1864 push_type (require_array_type (pop_type (reference_type),
1868 pop_type (int_type);
1869 push_type (require_array_type (pop_type (reference_type),
1873 pop_type (int_type);
1874 push_type (require_array_type (pop_type (reference_type),
1878 pop_type (int_type);
1879 require_array_type (pop_type (reference_type), byte_type);
1880 push_type (int_type);
1883 pop_type (int_type);
1884 require_array_type (pop_type (reference_type), char_type);
1885 push_type (int_type);
1888 pop_type (int_type);
1889 require_array_type (pop_type (reference_type), short_type);
1890 push_type (int_type);
1893 set_variable (get_byte (), pop_type (int_type));
1896 set_variable (get_byte (), pop_type (long_type));
1899 set_variable (get_byte (), pop_type (float_type));
1902 set_variable (get_byte (), pop_type (double_type));
1905 set_variable (get_byte (), pop_type (reference_type));
1911 set_variable (opcode - op_istore_0, pop_type (int_type));
1917 set_variable (opcode - op_lstore_0, pop_type (long_type));
1923 set_variable (opcode - op_fstore_0, pop_type (float_type));
1929 set_variable (opcode - op_dstore_0, pop_type (double_type));
1935 set_variable (opcode - op_astore_0, pop_type (reference_type));
1938 pop_type (int_type);
1939 pop_type (int_type);
1940 require_array_type (pop_type (reference_type), int_type);
1943 pop_type (long_type);
1944 pop_type (int_type);
1945 require_array_type (pop_type (reference_type), long_type);
1948 pop_type (float_type);
1949 pop_type (int_type);
1950 require_array_type (pop_type (reference_type), float_type);
1953 pop_type (double_type);
1954 pop_type (int_type);
1955 require_array_type (pop_type (reference_type), double_type);
1958 pop_type (reference_type);
1959 pop_type (int_type);
1960 require_array_type (pop_type (reference_type), reference_type);
1963 pop_type (int_type);
1964 pop_type (int_type);
1965 require_array_type (pop_type (reference_type), byte_type);
1968 pop_type (int_type);
1969 pop_type (int_type);
1970 require_array_type (pop_type (reference_type), char_type);
1973 pop_type (int_type);
1974 pop_type (int_type);
1975 require_array_type (pop_type (reference_type), short_type);
2002 type t2 = pop_raw ();
2017 type t = pop_raw ();
2030 type t1 = pop_raw ();
2048 type t1 = pop_raw ();
2051 type t2 = pop_raw ();
2069 type t3 = pop_raw ();
2107 pop_type (int_type);
2108 push_type (pop_type (int_type));
2121 pop_type (long_type);
2122 push_type (pop_type (long_type));
2129 pop_type (float_type);
2130 push_type (pop_type (float_type));
2137 pop_type (double_type);
2138 push_type (pop_type (double_type));
2144 push_type (pop_type (int_type));
2147 push_type (pop_type (long_type));
2150 push_type (pop_type (float_type));
2153 push_type (pop_type (double_type));
2156 get_variable (get_byte (), int_type);
2160 pop_type (int_type);
2161 push_type (long_type);
2164 pop_type (int_type);
2165 push_type (float_type);
2168 pop_type (int_type);
2169 push_type (double_type);
2172 pop_type (long_type);
2173 push_type (int_type);
2176 pop_type (long_type);
2177 push_type (float_type);
2180 pop_type (long_type);
2181 push_type (double_type);
2184 pop_type (float_type);
2185 push_type (int_type);
2188 pop_type (float_type);
2189 push_type (long_type);
2192 pop_type (float_type);
2193 push_type (double_type);
2196 pop_type (double_type);
2197 push_type (int_type);
2200 pop_type (double_type);
2201 push_type (long_type);
2204 pop_type (double_type);
2205 push_type (float_type);
2208 pop_type (long_type);
2209 pop_type (long_type);
2210 push_type (int_type);
2214 pop_type (float_type);
2215 pop_type (float_type);
2216 push_type (int_type);
2220 pop_type (double_type);
2221 pop_type (double_type);
2222 push_type (int_type);
2230 pop_type (int_type);
2231 push_jump (get_short ());
2239 pop_type (int_type);
2240 pop_type (int_type);
2241 push_jump (get_short ());
2245 pop_type (reference_type);
2246 pop_type (reference_type);
2247 push_jump (get_short ());
2250 push_jump (get_short ());
2254 handle_jsr_insn (get_short ());
2257 handle_ret_insn (get_byte ());
2259 case op_tableswitch:
2261 pop_type (int_type);
2263 push_jump (get_int ());
2264 jint low = get_int ();
2265 jint high = get_int ();
2266 // Already checked LOW -vs- HIGH.
2267 for (int i = low; i <= high; ++i)
2268 push_jump (get_int ());
2273 case op_lookupswitch:
2275 pop_type (int_type);
2277 push_jump (get_int ());
2278 jint npairs = get_int ();
2279 // Already checked NPAIRS >= 0.
2281 for (int i = 0; i < npairs; ++i)
2283 jint key = get_int ();
2284 if (i > 0 && key <= lastkey)
2285 verify_fail ("lookupswitch pairs unsorted", start_PC);
2287 push_jump (get_int ());
2293 check_return_type (pop_type (int_type));
2297 check_return_type (pop_type (long_type));
2301 check_return_type (pop_type (float_type));
2305 check_return_type (pop_type (double_type));
2309 check_return_type (pop_type (reference_type));
2313 check_return_type (void_type);
2317 push_type (check_field_constant (get_ushort ()));
2320 pop_type (check_field_constant (get_ushort ()));
2325 type field = check_field_constant (get_ushort (), &klass);
2333 type field = check_field_constant (get_ushort (), &klass);
2339 case op_invokevirtual:
2340 case op_invokespecial:
2341 case op_invokestatic:
2342 case op_invokeinterface:
2344 _Jv_Utf8Const *method_name, *method_signature;
2346 = check_method_constant (get_ushort (),
2347 opcode == (unsigned char) op_invokeinterface,
2350 int arg_count = _Jv_count_arguments (method_signature);
2351 if (opcode == (unsigned char) op_invokeinterface)
2353 int nargs = get_byte ();
2355 verify_fail ("too few arguments to invokeinterface",
2357 if (get_byte () != 0)
2358 verify_fail ("invokeinterface dummy byte is wrong",
2360 if (nargs - 1 != arg_count)
2361 verify_fail ("wrong argument count for invokeinterface",
2365 bool is_init = false;
2366 if (_Jv_equalUtf8Consts (method_name, gcj::init_name))
2369 if (opcode != (unsigned char) op_invokespecial)
2370 verify_fail ("can't invoke <init>", start_PC);
2372 else if (method_name->data[0] == '<')
2373 verify_fail ("can't invoke method starting with `<'",
2376 // Pop arguments and check types.
2377 type arg_types[arg_count];
2378 compute_argument_types (method_signature, arg_types);
2379 for (int i = arg_count - 1; i >= 0; --i)
2380 pop_type (arg_types[i]);
2382 if (opcode != (unsigned char) op_invokestatic)
2384 type t = class_type;
2387 // In this case the PC doesn't matter.
2388 t.set_uninitialized (type::UNINIT);
2392 current_state->set_initialized (t.get_pc (),
2393 current_method->max_locals);
2396 type rt = compute_return_type (method_signature);
2404 type t = check_class_constant (get_ushort ());
2405 if (t.isarray () || t.isinterface () || t.isabstract ())
2406 verify_fail ("type is array, interface, or abstract",
2408 t.set_uninitialized (start_PC);
2415 int atype = get_byte ();
2416 // We intentionally have chosen constants to make this
2418 if (atype < boolean_type || atype > long_type)
2419 verify_fail ("type not primitive", start_PC);
2420 pop_type (int_type);
2421 push_type (construct_primitive_array_type (type_val (atype)));
2425 pop_type (int_type);
2426 push_type (check_class_constant (get_ushort ()));
2428 case op_arraylength:
2430 type t = pop_type (reference_type);
2432 verify_fail ("array type expected", start_PC);
2433 push_type (int_type);
2437 pop_type (type (&java::lang::Throwable::class$));
2441 pop_type (reference_type);
2442 push_type (check_class_constant (get_ushort ()));
2445 pop_type (reference_type);
2446 check_class_constant (get_ushort ());
2447 push_type (int_type);
2449 case op_monitorenter:
2450 pop_type (reference_type);
2452 case op_monitorexit:
2453 pop_type (reference_type);
2457 switch (get_byte ())
2460 push_type (get_variable (get_ushort (), int_type));
2463 push_type (get_variable (get_ushort (), long_type));
2466 push_type (get_variable (get_ushort (), float_type));
2469 push_type (get_variable (get_ushort (), double_type));
2472 push_type (get_variable (get_ushort (), reference_type));
2475 set_variable (get_ushort (), pop_type (int_type));
2478 set_variable (get_ushort (), pop_type (long_type));
2481 set_variable (get_ushort (), pop_type (float_type));
2484 set_variable (get_ushort (), pop_type (double_type));
2487 set_variable (get_ushort (), pop_type (reference_type));
2490 handle_ret_insn (get_short ());
2493 get_variable (get_ushort (), int_type);
2497 verify_fail ("unrecognized wide instruction", start_PC);
2501 case op_multianewarray:
2503 type atype = check_class_constant (get_ushort ());
2504 int dim = get_byte ();
2506 verify_fail ("too few dimensions to multianewarray", start_PC);
2507 atype.verify_dimensions (dim);
2508 for (int i = 0; i < dim; ++i)
2509 pop_type (int_type);
2515 pop_type (reference_type);
2516 push_jump (get_short ());
2519 push_jump (get_int ());
2523 handle_jsr_insn (get_int ());
2527 // Unrecognized opcode.
2528 verify_fail ("unrecognized instruction in verify_instructions_0",
2536 void verify_instructions ()
2539 verify_instructions_0 ();
2542 _Jv_BytecodeVerifier (_Jv_InterpMethod *m)
2545 bytecode = m->bytecode ();
2546 exception = m->exceptions ();
2547 current_class = m->defining_class;
2554 ~_Jv_BytecodeVerifier ()
2561 _Jv_Free (jsr_ptrs);
2566 _Jv_VerifyMethod (_Jv_InterpMethod *meth)
2568 _Jv_BytecodeVerifier v (meth);
2569 v.verify_instructions ();
2572 // FIXME: add more info, like PC, when required.
2574 verify_fail (char *s, jint pc)
2576 using namespace java::lang;
2577 StringBuffer *buf = new StringBuffer ();
2579 buf->append (JvNewStringLatin1 ("verification failed"));
2582 buf->append (JvNewStringLatin1 (" at PC "));
2585 buf->append (JvNewStringLatin1 (": "));
2586 buf->append (JvNewStringLatin1 (s));
2587 throw new java::lang::VerifyError (buf->toString ());
2590 #endif /* INTERPRETER */