Ejemplo n.º 1
0
int
main(int argc, char *argv[])
{
    int ch;
    cpu_t *cpu = init_cpu();
    char *sys_file;

    while ((ch = getopt(argc, argv, "df:")) != EOF) {
        switch (ch) {
            case 'd':
                cpu->debug = true;
                break;

            case 'f':
                sys_file = strdup(optarg);
                break;
        }
    }

    argc -= optind;
    argv += optind;

    init_disk(cpu->port0, "/tmp/disk0");

    load_cpu(cpu, sys_file);

    while (true)
        run_cpu(cpu);

    free_cpu(cpu);
    return 0;
}
Ejemplo n.º 2
0
void retro_reset(void)
{
   init_cpu();
   init_roms();
   init_vpp();
   clearscr();
}
Ejemplo n.º 3
0
// ------------------------------------------------------------------------- //
// cpu_manager                                                               //
// ------------------------------------------------------------------------- //
void cpu_manager::configure() {
    // init cpu interface if unknown
    if (m_icpu == NULL)
        init_cpu();

    // get current thread and thread mask
    prl::thread current_thread = prl::thread::get_current_thread();
    prl::affinity_mask pam = current_thread.get_thread_mask();

    // affinity mask cutter
    prl::affinity_mask_cutter cutter(pam);

    // determin max topology layer size
    //TODO: optimize
    uint32_t max = pam.num_bits_set();
    m_smts.reserve( max );
    m_cores.reserve( max );
    m_pkgs.reserve( max );

    // split process affinity mask into multiple masks
    prl::affinity_mask single_lp;
    while (cutter.has_next()) {
        single_lp = cutter.next();
        current_thread.set_thread_mask(single_lp);

        apic apic = m_icpu->get_apic();
        register_lp(single_lp, apic);
    }
    // reset thread affinity
    current_thread.set_thread_mask(pam);
}
Ejemplo n.º 4
0
/*
 * Invoked by init_smp() to perform any per-cpu specific initialisation.
 */
void
smp_init_cpu()
{
	smp_exc_init();
	ppcbke_tlb_init(0);
	init_cpu();
}
Ejemplo n.º 5
0
SIM_DESC
sim_open (SIM_OPEN_KIND kind,
	  struct host_callback_struct *callback,
	  struct bfd *abfd, char **argv)
{
  if (open)
    fprintf (stderr, "rl78 minisim: re-opened sim\n");

  /* The 'run' interface doesn't use this function, so we don't care
     about KIND; it's always SIM_OPEN_DEBUG.  */
  if (kind != SIM_OPEN_DEBUG)
    fprintf (stderr, "rl78 minisim: sim_open KIND != SIM_OPEN_DEBUG: %d\n",
	     kind);

  /* We use this for the load command.  Perhaps someday, it'll be used
     for syscalls too.  */
  host_callbacks = callback;

  /* We don't expect any command-line arguments.  */

  init_cpu ();
  trace = 0;

  sim_disasm_init (abfd);
  open = 1;
  return &the_minisim;
}
Ejemplo n.º 6
0
int main(int argc, char *argv[]){
  if (argc != 3){
    printf("Usage: %s <cycles> <filename>\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  int cycles;
  xcpu *c = malloc(sizeof(xcpu));
  init_cpu(c);
  FILE *fd=load_file(argv[2]);
  load_programme(c, fd); // loads the bytes of fd into c->memory
  cycles = atoi(argv[1]);

  // the IHandler type is defined in xcpu.h, and the IHandler jump table
  // is implemented in xcpu.c
  IHandler *table = build_jump_table();
  // It is a jump table to the functions handling each instruction.
  char *graceful    = "CPU has halted.";
  char *out_of_time = "CPU ran out of time.";
  int halted, i=0;
  while (i++ < cycles || !cycles){
    if (MOREDEBUG) fprintf(LOG, "<CYCLE %d>\n",i-1);
    if (halted = !xcpu_execute(c, table)) break; 
  } // on halt, halted gets 0; otherwise halted remains 1
  char *exit_msg = (halted)? graceful : out_of_time;
  fprintf(stdout, "%s\n", exit_msg);
  fprintf(LOG, "(%d cycles completed.)\n", i-1);
  destroy_jump_table(table);
  shutdown(c);
  return !halted;
}
Ejemplo n.º 7
0
SIM_DESC
sim_open (SIM_OPEN_KIND kind,
	  struct host_callback_struct *callback,
	  struct bfd *abfd, char **argv)
{
  if (open)
    fprintf (stderr, "rl78 minisim: re-opened sim\n");

  /* The 'run' interface doesn't use this function, so we don't care
     about KIND; it's always SIM_OPEN_DEBUG.  */
  if (kind != SIM_OPEN_DEBUG)
    fprintf (stderr, "rl78 minisim: sim_open KIND != SIM_OPEN_DEBUG: %d\n",
	     kind);

  /* We use this for the load command.  Perhaps someday, it'll be used
     for syscalls too.  */
  host_callbacks = callback;

  /* We don't expect any command-line arguments.  */

  init_cpu ();
  trace = 0;

  sim_disasm_init (abfd);
  open = 1;

  while (argv != NULL && *argv != NULL)
    {
      if (strcmp (*argv, "g10") == 0 || strcmp (*argv, "-Mg10") == 0)
	{
	  fprintf (stderr, "rl78 g10 support enabled.\n");
	  rl78_g10_mode = 1;
	  g13_multiply = 0;
	  g14_multiply = 0;
	  mem_set_mirror (0, 0xf8000, 4096);
	  break;
	}
      if (strcmp (*argv, "g13") == 0 || strcmp (*argv, "-Mg13") == 0)
	{
	  fprintf (stderr, "rl78 g13 support enabled.\n");
	  rl78_g10_mode = 0;
	  g13_multiply = 1;
	  g14_multiply = 0;
	  break;
	}
      if (strcmp (*argv, "g14") == 0 || strcmp (*argv, "-Mg14") == 0)
	{
	  fprintf (stderr, "rl78 g14 support enabled.\n");
	  rl78_g10_mode = 0;
	  g13_multiply = 0;
	  g14_multiply = 1;
	  break;
	}
      argv++;
    }

  return &the_minisim;
}
Ejemplo n.º 8
0
Archivo: main.c Proyecto: HackLinux/ION
int main(int argc,char *argv[]){
    int exitcode = 0;
    t_state state, *s=&state;

    /* Parse command line and pass any relevant arguments to CPU record */
    parse_cmd_line(argc,argv, &cmd_line_args);

    fprintf(stderr,"ION (MIPS32 clone) core emulator (" __DATE__ ")\n\n");
    if(!init_cpu(s, &cmd_line_args)){
        fprintf(stderr,"Trouble allocating memory, quitting!\n");
        exit(71);
    };

    /* Read binary object files into memory*/
    if(!read_binary_files(s, &cmd_line_args)){
        exit(66);
    }
    fprintf(stderr,"\n\n");
    
    /* Open the CPU console output file if not stdout. */
    if (cmd_line_args.conout_filename!=NULL) {
        cpuconout = fopen(cmd_line_args.conout_filename, "w");
        if (cpuconout==NULL){
            fprintf(stderr,"Trouble opening console log file '%s', quitting.\n", cmd_line_args.conout_filename);
            exitcode = 2;
            goto main_quit;
        }
    }
    else {
        cpuconout = stdout;
    }

    init_trace_buffer(s, &cmd_line_args);

    /* NOTE: Original mlite supported loading little-endian code, which this
      program doesn't. The endianess-conversion code has been removed.
    */

    /* Simulate a CPU reset */
    reset_cpu(s);

    /* Simulate the work of the uClinux bootloader */
    if(cmd_line_args.memory_map == MAP_UCLINUX){
        /* FIXME this 'bootloader' is a stub, flesh it out */
        s->pc = 0x80002400;
    }

    /* Enter debug command interface; will only exit clean with user command */
    do_debug(s, cmd_line_args.no_prompt);

main_quit:
    /* Close and deallocate everything and quit */
    close_trace_buffer(s);
    free_cpu(s);
    if (cmd_line_args.conout_filename!=NULL && cpuconout!=NULL) fclose(cpuconout);
    exit(0);
}
Ejemplo n.º 9
0
void
init_smp() {
	//
	// We're back in the kernel, with a sideway dive
	//
	set_inkernel(INKERNEL_NOW|INKERNEL_LOCK);

	//nohalt = 1;

	init_cpu();

	// This will return through the kernel and idle will be running!
	set_inkernel(0);
	ker_start();
}
Ejemplo n.º 10
0
int main(int argc, char **argv) {
    steplimit = parse_args(argc, argv);
    cpu_t cpu = init_cpu();

    pcpu = &cpu;

    /* Code section is protected from writes by default, un-protect it */
    if (mprotect(gen_code, JIT_CODE_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC)) {
        perror("mprotect");
        exit(2);
    }
    /* Pre-populate resulting code buffer with INT3 (machine code 0xCC).
       This will help to catch jumps to wrong locations */
    memset(gen_code, 0xcc, JIT_CODE_SIZE);
    void* entrypoints[PROGRAM_SIZE] = {0}; /* a map of guest PCs to capsules */

    translate_program(cpu.pmem, gen_code, entrypoints, PROGRAM_SIZE);

    setjmp(return_buf); /* Will get here from generated code. */

    while (cpu.state == Cpu_Running && cpu.steps < steplimit) {
        if (cpu.pc > PROGRAM_SIZE) {
            cpu.state = Cpu_Break;
            break;
        }
        enter_generated_code(entrypoints[cpu.pc]); /* Will not return */
    }

    assert(cpu.state != Cpu_Running || cpu.steps == steplimit);
    /* Print CPU state */
    printf("CPU executed %lld steps. End state \"%s\".\n",
            cpu.steps, cpu.state == Cpu_Halted? "Halted":
                       cpu.state == Cpu_Running? "Running": "Break");
    printf("PC = %#x, SP = %d\n", cpu.pc, cpu.sp);
    printf("Stack: ");
    for (int32_t i=cpu.sp; i >= 0 ; i--) {
        printf("%#10x ", cpu.stack[i]);
    }
    printf("%s\n", cpu.sp == -1? "(empty)": "");

    free(LoadedProgram);

    return cpu.state == Cpu_Halted ||
           (cpu.state == Cpu_Running &&
            cpu.steps == steplimit)?0:1;
}
Ejemplo n.º 11
0
void main(int argc, char **argv)
{
    progname = (progname = strrchr(argv[0],'/')) ? progname : argv[0];

#ifndef BOOT
    FILE *f1;
    if (argc != 2)
    {
        fprintf(stderr,"Format: %s testfile\n",progname);
        exit(1);
    }
#endif
    if (!(memory = (BYTE *)malloc(MEMORY_SIZE)))
    {
        fprintf(stderr,"Insufficient available memory\n");
        exit(1);
    }
#ifdef BOOT
    memset(memory,0, MEMORY_SIZE);
#else
    if (!(f1 = fopen(argv[1],"rb")))
    {
        fprintf(stderr,"Cannot open test file\n");
        exit(1);
    }


    fread(memory+0x800,1,MEMORY_SIZE-0x800,f1);
    fclose(f1);
#endif

    read_pcemurc();
    disable();

    start_X();
    init_cpu();
    init_bios();
    init_vga();
    init_timer();

    enable();

    execute();

    /* NOT REACHED */
}
Ejemplo n.º 12
0
static void run() {
	int n_data_hazards = 0;
	int n_cycles = 0;
	char *mem;
	int rs, rt, rd, imm;
	int i, j = 0, k;

	init_cpu();
	while (cpu.pc_mem < ins_buf + n_ins) {
		if (need_resched())
			resched();
	
		if (debug) {
			printf("%d: ", cpu.pc_mem - ins_buf);
			print_ins(cpu.pc_rb);
		}

		history_buf[j] = *cpu.pc_rb;
		exec_ins();

		if (debug) {
			for (i = 0; i < 4; i++)
				printf("%ss%d=%d", i==0?"\t# ":", ", i, cpu.reg_value[REG_S0 + i]);
			for (i = 0; i < 2; i++)
				printf(", t%d=%d", i, cpu.reg_value[REG_T0 + i]);
			printf("\n");
		}

		cpu.pc_mem++;
		if (cpu.pc_rb != NULL) cpu.pc_rb++;
		n_cycles++;

		// count hazard
		for (k = 1; k < stall_range && k < n_cycles; k++)
			if (has_dep(&history_buf[(j - k + HISTORY_BUF_LEN) % HISTORY_BUF_LEN],
						&history_buf[j])) {
				n_data_hazards++;
				break;
			}
		j = (j + 1) % HISTORY_BUF_LEN;
	}

	if (profile)
		printf("Cycles: %d, data hazards: %d\n", n_cycles, n_data_hazards);
}
Ejemplo n.º 13
0
Archivo: boot_sys.c Proyecto: scan/seL4
static BOOT_CODE bool_t
try_boot_sys_node(cpu_id_t cpu_id)
{
    p_region_t boot_mem_reuse_p_reg;

    if (!map_kernel_window(
                boot_state.num_ioapic,
                boot_state.ioapic_paddr,
                boot_state.num_drhu,
                boot_state.drhu_list
            )) {
        return false;
    }
    setCurrentVSpaceRoot(kpptr_to_paddr(X86_GLOBAL_VSPACE_ROOT), 0);
    /* Sync up the compilers view of the world here to force the PD to actually
     * be set *right now* instead of delayed */
    asm volatile("" ::: "memory");

    /* reuse boot code/data memory */
    boot_mem_reuse_p_reg.start = PADDR_LOAD;
    boot_mem_reuse_p_reg.end = (paddr_t)ki_boot_end - KERNEL_BASE_OFFSET;

    /* initialise the CPU */
    if (!init_cpu(config_set(CONFIG_IRQ_IOAPIC) ? 1 : 0)) {
        return false;
    }

    /* initialise NDKS and kernel heap */
    if (!init_sys_state(
                cpu_id,
                boot_state.mem_p_regs,
                boot_state.ui_info,
                boot_mem_reuse_p_reg,
                /* parameters below not modeled in abstract specification */
                boot_state.num_drhu,
                boot_state.drhu_list,
                &boot_state.rmrr_list,
                &boot_state.vbe_info
            )) {
        return false;
    }

    return true;
}
Ejemplo n.º 14
0
/*
========================================================================
main:	This is the main entry point for the VirtualT application.
========================================================================
*/
int main(int argc, char **argv)
{
	if (process_args(argc, argv))	/* Parse command line args */
		return 1;

	setup_working_path(argv);	/* Create a working dir path */
	setup_unix_signals();		/* Setup Unix signal handling */

	// Added by JV for prefs
	init_pref();				/* load user Menu preferences */
	check_installation();		/* Test if install needs to be performed */
	load_setup_preferences();	/* Load user Peripheral setup preferences */
	load_memory_preferences();	/* Load user Memory setup preferences */
	load_remote_preferences();  /* Load user Remote Socket preferences */
	
	/* Perform initialization */
	init_mem();					/* Initialize Memory */
	init_io();					/* Initialize I/O structures */
	init_sound();				/* Initialize Sound system */
	init_display();				/* Initialize the Display */
	init_cpu();					/* Initialize the CPU */
	init_throttle_timer();		/* Initialize the throttle timer */
	init_remote();				/* Initialize the remote control */
	init_lpt();					/* Initialize the printer subsystem */
	init_other_windows();		/* Initialize other windows that were opened (memedit, regs, etc. */
	get_model_time();			/* Load the emulated time for current model */

	/* Perform Emulation */
	emulate();					/* Main emulation loop */

	/* Save RAM contents after emulation */
	save_ram();
	save_model_time();			/* Save the emulated time */

	/* Cleanup */
	deinit_io();				/* Deinitialize I/O */
	deinit_sound();				/* Deinitialize sound */
	deinit_lpt();				/* Deinitialize the printer */
	deinit_throttle_timer();	/* Deinitialize the throttle timer */
	deinit_display();			/* Deinitialze and free the main window */
	free_mem();					/* Free memory used by ReMem and/or Rampac */

	return 0;
}
Ejemplo n.º 15
0
Archivo: boot.c Proyecto: seL4/seL4
BOOT_CODE static bool_t try_init_kernel_secondary_core(void)
{
    /* need to first wait until some kernel init has been done */
    while (!node_boot_lock);

    /* Perform cpu init */
    init_cpu();

    /* Enable per-CPU timer interrupts */
    maskInterrupt(false, KERNEL_TIMER_IRQ);

    NODE_LOCK_SYS;

    ksNumCPUs++;

    init_core_state(SchedulerAction_ResumeCurrentThread);

    return true;
}
Ejemplo n.º 16
0
void main(void) {
	unsigned char i;
	init_cpu();
	
	//Initialize the checksum.
	captureBuffer.checksum = 0xFF;
	
	while(1) {
		/*
		//Echo everything back to the tagger.
		//Should put it in factory test mode.
		if(captureBuffer.size & 0x80 && !ser_tx_size && !ser_tx_cooldown) {
            //Block received.
            //Echo it back for testing.
            unsigned char rx_size = (captureBuffer.size & 0x7F);
			int i;
			
            for(i = 0; i < rx_size;i++) {
                queueByte(captureBuffer.buffer[i]);
            }
			
            sendQueue();
            captureBuffer.size = 0;
        } else {
			if(!(U0STAT0 ^ 0x06)) {
				IRQ0 |= 0x08;
			}
		}
		*/
		
		//The actual main loop if you want it to work like a weapon accessory.
		receiveSomething(); //Go check if there's anything to process in the receive buffer
		sendSomething(); //Go check if there's anything we need to transmit
		if(btn_pressed) { //If the button has been pressed and debounced
			btn_pressed = 0; //Clear the flag.
			if(weAreRegistered) { //If the tagger has acknowledged our presence
				sendLoadSpecial = 1; //Flag that we should start loading the attachment
			}
		}
	}
}
Ejemplo n.º 17
0
int main(int argc, char **argv) {

    if(argc < 2) {
        printf("Especifique o arquivo com o codigo\n");
        exit(0);
    }

    init_memory();

    init_stack();

    loadcode(argv[1]);

    init_cpu();

    while(cpu_cycle());

    memory_dump();

    free_memory();
    return 0;
}
Ejemplo n.º 18
0
Archivo: main.c Proyecto: deadbok/aMOS
int main(void)
{
	init_pmm();

	if (init_mm())
		return(1);

	vid_init();

	vid_set_attr(FG_COLOR, RED);

	printf("\naMOS BOSS V.%s %s\n", STRING_VERSION, BUILD_ARCH);
	printf("Build %s %s by %s on %s\n\n", COMPILE_DATE, COMPILE_TIME, COMPILE_BY, COMPILE_HOST);

	vid_set_attr(FG_COLOR, WHITE);

	init_pit();

	init_tss();

	if (init_intr())
		return(1);

	init_cpu();

	if (init_sched())
		return(1);

	init_fd();

	printf("System memory: %d Mb\n\n", (int)pmm_get_size_mb());
	printf("Free kernel mem: %d bytes\nUsed kernel mem: %d bytes\n", (int)get_free_mem(), (int)get_used_mem());

	for (;;) {}
		
	return(0);
}
Ejemplo n.º 19
0
int run_dgcuda(int argc, char *argv[]) {
    int local_num_elem, local_num_sides;
    int n_threads, n_blocks_elem, n_blocks_sides;
    int i, n, local_n_p, total_timesteps, local_n_quad, local_n_quad1d;
    int verbose, convergence, video, eval_error, benchmark;

    double endtime, t;
    double tol, total_error, max_error;
    double *min_radius;
    double min_r;
    double *V1x, *V1y, *V2x, *V2y, *V3x, *V3y;
    double *sides_x1, *sides_x2;
    double *sides_y1, *sides_y2;

    double *r1_local, *r2_local, *w_local;

    double *s_r, *oned_w_local;

    int *left_elem, *right_elem;
    int *elem_s1, *elem_s2, *elem_s3;
    int *left_side_number, *right_side_number;

    FILE *mesh_file, *out_file;

    char out_filename[100];
    char *mesh_filename;

    double *Uv1, *Uv2, *Uv3;
    double *error;

    clock_t start, end;
    double elapsed;

    // get input 
    endtime = -1;
    if (get_input(argc, argv, &n, &total_timesteps, &endtime, 
                              &verbose, &video, &convergence, &tol, 
                              &benchmark, &eval_error, 
                              &mesh_filename)) {
        return 1;
    }

    // set the order of the approximation & timestep
    local_n_p = (n + 1) * (n + 2) / 2;

    // sanity check on limiter
    if (limiter && n != 1) {
        printf("Error: limiter only enabled for p = 1\n");
        exit(0);
    }

    // open the mesh to get local_num_elem for allocations
    mesh_file = fopen(mesh_filename, "r");
    if (!mesh_file) {
        printf("\nERROR: mesh file not found.\n");
        return 1;
    }

    // read in the mesh and make all the mappings
    read_mesh(mesh_file, &local_num_sides, &local_num_elem,
                         &V1x, &V1y, &V2x, &V2y, &V3x, &V3y,
                         &left_side_number, &right_side_number,
                         &sides_x1, &sides_y1, 
                         &sides_x2, &sides_y2, 
                         &elem_s1, &elem_s2, &elem_s3,
                         &left_elem, &right_elem);

    // close the file
    fclose(mesh_file);

    // initialize the gpu
    init_cpu(local_num_elem, local_num_sides, local_n_p,
             V1x, V1y, V2x, V2y, V3x, V3y,
             left_side_number, right_side_number,
             sides_x1, sides_y1,
             sides_x2, sides_y2, 
             elem_s1, elem_s2, elem_s3,
             left_elem, right_elem,
             convergence, eval_error);

    // get the correct quadrature rules for this scheme
    set_quadrature(n, &r1_local, &r2_local, &w_local, 
                   &s_r, &oned_w_local, &local_n_quad, &local_n_quad1d);

    // set constant data
    set_N(local_N);
    set_n_p(local_n_p);
    set_num_elem(local_num_elem);
    set_num_sides(local_num_sides);
    set_n_quad(local_n_quad);
    set_n_quad1d(local_n_quad1d);

    // find the min inscribed circle
    preval_inscribed_circles(d_J, d_V1x, d_V1y, d_V2x, d_V2y, d_V3x, d_V3y);
    min_radius = (double *) malloc(local_num_elem * sizeof(double));
    memcpy(min_radius, d_J, local_num_elem * sizeof(double));
    min_r = min_radius[0];
    for (i = 1; i < local_num_elem; i++) {
        min_r = (min_radius[i] < min_r) ? min_radius[i] : min_r;
        // report problem
        if (min_radius[i] == 0) {
            printf("%i\n", i);
            printf("%.015lf, %.015lf, %.015lf, %.015lf, %.015lf, %.015lf\n", 
                                                     V1x[i], V1y[i],
                                                     V2x[i], V2y[i],
                                                     V3x[i], V3y[i]);
        }
    }
    free(min_radius);

    // pre computations
    preval_jacobian(d_J, d_V1x, d_V1y, d_V2x, d_V2y, d_V3x, d_V3y); 

    preval_side_length(d_s_length, d_s_V1x, d_s_V1y, d_s_V2x, d_s_V2y);
                                                      
    preval_normals(d_Nx, d_Ny, 
                   d_s_V1x, d_s_V1y, d_s_V2x, d_s_V2y,
                   d_V1x, d_V1y, 
                   d_V2x, d_V2y, 
                   d_V3x, d_V3y, 
                   d_left_side_number);


    preval_normals_direction(d_Nx, d_Ny, 
                             d_V1x, d_V1y, 
                             d_V2x, d_V2y, 
                             d_V3x, d_V3y, 
                             d_left_elem, d_left_side_number);

    preval_partials(d_V1x, d_V1y,
                    d_V2x, d_V2y,
                    d_V3x, d_V3y,
                    d_xr,  d_yr,
                    d_xs,  d_ys);

   // evaluate the basis functions at those points and store on GPU
    preval_basis(r1_local, r2_local, s_r, w_local, oned_w_local, local_n_quad, local_n_quad1d, local_n_p);

    // no longer need any of these CPU variables
    free(elem_s1);
    free(elem_s2);
    free(elem_s3);
    free(sides_x1);
    free(sides_x2);
    free(sides_y1);
    free(sides_y2);
    free(left_elem);
    free(right_elem);
    free(left_side_number);
    free(right_side_number);
    free(r1_local);
    free(r2_local);
    free(w_local);
    free(s_r);
    free(oned_w_local);

    // initial conditions
    init_conditions(d_c, d_J, d_V1x, d_V1y, d_V2x, d_V2y, d_V3x, d_V3y);

    printf(" ? %i degree polynomial interpolation (local_n_p = %i)\n", n, local_n_p);
    printf(" ? %i precomputed basis points\n", local_n_quad * local_n_p);
    printf(" ? %i elements\n", local_num_elem);
    printf(" ? %i sides\n", local_num_sides);
    printf(" ? min radius = %.015lf\n", min_r);

    if (endtime == -1 && convergence != 1) {
        printf(" ? total_timesteps = %i\n", total_timesteps);
    } else if (endtime != -1 && convergence != 1) {
        printf(" ? endtime = %lf\n", endtime);
    }


    if (benchmark) {
        start = clock();
    }

    t = time_integrate_rk4(local_num_elem, local_num_sides, 
                           n, local_n_p,
                           endtime, total_timesteps, min_r,
                           verbose, convergence, video, tol);

    if (benchmark) {
        end = clock();
        elapsed = ((double)(end - start)) / CLOCKS_PER_SEC;
        printf("Runtime: %lf seconds\n", elapsed);
    }

    // evaluate and write U to file
    write_U(local_num_elem, total_timesteps, total_timesteps);

    // free everything else
    free(d_s_V1x);
    free(d_s_V2x);
    free(d_s_V1y);
    free(d_s_V2y);

    free(d_s_length);
    free(d_lambda);
    free(d_k1);
    free(d_k2);
    free(d_k3);
    free(d_k4);
    free(d_rhs_volume);
    free(d_rhs_surface_left);
    free(d_rhs_surface_right);
    free(d_elem_s1);
    free(d_elem_s2);
    free(d_elem_s3);
    free(d_xr);
    free(d_yr);
    free(d_xs);
    free(d_ys);

    free(d_left_side_number);
    free(d_right_side_number);

    free(d_Nx);
    free(d_Ny);

    free(d_right_elem);
    free(d_left_elem);
    free(d_c);
    free(d_J);

    free(d_Uv1);
    free(d_Uv2);
    free(d_Uv3);
    free(d_V1x);
    free(d_V1y);
    free(d_V2x);
    free(d_V2y);
    free(d_V3x);
    free(d_V3y);

    // free CPU variables
    free(V1x);
    free(V1y);
    free(V2x);
    free(V2y);
    free(V3x);
    free(V3y);

    return 0;
}
Ejemplo n.º 20
0
/********************* Main*/
int omain(int argc, char *argv[]){
	int i, cnt, cntt, cnttt, way;
	static char file[MAXC], attr[MAXC], val[MAXC], *p, *binver;
	#if defined(ALLEGRO_WINDOWS)
	binver = "Windows binary";
	#elif defined(ALLEGRO_DOS)
	binver = "DOS binary";
	#elif defined(ALLEGRO_LINUX)
	binver = "Linux binary";
	#elif defined(ALLEGRO_BEOS)
	binver = "BEOS binary";
	#elif defined(ALLEGRO_QNX)
	binver = "QNX binary";
	#elif defined(ALLEGRO_UNIX)
	binver = "UNIX binary";
	#elif defined(ALLEGRO_MPW)
	binver = "MacOS binary";
	#else
	binver = "Unknown binary";
	#endif
	printf("%s %s\n","\nO2EM v" O2EM_VERSION " " RELEASE_DATE "  - ", binver);
	printf("Free Odyssey2 / Videopac+ Emulator - http://o2em.sourceforge.net\n");
	printf("Created by Daniel Boris (c)1996/1998\n");
    printf("Developed by:\n");
	printf("     Andre de la Rocha since version 0.80\n");
	printf("     Arlindo M. de Oliveira since version 1.16\n");
    printf("\n");

    app_data.debug = 0;
	app_data.stick[0] = app_data.stick[1] = 1;
	app_data.sticknumber[0] = app_data.sticknumber[1] = 0;
	set_defjoykeys(0,0);
	set_defjoykeys(1,1);
	set_defsystemkeys();
	app_data.bank = 0;
	app_data.limit = 1;
	app_data.sound_en = 1;
	app_data.speed = 100;
	app_data.wsize = 2;
	#ifdef ALLEGRO_DOS
	app_data.fullscreen = 1;
	#else
	app_data.fullscreen = 0;
	#endif
	app_data.scanlines = 0;
	app_data.voice = 1;
	app_data.window_title = "O2EM v" O2EM_VERSION;
	app_data.svolume = 100;
	app_data.vvolume = 100;
	app_data.filter = 0;
	app_data.exrom = 0;
	app_data.three_k = 0;
	app_data.crc = 0;
	app_data.scshot = scshot;
	app_data.statefile = statefile;
	app_data.euro = 0;
	app_data.openb = 0;
	app_data.vpp = 0;
	app_data.bios = 0;
	app_data.scoretype = 0;
	app_data.scoreaddress = 0;
	app_data.default_highscore = 0;
	app_data.breakpoint = 65535;
	app_data.megaxrom = 0;
	strcpy(file,"");
	strcpy(file_l,"");
	strcpy(bios_l,"");
    strcpy(bios,"");
	strcpy(scshot,"");
	strcpy(statefile,"");
    strcpy(xrom,"");
	strcpy(scorefile,"highscore.txt");
	read_default_config();
	if (argc >= 2){
    for(i=1; i<argc; i++) {
		if (argv[i][0] != '-') 	{
			strncat(file,argv[i],MAXC-1);
	        file[MAXC-1]=0;
	        strcpy(file_v,file);
		} else {
			p=strtok(argv[i],"=");
	        if (p){
				strncpy(attr,p+1,MAXC-1);
				attr[MAXC-1]=0;
			   } else
				strcpy(attr,"");
			    p=strtok(NULL,"=");
			if (p){
				strncpy(val,p,MAXC-1);
				val[MAXC-1]=0;
			    if (!strcmp(attr,"romdir")||!strcmp(attr,"ROMDIR"))
                   {
                    strcpy(romdir,val);
                    strcat(romdir,file);
                    strcpy(file,romdir);
                    strcpy(romdir,val);
                   }
                if (!strcmp(attr,"biosdir")||!strcmp(attr,"BIOSDIR"))
                   {
                    strcpy(biosdir,val);
                   }                                       
            } else
			strcpy(val,"");
			strlwr(attr);
			if (!parse_option(attr, val)) exit(EXIT_FAILURE);
		}
    }
    if (helpflag) helpus();
    if (strlen(file)==0) {
		fprintf(stderr,"Error: file name missing\n");
		exit(EXIT_FAILURE);
	}

#ifdef __LIBRETRO__
sprintf(statefile,"%s.state\0",file);
#endif
	printf("Starting emulation ...\n");
#ifndef __LIBRETRO__
	allegro_init();
	install_timer();
#endif
	init_audio();

#ifndef __LIBRETRO__
	printf("Using Allegro %s\n",allegro_id);
#endif 


/********************** ROMs if Launcher running... */
    k = strchr(romdir, '/'); 

    launcher_flag_r = strchr(file, '\\');

    if (k != 0) {
                 strcpy (xrom,romdir);
                }
                else if (!launcher_flag_r)
                        {

                        strcpy(xrom,"roms/");
                        strcpy(romdir,file);
#ifndef __LIBRETRO__
                        strcpy(file,xrom);
                        strcat(file,romdir);
#endif
                        strcpy(romdir,xrom);

                        }
                        else
                        {    
         
                        cnt = 0;
                        cntt = 0;
                        cnttt = 0;
                        way = 0;
                        for (cnt=0; file[cnt] != '\0'; cnt=cnt+1) 
                        { 
                        if ( file[cnt] == '\\' ) 
                           {
                           cnttt = cnt;
                           }
                        } 
                        for (cnt=0; cnt<=cnttt; cnt++)
                        { 
                        file_l[cnt] = file[cnt];
                        } 

                        strcpy (romdir,file_l);
                        strcpy (xrom,romdir);
                        }

#ifdef __LIBRETRO__
#ifdef AND
	sprintf(xrom,"%s\0","/mnt/sdcard/O2EM/roms/");
	strcpy(romdir,xrom);
#else
	sprintf(xrom,"%s\0","./roms/");
	strcpy(romdir,xrom);
#endif
#endif


    file_name(xrom);

    if (contax < 3)
                 {
                 printf("\nROMs directory empty!\n");
                 exit(EXIT_FAILURE);
                 }

    app_data.crc = crc32_file(file);

    crcx = app_data.crc;
    suck_roms(); 

/********************** BIOSs if Launcher running... */     
launcher_flag_b = strchr(bios, '\\');

if (!launcher_flag_b){
    k = strchr(biosdir, '/');

    if (k != 0) {    
                 strcpy (xbios,biosdir);
                }
                else           
                        {
                        strcpy (xbios,"bios/");
                        strcpy (biosdir,xbios);
                        }
#ifdef __LIBRETRO__
#ifdef AND
	sprintf(xbios,"%s\0","/mnt/sdcard/O2EM/bios/");
	strcpy (biosdir,xbios);
#else	
	sprintf(xbios,"%s\0","./bios/");
	strcpy (biosdir,xbios);
#endif
#endif

    file_name(xbios);

    if (contax < 3)
                 {
                 printf("\nBIOS directory empty!\n");
                 exit(EXIT_FAILURE);                 
                 }

    suck_bios();

    c_j = strcmp(bios,"jopac");
    if ((rom_f!=1) && (c_j!=0)) strcpy(bios,g7400);
    if ((!o2flag) && (!jopflag) && (!c52flag) && (!g74flag))
                                              {
                                             printf("\ndir '%s' without BIOS !",biosdir);
                                             exit(EXIT_FAILURE);
                                              }
    printf("BIOS found:\n");
    if (!strcmp(bios,"g7400")){
                               strcpy(bios,g7400);
                               if (g74flag != 1) {
                                             printf("\nG7400 BIOS not found !");
                                             exit(EXIT_FAILURE);
                                             } 
                               }
    if (g74flag) printf("  G7400 VP+\n");
    if (!strcmp(bios,"c52")){ 
                             strcpy(bios,c52);
                             if (c52flag != 1) {
                                             printf("\nC52 BIOS not found !");
                                             exit(EXIT_FAILURE);
                                             } 
                                 }
    if (c52flag) printf("  C52\n");
    if (!strcmp(bios,"jopac")){
                               strcpy(bios,jopac);
                               if (jopflag != 1) {
                                          printf("\nJOPAC BIOS not found !");
                                          exit(EXIT_FAILURE);
                                             } 
                               }
    if (jopflag) printf("  JOPAC VP+\n");
    if ((!strcmp(bios,"")) || (!strcmp(bios,"o2rom")))
                            {
                            strcpy(bios,odyssey2);
                            if ((!o2flag)&&(!c52flag)&&(rom_f)){
                                             printf("Odyssey2 BIOS not found !\n");
                                             exit(EXIT_FAILURE);
                                             } 
                            if ((!o2flag)&&(c52flag)&&(rom_f)){
                                             printf("\nOdyssey2 BIOS not found !\n");
                                             printf("Loading C52 BIOS ... ");
                                             strcpy(bios,c52);
                                             }
                            }
    if (o2flag) printf("  Odyssey 2\n");
    }                                           
    if (launcher_flag_b)
       {
       identify_bios(bios);
                if (rom_f!=1)
                   {
                   if (!((g74flag)||(jopflag)))
                      {
                      fprintf(stderr,"\nError: ROM only VP+ BIOS");
                      exit(EXIT_FAILURE);
                      }
                   }
       }      


      if (!launcher_flag_b)
                  {  
                  if (rom_f!=1)
                     {  
                     if (!((g74flag)||(jopflag)))
                         {
                         printf("\nROM only VP+ BIOS\n");
                         exit(EXIT_FAILURE);
                         }
                     if (!(g74flag))
                         {
                         printf("\nVP+ G7400 BIOS not found !");
                         printf("\nLoading VP+ Jopac BIOS ...");
                         strcpy(bios,jopac);
                         }
                     }
                  }
    load_bios(bios);

	load_cart(file);
	if (app_data.voice) load_voice_samples(path);

	init_display();

	init_cpu();

	init_system();

	set_score(app_data.scoretype, app_data.scoreaddress, app_data.default_highscore);
	int stateError;
	if ((stateError=loadstate(app_data.statefile))==0)
	{
		printf("Savefile loaded.");
	}
	else if (stateError>=199)
	{
		if (stateError==199) fprintf(stderr,"Wrong ROM-File for Savefile.");
		else if (stateError==200+ROM_O2) fprintf(stderr,"Wrong BIOS for Savefile: O2ROM needed.");
		else if (stateError==200+ROM_G7400) fprintf(stderr,"Wrong BIOS for Savefile: G7400 ROM needed.");
		else if (stateError==200+ROM_C52) fprintf(stderr,"Wrong BIOS for Savefile: C52 ROM needed.");
		else if (stateError==200+ROM_JOPAC) fprintf(stderr,"Wrong BIOS for Savefile: JOPAC ROM needed.");
		else fprintf(stderr,"Wrong BIOS for Savefile: UNKNOWN ROM needed.");
		return(0);
	}
	if (app_data.debug) key_debug=1;
	#ifndef _DEBUG
	#ifdef ALLEGRO_WINDOWS
	FreeConsole();
	#endif
	#endif

#ifdef __LIBRETRO__
return 1;
#endif
	run();

    if (app_data.scoretype!=0) save_highscore(get_score(app_data.scoretype, app_data.scoreaddress), scorefile);
	exit(EXIT_SUCCESS);
 }
if (!strcmp(attr,"help")||!strcmp(attr,"HELP")) helpus();
printf("type o2em -help");
exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
void
rl78_load (bfd *prog, host_callback *callbacks, const char * const simname)
{
  Elf_Internal_Phdr * phdrs;
  long sizeof_phdrs;
  int num_headers;
  int i;
  int max_rom = 0;

  init_cpu ();

  /* Note we load by ELF program header not by BFD sections.
     This is because BFD sections get their information from
     the ELF section structure, which only includes a VMA value
     and not an LMA value.  */
  sizeof_phdrs = bfd_get_elf_phdr_upper_bound (prog);
  if (sizeof_phdrs == 0)
    {
      fprintf (stderr, "%s: Failed to get size of program headers\n", simname);
      return;
    }
  phdrs = xmalloc (sizeof_phdrs);

  num_headers = bfd_get_elf_phdrs (prog, phdrs);
  if (num_headers < 1)
    {
      fprintf (stderr, "%s: Failed to read program headers\n", simname);
      return;
    }
  
  for (i = 0; i < num_headers; i++)
    {
      Elf_Internal_Phdr * p = phdrs + i;
      char *buf;
      bfd_vma size;
      bfd_vma base;
      file_ptr offset;

      size = p->p_filesz;
      if (size <= 0)
	continue;

      base = p->p_paddr;
      if (verbose > 1)
	fprintf (stderr, "[load segment: lma=%08x vma=%08x size=%08x]\n",
		 (int) base, (int) p->p_vaddr, (int) size);
      if (callbacks)
	xprintf (callbacks,
	         "Loading section %s, size %#lx lma %08lx vma %08lx\n",
	         find_section_name_by_offset (prog, p->p_offset),
		 size, base, p->p_vaddr);

      buf = xmalloc (size);

      offset = p->p_offset;
      if (prog->iovec->bseek (prog, offset, SEEK_SET) != 0)
	{
	  fprintf (stderr, "%s, Failed to seek to offset %lx\n", simname, (long) offset);
	  continue;
	}

      if (prog->iovec->bread (prog, buf, size) != size)
	{
	  fprintf (stderr, "%s: Failed to read %lx bytes\n", simname, size);
	  continue;
	}

      if (base > 0xeffff || base + size > 0xeffff)
	{
	  fprintf (stderr, "%s, Can't load image to RAM/SFR space: 0x%lx - 0x%lx\n",
		   simname, base, base+size);
	  continue;
	}
      if (max_rom < base + size)
	max_rom = base + size;

      mem_put_blk (base, buf, size);
      free (buf);
    }

  free (phdrs);

  mem_rom_size (max_rom);

  pc = prog->start_address;

  if (strcmp (bfd_get_target (prog), "srec") == 0
      || pc == 0)
    {
      pc = mem_get_hi (0);
    }

  if (verbose > 1)
    fprintf (stderr, "[start pc=%08x]\n", (unsigned int) pc);
}
Ejemplo n.º 22
0
void handle_key(void){
	if (NeedsPoll) poll_keyboard();


	if (key[syskeys[0]] || key[KEY_ESC]) {
		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();
		} while (key[syskeys[0]] || key[KEY_ESC]);
		key_done=1;
	}

if (key[syskeys[1]]) {
		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();
		} while (key[syskeys[1]]);

		mute_audio();
		mute_voice();
		abaut();

		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();

			if (key[KEY_ALT] && key[KEY_ENTER]) {
				app_data.fullscreen = app_data.fullscreen ? 0 : 1;
				grmode();
				abaut();
				do {
					rest(5);
					if (NeedsPoll) poll_keyboard();
				} while (key[KEY_ENTER]);
			}		

		} while ((!key[syskeys[1]]) && (!key[KEY_ESC]) && (!key[syskeys[0]]));
		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();
		} while (key[syskeys[1]]);
		
		init_sound_stream();
	}		

if (key[syskeys[5]])
	{
		if (savestate(app_data.statefile)==0)
		{
			display_msg("Savefile saved.",5);
		}
		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();
		} while (key[syskeys[5]]);

	}

	/* LOAD STATE */
	if (key[syskeys[6]])
	{
		int stateError;
		if ((stateError=loadstate(app_data.statefile))==0)
		{
			display_msg("Savefile loaded.",5);
		}
		else if (stateError>=199)
		{
			if (stateError==199) display_msg("Wrong ROM-File for Savefile.",5);
			else if (stateError==200+ROM_O2) display_msg("Wrong BIOS for Savefile: O2ROM needed.",5);
			else if (stateError==200+ROM_G7400) display_msg("Wrong BIOS for Savefile: G7400 ROM needed.",5);
			else if (stateError==200+ROM_C52) display_msg("Wrong BIOS for Savefile: C52 ROM needed.",5);
			else if (stateError==200+ROM_JOPAC) display_msg("Wrong BIOS for Savefile: JOPAC ROM needed.",5);
			else display_msg("Wrong BIOS for Savefile: UNKNOWN ROM needed.",5);
		}
		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();
		} while (key[syskeys[6]]);
	}

	if (key[syskeys[2]]) key_debug=1;

	if (key[syskeys[3]]) {
		init_cpu();
		init_roms();
		init_vpp();
		clearscr();
		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();
		} while (key[syskeys[3]]);
	}

    /* SET HIGHSCORE */
	if (key[syskeys[7]])
	{
		set_score(app_data.scoretype, app_data.scoreaddress, app_data.default_highscore);
	}


	if (key[syskeys[4]]) {
		BITMAP *bmp;
		PALETTE pal;
		char *p;
		static char name[1024];
		static int scshot_counter = 0;

		if (strlen(app_data.scshot)>0){
			if ((p=strchr(app_data.scshot,'@'))) {
				*p = 0;
				sprintf(name, "%s%02d%s", app_data.scshot, scshot_counter++, p+1);
				*p = '@';
			} else {
				strcpy(name, app_data.scshot);
			}
			get_palette(pal);
			bmp = create_sub_bitmap(screen, 0, 0, SCREEN_W, SCREEN_H);
			save_bitmap(name, bmp, pal);
			destroy_bitmap(bmp);
			do {
				rest(5);
				if (NeedsPoll) poll_keyboard();
			} while (key[syskeys[4]]);
		}
	}

	// switch joystick
	if (key[syskeys[8]]) {
		joyswitch = joyswitch ? 0 : 1;

		set_defjoykeys(0,joyswitch);
		set_defjoykeys(1,joyswitch ? 0 : 1);
		int tmp = app_data.stick[0];
		app_data.stick[0] = app_data.stick[1];
		app_data.stick[1] = tmp;

		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();
		} while (key[syskeys[8]]);

	}

	if (key[KEY_ALT] && key[KEY_ENTER]) {
		app_data.fullscreen = app_data.fullscreen ? 0 : 1;
		grmode();
		do {
			rest(5);
			if (NeedsPoll) poll_keyboard();
		} while (key[KEY_ENTER]);
	}		

}
Ejemplo n.º 23
0
Archivo: acpi.c Proyecto: qiyeboy/yaos
static int acpi_config_smp(struct acpi_madt *madt)
{
    uint32 lapic_addr;
    uint nioapic = 0;
    uchar *p, *e;
    void init_cpu(u32 apicid);

    if (!madt)
        return -1;
    if (madt->header.length < sizeof(struct acpi_madt))
        return -1;

    lapic_addr = madt->lapic_addr_phys;
    printk("lapic_addr:%lx\n", lapic_addr);
    p = madt->table;
    e = p + madt->header.length - sizeof(struct acpi_madt);

    while (p < e) {
        uint len;

        if ((e - p) < 2)
            break;
        len = p[1];
        if ((e - p) < len)
            break;
        switch (p[0]) {
        case TYPE_LAPIC:{
                struct madt_lapic *lapic = (void *)p;

                if (len < sizeof(*lapic))
                    break;
                if (!(lapic->flags & APIC_LAPIC_ENABLED))
                    break;
                printk("acpi: cpu#%d apicid %d\n", nr_cpu, lapic->apic_id);
                init_cpu(lapic->apic_id);
                break;
            }
        case TYPE_IOAPIC:{
                struct madt_ioapic *ioapic = (void *)p;

                if (len < sizeof(*ioapic))
                    break;
                printk("acpi: ioapic#%d @%x id=%d base=%d\n",
                       nioapic, ioapic->addr, ioapic->id,
                       ioapic->interrupt_base);
                if (nioapic) {
                    printk("warning: multiple ioapics are not supported");
                }
                else {
                    ioapicid = ioapic->id;
                }
                nioapic++;
                break;
            }

        }
        p += len;
    }

    if (nr_cpu) {
        ismp = 1;
        lapic_base = (u32 *) IO2V(((uintp) lapic_addr));
        printk("lapic:%lx,%lx\n", (ulong) lapic_base, lapic_read_base());
        return 0;
    }

    return -1;
}
Ejemplo n.º 24
0
Archivo: vasm.c Proyecto: ezrec/vasm
int main(int argc,char **argv)
{
    int i;
    for(i=1; i<argc; i++) {
        if(argv[i][0]=='-'&&argv[i][1]=='F') {
            output_format=argv[i]+2;
            argv[i][0]=0;
        }
        if(!strcmp("-quiet",argv[i])) {
            verbose=0;
            argv[i][0]=0;
        }
    }
    if(!init_output(output_format))
        general_error(16,output_format);
    if(!init_main())
        general_error(10,"main");
    if(verbose)
        printf("%s\n%s\n%s\n%s\n",copyright,cpu_copyright,syntax_copyright,output_copyright);
    for(i=1; i<argc; i++) {
        if(argv[i][0]==0)
            continue;
        if(argv[i][0]!='-') {
            if(inname)
                general_error(11);
            inname=argv[i];
            continue;
        }
        if(!strcmp("-o",argv[i])&&i<argc-1) {
            if(outname)
                general_error(28,'o');
            outname=argv[++i];
            continue;
        }
        if(!strcmp("-L",argv[i])&&i<argc-1) {
            if(listname)
                general_error(28,'L');
            listname=argv[++i];
            produce_listing=1;
            continue;
        }
        if(!strcmp("-Lnf",argv[i])) {
            listformfeed=0;
            continue;
        }
        if(!strcmp("-Lns",argv[i])) {
            listnosyms=1;
            continue;
        }
        if(!strncmp("-Ll",argv[i],3)) {
            sscanf(argv[i]+3,"%i",&listlinesperpage);
            continue;
        }
        if(!strncmp("-D",argv[i],2)) {
            char *def=NULL;
            expr *val;
            if(argv[i][2])
                def=&argv[i][2];
            else if (i<argc-1)
                def=argv[++i];
            if(def) {
                char *s=def;
                if(ISIDSTART(*s)) {
                    s++;
                    while(ISIDCHAR(*s))
                        s++;
                    def=cnvstr(def,s-def);
                    if(*s=='=') {
                        s++;
                        val=parse_expr(&s);
                    }
                    else
                        val=number_expr(1);
                    if(*s)
                        general_error(23,'D');  /* trailing garbage after option */
                    new_abs(def,val);
                    myfree(def);
                    continue;
                }
            }
        }
        if(!strncmp("-I",argv[i],2)) {
            char *path=NULL;
            if(argv[i][2])
                path=&argv[i][2];
            else if (i<argc-1)
                path=argv[++i];
            if(path) {
                new_include_path(path);
                continue;
            }
        }
        if(!strcmp("-unnamed-sections",argv[i])) {
            unnamed_sections=1;
            continue;
        }
        if(!strcmp("-ignore-mult-inc",argv[i])) {
            ignore_multinc=1;
            continue;
        }
        if(!strcmp("-nocase",argv[i])) {
            nocase=1;
            continue;
        }
        if(!strcmp("-noesc",argv[i])) {
            esc_sequences=0;
            continue;
        }
        if(!strcmp("-nosym",argv[i])) {
            no_symbols=1;
            continue;
        }
        if(!strncmp("-nowarn=",argv[i],8)) {
            int wno;
            sscanf(argv[i]+8,"%i",&wno);
            disable_warning(wno);
            continue;
        }
        else if(!strcmp("-w",argv[i])) {
            no_warn=1;
            continue;
        }
        if(!strncmp("-maxerrors=",argv[i],11)) {
            sscanf(argv[i]+11,"%i",&max_errors);
            continue;
        }
        else if(!strcmp("-pic",argv[i])) {
            pic_check=1;
            continue;
        }
        if(cpu_args(argv[i]))
            continue;
        if(syntax_args(argv[i]))
            continue;
        if(output_args(argv[i]))
            continue;
        if (!strncmp("-x",argv[i],2)) {
            auto_import=0;
            continue;
        }
        general_error(14,argv[i]);
    }
    if(inname) {
        setfilename(inname);
        setdebugname(inname);
        include_source(inname);
    } else
        general_error(15);
    if(!init_parse())
        general_error(10,"parse");
    if(!init_syntax())
        general_error(10,"syntax");
    if(!init_cpu())
        general_error(10,"cpu");
    parse();
    if(errors==0||produce_listing)
        resolve();
    if(errors==0||produce_listing)
        assemble();
    if(errors==0&&!auto_import)
        undef_syms();
    if(!listname)
        listname="a.lst";
    if(produce_listing)
        write_listing(listname);
    if(!outname)
        outname="a.out";
    if(errors==0) {
        if(verbose)
            statistics();
        outfile=fopen(outname,"wb");
        if(!outfile)
            general_error(13,outname);
        write_object(outfile,first_section,first_symbol);
    }
    leave();
    return 0; /* not reached */
}
Ejemplo n.º 25
0
Archivo: boot.c Proyecto: seL4/seL4
static BOOT_CODE bool_t try_init_kernel(
    paddr_t ui_p_reg_start,
    paddr_t ui_p_reg_end,
    sword_t pv_offset,
    vptr_t  v_entry,
    paddr_t dtb_addr_start,
    paddr_t dtb_addr_end
)
{
    cap_t root_cnode_cap;
    cap_t it_ap_cap;
    cap_t it_pd_cap;
    cap_t ipcbuf_cap;
    region_t ui_reg = paddr_to_pptr_reg((p_region_t) {
        ui_p_reg_start, ui_p_reg_end
    });
    region_t dtb_reg;
    word_t extra_bi_size = sizeof(seL4_BootInfoHeader) + (dtb_addr_end - dtb_addr_start);
    region_t extra_bi_region;
    pptr_t extra_bi_offset = 0;
    vptr_t extra_bi_frame_vptr;
    pptr_t bi_frame_pptr;
    vptr_t bi_frame_vptr;
    vptr_t ipcbuf_vptr;
    create_frames_of_region_ret_t create_frames_ret;
    create_frames_of_region_ret_t extra_bi_ret;

    /* convert from physical addresses to userland vptrs */
    v_region_t ui_v_reg;
    v_region_t it_v_reg;
    ui_v_reg.start = ui_p_reg_start - pv_offset;
    ui_v_reg.end   = ui_p_reg_end   - pv_offset;

    ipcbuf_vptr = ui_v_reg.end;
    bi_frame_vptr = ipcbuf_vptr + BIT(PAGE_BITS);
    extra_bi_frame_vptr = bi_frame_vptr + BIT(PAGE_BITS);

    /* If no DTB was provided, skip allocating extra bootinfo */
    if (dtb_addr_start == 0) {
        extra_bi_size = 0;
        dtb_reg = (region_t) {
            0, 0
        };
    } else {
        dtb_reg = paddr_to_pptr_reg((p_region_t) {
            dtb_addr_start, ROUND_UP(dtb_addr_end, PAGE_BITS)
        });
    }

    /* The region of the initial thread is the user image + ipcbuf and boot info */
    it_v_reg.start = ui_v_reg.start;
    it_v_reg.end = extra_bi_frame_vptr;

    if (it_v_reg.end > kernelBase) {
        printf("Userland image virtual end address too high\n");
        return false;
    }

    /* setup virtual memory for the kernel */
    map_kernel_window();

    /* initialise the CPU */
    if (!init_cpu()) {
        return false;
    }

    /* debug output via serial port is only available from here */
    printf("Bootstrapping kernel\n");

    /* initialise the platform */
    init_plat();

    /* make the free memory available to alloc_region() */
    arch_init_freemem(ui_reg, dtb_reg);

    /* create the root cnode */
    root_cnode_cap = create_root_cnode();
    if (cap_get_capType(root_cnode_cap) == cap_null_cap) {
        return false;
    }

    /* create the cap for managing thread domains */
    create_domain_cap(root_cnode_cap);

    /* initialise the IRQ states and provide the IRQ control cap */
    init_irqs(root_cnode_cap);

    /* create the bootinfo frame */
    bi_frame_pptr = allocate_bi_frame(0, CONFIG_MAX_NUM_NODES, ipcbuf_vptr);
    if (!bi_frame_pptr) {
        return false;
    }

    /* create extra bootinfo region - will return an empty allocation if extra_bi_size = 0 */
    extra_bi_region = allocate_extra_bi_region(extra_bi_size);
    if (extra_bi_region.start == 0) {
        return false;
    }

    /* update initial thread virtual address range for extra bootinfo */
    it_v_reg.end += extra_bi_region.end - extra_bi_region.start;
    if (it_v_reg.end > kernelBase) {
        printf("Userland extra bootinfo end address too high\n");
        return false;
    }

    /* put DTB in the bootinfo block, if present. */
    seL4_BootInfoHeader header;
    if (dtb_reg.start) {
        header.id = SEL4_BOOTINFO_HEADER_FDT;
        header.len = sizeof(header) + dtb_reg.end - dtb_reg.start;
        *(seL4_BootInfoHeader *)(extra_bi_region.start + extra_bi_offset) = header;
        extra_bi_offset += sizeof(header);
        memcpy((void *)(extra_bi_region.start + extra_bi_offset), (void *)dtb_reg.start,
               dtb_reg.end - dtb_reg.start);
        extra_bi_offset += dtb_reg.end - dtb_reg.start;
    }

    if ((extra_bi_region.end - extra_bi_region.start) - extra_bi_offset > 0) {
        /* provde a chunk for any leftover padding in the extended boot info */
        header.id = SEL4_BOOTINFO_HEADER_PADDING;
        header.len = (extra_bi_region.end - extra_bi_region.start) - extra_bi_offset;
        *(seL4_BootInfoHeader *)(extra_bi_region.start + extra_bi_offset) = header;
    }

    if (config_set(CONFIG_ARM_SMMU)) {
        ndks_boot.bi_frame->ioSpaceCaps = create_iospace_caps(root_cnode_cap);
        if (ndks_boot.bi_frame->ioSpaceCaps.start == 0 &&
            ndks_boot.bi_frame->ioSpaceCaps.end == 0) {
            return false;
        }
    } else {
        ndks_boot.bi_frame->ioSpaceCaps = S_REG_EMPTY;
    }

    /* Construct an initial address space with enough virtual addresses
     * to cover the user image + ipc buffer and bootinfo frames */
    it_pd_cap = create_it_address_space(root_cnode_cap, it_v_reg);
    if (cap_get_capType(it_pd_cap) == cap_null_cap) {
        return false;
    }

    /* Create and map bootinfo frame cap */
    create_bi_frame_cap(
        root_cnode_cap,
        it_pd_cap,
        bi_frame_pptr,
        bi_frame_vptr
    );

    /* create and map extra bootinfo region */
    if (extra_bi_size > 0) {
        extra_bi_ret =
            create_frames_of_region(
                root_cnode_cap,
                it_pd_cap,
                extra_bi_region,
                true,
                pptr_to_paddr((void *)extra_bi_region.start) - extra_bi_frame_vptr
            );
        if (!extra_bi_ret.success) {
            return false;
        }
        ndks_boot.bi_frame->extraBIPages = extra_bi_ret.region;
    }

    /* create the initial thread's IPC buffer */
    ipcbuf_cap = create_ipcbuf_frame(root_cnode_cap, it_pd_cap, ipcbuf_vptr);
    if (cap_get_capType(ipcbuf_cap) == cap_null_cap) {
        return false;
    }

    /* create all userland image frames */
    create_frames_ret =
        create_frames_of_region(
            root_cnode_cap,
            it_pd_cap,
            ui_reg,
            true,
            pv_offset
        );
    if (!create_frames_ret.success) {
        return false;
    }
    ndks_boot.bi_frame->userImageFrames = create_frames_ret.region;

    /* create/initialise the initial thread's ASID pool */
    it_ap_cap = create_it_asid_pool(root_cnode_cap);
    if (cap_get_capType(it_ap_cap) == cap_null_cap) {
        return false;
    }
    write_it_asid_pool(it_ap_cap, it_pd_cap);

    /* create the idle thread */
    if (!create_idle_thread()) {
        return false;
    }

    /* Before creating the initial thread (which also switches to it)
     * we clean the cache so that any page table information written
     * as a result of calling create_frames_of_region will be correctly
     * read by the hardware page table walker */
    cleanInvalidateL1Caches();

    /* create the initial thread */
    tcb_t *initial = create_initial_thread(
                         root_cnode_cap,
                         it_pd_cap,
                         v_entry,
                         bi_frame_vptr,
                         ipcbuf_vptr,
                         ipcbuf_cap
                     );

    if (initial == NULL) {
        return false;
    }

    init_core_state(initial);

    /* create all of the untypeds. Both devices and kernel window memory */
    if (!create_untypeds(
            root_cnode_cap,
    (region_t) {
    kernelBase, (pptr_t)ki_boot_end
    } /* reusable boot code/data */
        )) {
        return false;
    }

    /* no shared-frame caps (ARM has no multikernel support) */
    ndks_boot.bi_frame->sharedFrames = S_REG_EMPTY;

    /* finalise the bootinfo frame */
    bi_finalise();

    /* make everything written by the kernel visible to userland. Cleaning to PoC is not
     * strictly neccessary, but performance is not critical here so clean and invalidate
     * everything to PoC */
    cleanInvalidateL1Caches();
    invalidateLocalTLB();
    if (config_set(CONFIG_ARM_HYPERVISOR_SUPPORT)) {
        invalidateHypTLB();
    }


    ksNumCPUs = 1;

    /* initialize BKL before booting up other cores */
    SMP_COND_STATEMENT(clh_lock_init());
    SMP_COND_STATEMENT(release_secondary_cpus());

    /* grab BKL before leaving the kernel */
    NODE_LOCK_SYS;

    printf("Booting all finished, dropped to user space\n");

    /* kernel successfully initialized */
    return true;
}
Ejemplo n.º 26
0
int main(int argc, char** argv) {
    unsigned char flags = 0;
    init_cpu();
    hw_init_flags();
    hw_write_flags(0);
    link_init();
    
    POINTER c = (POINTER)(ADDR_BASE_XIL + 0x06);
    *c = 0x100;
    UINT16 len = 0;
    
    /* IP address */
    localmachine.localip = 0xC0A80146 + flags;  /* 192.168.0.*	*/
    /* Default gateway */
    localmachine.defgw   = 0xC0A80101;  /* 192.168.0.1	*/
    /* Subnet mask */
    localmachine.netmask = 0xFFFFFF00;
    /* Ethernet (MAC) address */
    localmachine.localHW[5] = 0x00;
    localmachine.localHW[4] = 0x33;
    localmachine.localHW[3] = 0xCC;
    localmachine.localHW[2] = 0xAB;
    localmachine.localHW[1] = 0xBA;
    localmachine.localHW[0] = 0x11 + flags;

    data_port = UDP_DATA_PORT + flags;
    
    timer_pool_init();
    NE2000Init(&localmachine.localHW[0]);
    arp_init();
    udp_init();
    tcp_init();

    /* Initialize applications	*/
    tcps_init();
    udps_init();

    while(1) {
        if (NETWORK_CHECK_IF_RECEIVED() == TRUE) {
            switch( received_frame.protocol) {
                case PROTOCOL_ARP:
                    process_arp(&received_frame);	
                    break;

                case PROTOCOL_IP:
                    len = process_ip_in(&received_frame);
                    if(len < 0) 
                    break;
                    
                switch(received_ip_packet.protocol){
                    case IP_ICMP:
                        process_icmp_in (&received_ip_packet, len);
                        break;

                    case IP_UDP:
                        process_udp_in (&received_ip_packet,len);
                        break;

                    case IP_TCP:
                        process_tcp_in (&received_ip_packet, len);				
                        break;
                }

                break;
            }

        /* discard received frame */    		
        NETWORK_RECEIVE_END();
    }

        /* Application main loops */
        /* Do not forget this!!! These don't get invoked magically :-) */
    	tcps_run();
        udps_run();
        /* manage arp cache tables */
        arp_manage();
        /* manage opened TCP connections (retransmissions, timeouts,...)*/
        tcp_poll();
    }
    return (EXIT_SUCCESS);
}
Ejemplo n.º 27
0
int main(int argc, char *argv[])
{
	register char *s, *p;
	register int i;
	char *pn = basename(argv[0]);
	struct timeval tv;
#ifdef HAS_CONFIG
	struct stat sbuf;
#endif
#ifdef BOOTROM
	char *rom = "-r ";
#else
	char *rom = "";
#endif
#ifdef CPU_SPEED
	f_flag = CPU_SPEED;
	tmax = CPU_SPEED * 10000;
#endif

	while (--argc > 0 && (*++argv)[0] == '-')
		for (s = argv[0] + 1; *s != '\0'; s++)

			switch (*s) {
			case 's':	/* save core and CPU on exit */
				s_flag = 1;
				break;

			case 'l':	/* load core and CPU from file */
				l_flag = 1;
				break;

			case 'u':	/* trap undocumented ops */
				u_flag = 1;
				break;

			case 'i':	/* trap I/O on unused ports */
				i_flag = 1;
				break;

			case 'm':	/* initialise Z80 memory */
				if (*(s+1) != '\0') {
					m_flag = exatoi(s+1);
					s += strlen(s+1);
				} else {
					if (argc <= 1)
						goto usage;
					argc--;
					argv++;
					m_flag = exatoi(argv[0]);
				}
				break;

			case 'f':	/* set emulation speed */
				if (*(s+1) != '\0') {
					f_flag = atoi(s+1);
					s += strlen(s+1);
				} else {
					if (argc <= 1)
						goto usage;
					argc--;
					argv++;
					f_flag = atoi(argv[0]);
				}
				tmax = f_flag * 10000;
				break;

			case 'x':	/* get filename with Z80 executable */
				x_flag = 1;
				s++;
				if (*s == '\0') {
					if (argc <= 1)
						goto usage;
					argc--;
					argv++;
					s = argv[0];
				}
				p = xfn;
				while (*s)
					*p++ = *s++;
				*p = '\0';
				s--;
				break;

#ifdef BOOTROM
			case 'r':	/* load default boot ROM */
				x_flag = 1;
				strcpy(xfn, BOOTROM);
				break;
#endif

#ifdef HAS_DISKS
			case 'd':	/* get path for disk images */
				s++;
				if (*s == '\0') {
					if (argc <= 1)
						goto usage;
					argc--;
					argv++;
					s = argv[0];
				}
				p = diskdir = diskd;
				while (*s)
					*p++ = *s++;
				*p = '\0';
				s--;
				break;
#endif

			case '8':
				cpu = I8080;
				break;

			case 'z':
				cpu = Z80;
				break;

			case '?':
			case 'h':
				goto usage;

			default:
				printf("illegal option %c\n", *s);

usage:

#ifdef HAS_DISKS
				printf("usage:\t%s -z -8 -s -l -i -u %s-m val -f freq -x filename -d diskpath\n", pn, rom);
#else
				printf("usage:\t%s -z -8 -s -l -i -u %s-m val -f freq -x filename\n", pn, rom);
#endif
				puts("\t-z = emulate Zilog Z80");
				puts("\t-8 = emulate Intel 8080");
				puts("\t-s = save core and CPU");
				puts("\t-l = load core and CPU");
				puts("\t-i = trap on I/O to unused ports");
				puts("\t-u = trap on undocumented instructions");
#ifdef BOOTROM
				puts("\t-r = load and execute default ROM");
				printf("\t     %s\n", BOOTROM);
#endif
				puts("\t-m = init memory with val (00-FF)");
				puts("\t-f = CPU clock frequency freq in MHz");
				puts("\t-x = load and execute filename");
#ifdef HAS_DISKS
				puts("\t-d = use disks images at diskpath");
				puts("\t     default path for disk images:");
				puts("\t     ./disks");
				printf("\t     %s\n", DISKSDIR);
#endif
				exit(1);
			}

	putchar('\n');

	if (cpu == Z80) {
puts("#######  #####    ###            #####    ###   #     #");
puts("     #  #     #  #   #          #     #    #    ##   ##");
puts("    #   #     # #     #         #          #    # # # #");
puts("   #     #####  #     #  #####   #####     #    #  #  #");
puts("  #     #     # #     #               #    #    #     #");
puts(" #      #     #  #   #          #     #    #    #     #");
puts("#######  #####    ###            #####    ###   #     #");

	} else {

puts(" #####    ###     #####    ###            #####    ###   #     #");
puts("#     #  #   #   #     #  #   #          #     #    #    ##   ##");
puts("#     # #     #  #     # #     #         #          #    # # # #");
puts(" #####  #     #   #####  #     #  #####   #####     #    #  #  #");
puts("#     # #     #  #     # #     #               #    #    #     #");
puts("#     #  #   #   #     #  #   #          #     #    #    #     #");
puts(" #####    ###     #####    ###            #####    ###   #     #");
	}

	printf("\nRelease %s, %s\n", RELEASE, COPYR);

#ifdef	USR_COM
	printf("%s Release %s, %s\n\n", USR_COM, USR_REL, USR_CPR);
#else
	putchar('\n');
#endif
	if (f_flag > 0)
		printf("CPU speed is %d MHz\n", f_flag);
	else
		printf("CPU speed is unlimited\n");

	fflush(stdout);

	/* if the machine has configuration files try to find them */
#ifdef HAS_CONFIG
	/* first try ./conf */
	if ((stat("./conf", &sbuf) == 0) && S_ISDIR(sbuf.st_mode)) {
		strcpy(&confdir[0], "./conf");
	/* then CONFDIR as set in Makefile */
	} else {
		strcpy(&confdir[0], CONFDIR);
	}

	//printf("config = %s\n", &confdir[0]);
#endif

	/* seed random generator */
	gettimeofday(&tv, NULL);
	srand(tv.tv_sec);

	config();		/* read system configuration */
	init_memory();		/* initialise memory configuration */
	init_cpu();		/* initialise CPU */
	wrk_ram	= mem_base();	/* set work pointer for memory */

	/* fill memory content with some initial value */
	if (m_flag >= 0) {
		memset((char *) wrk_ram, m_flag, 65536);
	} else {
		for (i = 0; i < 65536; i++)
			*(wrk_ram + i) = (BYTE) (rand() % 256);
	}

	init_rom();		/* initialise ROM's */

	if (l_flag)		/* load core */
		if (load_core())
			return(1);

	int_on();		/* initialize UNIX interrupts */
	init_io();		/* initialize I/O devices */

	mon();			/* run system */

	if (s_flag)		/* save core */
		save_core();

	exit_io();		/* stop I/O devices */
	int_off();		/* stop UNIX interrupts */

	return(0);
}
Ejemplo n.º 28
0
bool retro_load_game(const struct retro_game_info *info)
{
    char bios_file_path[256];
    const char *full_path, *system_directory_c;

    enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
    if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt))
    {
        if (log_cb)
            log_cb(RETRO_LOG_INFO, "[O2EM]: RGB565 is not supported.\n");
        return false;
    }

    struct retro_input_descriptor desc[] = {
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "Left" },
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "Up" },
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "Down" },
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Fire" },

       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "Left" },
       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "Up" },
       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "Down" },
       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Action" },

       { 0 },
    };

   environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc);

    full_path = info->path;
    system_directory_c = NULL;

    // BIOS is required
    environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &system_directory_c);
    if (!system_directory_c)
    {
       if (log_cb)
          log_cb(RETRO_LOG_WARN, "[O2EM]: no system directory defined, unable to look for o2rom.bin\n");
       return false;
    }
    else
    {

#ifdef _WIN32
      char slash = '\\';
#else
      char slash = '/';
#endif

       snprintf(bios_file_path, sizeof(bios_file_path), "%s%c%s", system_directory_c, slash, "o2rom.bin");

       if (!does_file_exist(bios_file_path))
       {
          if (log_cb)
             log_cb(RETRO_LOG_WARN, "[O2EM]: o2rom.bin not found, cannot load BIOS\n");
          return false;
       }
    }

    app_data.debug = 0;
    app_data.stick[0] = app_data.stick[1] = 1;
    app_data.sticknumber[0] = app_data.sticknumber[1] = 0;
    set_defjoykeys(0,0);
    set_defjoykeys(1,1);
    set_defsystemkeys();
    app_data.bank = 0;
    app_data.limit = 1;
    app_data.sound_en = 1;
    app_data.speed = 100;
    app_data.wsize = 2;
    app_data.fullscreen = 0;
    app_data.scanlines = 0;
    app_data.voice = 1;
    app_data.window_title = "O2EM v" O2EM_VERSION;
    app_data.svolume = 100;
    app_data.vvolume = 100;
    app_data.filter = 0;
    app_data.exrom = 0;
    app_data.three_k = 0;
    app_data.crc = 0;
    app_data.scshot = scshot;
    app_data.statefile = statefile;
    app_data.euro = 0;
    app_data.openb = 0;
    app_data.vpp = 0;
    app_data.bios = 0;
    app_data.scoretype = 0;
    app_data.scoreaddress = 0;
    app_data.default_highscore = 0;
    app_data.breakpoint = 65535;
    app_data.megaxrom = 0;
    //strcpy(file,"");
    //strcpy(file_l,"");
    //strcpy(bios_l,"");
    //strcpy(bios,"");
    //strcpy(scshot,"");
    //strcpy(statefile,"");
    //strcpy(xrom,"");
    strcpy(scorefile,"highscore.txt");
    //read_default_config();

    init_audio();

    app_data.crc = crc32_file(full_path);

    //suck_bios();
    o2flag = 1;

    crcx = app_data.crc;
    //suck_roms();

    load_bios(bios_file_path);

    load_cart(full_path);
    //if (app_data.voice) load_voice_samples(path2);

    init_display();

    init_cpu();

    init_system();

    set_score(app_data.scoretype, app_data.scoreaddress, app_data.default_highscore);

    return true;
}
Ejemplo n.º 29
0
int
main (int argc, char **argv)
{
  int o;
  int save_trace;
  bfd *prog;
  int rc;

  xmalloc_set_program_name (argv[0]);

  while ((o = getopt (argc, argv, "tvdr:D:")) != -1)
    {
      switch (o)
	{
	case 't':
	  trace ++;
	  break;
	case 'v':
	  verbose ++;
	  break;
	case 'd':
	  disassemble ++;
	  break;
	case 'r':
	  mem_ram_size (atoi (optarg));
	  break;
	case 'D':
	  dump_counts_filename = optarg;
	  break;
	case '?':
	  {
	    fprintf (stderr,
		     "usage: run [options] program [arguments]\n");
	    fprintf (stderr,
		     "\t-v\t\t- increase verbosity.\n"
		     "\t-t\t\t- trace.\n"
		     "\t-d\t\t- disassemble.\n"
		     "\t-r <bytes>\t- ram size.\n"
		     "\t-D <filename>\t- dump cycle count histogram\n");
	    exit (1);
	  }
	}
    }

  prog = bfd_openr (argv[optind], 0);
  if (!prog)
    {
      fprintf (stderr, "Can't read %s\n", argv[optind]);
      exit (1);
    }

  if (!bfd_check_format (prog, bfd_object))
    {
      fprintf (stderr, "%s not a rl78 program\n", argv[optind]);
      exit (1);
    }

  init_cpu ();

  rl78_in_gdb = 0;
  save_trace = trace;
  trace = 0;
  rl78_load (prog, 0, argv[0]);
  trace = save_trace;

  sim_disasm_init (prog);

  rc = setjmp (decode_jmp_buf);

  if (rc == 0)
    {
      if (!trace && !disassemble)
	{
	  /* This will longjmp to the above if an exception
	     happens.  */
	  for (;;)
	    decode_opcode ();
	}
      else
	while (1)
	  {

	    if (trace)
	      printf ("\n");

	    if (disassemble)
	      sim_disasm_one ();

	    rc = decode_opcode ();

	    if (trace)
	      trace_register_changes ();
	  }
    }

  if (RL78_HIT_BREAK (rc))
    done (1);
  else if (RL78_EXITED (rc))
    done (RL78_EXIT_STATUS (rc));
  else if (RL78_STOPPED (rc))
    {
      if (verbose)
	printf ("Stopped on signal %d\n", RL78_STOP_SIG (rc));
      exit (1);
    }
  done (0);
  exit (0);
}