示例#1
0
/* Verify the bytecodes of the current method, with the instructions
   starting at BYTE_OPS and LENGTH in number, from the class file pointed to
   by JCF.
   Return 1 on success, 0 on failure.  */
int
verify_jvm_instructions (JCF* jcf, const unsigned char *byte_ops, long length)
{
  tree label;
  int wide = 0;
  int op_code;
  int PC;
  int oldpc = 0; /* PC of start of instruction. */
  int prevpc = 0;  /* If >= 0, PC of previous instruction. */
  const char *message = 0;
  char *pmessage;
  int i;
  int index;
  unsigned char *p;
  struct eh_range *prev_eh_ranges = NULL_EH_RANGE;
  struct eh_range *eh_ranges;
  tree return_type = TREE_TYPE (TREE_TYPE (current_function_decl));
  struct pc_index *starts;
  int eh_count;

  jint int_value = -1;

  pending_blocks = NULL_TREE;

  current_subr = NULL_TREE;

  /* Handle the exception table.  */
  method_init_exceptions ();
  JCF_SEEK (jcf, DECL_CODE_OFFSET (current_function_decl) + length);
  eh_count = JCF_readu2 (jcf);

  /* We read the exception handlers in order of increasing start PC.
     To do this we first read and sort the start PCs.  */
  starts = xmalloc (eh_count * sizeof (struct pc_index));
  for (i = 0; i < eh_count; ++i)
    {
      starts[i].start_pc = GET_u2 (jcf->read_ptr + 8 * i);
      starts[i].index = i;
    }
  qsort (starts, eh_count, sizeof (struct pc_index), start_pc_cmp);

  for (i = 0; i < eh_count; ++i)
    {
      int start_pc, end_pc, handler_pc, catch_type;

      p = jcf->read_ptr + 8 * starts[i].index;

      start_pc = GET_u2 (p);
      end_pc = GET_u2 (p+2);
      handler_pc = GET_u2 (p+4);
      catch_type = GET_u2 (p+6);

      if (start_pc < 0 || start_pc >= length
	  || end_pc < 0 || end_pc > length || start_pc >= end_pc
	  || handler_pc < 0 || handler_pc >= length
	  || ! (instruction_bits[start_pc] & BCODE_INSTRUCTION_START)
	  || (end_pc < length &&
	     ! (instruction_bits[end_pc] & BCODE_INSTRUCTION_START))
	  || ! (instruction_bits[handler_pc] & BCODE_INSTRUCTION_START))
	{
	  error ("bad pc in exception_table");
	  free (starts);
	  return 0;
	}

      add_handler (start_pc, end_pc,
		   lookup_label (handler_pc),
		   catch_type == 0 ? NULL_TREE
		   : get_class_constant (jcf, catch_type));

      instruction_bits[handler_pc] |= BCODE_EXCEPTION_TARGET;
    }

  free (starts);
  handle_nested_ranges ();

  for (PC = 0;;)
    {
      tree type, tmp;

      if (((PC != INVALID_PC
	   && instruction_bits[PC] & BCODE_TARGET) != 0)
	  || PC == 0)
	{
	  PUSH_PENDING (lookup_label (PC));
	  INVALIDATE_PC;
	}

      /* Check if there are any more pending blocks in the current
	 subroutine.  Because we push pending blocks in a
	 last-in-first-out order, and because we don't push anything
	 from our caller until we are done with this subroutine or
	 anything nested in it, we are done if the top of the
	 pending_blocks stack is not in a subroutine, or it is in our
	 caller. */
      if (current_subr && PC == INVALID_PC)
	{
	  if (pending_blocks == NULL_TREE
	      || (subroutine_nesting (pending_blocks)
		  < subroutine_nesting (current_subr)))
	    {
	      int size
                = DECL_MAX_LOCALS (current_function_decl) + stack_pointer;

	      tree ret_map = LABEL_RETURN_TYPE_STATE (current_subr);
	      tmp = LABEL_RETURN_LABELS (current_subr);
	      
	      /* FIXME: If we exit a subroutine via a throw, we might
		 have returned to an earlier caller.  Obviously a
		 "ret" can only return one level, but a throw may
		 return many levels.  */
	      current_subr = LABEL_SUBR_CONTEXT (current_subr);

	      if (RETURN_MAP_ADJUSTED (ret_map))
		{
		  /* Since we are done with this subroutine, set up
		     the (so far known) return address as pending -
		     with the merged type state.  */
		  for ( ; tmp != NULL_TREE;  tmp = TREE_CHAIN (tmp))
		    {
		      tree return_label = TREE_VALUE (tmp);
		      tree return_state = LABEL_TYPE_STATE (return_label);
		      if (return_state == NULL_TREE)
			{
			  /* This means we had not verified the subroutine
                             earlier, so this is the first jsr to call it.
                             In this case, the type_map of the return
			     address is just the current type_map - and that
			     is handled by the following PUSH_PENDING.  */
			}
		      else
			{
			  /* In this case we have to do a merge.  But first
			     restore the type_map for unused slots to those
			     that were in effect at the jsr.  */
			  for (index = size; --index >= 0; )
			    {
			      type_map[index]
                                = TREE_VEC_ELT (ret_map, index);

			      if (type_map[index] == TYPE_UNUSED)
				type_map[index]
				  = TREE_VEC_ELT (return_state, index);
			    }
			}
		      PUSH_PENDING (return_label);
		    }
		}
	    }
	}

      if (PC == INVALID_PC)
	{
	  label = pending_blocks;

	  if (label == NULL_TREE)
	    break;  /* We're done! */

	  pending_blocks = LABEL_PENDING_CHAIN (label);
	  LABEL_CHANGED (label) = 0;

	  if (LABEL_IN_SUBR (label))
	    current_subr = LABEL_SUBR_START (label);
	  else
	    current_subr = NULL_TREE;

	  /* Restore type_map and stack_pointer from
	     LABEL_TYPE_STATE (label), and continue
	     compiling from there.  */
	  load_type_state (label);

	  PC = LABEL_PC (label);
	}
      else if (PC >= length)
	VERIFICATION_ERROR ("falling through the end of the method");


      oldpc = PC;

      if (! (instruction_bits[PC] & BCODE_INSTRUCTION_START) && ! wide)
	VERIFICATION_ERROR ("PC not at instruction start");

      instruction_bits[PC] |= BCODE_VERIFIED;

      eh_ranges = find_handler (oldpc);

      op_code = byte_ops[PC++];
      switch (op_code)
	{
	  int is_static, is_putting;

	case OPCODE_nop:
	  break;

	case OPCODE_iconst_m1:
	case OPCODE_iconst_0:	case OPCODE_iconst_1:	case OPCODE_iconst_2:
	case OPCODE_iconst_3:	case OPCODE_iconst_4:	case OPCODE_iconst_5:
	  i = op_code - OPCODE_iconst_0;
	  goto push_int;
	push_int:
	  if (byte_ops[PC] == OPCODE_newarray
	      || byte_ops[PC] == OPCODE_anewarray)
	    int_value = i;
	  PUSH_TYPE (int_type_node);  break;

	case OPCODE_lconst_0:	case OPCODE_lconst_1:
	  PUSH_TYPE (long_type_node);  break;

	case OPCODE_fconst_0:	case OPCODE_fconst_1:	case OPCODE_fconst_2:
	  PUSH_TYPE (float_type_node);  break;

	case OPCODE_dconst_0:	case OPCODE_dconst_1:
	  PUSH_TYPE (double_type_node);  break;

	case OPCODE_bipush:
	  i = IMMEDIATE_s1;
	  goto push_int;

	case OPCODE_sipush:
	  i = IMMEDIATE_s2;
	  goto push_int;

	case OPCODE_iload:  type = int_type_node;  goto general_load;
	case OPCODE_lload:  type = long_type_node;  goto general_load;
	case OPCODE_fload:  type = float_type_node;  goto general_load;
	case OPCODE_dload:  type = double_type_node;  goto general_load;
	case OPCODE_aload:  type = ptr_type_node;  goto general_load;
	general_load:
	index = wide ? IMMEDIATE_u2 : IMMEDIATE_u1;
	wide = 0;
	goto load;
	case OPCODE_iload_0:  type = int_type_node;  index = 0; goto load;
	case OPCODE_iload_1:  type = int_type_node;  index = 1; goto load;
	case OPCODE_iload_2:  type = int_type_node;  index = 2; goto load;
	case OPCODE_iload_3:  type = int_type_node;  index = 3; goto load;
	case OPCODE_lload_0:  type = long_type_node; index = 0; goto load;
	case OPCODE_lload_1:  type = long_type_node; index = 1; goto load;
	case OPCODE_lload_2:  type = long_type_node; index = 2; goto load;
	case OPCODE_lload_3:  type = long_type_node; index = 3; goto load;
	case OPCODE_fload_0:  type = float_type_node; index = 0; goto load;
	case OPCODE_fload_1:  type = float_type_node; index = 1; goto load;
	case OPCODE_fload_2:  type = float_type_node; index = 2; goto load;
	case OPCODE_fload_3:  type = float_type_node; index = 3; goto load;
	case OPCODE_dload_0: type = double_type_node; index = 0; goto load;
	case OPCODE_dload_1: type = double_type_node; index = 1; goto load;
	case OPCODE_dload_2: type = double_type_node; index = 2; goto load;
	case OPCODE_dload_3: type = double_type_node; index = 3; goto load;
	case OPCODE_aload_0:  type = ptr_type_node;  index = 0;  goto load;
	case OPCODE_aload_1:  type = ptr_type_node;  index = 1;  goto load;
	case OPCODE_aload_2:  type = ptr_type_node;  index = 2;  goto load;
	case OPCODE_aload_3:  type = ptr_type_node;  index = 3;  goto load;
	load:
	if (index < 0
	    || (index + TYPE_IS_WIDE (type)
		>= DECL_MAX_LOCALS (current_function_decl)))
	  VERIFICATION_ERROR_WITH_INDEX
	    ("invalid local variable index %d in load");
	tmp = type_map[index];
	if (tmp == TYPE_UNKNOWN)
	  VERIFICATION_ERROR_WITH_INDEX
	    ("loading local variable %d which has unknown type");
	else if (tmp == TYPE_SECOND
	    || (TYPE_IS_WIDE (type)
		&& type_map[index+1] != void_type_node)
	    || (type == ptr_type_node
		? TREE_CODE (tmp) != POINTER_TYPE
		: type == int_type_node
		? (! INTEGRAL_TYPE_P (tmp) || TYPE_PRECISION (tmp) > 32)
		: type != tmp))
	  VERIFICATION_ERROR_WITH_INDEX
	    ("loading local variable %d which has invalid type");
	PUSH_TYPE (tmp);
	goto note_used;
	case OPCODE_istore:  type = int_type_node;  goto general_store;
	case OPCODE_lstore:  type = long_type_node;  goto general_store;
	case OPCODE_fstore:  type = float_type_node;  goto general_store;
	case OPCODE_dstore:  type = double_type_node;  goto general_store;
	case OPCODE_astore:  type = object_ptr_type_node;  goto general_store;
	general_store:
	index = wide ? IMMEDIATE_u2 : IMMEDIATE_u1;
	wide = 0;
	goto store;
	case OPCODE_istore_0:  type = int_type_node; index = 0; goto store;
	case OPCODE_istore_1:  type = int_type_node; index = 1; goto store;
	case OPCODE_istore_2:  type = int_type_node; index = 2; goto store;
	case OPCODE_istore_3:  type = int_type_node; index = 3; goto store;
	case OPCODE_lstore_0:  type = long_type_node; index=0; goto store;
	case OPCODE_lstore_1:  type = long_type_node; index=1; goto store;
	case OPCODE_lstore_2:  type = long_type_node; index=2; goto store;
	case OPCODE_lstore_3:  type = long_type_node; index=3; goto store;
	case OPCODE_fstore_0:  type=float_type_node; index=0; goto store;
	case OPCODE_fstore_1:  type=float_type_node; index=1; goto store;
	case OPCODE_fstore_2:  type=float_type_node; index=2; goto store;
	case OPCODE_fstore_3:  type=float_type_node; index=3; goto store;
	case OPCODE_dstore_0:  type=double_type_node; index=0; goto store;
	case OPCODE_dstore_1:  type=double_type_node; index=1; goto store;
	case OPCODE_dstore_2:  type=double_type_node; index=2; goto store;
	case OPCODE_dstore_3:  type=double_type_node; index=3; goto store;
	case OPCODE_astore_0:  type = ptr_type_node; index = 0; goto store;
	case OPCODE_astore_1:  type = ptr_type_node; index = 1; goto store;
	case OPCODE_astore_2:  type = ptr_type_node; index = 2; goto store;
	case OPCODE_astore_3:  type = ptr_type_node; index = 3; goto store;
	store:
	if (index < 0
	    || (index + TYPE_IS_WIDE (type)
		>= DECL_MAX_LOCALS (current_function_decl)))
	  {
	    VERIFICATION_ERROR_WITH_INDEX
	      ("invalid local variable index %d in store");
	    return 0;
	  }
	POP_TYPE_CONV (type, type, NULL);
	type_map[index] = type;

	/* If a local variable has changed, we need to reconsider exception
        handlers.  */
	prev_eh_ranges = NULL_EH_RANGE;

	/* Allocate decl for this variable now, so we get a temporary
! 	   that survives the whole method. */
	find_local_variable (index, type, oldpc);

        if (TYPE_IS_WIDE (type))
          type_map[index+1] = TYPE_SECOND;

	/* ... fall through to note_used ... */
	note_used:
	  /* For store or load, note that local variable INDEX is used.
	     This is needed to verify try-finally subroutines. */
	  if (current_subr)
	    {
	      tree vec = LABEL_RETURN_TYPE_STATE (current_subr);
	      tree subr_vec = LABEL_TYPE_STATE (current_subr);
	      int len = 1 + TYPE_IS_WIDE (type);
	      while (--len >= 0)
		{
		  if (TREE_VEC_ELT (vec, index) == TYPE_UNUSED)
		    TREE_VEC_ELT (vec, index) = TREE_VEC_ELT (subr_vec, index);
		}
	    }
	break;
	case OPCODE_iadd:
	case OPCODE_iand:
	case OPCODE_idiv:
	case OPCODE_imul:
	case OPCODE_ior:
	case OPCODE_irem:
	case OPCODE_ishl:
	case OPCODE_ishr:
	case OPCODE_isub:
	case OPCODE_iushr:
	case OPCODE_ixor:
	  type = int_type_node;  goto binop;
	case OPCODE_ineg:
	case OPCODE_i2c:
	case OPCODE_i2b:
	case OPCODE_i2s:
	  type = int_type_node;  goto unop;
	case OPCODE_ladd:
	case OPCODE_land:
	case OPCODE_ldiv:
	case OPCODE_lsub:
	case OPCODE_lmul:
	case OPCODE_lrem:
	case OPCODE_lor:
	case OPCODE_lxor:
	  type = long_type_node;  goto binop;
	case OPCODE_lneg:
	  type = long_type_node;  goto unop;
	case OPCODE_fadd:	case OPCODE_fsub:
	case OPCODE_fmul:	case OPCODE_fdiv:	case OPCODE_frem:
	  type = float_type_node;  goto binop;
	case OPCODE_fneg:
	  type = float_type_node;  goto unop;
	case OPCODE_dadd:	case OPCODE_dsub:
	case OPCODE_dmul:	case OPCODE_ddiv:	case OPCODE_drem:
	  type = double_type_node;  goto binop;
	case OPCODE_dneg:
	  type = double_type_node;  goto unop;

	unop:
	  pop_type (type);
	  PUSH_TYPE (type);
	  break;

	binop:
	  pop_type (type);
	  pop_type (type);
	  PUSH_TYPE (type);
	  break;

	case OPCODE_lshl:
	case OPCODE_lshr:
	case OPCODE_lushr:
	  pop_type (int_type_node);
	  pop_type (long_type_node);
	  PUSH_TYPE (long_type_node);
	  break;

	case OPCODE_iinc:
	  index = wide ? IMMEDIATE_u2 : IMMEDIATE_u1;
	  PC += wide + 1;
	  wide = 0;
	  if (index < 0 || index >= DECL_MAX_LOCALS (current_function_decl))
	    VERIFICATION_ERROR ("invalid local variable index in iinc");
	  tmp = type_map[index];
	  if (tmp == NULL_TREE
	      || ! INTEGRAL_TYPE_P (tmp) || TYPE_PRECISION (tmp) > 32)
	    VERIFICATION_ERROR ("invalid local variable type in iinc");
	  break;

	case OPCODE_i2l:
	  pop_type (int_type_node);    PUSH_TYPE (long_type_node);   break;
	case OPCODE_i2f:
	  pop_type (int_type_node);    PUSH_TYPE (float_type_node);  break;
	case OPCODE_i2d:
	  pop_type (int_type_node);    PUSH_TYPE (double_type_node); break;
	case OPCODE_l2i:
	  pop_type (long_type_node);   PUSH_TYPE (int_type_node);    break;
	case OPCODE_l2f:
	  pop_type (long_type_node);   PUSH_TYPE (float_type_node);  break;
	case OPCODE_l2d:
	  pop_type (long_type_node);   PUSH_TYPE (double_type_node); break;
	case OPCODE_f2i:
	  pop_type (float_type_node);  PUSH_TYPE (int_type_node);    break;
	case OPCODE_f2l:
	  pop_type (float_type_node);  PUSH_TYPE (long_type_node);   break;
	case OPCODE_f2d:
	  pop_type (float_type_node);  PUSH_TYPE (double_type_node); break;
	case OPCODE_d2i:
	  pop_type (double_type_node); PUSH_TYPE (int_type_node);    break;
	case OPCODE_d2l:
	  pop_type (double_type_node); PUSH_TYPE (long_type_node);   break;
	case OPCODE_d2f:
	  pop_type (double_type_node); PUSH_TYPE (float_type_node);  break;

	case OPCODE_lcmp:
	  type = long_type_node;  goto compare;
	case OPCODE_fcmpl:
	case OPCODE_fcmpg:
	  type = float_type_node;  goto compare;
	case OPCODE_dcmpl:
	case OPCODE_dcmpg:
	  type = double_type_node;  goto compare;
	compare:
	  pop_type (type);  pop_type (type);
	  PUSH_TYPE (int_type_node);  break;

	case OPCODE_ifeq:
	case OPCODE_ifne:
	case OPCODE_iflt:
	case OPCODE_ifge:
	case OPCODE_ifgt:
	case OPCODE_ifle:
	  pop_type (int_type_node);  goto cond;
	case OPCODE_ifnull:
	case OPCODE_ifnonnull:
	  pop_type (ptr_type_node ); goto cond;
	case OPCODE_if_icmpeq:
	case OPCODE_if_icmpne:
	case OPCODE_if_icmplt:
	case OPCODE_if_icmpge:
	case OPCODE_if_icmpgt:
	case OPCODE_if_icmple:
	  pop_type (int_type_node);  pop_type (int_type_node);  goto cond;
	case OPCODE_if_acmpeq:
	case OPCODE_if_acmpne:
	  pop_type (object_ptr_type_node);  pop_type (object_ptr_type_node);
	  goto cond;

	cond:
	  PUSH_PENDING (lookup_label (oldpc + IMMEDIATE_s2));
	  break;
          
	case OPCODE_goto:
	  PUSH_PENDING (lookup_label (oldpc + IMMEDIATE_s2));
	  INVALIDATE_PC;
	  break;

	case OPCODE_wide:
	  switch (byte_ops[PC])
	    {
	    case OPCODE_iload:  case OPCODE_lload:
	    case OPCODE_fload:  case OPCODE_dload:  case OPCODE_aload:
	    case OPCODE_istore:  case OPCODE_lstore:
	    case OPCODE_fstore:  case OPCODE_dstore:  case OPCODE_astore:
	    case OPCODE_iinc:
	    case OPCODE_ret:
	      wide = 1;
	      break;
	    default:
	      VERIFICATION_ERROR ("invalid use of wide instruction");
	    }
	  break;

	case OPCODE_return:   type = void_type_node;   goto ret;
	case OPCODE_ireturn:
	  if ((TREE_CODE (return_type) == BOOLEAN_TYPE
	       || TREE_CODE (return_type) == CHAR_TYPE
	       || TREE_CODE (return_type) == INTEGER_TYPE)
	      && TYPE_PRECISION (return_type) <= 32)
	    type = return_type;
	  else
	    type = NULL_TREE;
	  goto ret;
	case OPCODE_lreturn:  type = long_type_node;   goto ret;
	case OPCODE_freturn:  type = float_type_node;  goto ret;
	case OPCODE_dreturn:  type = double_type_node; goto ret;
	case OPCODE_areturn:
	  if (TREE_CODE (return_type) == POINTER_TYPE)
	    type = return_type;
	  else
	    type = NULL_TREE;
	  goto ret;

	ret:
	  if (type != return_type)
	    VERIFICATION_ERROR ("incorrect ?return opcode");
	  if (type != void_type_node)
	    POP_TYPE (type, "return value has wrong type");
	  INVALIDATE_PC;
	  break;

	case OPCODE_getstatic: is_putting = 0;  is_static = 1;  goto field;
	case OPCODE_putstatic: is_putting = 1;  is_static = 1;  goto field;
	case OPCODE_getfield:  is_putting = 0;  is_static = 0;  goto field;
	case OPCODE_putfield:  is_putting = 1;  is_static = 0;  goto field;
	field:
	  {
	    tree field_signature, field_type;
	    index = IMMEDIATE_u2;

	    if (index <= 0 || index >= JPOOL_SIZE (current_jcf))
	      VERIFICATION_ERROR_WITH_INDEX ("bad constant pool index %d");

	    if (JPOOL_TAG (current_jcf, index) != CONSTANT_Fieldref)
	      VERIFICATION_ERROR
		("field instruction does not reference a Fieldref");

	    field_signature
              = COMPONENT_REF_SIGNATURE (&current_jcf->cpool, index);

	    field_type = get_type_from_signature (field_signature);

	    if (is_putting)
	      POP_TYPE (field_type, "incorrect type for field");

	    if (! is_static)
	      {
		int clindex
                  = COMPONENT_REF_CLASS_INDEX (&current_jcf->cpool, index);

		tree self_type = get_class_constant (current_jcf, clindex);

		/* Defer actual checking until next pass. */
		POP_TYPE (self_type, "incorrect type for field reference");
	      }

	    if (! is_putting)
	      PUSH_TYPE (field_type);
	    break;
	  }

	case OPCODE_new:
	  PUSH_TYPE (get_class_constant (jcf, IMMEDIATE_u2));
	  break;

	case OPCODE_dup:     wide = 1; index = 0;  goto dup;
	case OPCODE_dup_x1:  wide = 1; index = 1;  goto dup;
	case OPCODE_dup_x2:  wide = 1; index = 2;  goto dup;
	case OPCODE_dup2:    wide = 2; index = 0;  goto dup;
	case OPCODE_dup2_x1: wide = 2; index = 1;  goto dup;
	case OPCODE_dup2_x2: wide = 2; index = 2;  goto dup;

	dup:
	  if (wide + index > stack_pointer)
	    VERIFICATION_ERROR ("stack underflow - dup* operation");
	  type_stack_dup (wide, index);
	  wide = 0;
	  break;

	case OPCODE_pop:  index = 1;  goto pop;
	case OPCODE_pop2: index = 2;  goto pop;

	pop:
	  if (stack_pointer < index)
	    VERIFICATION_ERROR ("stack underflow");
	  stack_pointer -= index;
	  break;

	case OPCODE_swap:
	  if (stack_pointer < 2)
	    VERIFICATION_ERROR ("stack underflow (in swap)");
	  else
	    {
	      tree type1 = stack_type_map[stack_pointer - 1];
	      tree type2 = stack_type_map[stack_pointer - 2];

	      if (type1 == void_type_node || type2 == void_type_node)
		VERIFICATION_ERROR ("verifier (swap):  double or long value");

	      stack_type_map[stack_pointer - 2] = type1;
	      stack_type_map[stack_pointer - 1] = type2;
	    }
	  break;

	case OPCODE_ldc:   index = IMMEDIATE_u1;  goto ldc;
	case OPCODE_ldc2_w:
	case OPCODE_ldc_w:
	  index = IMMEDIATE_u2;  goto ldc;

	ldc:
	  if (index <= 0 || index >= JPOOL_SIZE (current_jcf))
	    VERIFICATION_ERROR_WITH_INDEX ("bad constant pool index %d in ldc");

	  int_value = -1;
	  switch (JPOOL_TAG (current_jcf, index) & ~CONSTANT_ResolvedFlag)
	    {
	    case CONSTANT_Integer:  type = int_type_node;  goto check_ldc;
	    case CONSTANT_Float:    type = float_type_node;  goto check_ldc;
	    case CONSTANT_String:   type = string_type_node; goto check_ldc;
	    case CONSTANT_Long:    type = long_type_node;    goto check_ldc;
	    case CONSTANT_Double:  type = double_type_node;  goto check_ldc;
	    check_ldc:
	      if (TYPE_IS_WIDE (type) == (op_code == OPCODE_ldc2_w))
		break;
	      /* ... else fall through ... */
	    default:
	      VERIFICATION_ERROR ("bad constant pool tag in ldc");
	    }
	  if (type == int_type_node)
	    {
	      i = TREE_INT_CST_LOW (get_constant (current_jcf, index));
	      goto push_int;
	    }
	  PUSH_TYPE (type);
	  break;

	case OPCODE_invokevirtual:
	case OPCODE_invokespecial:
	case OPCODE_invokestatic:
	case OPCODE_invokeinterface:
	  {
	    tree sig, method_name, method_type, self_type;
	    int self_is_interface, tag;
	    index = IMMEDIATE_u2;

	    if (index <= 0 || index >= JPOOL_SIZE (current_jcf))
	      VERIFICATION_ERROR_WITH_INDEX
		("bad constant pool index %d for invoke");

	    tag = JPOOL_TAG (current_jcf, index);

	    if (op_code == OPCODE_invokeinterface)
	      {
		if (tag != CONSTANT_InterfaceMethodref)
		  VERIFICATION_ERROR
		    ("invokeinterface does not reference an InterfaceMethodref");
	      }
	    else
	      {
		if (tag != CONSTANT_Methodref)
		  VERIFICATION_ERROR ("invoke does not reference a Methodref");
	      }

	    sig = COMPONENT_REF_SIGNATURE (&current_jcf->cpool, index);

	    self_type
              = get_class_constant (current_jcf,
                                    COMPONENT_REF_CLASS_INDEX
                                      (&current_jcf->cpool, index));

	    if (! CLASS_LOADED_P (self_type))
	      load_class (self_type, 1);

	    self_is_interface = CLASS_INTERFACE (TYPE_NAME (self_type));
	    method_name = COMPONENT_REF_NAME (&current_jcf->cpool, index);
	    method_type = parse_signature_string ((const unsigned char *) IDENTIFIER_POINTER (sig),
						  IDENTIFIER_LENGTH (sig));

	    if (TREE_CODE (method_type) != FUNCTION_TYPE)
	      VERIFICATION_ERROR ("bad method signature");

	    pmessage = pop_argument_types (TYPE_ARG_TYPES (method_type));
	    if (pmessage != NULL)
	      {
		message = "invalid argument type";
		goto pop_type_error;
	      }

	    /* Can't invoke <clinit>.  */
	    if (ID_CLINIT_P (method_name))
	      VERIFICATION_ERROR ("invoke opcode can't invoke <clinit>");

	    /* Apart from invokespecial, can't invoke <init>.  */
	    if (op_code != OPCODE_invokespecial && ID_INIT_P (method_name))
	      VERIFICATION_ERROR ("invoke opcode can't invoke <init>");

	    if (op_code != OPCODE_invokestatic)
	      POP_TYPE (self_type,
			"stack type not subclass of invoked method's class");

	    switch (op_code)
	      {
	      case OPCODE_invokeinterface:
	        {
		  int nargs    = IMMEDIATE_u1;
		  int notZero  = IMMEDIATE_u1;
		
		  if (!nargs || notZero)
		      VERIFICATION_ERROR 
		        ("invalid argument number in invokeinterface");

		  /* If we verify/resolve the constant pool, as we should,
		     this test (and the one just following) are redundant.  */
		  if (! self_is_interface)
		    VERIFICATION_ERROR
                      ("invokeinterface calls method not in interface");
		  break;

		default:
		  if (self_is_interface)
		    VERIFICATION_ERROR ("method in interface called");
		}
	      }

	    if (TREE_TYPE (method_type) != void_type_node)
	      PUSH_TYPE (TREE_TYPE (method_type));
	    break;
	  }

	case OPCODE_arraylength:
	    /* Type checking actually made during code generation.  */
	    pop_type (ptr_type_node);
	    PUSH_TYPE (int_type_node);
	    break;
	    
        /* Q&D verification *or* more checking done during code generation
	   for byte/boolean/char/short, the value popped is a int coerced
	   into the right type before being stored.  */
	case OPCODE_iastore: type = int_type_node;     goto astore;
	case OPCODE_lastore: type = long_type_node;    goto astore;
	case OPCODE_fastore: type = float_type_node;   goto astore;
	case OPCODE_dastore: type = double_type_node;  goto astore;
	case OPCODE_aastore: type = ptr_type_node;     goto astore;
	case OPCODE_bastore: type = int_type_node; goto astore;
	case OPCODE_castore: type = int_type_node; goto astore;
	case OPCODE_sastore: type = int_type_node; goto astore;

	astore:
	  /* FIXME - need better verification here.  */
	  pop_type (type);	     /* new value */
	  pop_type (int_type_node);  /* index */
	  pop_type (ptr_type_node);  /* array */
	  break;

        /* Q&D verification *or* more checking done during code generation
	   for byte/boolean/char/short, the value pushed is a int.  */
	case OPCODE_iaload: type = int_type_node;     goto aload;
	case OPCODE_laload: type = long_type_node;    goto aload;
	case OPCODE_faload: type = float_type_node;   goto aload;
	case OPCODE_daload: type = double_type_node;  goto aload;
	case OPCODE_aaload: type = ptr_type_node;     goto aload;
	case OPCODE_baload: type = promote_type (byte_type_node);  goto aload;
	case OPCODE_caload: type = promote_type (char_type_node);  goto aload;
	case OPCODE_saload: type = promote_type (short_type_node); goto aload;

        aload:
	  pop_type (int_type_node);
	  tmp = pop_type (ptr_type_node);
	  if (is_array_type_p (tmp))
	    type = TYPE_ARRAY_ELEMENT (TREE_TYPE (tmp));
	  else if (tmp != TYPE_NULL)
	    VERIFICATION_ERROR ("array load from non-array type");
	  PUSH_TYPE (type);
	  break;

	case OPCODE_anewarray:
	  type = get_class_constant (current_jcf, IMMEDIATE_u2);
	  type = promote_type (type);
	  goto newarray;

	case OPCODE_newarray:
	  index = IMMEDIATE_u1;
	  type = decode_newarray_type (index);
	  if (type == NULL_TREE)
	    VERIFICATION_ERROR ("invalid type code in newarray opcode");
	  goto newarray;

	newarray:
	  if (int_value >= 0 && prevpc >= 0)
	    {
	      /* If the previous instruction pushed an int constant,
		 we want to use it. */
	      switch (byte_ops[prevpc])
		{
		case OPCODE_iconst_0: case OPCODE_iconst_1:
		case OPCODE_iconst_2: case OPCODE_iconst_3:
		case OPCODE_iconst_4: case OPCODE_iconst_5:
		case OPCODE_bipush:  case OPCODE_sipush:
		case OPCODE_ldc: case OPCODE_ldc_w:
		  break;
		default:
		  int_value = -1;
		}
	    }
	  else
	    int_value = -1;

	  type = build_java_array_type (type, int_value);
	  pop_type (int_type_node);
	  PUSH_TYPE (type);
	  break;

	case OPCODE_multianewarray:
	  {
	    int ndim, i;
	    index = IMMEDIATE_u2;
	    ndim  = IMMEDIATE_u1;

            if (ndim < 1)
              VERIFICATION_ERROR
                ("number of dimension lower that 1 in multianewarray" );

	    for (i = 0; i < ndim; i++)
	      pop_type (int_type_node);

	    PUSH_TYPE (get_class_constant (current_jcf, index));
	    break;
	  }

	case OPCODE_aconst_null:
	  PUSH_TYPE (ptr_type_node);
	  break;

	case OPCODE_athrow:
	  /* FIXME: athrow also empties the stack.  */
	  POP_TYPE (throwable_type_node, "missing throwable at athrow" );
	  INVALIDATE_PC;
	  break;

	case OPCODE_checkcast:
	  POP_TYPE (object_ptr_type_node,
		    "checkcast operand is not a pointer");
	  type = get_class_constant (current_jcf, IMMEDIATE_u2);
	  PUSH_TYPE (type);
	  break;

	case OPCODE_instanceof:
	  POP_TYPE (object_ptr_type_node,
		    "instanceof operand is not a pointer");
	  get_class_constant (current_jcf, IMMEDIATE_u2);
	  PUSH_TYPE (int_type_node);
	  break;

	case OPCODE_tableswitch:
	  {
	    jint low, high;

	    POP_TYPE (int_type_node, "missing int for tableswitch");

	    while (PC%4)
	      {
	        if (byte_ops[PC++])
		  VERIFICATION_ERROR ("bad alignment in tableswitch pad");
	      }

	    PUSH_PENDING (lookup_label (oldpc + IMMEDIATE_s4));
	    low  = IMMEDIATE_s4;
	    high = IMMEDIATE_s4;

	    if (low > high)
	      VERIFICATION_ERROR ("unsorted low/high value in tableswitch");

	    while (low++ <= high)
	      PUSH_PENDING (lookup_label (oldpc + IMMEDIATE_s4));

	    INVALIDATE_PC;
	    break;
	  }

	case OPCODE_lookupswitch:
	  {
	    jint npairs, last = 0, not_registered = 1;

	    POP_TYPE (int_type_node, "missing int for lookupswitch");

	    while (PC%4)
	      {
	        if (byte_ops[PC++])
		  VERIFICATION_ERROR ("bad alignment in lookupswitch pad");
	      }

	    PUSH_PENDING (lookup_label (oldpc + IMMEDIATE_s4));
	    npairs = IMMEDIATE_s4;
	    
	    if (npairs < 0)
	      VERIFICATION_ERROR ("invalid number of targets in lookupswitch");

	    while (npairs--)
	      {
	        int match = IMMEDIATE_s4;

		if (not_registered)
		  not_registered = 0;
		else if (last >= match)
		  VERIFICATION_ERROR ("unsorted match value in lookupswitch");

		last = match;
		PUSH_PENDING (lookup_label (oldpc + IMMEDIATE_s4));
	      }
	    INVALIDATE_PC;
	    break;
	  }

	case OPCODE_monitorenter: 
	  /* fall thru */
	case OPCODE_monitorexit:
	  pop_type (ptr_type_node);
	  break;

	case OPCODE_goto_w:
	  PUSH_PENDING (lookup_label (oldpc + IMMEDIATE_s4));
	  INVALIDATE_PC;
	  break;

	case OPCODE_jsr:
	  {
	    tree target = lookup_label (oldpc + IMMEDIATE_s2);
	    tree return_label = lookup_label (PC);
	    PUSH_TYPE (return_address_type_node);
	    /* The return label chain will be null if this is the first
	       time we've seen this jsr target.  */
            if (LABEL_RETURN_LABEL (target) == NULL_TREE)
	      {
		tree return_type_map;
		int nlocals = DECL_MAX_LOCALS (current_function_decl);
		index = nlocals + DECL_MAX_STACK (current_function_decl);
		return_type_map = make_tree_vec (index);

		while (index > nlocals)
		  TREE_VEC_ELT (return_type_map, --index) = TYPE_UNKNOWN;

		while (index > 0)
		  TREE_VEC_ELT (return_type_map, --index) = TYPE_UNUSED;

		LABEL_RETURN_LABEL (target)
		  = build_decl (LABEL_DECL, NULL_TREE, TREE_TYPE (target));
		LABEL_PC (LABEL_RETURN_LABEL (target)) = INVALID_PC;
		LABEL_RETURN_TYPE_STATE (target) = return_type_map;
		LABEL_IS_SUBR_START (target) = 1;
		LABEL_IN_SUBR (target) = 1;
		LABEL_SUBR_START (target) = target;
		LABEL_SUBR_CONTEXT (target) = current_subr;
	      }
	    else if (! LABEL_IS_SUBR_START (target)
		     || LABEL_SUBR_CONTEXT (target) != current_subr)
	      VERIFICATION_ERROR ("label part of different subroutines");

	    i = merge_type_state (target);
	    if (i != 0)
	      {
		if (i < 0)
		  VERIFICATION_ERROR ("types could not be merged at jsr");
		push_pending_label (target);
	      }
	    current_subr = target;

	    /* Chain return_pc onto LABEL_RETURN_LABELS (target) if needed. */
	    if (! value_member (return_label, LABEL_RETURN_LABELS (target)))
	      {
		LABEL_RETURN_LABELS (target)
		  = tree_cons (NULL_TREE, return_label,
			       LABEL_RETURN_LABELS (target));
	      }

	    if (LABEL_VERIFIED (target))
	      {
		tree return_map = LABEL_RETURN_TYPE_STATE (target);
		int len = TREE_VEC_LENGTH (return_map);
		stack_pointer = len - DECL_MAX_LOCALS (current_function_decl);
		while (--len >= 0)
		  {
		    if (TREE_VEC_ELT (return_map, len) != TYPE_UNUSED)
		      type_map[len] = TREE_VEC_ELT (return_map, len);
		  }
		current_subr = LABEL_SUBR_CONTEXT (target);
		if (RETURN_MAP_ADJUSTED (return_map))
		  PUSH_PENDING (return_label);
	      }

	    INVALIDATE_PC;
	  }
	  break;

	case OPCODE_ret:
	  if (current_subr == NULL_TREE)
	    VERIFICATION_ERROR ("ret instruction not in a jsr subroutine");
	  else
	    {
	      tree ret_map = LABEL_RETURN_TYPE_STATE (current_subr);
	      int size
                = DECL_MAX_LOCALS (current_function_decl) + stack_pointer;
	      index = wide ? IMMEDIATE_u2 : IMMEDIATE_u1;
	      wide = 0;
	      INVALIDATE_PC;
	      if (index < 0 || index >= DECL_MAX_LOCALS (current_function_decl)
		  || type_map[index] != TYPE_RETURN_ADDR)
		VERIFICATION_ERROR ("invalid ret index");

	      /* The next chunk of code is similar to an inlined version of
               merge_type_state (LABEL_RETURN_LABEL (current_subr)).
	       The main differences are that LABEL_RETURN_LABEL is
	       pre-allocated by the jsr (but we don't know the size then);
	       and that we have to handle TYPE_UNUSED.  */

	      if (! RETURN_MAP_ADJUSTED (ret_map))
		{
                  /* First return from this subroutine - fix stack
                  pointer.  */
		  TREE_VEC_LENGTH (ret_map) = size;
		  for (index = size;  --index >= 0; )
		    {
		      if (TREE_VEC_ELT (ret_map, index) != TYPE_UNUSED)
			TREE_VEC_ELT (ret_map, index) = type_map[index];
		    }
		  RETURN_MAP_ADJUSTED (ret_map) = 1;
		}
	      else
		{
		  if (TREE_VEC_LENGTH (ret_map) != size)
		    VERIFICATION_ERROR ("inconsistent stack size on ret");
		  for (index = 0;  index < size;  index++)
		    {
		      tree type = TREE_VEC_ELT (ret_map, index);
		      if (type != TYPE_UNUSED)
			{
			  type = merge_types (type, type_map[index]);
			  TREE_VEC_ELT (ret_map, index) = type;
			  if (type == TYPE_UNKNOWN)
			    {
			      if (index >= size - stack_pointer)
				VERIFICATION_ERROR
				  ("inconsistent types on ret from jsr");
			    }
			  else if (TYPE_IS_WIDE (type))
			    index++;
			}
		    }
		}
            }
          break;

        case OPCODE_jsr_w:        
        case OPCODE_ret_w:
        default:
          error ("unknown opcode %d@pc=%d during verification", op_code, PC-1);
          return 0;
        }

      prevpc = oldpc;

      /* The following test is true if we have entered or exited an exception
	 handler range *or* we have done a store to a local variable.
	 In either case we need to consider any exception handlers that
	 might "follow" this instruction.  */

      if (eh_ranges != prev_eh_ranges)
	{
	  int save_stack_pointer = stack_pointer;
	  int index = DECL_MAX_LOCALS (current_function_decl);
	  tree save_type = type_map[index];
	  tree save_current_subr = current_subr;
	  struct eh_range *ranges = find_handler (oldpc);
	  stack_pointer = 1;

	  for ( ; ranges != NULL_EH_RANGE; ranges = ranges->outer)
	    {
	      tree chain = ranges->handlers;

	      /* We need to determine if the handler is part of current_subr.
		 The are two cases:  (1) The exception catch range
		 is entirely within current_subr.  In that case the handler
		 is also part of current_subr.
		 (2) Some of the catch range is not in current_subr.
		 In that case, the handler is *not* part of current_subr.

		 Figuring out which is the case is not necessarily obvious,
		 in the presence of clever code generators (and obfuscators).
		 We make a simplifying assumption that in case (2) we
		 have that the current_subr is entirely within the catch range.
		 In that case we can assume if that if a caller (the jsr) of
		 a subroutine is within the catch range, then the handler is
		 *not* part of the subroutine, and vice versa.  */

	      current_subr = save_current_subr;
	      for ( ; current_subr != NULL_TREE;
		    current_subr = LABEL_SUBR_CONTEXT (current_subr))
		{
		  tree return_labels = LABEL_RETURN_LABELS (current_subr);
		  /* There could be multiple return_labels, but
		     we only need to check one.  */
		  int return_pc = LABEL_PC (TREE_VALUE (return_labels));
		  if (return_pc <= ranges->start_pc
		      || return_pc > ranges->end_pc)
		    break;
		}

	      for ( ; chain != NULL_TREE; chain = TREE_CHAIN (chain))
		{
		  tree handler = TREE_VALUE (chain);
		  tree type = TREE_PURPOSE (chain);

		  if (type == NULL_TREE)  /* a finally handler */
		    type = throwable_type_node;

		  type_map[index] = promote_type (type);

		  PUSH_PENDING (handler);
		}
	    }
	  stack_pointer = save_stack_pointer;
	  current_subr = save_current_subr;
	  type_map[index] = save_type;
	  prev_eh_ranges = eh_ranges;
	}
    }

  return 1;

 pop_type_error:
  error ("verification error at PC=%d", oldpc);
  if (message != NULL)
    error ("%s", message);
  error ("%s", pmessage);
  free (pmessage);
  return 0;

 stack_overflow:
  message = "stack overflow";
  goto verify_error;

 bad_pc:
  message = "program counter out of range";
  goto verify_error;

 error_with_index:
  error ("verification error at PC=%d", oldpc);
  error (message, index);
  return 0;

 verify_error:
  error ("verification error at PC=%d", oldpc);
  error ("%s", message);
  return 0;
}
示例#2
0
static void
execute_instr_at_pc(void) {

    Instr       *instr;
    int         i1, i2;
    float       r1, r2;
    char        *s1, *s2;
    int         l;
    char        *s;
    const char  *builtin_func;
    int         slot;
    int         offset;
    char        buf[1024];

    if (print_instrs) 
        printf("instr %d, pc %d: ", cur_instr, pc);

    instr = &instrs[pc];
    switch (instr->opcode) {

    case OP_PUSH_STACK_FRAME:
        if (print_instrs) 
            printf("push_stack_frame %d\n", instr->int_const);
        top_slot++;
        if (stack_check_overflow())
            break;
        stack[top_slot].store_valid = TRUE;
        stack[top_slot].store_type = TYPE_FRAME_SIZE;
        stack[top_slot].int_val = cur_frame_size;
        cur_frame_size = instr->int_const;
        top_slot += instr->int_const;
        if (stack_check_overflow())
            break;
        break;

    case OP_POP_STACK_FRAME:
        if (print_instrs) 
            printf("pop_stack_frame %d\n", instr->int_const);

        if (instr->int_const != cur_frame_size) {
            fprintf(stderr, "pop_stack_frame %d doesn't match "
                "previous push_stack_frame %d\n",
                instr->int_const, cur_frame_size);
            found_error = TRUE;
            break;
        }

        for (slot = 0; slot < instr->int_const; slot++) 
            stack_slot(slot).store_valid = FALSE;

        top_slot -= instr->int_const;

        cur_frame_size = stack[top_slot].int_val;
        stack[top_slot].store_valid = FALSE;
        top_slot--;
        break;

    case OP_LOAD:
        if (print_instrs) 
            printf("load r%d, %d\n", instr->rd, instr->int_const);

        check_slot(instr->int_const, TRUE, TRUE);
        regs[instr->rd] = stack_slot(instr->int_const);
        break;

    case OP_STORE:
        if (print_instrs) 
            printf("store %d, r%d\n", instr->int_const, instr->rs1);

        check_reg(instr->rs1);
        check_slot(instr->int_const, FALSE, TRUE);
        stack_slot(instr->int_const) = regs[instr->rs1];
        break;

    case OP_LOAD_ADDRESS:
        if (print_instrs) 
            printf("load_address r%d, %d\n", instr->rd, instr->int_const);

        check_slot(instr->int_const, FALSE, TRUE);
        set_reg_addr(instr->rd, top_slot - instr->int_const);
        break;

    case OP_LOAD_INDIRECT:
         if (print_instrs) 
            printf("load_indirect r%d, r%d\n", instr->rd, instr->rs1);

        offset = addr_reg(instr->rs1);
        check_offset(offset, TRUE, TRUE);       /* Must be valid */
        regs[instr->rd] = stack[offset];
        break;

    case OP_STORE_INDIRECT:
        if (print_instrs) 
            printf("store_indirect r%d, r%d\n", instr->rd, instr->rs1);

        check_reg(instr->rs1);
        offset = addr_reg(instr->rd);
        check_offset(offset, FALSE, TRUE);      /* Need not be valid */
        stack[offset] = regs[instr->rs1];
        break;

    case OP_INT_CONST:
        if (print_instrs) 
            printf("int_const r%d, %d\n", instr->rd, instr->int_const);

        set_reg_int(instr->rd, instr->int_const);
        break;

    case OP_REAL_CONST:
        if (print_instrs) 
            printf("real_const r%d, %f\n", instr->rd, instr->real_const);

        set_reg_real(instr->rd, instr->real_const);
        break;

    case OP_STRING_CONST:
        if (print_instrs) 
            printf("string_const r%d, %s\n", instr->rd, instr->string_const);

        set_reg_string(instr->rd, make_string_const(instr->string_const));
        break;

    case OP_ADD_INT:
        if (print_instrs) 
            printf("add_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 + i2);
        break;

    case OP_ADD_REAL:
        if (print_instrs) 
            printf("add_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_real(instr->rd, r1 + r2);
        break;

    case OP_ADD_OFFSET:
        if (print_instrs) 
            printf("add_offset r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        offset = addr_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        offset += i2;
        check_offset(offset, FALSE, TRUE);
        set_reg_addr(instr->rd, offset);
        break;

    case OP_SUB_INT:
        if (print_instrs) 
            printf("sub_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 - i2);
        break;

    case OP_SUB_REAL:
        if (print_instrs) 
            printf("sub_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_real(instr->rd, r1 - r2);
        break;

    case OP_SUB_OFFSET:
        if (print_instrs) 
            printf("sub_offset r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        offset = addr_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        offset -= i2;
        check_offset(offset, FALSE, TRUE);
        set_reg_addr(instr->rd, offset);
        break;

    case OP_MUL_INT:
        if (print_instrs) 
            printf("mul_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 * i2);
        break;

    case OP_MUL_REAL:
        if (print_instrs) 
            printf("mul_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_real(instr->rd, r1 * r2);
        break;

    case OP_DIV_INT:
        if (print_instrs) 
            printf("div_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 / i2);
        break;

    case OP_DIV_REAL:
        if (print_instrs) 
            printf("div_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_real(instr->rd, r1 / r2);
        break;

    case OP_CMP_EQ_INT:
        if (print_instrs) 
            printf("cmp_eq_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 == i2);
        break;

    case OP_CMP_NE_INT:
        if (print_instrs) 
            printf("cmp_ne_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 != i2);
        break;

    case OP_CMP_GT_INT:
        if (print_instrs) 
            printf("cmp_gt_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 > i2);
        break;

    case OP_CMP_GE_INT:
        if (print_instrs) 
            printf("cmp_ge_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 >= i2);
        break;

    case OP_CMP_LT_INT:
        if (print_instrs) 
            printf("cmp_lt_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 < i2);
        break;

    case OP_CMP_LE_INT:
        if (print_instrs) 
            printf("cmp_le_int r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 <= i2);
        break;

    case OP_CMP_EQ_REAL:
        if (print_instrs) 
            printf("cmp_eq_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_int(instr->rd, r1 == r2);
        break;

    case OP_CMP_NE_REAL:
        if (print_instrs) 
            printf("cmp_ne_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_int(instr->rd, r1 != r2);
        break;

    case OP_CMP_GT_REAL:
        if (print_instrs) 
            printf("cmp_gt_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_int(instr->rd, r1 > r2);
        break;

    case OP_CMP_GE_REAL:
        if (print_instrs) 
            printf("cmp_ge_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_int(instr->rd, r1 >= r2);
        break;

    case OP_CMP_LT_REAL:
        if (print_instrs) 
            printf("cmp_lt_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_int(instr->rd, r1 < r2);
        break;

    case OP_CMP_LE_REAL:
        if (print_instrs) 
            printf("cmp_le_real r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        r1 = real_reg(instr->rs1);
        r2 = real_reg(instr->rs2);
        set_reg_int(instr->rd, r1 <= r2);
        break;

    case OP_CMP_EQ_STRING:
        if (print_instrs) 
            printf("cmp_eq_string r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        s1 = string_reg(instr->rs1);
        s2 = string_reg(instr->rs2);
        set_reg_int(instr->rd, strcmp(s1, s2) == 0);
        break;

    case OP_CMP_NE_STRING:
        if (print_instrs) 
            printf("cmp_ne_string r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        s1 = string_reg(instr->rs1);
        s2 = string_reg(instr->rs2);
        set_reg_int(instr->rd, strcmp(s1, s2) != 0);
        break;

    case OP_CMP_GT_STRING:
        if (print_instrs) 
            printf("cmp_gt_string r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        s1 = string_reg(instr->rs1);
        s2 = string_reg(instr->rs2);
        set_reg_int(instr->rd, strcmp(s1, s2) > 0);
        break;

    case OP_CMP_GE_STRING:
        if (print_instrs) 
            printf("cmp_ge_string r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        s1 = string_reg(instr->rs1);
        s2 = string_reg(instr->rs2);
        set_reg_int(instr->rd, strcmp(s1, s2) >= 0);
        break;

    case OP_CMP_LT_STRING:
        if (print_instrs) 
            printf("cmp_lt_string r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        s1 = string_reg(instr->rs1);
        s2 = string_reg(instr->rs2);
        set_reg_int(instr->rd, strcmp(s1, s2) < 0);
        break;

    case OP_CMP_LE_STRING:
        if (print_instrs) 
            printf("cmp_le_string r%d, r%d, r%d\n",
                instr->rd, instr->rs1, instr->rs2);

        s1 = string_reg(instr->rs1);
        s2 = string_reg(instr->rs2);
        set_reg_int(instr->rd, strcmp(s1, s2) <= 0);
        break;

    case OP_AND:
        if (print_instrs) 
            printf("and r%d, r%d, r%d\n", instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 && i2);
        break;

    case OP_OR:
        if (print_instrs) 
            printf("or r%d, r%d, r%d\n", instr->rd, instr->rs1, instr->rs2);

        i1 = int_reg(instr->rs1);
        i2 = int_reg(instr->rs2);
        set_reg_int(instr->rd, i1 || i2);
        break;

    case OP_NOT:
        if (print_instrs) 
            printf("not r%d, r%d\n", instr->rd, instr->rs1);

        i1 = int_reg(instr->rs1);
        set_reg_int(instr->rd, !i1);
        break;

    case OP_BRANCH_UNCOND:
        if (print_instrs) 
            printf("branch_uncond %s\n", instr->string_const);

        next_pc = lookup_label(instr->string_const);
        break;

    case OP_BRANCH_ON_TRUE:
        if (print_instrs) 
            printf("branch_on_true r%d, %s\n",
                instr->rs1, instr->string_const);

        i1 = int_reg(instr->rs1);
        if (i1) 
            next_pc = lookup_label(instr->string_const);
        break;

    case OP_BRANCH_ON_FALSE:
        if (print_instrs) 
            printf("branch_on_false r%d, %s\n",
                instr->rs1, instr->string_const);

        i1 = int_reg(instr->rs1);
        if (! i1) 
            next_pc = lookup_label(instr->string_const);
        break;

    case OP_RETURN:
        if (print_instrs) 
            printf("return\n");

        check_slot(0, TRUE, FALSE);
        if (stack_slot(0).store_type != TYPE_RETURN_ADDR) {
            print_dynamic_context();
            fprintf(stderr, "top of stack doesn't hold a return address\n");
            found_error = TRUE;
        }

        next_pc = stack_slot(0).int_val;
        top_slot--;
        break;

    case OP_CALL:
        if (print_instrs) 
            printf("call %s\n", instr->string_const);

        top_slot++;
        if (stack_check_overflow())
            break;
        stack[top_slot].store_valid = TRUE;
        stack[top_slot].store_type = TYPE_RETURN_ADDR;
        stack[top_slot].int_val = next_pc;
        next_pc = lookup_label(instr->string_const);
        break;

    case OP_CALL_BUILTIN:
        if (instr->func >= FUNCOP_LAST) 
            report_error_and_exit("bad function in call");

        builtin_func = func_names[instr->func];
        if (print_instrs) 
            printf("call_builtin %s\n", builtin_func);

        switch (instr->func) {
            case FUNCOP_READ_INT:
                init_all_regs();
                if (scanf("%d", &i1) != 1) 
                    report_error_and_exit("cannot read integer");
                set_reg_int(0, i1);
                break;

            case FUNCOP_READ_REAL:
                init_all_regs();
                if (scanf("%f", &r1) != 1) 
                    report_error_and_exit("cannot read real");
                set_reg_real(0, r1);
                break;

            case FUNCOP_READ_BOOL:
                init_all_regs();
                if (scanf("%s", buf) != 1) 
                    report_error_and_exit("cannot read bool");
                if (streq(buf, "true")) 
                    set_reg_int(0, 1);
                else if (streq(buf, "false")) 
                    set_reg_int(0, 0);
                else 
                    report_error_and_exit("read invalid bool");
                break;

            case FUNCOP_READ_STRING:
                init_all_regs();
                if (scanf("%s", buf) != 1) 
                    report_error_and_exit("cannot read string");
                set_reg_string(0, strdup(buf));
                break;

            case FUNCOP_PRINT_INT:
                printf("%d", int_reg(0));
                init_all_regs();
                break;

            case FUNCOP_PRINT_REAL:
                printf("%f", real_reg(0));
                init_all_regs();
                break;

            case FUNCOP_PRINT_BOOL:
                printf("%s", int_reg(0) ? "true" : "false");
                init_all_regs();
                break;

            case FUNCOP_PRINT_STRING:
                printf("%s", string_reg(0));
                init_all_regs();
                break;

            case FUNCOP_STRING_CONCAT:
                s1 = string_reg(0);
                s2 = string_reg(1);
                l = (int) strlen(s1) + (int) strlen(s2) + 1;
                s = checked_malloc(l);
                s = strcpy(s, s1);
                s = strcat(s, s2);
                init_all_regs();
                set_reg_string(0, s);
                break;

            case FUNCOP_STRING_LENGTH:
                s1 = string_reg(0);
                init_all_regs();
                set_reg_int(0, (int) strlen(s1));
                break;

            case FUNCOP_SUBSTRING:
                s1 = string_reg(0);
                i1 = int_reg(1);
                i2 = int_reg(2);
                l = (int) strlen(s1) + 1;
                s = checked_malloc(l);
                if (i1 > l) 
                    report_error_and_exit("substring: invalid start");

                strcpy(s, s1 + i1);
                l = l - i1;
                if (i2 < l) 
                    s[i2] = '\0';
                init_all_regs();
                set_reg_string(0, s);
                break;

            case FUNCOP_SQRT:
                r1 = real_reg(0);
                init_all_regs();
                set_reg_real(0, (float) sqrt(r1));
                break;

            case FUNCOP_TRUNC:
                r1 = real_reg(0);
                init_all_regs();
                set_reg_int(instr->rd, oztrunc(r1));
                break;

            case FUNCOP_ROUND:
                r1 = real_reg(0);
                init_all_regs();
                set_reg_int(instr->rd, ozround(r1));
                break;

            case FUNCOP_LAST:
                report_error_and_exit("call: invalid function");
        }

        break;

    case OP_INT_TO_REAL:
        if (print_instrs) 
            printf("int_to_real r%d, r%d\n", instr->rd, instr->rs1);

        i1 = int_reg(instr->rs1);
        set_reg_real(instr->rd, (float) i1);
        break;

    case OP_MOVE:
        if (print_instrs) 
            printf("move r%d, r%d\n", instr->rd, instr->rs1);

        set_reg_any(instr->rd, instr->rs1);
        break;

    case OP_DEBUG_REG:
        if (print_instrs) 
            printf("debug_reg r%d\n", instr->rs1);

        check_reg(instr->rs1);
        if (quiet) 
            break;

        switch (regs[instr->rs1].store_type) {
            case TYPE_INT:
                printf("register %d: %d\n", instr->rs1, int_reg(instr->rs1));
                break;

            case TYPE_REAL:
                printf("register %d: %f\n", instr->rs1, real_reg(instr->rs1));
                break;

            case TYPE_ADDRESS:
                printf("register %d: @%d\n", instr->rs1,
                    regs[instr->rs1].int_val);
                break;

            case TYPE_STRING:
                printf("register %d: %s\n",
                    instr->rs1, string_reg(instr->rs1));
                break;

            default:
                report_error_and_exit("invalid register type");
                break;
        }

        break;

    case OP_DEBUG_SLOT:
        if (print_instrs) 
            printf("debug_slot %d\n", instr->int_const);

        check_slot(instr->int_const, TRUE, TRUE);
        if (quiet) 
            break;

        switch (stack_slot(instr->int_const).store_type) {
            case TYPE_INT:
                printf("slot %d: %d\n",
                    instr->int_const, int_slot(instr->int_const));
                break;

            case TYPE_REAL:
                printf("slot %d: %f\n",
                    instr->int_const, real_slot(instr->int_const));
                break;

            case TYPE_ADDRESS:
                printf("slot %d: @%d\n",
                    instr->int_const, stack_slot(instr->int_const).int_val);
                break;

            case TYPE_STRING:
                printf("slot %d: %s\n",
                    instr->int_const, string_slot(instr->int_const));
                break;

            case TYPE_FRAME_SIZE:
                report_error_and_exit("frame size slot");
                break;

            case TYPE_RETURN_ADDR:
                report_error_and_exit("return address slot");
                break;

            default:
                report_error_and_exit("invalid slot type");
                break;
        }

        break;

    case OP_DEBUG_STACK:
        if (print_instrs) 
            printf("debug_stack\n");

        if (quiet) 
            break;

        printf("\n");
        printf("cur_frame_size = %d\n", cur_frame_size);
        for (offset = 0; offset <= top_slot; offset++) {
            if (! stack[offset].store_valid) {
                printf("offset %d is invalid\n", offset);
                continue;
            }

            switch (stack[offset].store_type) {

            case TYPE_INT:
                printf("offset %d: %d\n", offset, stack[offset].int_val);
                break;

            case TYPE_REAL:
                printf("offset %d: %f\n", offset, stack[offset].real_val);
                break;

            case TYPE_ADDRESS:
                printf("offset %d: @%d\n", offset, stack[offset].int_val);
                break;

            case TYPE_STRING:
                printf("offset %d: %s\n", offset, stack[offset].string_val);
                break;

            case TYPE_FRAME_SIZE:
                printf("offset %d: frame size %d\n",
                    offset, stack[offset].int_val);
                break;

            case TYPE_RETURN_ADDR:
                printf("offset %d: return address %d\n",
                    offset, stack[offset].int_val);
                break;

            default:
                report_error_and_exit("invalid slot type");
                break;
            }
        }

        printf("\n");
        break;

    case OP_HALT:
        if (print_instrs) 
            printf("halt\n");

        halted = TRUE;
        break;

    default:
        report_internal_error_and_exit("unknown opcode");
        break;
    }
}
示例#3
0
文件: eval.c 项目: AxFab/nasm
static expr *expr6(int critical)
{
    int32_t type;
    expr *e;
    int32_t label_seg;
    int64_t label_ofs;
    int64_t tmpval;
    bool rn_warn;
    char *scope;

    switch (i) {
    case '-':
        i = scan(scpriv, tokval);
        e = expr6(critical);
        if (!e)
            return NULL;
        return scalar_mult(e, -1L, false);

    case '+':
        i = scan(scpriv, tokval);
        return expr6(critical);

    case '~':
        i = scan(scpriv, tokval);
        e = expr6(critical);
        if (!e)
            return NULL;
        if (is_just_unknown(e))
            return unknown_expr();
        else if (!is_simple(e)) {
            nasm_error(ERR_NONFATAL, "`~' operator may only be applied to"
                  " scalar values");
            return NULL;
        }
        return scalarvect(~reloc_value(e));

    case '!':
        i = scan(scpriv, tokval);
        e = expr6(critical);
        if (!e)
            return NULL;
        if (is_just_unknown(e))
            return unknown_expr();
        else if (!is_simple(e)) {
            nasm_error(ERR_NONFATAL, "`!' operator may only be applied to"
                  " scalar values");
            return NULL;
        }
        return scalarvect(!reloc_value(e));

    case TOKEN_IFUNC:
    {
        enum ifunc func = tokval->t_integer;
        i = scan(scpriv, tokval);
        e = expr6(critical);
        if (!e)
            return NULL;
        if (is_just_unknown(e))
            return unknown_expr();
        else if (!is_simple(e)) {
            nasm_error(ERR_NONFATAL, "function may only be applied to"
                  " scalar values");
            return NULL;
        }
        return scalarvect(eval_ifunc(reloc_value(e), func));
    }

    case TOKEN_SEG:
        i = scan(scpriv, tokval);
        e = expr6(critical);
        if (!e)
            return NULL;
        e = segment_part(e);
        if (!e)
            return NULL;
        if (is_unknown(e) && critical) {
            nasm_error(ERR_NONFATAL, "unable to determine segment base");
            return NULL;
        }
        return e;

    case TOKEN_FLOATIZE:
        return eval_floatize(tokval->t_integer);

    case TOKEN_STRFUNC:
        return eval_strfunc(tokval->t_integer);

    case '(':
        i = scan(scpriv, tokval);
        e = bexpr(critical);
        if (!e)
            return NULL;
        if (i != ')') {
            nasm_error(ERR_NONFATAL, "expecting `)'");
            return NULL;
        }
        i = scan(scpriv, tokval);
        return e;

    case TOKEN_NUM:
    case TOKEN_STR:
    case TOKEN_REG:
    case TOKEN_ID:
    case TOKEN_INSN:            /* Opcodes that occur here are really labels */
    case TOKEN_HERE:
    case TOKEN_BASE:
    case TOKEN_DECORATOR:
        begintemp();
        switch (i) {
        case TOKEN_NUM:
            addtotemp(EXPR_SIMPLE, tokval->t_integer);
            break;
        case TOKEN_STR:
            tmpval = readstrnum(tokval->t_charptr, tokval->t_inttwo, &rn_warn);
            if (rn_warn)
                nasm_error(ERR_WARNING|ERR_PASS1, "character constant too long");
            addtotemp(EXPR_SIMPLE, tmpval);
            break;
        case TOKEN_REG:
            addtotemp(tokval->t_integer, 1L);
            if (hint && hint->type == EAH_NOHINT)
                hint->base = tokval->t_integer, hint->type = EAH_MAKEBASE;
            break;
        case TOKEN_ID:
        case TOKEN_INSN:
        case TOKEN_HERE:
        case TOKEN_BASE:
            /*
             * If !location.known, this indicates that no
             * symbol, Here or Base references are valid because we
             * are in preprocess-only mode.
             */
            if (!location.known) {
                nasm_error(ERR_NONFATAL,
                      "%s not supported in preprocess-only mode",
                      (i == TOKEN_HERE ? "`$'" :
                       i == TOKEN_BASE ? "`$$'" :
                       "symbol references"));
                addtotemp(EXPR_UNKNOWN, 1L);
                break;
            }

            type = EXPR_SIMPLE; /* might get overridden by UNKNOWN */
            if (i == TOKEN_BASE) {
                label_seg = in_abs_seg ? abs_seg : location.segment;
                label_ofs = 0;
            } else if (i == TOKEN_HERE) {
                label_seg = in_abs_seg ? abs_seg : location.segment;
                label_ofs = in_abs_seg ? abs_offset : location.offset;
            } else {
                if (!lookup_label(tokval->t_charptr, &label_seg, &label_ofs)) {
                    scope = local_scope(tokval->t_charptr);
                    if (critical == 2) {
                        nasm_error(ERR_NONFATAL, "symbol `%s%s' undefined",
                              scope,tokval->t_charptr);
                        return NULL;
                    } else if (critical == 1) {
                        nasm_error(ERR_NONFATAL,
                              "symbol `%s%s' not defined before use",
                              scope,tokval->t_charptr);
                        return NULL;
                    } else {
                        if (opflags)
                            *opflags |= OPFLAG_FORWARD;
                        type = EXPR_UNKNOWN;
                        label_seg = NO_SEG;
                        label_ofs = 1;
                    }
                }
                if (opflags && is_extern(tokval->t_charptr))
                    *opflags |= OPFLAG_EXTERN;
            }
            addtotemp(type, label_ofs);
            if (label_seg != NO_SEG)
                addtotemp(EXPR_SEGBASE + label_seg, 1L);
            break;
        case TOKEN_DECORATOR:
            addtotemp(EXPR_RDSAE, tokval->t_integer);
            break;
        }
        i = scan(scpriv, tokval);
        return finishtemp();

    default:
        nasm_error(ERR_NONFATAL, "expression syntax error");
        return NULL;
    }
}