/* run front end support for arm
   Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc.

This file is part of ARM SIM.

GNU CC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU CC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

/* This file provides the interface between the simulator and run.c and gdb
   (when the simulator is linked with gdb).
   All simulator interaction should go through this file.  */

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <bfd.h>
#include <signal.h>
#include "callback.h"
#include "remote-sim.h"
#include "armdefs.h"
#include "armemu.h"
#include "dbg_rdi.h"
#include "ansidecl.h"

extern int skyeye_net_on;

host_callback *sim_callback;

static struct ARMul_State *state;

/* Who is using the simulator.  */
static SIM_OPEN_KIND sim_kind;

/* argv[0] */
static char *myname;

/* Memory size in bytes.  */
static int mem_size = (1 << 21);

/* Non-zero to display start up banner, and maybe other things.  */
static int verbosity;

/* Non-zero to set big endian mode.  */
int big_endian;

int stop_simulator;

/*added by ksh for energy estimation,in 2004-11-26*/
static FILE* pf;
//--------------------------------
//chy 2002-01-14 
#define NETENABLE
extern void nic_init(void);
#define DEBUG_NET 1
#if DEBUG_NET
 #define NET_DBG(a...) fprintf(stderr, ##a)
#else
 #define NET_DBG(a...)
#endif
//--------------------------------

static void
init ()
{
  static int done;

  if (!done)
    {
      
      ARMul_EmulateInit ();
      state = ARMul_NewState ();
      state->bigendSig = (big_endian ? HIGH : LOW);
      ARMul_MemoryInit (state, mem_size);
      ARMul_OSInit (state);
      //chy:2003-08-19 below  fun should be called in ARMul_SelectProcessor......
      //ARMul_CoProInit (state);
      state->verbose = verbosity;
      done = 1;
      //chy:2003-08-19 below two funs should exec after or in skyeye_config.mach->mach_init......
      //armul_setcpsr is in ARMul_Reset
      //ARMul_SelectProcessor(state, ARM600);
      //ARMul_SetCPSR(state, USER32MODE);

      /*some option should init before read config. e.g. uart option.*/
      skyeye_option_init(&skyeye_config);
      skyeye_read_config();
    	/*added by ksh for energy estimation,in 2004-11-26*/
	  	state->energy.energy_prof = skyeye_config.energy.energy_prof;
			if(state->energy.energy_prof){
		   	ARMul_ProfInit(state);
		   	ARMul_EnergyInit(state);
		  	ARMul_InitSymTable(&(skyeye_config.energy.filename));
				/*get energy option from skyeye.conf,and set state->energy.energy_prof*/
				pf = NULL;
			  pf = fopen(skyeye_config.energy.logfile, "w");
				if (pf == NULL) {
					printf("ARMul_EnergyInit: Error opening logfile %s\n",skyeye_config.energy.logfile);
					exit(-1);
				}
					
			}
    
      
    if(skyeye_net_on){
      //chy 2003-01-14 init_network
#ifdef NETENABLE
      NET_DBG("nic_init_begin\n");
      nic_init();
      NET_DBG("nic_init_end\n");
#endif
     }
      
      //chy 2003-01-14 seems another ARMul_Reset, the first is in ARMul_NewState
      //ARMul_Reset(state);
      //chy 2003-08-19 mach_init should call ARMul_SelectProcess
      skyeye_config.mach->mach_init(state, skyeye_config.mach);
      //chy:2003-08-19, after mach_init, because ARMul_Reset should after ARMul_SelectProcess
      ARMul_Reset(state);

      // add step disassemble code here :teawater
     state -> disassemble = skyeye_config.can_step_disassemble;


      io_reset(state); /*from ARMul_Reset.*/
    }
}

/* Set verbosity level of simulator.
   This is not intended to produce detailed tracing or debugging information.
   Just summaries.  */
/* FIXME: common/run.c doesn't do this yet.  */

void
sim_set_verbose (v)
     int v;
{
  verbosity = v;
}

/* Set the memory size to SIZE bytes.
   Must be called before initializing simulator.  */
/* FIXME: Rename to sim_set_mem_size.  */

void
sim_size (size)
     int size;
{
  mem_size = size;
}

void
ARMul_ConsolePrint (ARMul_State * state, const char *format, ...)
{
  va_list ap;

  if (state->verbose)
    {
      va_start (ap, format);
      vprintf (format, ap);
      va_end (ap);
    }
}

ARMword
ARMul_Debug (ARMul_State * state, ARMword pc ATTRIBUTE_UNUSED, ARMword instr ATTRIBUTE_UNUSED)
{
  state->Emulate = STOP;
  stop_simulator = 1;
  return 1;
}

int
sim_write (sd, addr, buffer, size)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     SIM_ADDR addr;
     unsigned char *buffer;
     int size;
{
  int i;
  init ();
  for (i = 0; i < size; i++)
    {
      ARMul_WriteByte (state, addr + i, buffer[i]);
    }
  return size;
}

int
sim_read (sd, addr, buffer, size)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     SIM_ADDR addr;
     unsigned char *buffer;
     int size;
{
  int i;
  init ();
  for (i = 0; i < size; i++)
    {
      buffer[i] = ARMul_ReadByte (state, addr + i);
    }
  return size;
}

int
sim_trace (sd)
     SIM_DESC sd ATTRIBUTE_UNUSED;
{  
  (*sim_callback->printf_filtered) (sim_callback,
				    "This simulator does not support tracing\n");
  return 1;
}

int
sim_stop (sd)
     SIM_DESC sd ATTRIBUTE_UNUSED;
{
	/*Now only do some energy profiling in sim_info,added by ksh in 2004-11-26*/
	sim_info(sd,1);

  state->Emulate = STOP;
  stop_simulator = 1;
  return 1;
}












/**
 * Thanks to teawater's code  
 *
 */


#include "dis-asm.h"

static ARMul_State	tea_state;

#define TEA_ERROR_LEN	1
#define TEA_ERROR_ABORT	2

static int
tea_read_memory_func(bfd_vma memaddr, bfd_byte *myaddr, unsigned int length,struct disassemble_info *info)
{
	ARMword	data;
       
       if (length!=2 && length!=4) {
        	return(TEA_ERROR_LEN);
	}
    	data=ARMul_ReadWord(&tea_state,memaddr);
		if (data==ARMul_ABORTWORD) {
		return(TEA_ERROR_ABORT);
			}
	if (length==4) {
		memcpy(myaddr,&data,4);
				}
	else {
		if (info->endian==BFD_ENDIAN_BIG) {
			memcpy(myaddr,&data,2);
	    			}
	 	else {
					memcpy(myaddr,(char *)&data+2,2);
							}
			}

			return(0);
}

static void
tea_memory_error_func(int status, bfd_vma memaddr, struct disassemble_info *info)
{
			switch(status) {
			case TEA_ERROR_LEN:
											printf("len error. only support 2 byte or 4 byte.\n");
											break;
	case TEA_ERROR_ABORT:
											printf("abort\n");
			break;
	default:
		printf("Unrecognized status number.\n");
								 			break;
	}
}

static void
tea_print_address_func(bfd_vma addr, struct disassemble_info *info)
{
					printf("0x%08x ",addr);
}

static void
tea_print_insn(ARMul_State * state,ARMword pc,int is_thumb)
{
		disassemble_info	info;
		int			ret;
		char			options[20];

		bzero(&info,sizeof(disassemble_info));
		info.fprintf_func=(fprintf_ftype)fprintf;
		info.stream=(PTR)stdout;
		
		if (state->bigendSig) {
		info.endian=BFD_ENDIAN_BIG;
		}
    	else {
			info.endian=BFD_ENDIAN_LITTLE;
		}
		info.read_memory_func=tea_read_memory_func;
	info.memory_error_func=tea_memory_error_func;
		info.print_address_func=tea_print_address_func;
		info.symbol_at_address_func=generic_symbol_at_address;
			if (is_thumb) {
					strncpy(options,"force-thumb",20);
				}
			else {
					strncpy(options,"no-force-thumb",20);
			}
		info.disassembler_options=options;
			tea_state=*state;
			if (state->bigendSig) {
			ret=print_insn_big_arm(pc,&info);
			}
			else {
				ret=print_insn_little_arm(pc,&info);
				}
			if (ret==-1) {
				printf(" ,disassemble code in 0x%08x error\n",pc);
					}
					else {
			       printf("\n");
							}
}

/*tea end of here*/












void
sim_resume (sd, step, siggnal)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     int step;
     int siggnal ATTRIBUTE_UNUSED;
{
  state->EndCondition = 0;
  stop_simulator = 0;

  if (step)
    {
      state->Reg[15] = ARMul_DoInstr (state);

//teawater add for next_dis 2004.10.27------------------------------------------
    	if (state->disassemble) {
		#ifdef MODET
		if (TFLAG) {
		tea_print_insn(state,state->Reg[15],1);
			}
		else {
		tea_print_insn(state,state->Reg[15],0);
		}
		#else
		tea_print_insn(state,state->Reg[15],0);
	  #endif	//MODET
											}
	//AJ2D------------------------------------------------------




      if (state->EndCondition == 0)
	state->EndCondition = RDIError_BreakpointReached;
    }
  else
    {
#if 1				/* JGS */
      state->NextInstr = RESUME;	/* treat as PC change */
#endif
      state->Reg[15] = ARMul_DoProg (state);
    }

  FLUSHPIPE;
}

SIM_RC
sim_create_inferior (sd, abfd, argv, env)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     struct _bfd *abfd;
     char **argv;
     char **env;
{
  int argvlen = 0;
  char **arg;

#if 0
  if (abfd != NULL)
    ARMul_SetPC (state, bfd_get_start_address (abfd));
  else
    ARMul_SetPC (state, 0);	/* ??? */
#endif

#if 0				/* JGS */
  /* We explicitly select a processor capable of supporting the ARM
     32bit mode, and then we force the simulated CPU into the 32bit
     User mode: */
  ARMul_SelectProcessor (state, ARM600);
  ARMul_SetCPSR (state, USER32MODE);
#endif

  /* Check if there is a bootrom */
  if ((abfd != NULL) /* DAVIDM && (state->mem.rom[0] == NULL) */) {
    ARMul_SetPC (state, bfd_get_start_address (abfd));
  } else {
    /* Run the bootrom at zero */
    ARMul_SetPC (state, 0);
  }
  /*we specify start address in config file.*/
  if (skyeye_config.start_address != 0)
  	ARMul_SetPC(state, skyeye_config.start_address);

  if (argv != NULL)
    {
      /*
         ** Set up the command line (by laboriously stringing together the
         ** environment carefully picked apart by our caller...)
       */
      /* Free any old stuff */
      if (state->CommandLine != NULL)
	{
	  free (state->CommandLine);
	  state->CommandLine = NULL;
	}

      /* See how much we need */
      for (arg = argv; *arg != NULL; arg++)
	argvlen += strlen (*arg) + 1;

      /* allocate it... */
      state->CommandLine = malloc (argvlen + 1);
      if (state->CommandLine != NULL)
	{
	  arg = argv;
	  state->CommandLine[0] = '\0';
	  for (arg = argv; *arg != NULL; arg++)
	    {
	      strcat (state->CommandLine, *arg);
	      strcat (state->CommandLine, " ");
	    }
	}else{
		printf("SKYEYE:sim_create_inferior: malloc state->CommandLine error\n");
		exit(-1);
        }
    }

  if (env != NULL)
    {
      /* Now see if there's a MEMSIZE spec in the environment */
      while (*env)
	{
	  if (strncmp (*env, "MEMSIZE=", sizeof ("MEMSIZE=") - 1) == 0)
	    {
	      char *end_of_num;

	      /* Set up memory limit */
	      state->MemSize =
		strtoul (*env + sizeof ("MEMSIZE=") - 1, &end_of_num, 0);
	    }
	  env++;
	}
    }

  return SIM_RC_OK;
}

void
sim_info (sd, verbose)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     int verbose ATTRIBUTE_UNUSED;
{
				/*added by ksh for energy estimation,in 2004-11-26 */
				printf("sim_info called \n");
				/* <tktan> ARM_ENERGY */
				  if (pf) { /* BUG200103282109 */
						ARMul_ReportEnergy(state,pf); /* <tktan> BUG200104111423, BUG200105222137 */
				    fprintf(pf, "total instructions = %lld\n", state->NumInstrs);
				    fprintf(pf, "total cycles = %lld\n", state->energy.tcycle) ;
				    fprintf(pf, "total energy = %lf\n", state->energy.t_energy) ;
				}
}


static int
frommem (state, memory)
     struct ARMul_State *state;
     unsigned char *memory;
{
  if (state->bigendSig == HIGH)
    {
      return (memory[0] << 24)
	| (memory[1] << 16) | (memory[2] << 8) | (memory[3] << 0);
    }
  else
    {
      return (memory[3] << 24)
	| (memory[2] << 16) | (memory[1] << 8) | (memory[0] << 0);
    }
}


static void
tomem (state, memory, val)
     struct ARMul_State *state;
     unsigned char *memory;
     int val;
{
  if (state->bigendSig == HIGH)
    {
      memory[0] = val >> 24;
      memory[1] = val >> 16;
      memory[2] = val >> 8;
      memory[3] = val >> 0;
    }
  else
    {
      memory[3] = val >> 24;
      memory[2] = val >> 16;
      memory[1] = val >> 8;
      memory[0] = val >> 0;
    }
}

int
sim_store_register (sd, rn, memory, length)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     int rn;
     unsigned char *memory;
     int length ATTRIBUTE_UNUSED;
{
  init ();
  ARMul_SetReg (state, state->Mode, rn, frommem (state, memory));
  return -1;
}

int
sim_fetch_register (sd, rn, memory, length)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     int rn;
     unsigned char *memory;
     int length ATTRIBUTE_UNUSED;
{
  ARMword regval;

  init ();
  if (rn < 16)
    regval = ARMul_GetReg (state, state->Mode, rn);
  else if (rn == 25)		/* FIXME: use PS_REGNUM from gdb/config/arm/tm-arm.h */
    regval = ARMul_GetCPSR (state);
  else
    regval = 0;			/* FIXME: should report an error */
  tomem (state, memory, regval);
  return -1;
}

SIM_DESC
sim_open (kind, ptr, abfd, argv)
     SIM_OPEN_KIND kind;
     host_callback *ptr;
     struct _bfd *abfd;
     char **argv;
{
  sim_kind = kind;
  if (myname) free (myname);
  myname = (char *) xstrdup (argv[0]);
  sim_callback = ptr;

  /* Decide upon the endian-ness of the processor.
     If we can, get the information from the bfd itself.
     Otherwise look to see if we have been given a command
     line switch that tells us.  Otherwise default to little endian.  */
  if (abfd != NULL)
    big_endian = bfd_big_endian (abfd);
  else if (argv[1] != NULL)
    {
      int i;

      /* Scan for endian-ness switch.  */
      for (i = 0; (argv[i] != NULL) && (argv[i][0] != 0); i++)
	if (argv[i][0] == '-' && argv[i][1] == 'E')
	  {
	    char c;

	    if ((c = argv[i][2]) == 0)
	      {
		++i;
		c = argv[i][0];
	      }

	    switch (c)
	      {
	      case 0:
		sim_callback->printf_filtered
		  (sim_callback, "No argument to -E option provided\n");
		break;

	      case 'b':
	      case 'B':
		big_endian = 1;
		break;

	      case 'l':
	      case 'L':
		big_endian = 0;
		break;

	      default:
		sim_callback->printf_filtered
		  (sim_callback, "Unrecognised argument to -E option\n");
		break;
	      }
	  }
    }

  return (SIM_DESC) 1;
}

void
sim_close (sd, quitting)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     int quitting ATTRIBUTE_UNUSED;
{
  if (myname) free (myname);
  myname = NULL;
}

SIM_RC
sim_load (sd, prog, abfd, from_tty)
     SIM_DESC sd;
     char *prog;
     bfd *abfd;
     int from_tty ATTRIBUTE_UNUSED;
{
  extern bfd *sim_load_file ();	/* ??? Don't know where this should live.  */
  bfd *prog_bfd;

  prog_bfd = sim_load_file (sd, myname, sim_callback, prog, abfd,
			    sim_kind == SIM_OPEN_DEBUG, 0, sim_write);
  if (prog_bfd == NULL)
    return SIM_RC_FAIL;
  /* Check if there is a bootrom */
  if ((abfd != NULL) && (state->mem.rom[0] == NULL)) {
    ARMul_SetPC (state, bfd_get_start_address (prog_bfd));
  } else {
    /* Run the bootrom at zero */
    ARMul_SetPC (state, 0);
  }
  if (abfd == NULL)
    bfd_close (prog_bfd);
  return SIM_RC_OK;
}

void
sim_stop_reason (sd, reason, sigrc)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     enum sim_stop *reason;
     int *sigrc;
{
  if (stop_simulator)
    {
      *reason = sim_stopped;
      *sigrc = SIGINT;
    }
  else if (state->EndCondition == 0)
    {
      *reason = sim_exited;
      *sigrc = state->Reg[0] & 255;
    }
  else
    {
      *reason = sim_stopped;
      if (state->EndCondition == RDIError_BreakpointReached)
	*sigrc = SIGTRAP;
      else
	*sigrc = 0;
    }
}

void
sim_do_command (sd, cmd)
     SIM_DESC sd ATTRIBUTE_UNUSED;
     char *cmd ATTRIBUTE_UNUSED;
{  
  /*ywc 2005-04-01*/
  if(skyeye_config.no_dbct){
  (*sim_callback->printf_filtered) (sim_callback,
				    "This simulator does not accept any commands.\n");
  }else{
        //teawater add for arm2x86 2005.02.15-------------------------------------------
        if (!cmd) {
                return;
        }
        if (!strcmp(cmd, "pc on")) {
                state->tea_pc = 1;
                return;
        }
        if (!strcmp(cmd, "pc off")) {
                state->tea_pc = 0;
                return;
        }
        if (!strcmp(cmd, "b off")) {
                state->tea_break_ok = 0;
                return;
        }
        state->tea_break_addr = strtoul(cmd, NULL, 0);
        //AJ2D--------------------------------------------------------------------------
  }
}


void
sim_set_callbacks (ptr)
     host_callback *ptr;
{
  sim_callback = ptr;
}
