Esempio n. 1
0
main(){
	
	sim_init();
	
	
	while (narr < TOTAL_EVENTS){
		switch (act()){
			case ARRIVAL:
				arrival();
				break;
			case DEPARTURE:
				departure();
				break;
			default:
				printf("error in act procedure\n");
				exit(1);
				break;
		} /* end switch */
	}      /* end while */

	printf("Probablity a packet is blocked: \nbatch arrival: %8.4f \nsingle packet arrival: %8.4f\n",
		   ((float) batch_nloss) / batch_packets, ((float) nloss) / (total_packets - batch_packets));
	
	return(0);
	
} /* end main */
Esempio n. 2
0
int main(int argc, char **argv, char **env)
{
	float speed;

#ifndef WITH_SERIAL_PTY
	set_conio_terminal_mode();
#endif

	Verilated::commandArgs(argc, argv);
	dut = new Vdut;

	Verilated::traceEverOn(true);
	tfp = new VerilatedVcdC;
	dut->trace(tfp, 99);
	tfp->open("dut.vcd");

	struct sim s;
	sim_init(&s);

#ifdef WITH_SERIAL_PTY
	console_init(&s);
	console_open(&s);
#endif

#ifdef WITH_ETH
	eth_init(&s, "/dev/net/tap0", "tap0"); // XXX get this from /tmp/simethernet
	eth_open(&s);
#endif

	s.run = true;
	while(s.run) {
		sim_tick(&s);
		if(SYS_CLK) {
#ifdef WITH_SERIAL
			if(console_service(&s) != 0)
				s.run = false;
#endif
#ifdef WITH_ETH
			ethernet_service(&s);
#endif
		}
	}
	s.end = clock();

	speed = (s.tick/2)/((s.end-s.start)/CLOCKS_PER_SEC);

	printf("average speed: %3.3f MHz\n\r", speed/1000000);

	tfp->close();


#ifdef WITH_SERIAL_PTY
	console_close(&s);
#endif
#ifdef WITH_ETH
	eth_close(&s);
#endif

	exit(0);
}
Esempio n. 3
0
static void *periodic_thread(void *arg)
{
    sigset_t alarm_sig;
    noble_simulation * sim;
    make_periodic(1000 * TIMING_CONST_MS, &alarm_sig);
    while (1) {
        
        sim = sim_sim();


        sim_cycle();
        count++;
        if ((count & 2047) == 0)
        {
            printf("count is %ld\n", count);
        }
        if (sim->num == 0)
        {
            printf("new run at %ld\n", count);
            
            sim_init(1,rand(),MAP_AREA,0);
        }
        
        wait_period(&alarm_sig);
    }
    return NULL;
}
Esempio n. 4
0
int main() {
    seed = time(NULL);
    float prob[TOTAL_SIZE];
    int iter;
    float avg = 1;
    float current;
    int counter;
    int if_continue = 1;
    buffer_size = 41;

    avg = 0;
    for(iter=0; iter<TOTAL_SIZE; ++iter) {
        sim_init();
        current = run();
        avg += current;

        buffer_size /= 1024;
        prob[iter] = current;
    }
    printf("%d %.6f %0.6f\n", buffer_size, avg/100,
           1.96*sdv(prob, avg/100, TOTAL_SIZE)/sqrt(TOTAL_SIZE));



    return 0;
}
Esempio n. 5
0
void *snmp_bc_open(GHashTable *handler_config)
{
        struct oh_handler_state *handle;
        struct snmp_bc_hnd *custom_handle;
        char *root_tuple;

        root_tuple = (char *)g_hash_table_lookup(handler_config, "entity_root");
        if(!root_tuple) {
                dbg("ERROR: Cannot open snmp_bc plugin. No entity root found in configuration.");
                return NULL;
        }
        
        handle = (struct oh_handler_state *)g_malloc0(sizeof(struct oh_handler_state));
        custom_handle =
                (struct snmp_bc_hnd *)g_malloc0(sizeof(struct snmp_bc_hnd));
        if(!handle || !custom_handle) {
                dbg("Could not allocate memory for handle or custom_handle.");
                return NULL;
        }
        handle->data = custom_handle;
        
        handle->config = handler_config;

        /* Initialize RPT cache */
        handle->rptcache = (RPTable *)g_malloc0(sizeof(RPTable));
        
        custom_handle->ss = NULL;
        
        /* this initializes the simulator tables */
        sim_init();

        return handle;
}
Esempio n. 6
0
void sim_reset()
{
    if (!initialized)
	sim_init();
    clear_pipes();
    clear_mem(reg);
    minAddr = 0;
    memCnt = 0;
    starting_up = 1;
    cycles = instructions = 0;

#ifdef HAS_GUI
    if (gui_mode) {
	signal_register_clear();
	create_memory_display(minAddr, memCnt);
    }
#endif

    amux = bmux = MUX_NONE;
    cc = cc_in = DEFAULT_CC;
    wb_destE = REG_NONE;
    wb_valE = 0;
    wb_destM = REG_NONE;
    wb_valM = 0;
    mem_addr = 0;
    mem_data = 0;
    mem_write = FALSE;
    sim_report();
}
Esempio n. 7
0
int
main(int argv, char **argc)
{
  int i;
  sim_object_t * object;
  /*Create a sim_data object*/
  sim_data_t* test_sim = sim_new();
  sim_init(test_sim,1, 10, 192, 120);

  /*Create a display_state*/
  display_state_t * state = calloc(1,sizeof(display_state_t));
  /* memset(state, 0, sizeof(*state)); */
  bcm_egl_openvg_init(state);
  display_init(state, 0);
  state->showfps = true;
  /*
  for(i = 0; i < 1000; i++)
  */
  while(1)
  {
    sim_tick(test_sim);
    /*Pass to display and alter*/
    display_draw(state, test_sim);

    /*
    for(i = 0; i < test_sim->size; i++)
    {
      object = test_sim->objects[i];
      object->x += 1;
      object->y += 1;
    }
    */
  }
  return EXIT_SUCCESS;
}
Esempio n. 8
0
int main(int argc, const char * argv[])
{
    n_int   counter = 0;

    printf(" --- test sim --- start -----------------------------------------------\n");
    
    sim_init(2, 0x12738291, MAP_AREA, 0);
    
    {
        noble_simulation * local_sim = sim_sim();
        noble_being      * first_being = &(local_sim->beings[0]);
        noble_being      * second_being = &(local_sim->beings[1]);
        noble_being_constant * first_being_constant = &(first_being->constant);
        noble_being_delta * first_being_delta = &(first_being->delta);
        noble_being_events * first_being_events = &(first_being->events);
        noble_being_brain * first_being_brain = &(first_being->braindata);
        noble_immune_system * first_being_immune = &(first_being->immune_system);
        noble_being_volatile * first_being_volatile = &(first_being->changes);
        
        n_uint being_hash1 = math_hash((n_byte *)first_being, sizeof(noble_being));
        n_uint being_constant_hash1 = math_hash((n_byte *)first_being_constant, sizeof(noble_being_constant));
        n_uint being_delta_hash1 = math_hash((n_byte *)first_being_delta, sizeof(noble_being_delta));
        n_uint being_events_hash1 = math_hash((n_byte *)first_being_events, sizeof(noble_being_events));
        n_uint being_brain_hash1 = math_hash((n_byte *)first_being_brain, sizeof(noble_being_brain));
        n_uint being_immune_hash1 = math_hash((n_byte*)first_being_immune, sizeof(noble_immune_system));
        n_uint being_volatile_hash1 = math_hash((n_byte*)first_being_volatile, sizeof(noble_being_volatile));

        while (counter < 1000)
        {
            sim_cycle();
            counter ++;
        }
 
        n_uint being_hash2 = math_hash((n_byte *)first_being, sizeof(noble_being));
        n_uint being_constant_hash2 = math_hash((n_byte *)first_being_constant, sizeof(noble_being_constant));
        n_uint being_delta_hash2 = math_hash((n_byte *)first_being_delta, sizeof(noble_being_delta));
        n_uint being_events_hash2 = math_hash((n_byte *)first_being_events, sizeof(noble_being_events));
        n_uint being_brain_hash2 = math_hash((n_byte *)first_being_brain, sizeof(noble_being_brain));
        n_uint being_immune_hash2 = math_hash((n_byte*)first_being_immune, sizeof(noble_immune_system));
        n_uint being_volatile_hash2 = math_hash((n_byte*)first_being_volatile, sizeof(noble_being_volatile));

        printf("hash %lx\n", being_hash1 ^ being_hash2);
        printf("constant %lx\n", being_constant_hash1 ^ being_constant_hash2);

        printf("delta %lx\n", being_delta_hash1 ^ being_delta_hash2);
        printf("events %lx\n", being_events_hash1 ^ being_events_hash2);

        printf("brain %lx\n", being_brain_hash1 ^ being_brain_hash2);
        printf("immune %lx\n", being_immune_hash1 ^ being_immune_hash2);

        printf("volatile %lx\n", being_volatile_hash1 ^ being_volatile_hash2);

    }
    sim_close();
    
    printf(" --- test sim ---  end  -----------------------------------------------\n");
    
    return 1;
}
Esempio n. 9
0
/**
 * Main body of the program.
 *
 * @param argc Number of arguments from the command line.
 * @param argv Array of strings containing the command line arguments.
 * @return The exit status of the program (EXIT_SUCCESS or EXIT_FAILURE).
 */
int main(int argc, char **argv) {
  sim_setoptions(argc, argv);
  sim_init();
  sim_readdata();
  display_statistics();
  sim_free();
  return EXIT_SUCCESS;
}
Esempio n. 10
0
File: ssim.c Progetto: Azard/icslabs
void sim_reset()
{
    if (!initialized)
	sim_init();
    clear_mem(reg);
    minAddr = 0;
    memCnt = 0;

#ifdef HAS_GUI
    if (gui_mode) {
	signal_register_clear();
	create_memory_display(minAddr, memCnt);
	sim_report();
    }
#endif

    if (plusmode) {
	prev_icode = prev_icode_in = I_NOP;
	prev_ifun = prev_ifun_in = 0;
	prev_valc = prev_valc_in = 0;
	prev_valm = prev_valm_in = 0;
	prev_valp = prev_valp_in = 0;
	prev_bcond = prev_bcond_in = FALSE;
	pc = 0;
    } else {
	pc_in = 0;
    }
    cc = DEFAULT_CC;
    cc_in = DEFAULT_CC;
    destE = REG_NONE;
    destM = REG_NONE;
    mem_write = FALSE;
    mem_addr = 0;
    mem_data = 0;

    /* Reset intermediate values to clear display */
    icode = I_NOP;
    ifun = 0;
    instr = HPACK(I_NOP, F_NONE);
    ra = REG_NONE;
    rb = REG_NONE;
    valc = 0;
    valp = 0;

    srcA = REG_NONE;
    srcB = REG_NONE;
    destE = REG_NONE;
    destM = REG_NONE;
    vala = 0;
    valb = 0;
    vale = 0;

    cond = FALSE;
    bcond = FALSE;
    valm = 0;

    sim_report();
}
Esempio n. 11
0
static void
initialize()
{
	constants_init();
	set_default_parameters();
	parse_input();
	parameter_setup();
	sim_init();
	simple_tank_fill();
}
Esempio n. 12
0
int
init_sim(int argc, char*argv[])
{
  // Initialise SDL, GL and AL
  init_al();

  sim_init();


  return 0;
}
Esempio n. 13
0
int command_line_run(void)
{
    printf("\n *** %sConsole, %s ***\n", SHORT_VERSION_NAME, FULL_DATE);
    printf("      For a list of commands type 'help'\n\n");
    
    sprintf(simulation_filename,"%s","realtime.txt");
    
#ifdef AUDIT_FILE
    audit();
#endif
    
    local_sim = sim_sim();
    io_command_line_execution_set();
    
    srand((unsigned int) time(NULL) );
    sim_init(KIND_START_UP, rand(), MAP_AREA, 0);
    
    cle_load(local_sim, (n_string)simulation_filename, io_console_out);
    
#ifndef    _WIN32
    do
    {
        sim_thread_console();
    }
    while (sim_thread_console_quit() == 0);
#else
    {
        n_int return_value = 0;
        do
        {
            return_value = io_console(local_sim,
                                      (noble_console_command *)control_commands,
                                      io_console_entry,
                                      io_console_out);
        }
        while (return_value == 0);
    }
#endif
    
    sim_close();
    
    return(1);
}
Esempio n. 14
0
bool read_history(char *filename)
{
    FILE *f = fopen(filename, "rb");
    if (!f)
    {
        Printf("Failed to open file\n");
        return false;
    }
    static FileData data;
    fread((char*)&data, sizeof(data), 1, f);
    HISTORY_LENGTH = data.length;
    STATE = sim_init(data.seed);
    for (int i = 0; i < HISTORY_LENGTH; i++)
    {
        HISTORY_CMD[i] = data.cmds[i];
        STATE = sim_tick(STATE, HISTORY_CMD[i]);
        HISTORY_STATE[i] = STATE;
    }
    fclose(f);
    return true;
}
Esempio n. 15
0
int cycle_run(void)
{
    pthread_t t_1;
    sigset_t alarm_sig;
    
    printf("\n *** %sConsole, %s ***\n", SHORT_VERSION_NAME, FULL_DATE);

    /* Block SIGALRM (not really necessary with uClibc) */
    sigemptyset(&alarm_sig);
    sigaddset(&alarm_sig, SIGALRM);
    sigprocmask(SIG_BLOCK, &alarm_sig, NULL);
    
    srand((unsigned int) time(NULL));
    sim_init(2,rand(),MAP_AREA,0);
    
    pthread_create(&t_1, NULL, periodic_thread, NULL);
    while (1)
    {
        sleep(100);
    }
    return 0;
}
Esempio n. 16
0
/**@brief Application main function.
 */
int main(void)
{
    uint32_t err_code;
    bool erase_bonds;

    err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);

    // Initialize
    timers_init();
    buttons_leds_init(&erase_bonds);

    ble_stack_init();
    peer_manager_init(erase_bonds);
    if (erase_bonds == true)
    {
        NRF_LOG_INFO("Bonds erased!\r\n");
    }
    gap_params_init();
    advertising_init();
    services_init();
    sim_init();
    conn_params_init();

    // Start execution
    application_timers_start();
    NRF_LOG_INFO("Location and Navigation App started\r\n");
    err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
    APP_ERROR_CHECK(err_code);

    // Enter main loop
    for (;;)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            power_manage();
        }
    }
}
Esempio n. 17
0
void sim_reset()
{
    if (!initialized)
        sim_init();
    clear_pipes();
    clear_reg(reg);
    minAddr = 0;
    memCnt = 0;
    starting_up = 1;
    cycles = instructions = 0;
    cc = DEFAULT_CC;
    status = STAT_AOK;

    amux = bmux = MUX_NONE;
    cc = cc_in = DEFAULT_CC;
    wb_destE = REG_NONE;
    wb_valE = 0;
    wb_destM = REG_NONE;
    wb_valM = 0;
    mem_addr = 0;
    mem_data = 0;
    mem_write = FALSE;
    sim_report();
}
Esempio n. 18
0
int
main(int argc, char **argv, char **envp)
{
  char *s;
  int i, exit_code;

#ifndef _MSC_VER
  /* catch SIGUSR1 and dump intermediate stats */
  signal(SIGUSR1, signal_sim_stats);

  /* catch SIGUSR2 and dump final stats and exit */
  signal(SIGUSR2, signal_exit_now);
#endif /* _MSC_VER */

  /* register an error handler */
  fatal_hook(sim_print_stats);

  /* set up a non-local exit point */
  if ((exit_code = setjmp(sim_exit_buf)) != 0)
    {
      /* special handling as longjmp cannot pass 0 */
      exit_now(exit_code-1);
    }

  /* register global options */
  sim_odb = opt_new(orphan_fn);
  opt_reg_flag(sim_odb, "-h", "print help message",
	       &help_me, /* default */FALSE, /* !print */FALSE, NULL);
  opt_reg_flag(sim_odb, "-v", "verbose operation",
	       &verbose, /* default */FALSE, /* !print */FALSE, NULL);
#ifdef DEBUG
  opt_reg_flag(sim_odb, "-d", "enable debug message",
	       &debugging, /* default */FALSE, /* !print */FALSE, NULL);
#endif /* DEBUG */
  opt_reg_flag(sim_odb, "-i", "start in Dlite debugger",
	       &dlite_active, /* default */FALSE, /* !print */FALSE, NULL);
  opt_reg_int(sim_odb, "-seed",
	      "random number generator seed (0 for timer seed)",
	      &rand_seed, /* default */1, /* print */TRUE, NULL);
  opt_reg_flag(sim_odb, "-q", "initialize and terminate immediately",
	       &init_quit, /* default */FALSE, /* !print */FALSE, NULL);
  opt_reg_string(sim_odb, "-chkpt", "restore EIO trace execution from <fname>",
		 &sim_chkpt_fname, /* default */NULL, /* !print */FALSE, NULL);

  /* stdio redirection options */
  opt_reg_string(sim_odb, "-redir:sim",
		 "redirect simulator output to file (non-interactive only)",
		 &sim_simout,
		 /* default */NULL, /* !print */FALSE, NULL);
  opt_reg_string(sim_odb, "-redir:prog",
		 "redirect simulated program output to file",
		 &sim_progout, /* default */NULL, /* !print */FALSE, NULL);

#ifndef _MSC_VER
  /* scheduling priority option */
  opt_reg_int(sim_odb, "-nice",
	      "simulator scheduling priority", &nice_priority,
	      /* default */NICE_DEFAULT_VALUE, /* print */TRUE, NULL);
#endif

  /* FIXME: add stats intervals and max insts... */

  /* register all simulator-specific options */
  sim_reg_options(sim_odb);

  /* parse simulator options */
  exec_index = -1;
  opt_process_options(sim_odb, argc, argv);

  /* redirect I/O? */
  if (sim_simout != NULL)
    {
      /* send simulator non-interactive output (STDERR) to file SIM_SIMOUT */
      fflush(stderr);
      if (!freopen(sim_simout, "w", stderr))
	fatal("unable to redirect simulator output to file `%s'", sim_simout);
    }

  if (sim_progout != NULL)
    {
      /* redirect simulated program output to file SIM_PROGOUT */
      sim_progfd = fopen(sim_progout, "w");
      if (!sim_progfd)
	fatal("unable to redirect program output to file `%s'", sim_progout);
    }

  /* need at least two argv values to run */
  if (argc < 2)
    {
      banner(stderr, argc, argv);
      usage(stderr, argc, argv);
      exit(1);
    }

  /* opening banner */
  banner(stderr, argc, argv);

  if (help_me)
    {
      /* print help message and exit */
      usage(stderr, argc, argv);
      exit(1);
    }

  /* seed the random number generator */
  if (rand_seed == 0)
    {
      /* seed with the timer value, true random */
      mysrand(time((time_t *)NULL));
    }
  else
    {
      /* seed with default or user-specified random number generator seed */
      mysrand(rand_seed);
    }

  /* exec_index is set in orphan_fn() */
  if (exec_index == -1)
    {
      /* executable was not found */
      fprintf(stderr, "error: no executable specified\n");
      usage(stderr, argc, argv);
      exit(1);
    }
  /* else, exec_index points to simulated program arguments */

  /************modification for XAMP*************/
  cseq_outfile=argv[exec_index];
  /***************end****************************/
  
  /* check simulator-specific options */
  sim_check_options(sim_odb, argc, argv);

#ifndef _MSC_VER
  /* set simulator scheduling priority */
  if (nice(0) < nice_priority)
    {
      if (nice(nice_priority - nice(0)) < 0)
        fatal("could not renice simulator process");
    }
#endif

  /* default architected value... */
  sim_num_insn = 0;

#ifdef BFD_LOADER
  /* initialize the bfd library */
  bfd_init();
#endif /* BFD_LOADER */

  /* initialize the instruction decoder */
  md_init_decoder();

  /* initialize all simulation modules */
  sim_init();

  /* initialize architected state */
  sim_load_prog(argv[exec_index], argc-exec_index, argv+exec_index, envp);

  /* register all simulator stats */
  sim_sdb = stat_new();
  sim_reg_stats(sim_sdb);
#if 0 /* not portable... :-( */
  stat_reg_uint(sim_sdb, "sim_mem_usage",
		"total simulator (data) memory usage",
		&sim_mem_usage, sim_mem_usage, "%11dk");
#endif

  /* record start of execution time, used in rate stats */
  sim_start_time = time((time_t *)NULL);

  /* emit the command line for later reuse */
  fprintf(stderr, "sim: command line: ");
  for (i=0; i < argc; i++)
    fprintf(stderr, "%s ", argv[i]);
  fprintf(stderr, "\n");

  /* output simulation conditions */
  s = ctime(&sim_start_time);
  if (s[strlen(s)-1] == '\n')
    s[strlen(s)-1] = '\0';
  fprintf(stderr, "\nsim: simulation started @ %s, options follow:\n", s);
  opt_print_options(sim_odb, stderr, /* short */TRUE, /* notes */TRUE);
  sim_aux_config(stderr);
  fprintf(stderr, "\n");

  /* omit option dump time from rate stats */
  sim_start_time = time((time_t *)NULL);

  if (init_quit)
    exit_now(0);

  running = TRUE;
  sim_main();

  /* simulation finished early */
  exit_now(0);

  return 0;
}
Esempio n. 19
0
int main(int argc, char** argv) {
	// read all used flags
	while (1) {
		static struct option long_options[] = {
			{"invert-match", no_argument, 0, 'v'},
			{"line-regexp",  no_argument, 0, 'x'},
			{"count",        no_argument, 0, 'c'},
			{"help",         no_argument, &display_help, 1},
			{"version",      no_argument, 0, 'V'},
			{"cache-limit",  required_argument, 0, OPTION_CACHE_LIMIT},
			{0, 0, 0, 0}
		};
		int option_index = 0;
		int c = getopt_long(argc, argv, "vxcV", long_options, &option_index);
		if (c == -1) break;
		switch (c) {
			case 'v': invert_match = true; break;
			case 'x': whole_lines = true; break;
			case 'c': count_matches = true; break;
			case OPTION_CACHE_LIMIT:
				cache_mem_limit = parse_size_in_kb(optarg);
				if (cache_mem_limit == -1U) {
					print_usage(argv[0]);
					return 2;
				}
				break;
			case 'V':
				display_version = true;
				break;
			case 0: break;
			default:
				print_usage(argv[0]);
				return 2;
		}
	}

	if (display_help) {
		printf(help_message, argv[0]);
		return 0;
	}

	if (display_version) {
		printf(version_message);
		return 0;
	}

	// check if there is exactly one regular expression
	if (optind != argc-1) {
		print_usage(argv[0]);
		return 2;
	}

	char* regex = argv[optind];

	// parse the regular expression to abstract syntax tree
	struct syntree* tree;
	tree = parse(regex, strlen(regex));

	// build nfa for the regular expression
	struct nfa* nfa;
	nfa = build_nfa(tree, whole_lines);
	free_tree(tree);

	// initialize simulation state
	sim_init(&state, nfa, invert_match, cache_mem_limit);

	// initialize buffer
	uintptr_t buffer_size = 65536;
	buffer_init(&buffer, STDIN_FILENO, STDOUT_FILENO, buffer_size);

	// main matching loop
	uintmax_t match_count = 0;
	bool new_line = true;
	bool some_match = false;
	intptr_t res = buffer_next(&buffer);
	if (!count_matches) buffer_mark(&buffer);
	while (res == 1) {
		// save next input byte to ch
		uint_fast8_t ch = buffer_get(&buffer);

		if (ch == '\n') {
			// handle the end of line here
			new_line = true;
			// simulate the special line end character
			if (!state.dfa_state->accept) sim_step(&state, CHAR_INPUT_END);
			if (sim_is_match(&state)) {
				// the last line matched, either print it or count it
				some_match = true;
				if (count_matches) {
					++match_count;
				} else {
					int_fast8_t res = buffer_print(&buffer, true);
					if (res != 1) die(2, (res == -1) ? errno : 0,
							"Error writing to stdout");
				}
			}
			// reset simulation state
			state.dfa_state = state.after_begin;
			// read next character from input
			res = buffer_next(&buffer);
			if (!count_matches) buffer_mark(&buffer);
		} else {
			new_line = false;
			// simulate only if there was no match on the current line
			if (!state.dfa_state->accept) {
				// if the character is not valid ASCII, no transitions will take place
				if (ch > MAX_CHAR) state.dfa_state = state.before_begin;
				// otherwise do the simulation
				else sim_step(&state, ch);
			}
			// read next character from input
			res = buffer_next(&buffer);
		}
	}
	if (res == -1) die(2, errno, "Error reading from stdin");

	// check if there is no \n at the end of the input
	// if it is the case, behave as if it was there
	if (!new_line) {
		if (!state.dfa_state->accept) sim_step(&state, CHAR_INPUT_END);
		if (sim_is_match(&state)) {
			some_match = true;
			if (count_matches) {
				++match_count;
			} else {
				int_fast8_t res = buffer_print(&buffer, false);
				puts("");
				if (res != 1) die(2, (res == -1) ? errno : 0,
						"Error writing to stdout");
			}
		}
	}

	// if -c is used, print the count of matches
	if (count_matches) {
		printf("%" PRIuMAX "\n", match_count);
	}

	// clean up
	buffer_cleanup(&buffer);
	sim_cleanup(&state);
	free_nfa(nfa);

	// return status is based on whether there was a match or not
	return some_match ? 0 : 1;
}
Esempio n. 20
0
/* 
 * run_tty_sim - Run the simulator in TTY mode
 */
static void run_tty_sim() 
{
    int icount = 0;
    exc_t status = EXC_NONE;
    cc_t result_cc = 0;
    int byte_cnt = 0;
    mem_t mem0, reg0;
    state_ptr isa_state = NULL;


    /* In TTY mode, the default object file comes from stdin */
    if (!object_file) {
	object_file = stdin;
    }

    /* Initializations */
    if (verbosity >= 2)
	sim_set_dumpfile(stdout);
    sim_init();

    /* Emit simulator name */
    printf("%s\n", simname);

    byte_cnt = load_mem(mem, object_file, 1);
    if (byte_cnt == 0) {
	fprintf(stderr, "No lines of code found\n");
	exit(1);
    } else if (verbosity >= 2) {
	printf("%d bytes of code read\n", byte_cnt);
    }
    fclose(object_file);
    if (do_check) {
	isa_state = new_state(0);
	free_mem(isa_state->r);
	free_mem(isa_state->m);
	isa_state->m = copy_mem(mem);
	isa_state->r = copy_mem(reg);
	isa_state->cc = cc;
    }

    mem0 = copy_mem(mem);
    reg0 = copy_mem(reg);
    

    icount = sim_run(instr_limit, &status, &result_cc);
    if (verbosity > 0) {
	printf("%d instructions executed\n", icount);
	printf("Exception status = %s\n", exc_name(status));
	printf("Condition Codes: %s\n", cc_name(result_cc));
	printf("Changed Register State:\n");
	diff_reg(reg0, reg, stdout);
	printf("Changed Memory State:\n");
	diff_mem(mem0, mem, stdout);
    }
    if (do_check) {
	exc_t e = EXC_NONE;
	int step;
	bool_t match = TRUE;

	for (step = 0; step < instr_limit && e == EXC_NONE; step++) {
	    e = step_state(isa_state, stdout);
	}

	if (diff_reg(isa_state->r, reg, NULL)) {
	    match = FALSE;
	    if (verbosity > 0) {
		printf("ISA Register != Pipeline Register File\n");
		diff_reg(isa_state->r, reg, stdout);
	    }
	}
	if (diff_mem(isa_state->m, mem, NULL)) {
	    match = FALSE;
	    if (verbosity > 0) {
		printf("ISA Memory != Pipeline Memory\n");
		diff_mem(isa_state->m, mem, stdout);
	    }
	}
	if (isa_state->cc != result_cc) {
	    match = FALSE;
	    if (verbosity > 0) {
		printf("ISA Cond. Codes (%s) != Pipeline Cond. Codes (%s)\n",
		       cc_name(isa_state->cc), cc_name(result_cc));
	    }
	}
	if (match) {
	    printf("ISA Check Succeeds\n");
	} else {
	    printf("ISA Check Fails\n");
	}
    }
}
Esempio n. 21
0
int main(int argc,char **argv) {
	if(sizeof(byte) != 1 || sizeof(wyde) != 2 || sizeof(tetra) != 4 || sizeof(octa) != 8)
		error("Type-sizes are wrong. Please change the typedefs in common.h for your platform!");

	bool interactive = false;
	for(int i = 1; i < argc; i++) {
		if(strcmp(argv[i],"-i") == 0)
			interactive = true;
		else if(strncmp(argv[i],"--postcmds=",sizeof("--postcmds=") - 1) == 0)
			postCmds = argv[i] + sizeof("--postcmds=") - 1;
		else if(strncmp(argv[i],"--script=",sizeof("--script=") - 1) == 0) {
			script = argv[i] + sizeof("--script=") - 1;
			interactive = true;
		}
		else if(strncmp(argv[i],"--start=",sizeof("--start=") - 1) == 0) {
			octa cpc = mstrtoo(argv[i] + sizeof("--start=") - 1,NULL,0);
			cfg_setStartAddr(cpc);
		}
		else if(strcmp(argv[i],"--user") == 0) {
			cfg_setUserMode(true);
			cfg_setStartAddr(0x1000);
			cfg_setRAMSize((octa)32 * 1024 * 1024 * 1024);
		}
		else if(strcmp(argv[i],"--test") == 0)
			cfg_setTestMode(true);
		else if(strcmp(argv[i],"-t") == 0) {
			if(i >= argc - 1)
				error(usage,argv[0]);
			cfg_setTermCount(mstrtoo(argv[i + 1],NULL,0));
			i++;
		}
		else if(strcmp(argv[i],"-l") == 0) {
			if(i >= argc - 1)
				error(usage,argv[0]);
			cfg_setProgram(argv[i + 1]);
			i++;
		}
		else if(strcmp(argv[i],"-r") == 0) {
			if(i >= argc - 1)
				error(usage,argv[0]);
			cfg_setROM(argv[i + 1]);
			cfg_setStartAddr(MSB(64) | ROM_START_ADDR);
			i++;
		}
		else if(strcmp(argv[i],"-d") == 0) {
			if(i >= argc - 1)
				error(usage,argv[0]);
			cfg_setDiskImage(argv[i + 1]);
			i++;
		}
		else if(strcmp(argv[i],"-o") == 0) {
			if(i >= argc - 1)
				error(usage,argv[0]);
			cfg_setOutputFile(argv[i + 1]);
			i++;
		}
		else if(strcmp(argv[i],"-m") == 0) {
			if(i >= argc - 1)
				error(usage,argv[0]);
			cfg_setRAMSize(mstrtoo(argv[i + 1],NULL,0) * 1024 * 1024);
			i++;
		}
		else if(strcmp(argv[i],"-c") == 0)
			cfg_setUseDspKbd(true);
		else if(strcmp(argv[i],"-p") == 0) {
			if(i >= argc - 1)
				error(usage,argv[0]);
			gdbport = atoi(argv[i + 1]);
			i++;
		}
		else if(strcmp(argv[i],"-b") == 0)
			cfg_setUseBacktracing(true);
		else if(strcmp(argv[i],"-s") == 0) {
			const char *mapNames[MAX_MAPS];
			for(int x = 0; x < MAX_MAPS; x++)
				mapNames[x] = NULL;
			if(i == argc - 1 || mapNames[0] != NULL)
				error(usage,argv[0]);
			for(int x = 0; x < MAX_MAPS && i < argc - 1; x++) {
				mapNames[x] = argv[++i];
				if(mapNames[x][0] == '-') {
					mapNames[x] = NULL;
					i--;
					break;
				}
			}
			cfg_setMaps(mapNames);
		}
		else
			error(usage,argv[0]);
	}

	// in non-interactive mode, either a program or ROM is required
	if(!interactive && cfg_getProgram() == NULL && cfg_getROM() == NULL)
		error(usage,argv[0]);

	// catch exceptions that are not catched by anybody else. it may occur an exception during
	// initialization for example.
	jmp_buf env;
	int ex = setjmp(env);
	if(ex != EX_NONE)
		mprintf("Exception: %s\n",ex_toString(ex,ex_getBits()));
	else {
		ex_push(&env);
		sim_init();
		if(gdbport != -1)
			gdbstub_init(gdbport);
		else if(interactive) {
			cons_init();
			if(script)
				cons_exec(script,true);
			cons_start();
			cons_shutdown();
		}
		else {
			cpu_run();
			if(postCmds)
				postcmds_perform(postCmds);
		}
	}
	ex_pop();
	sim_shutdown();

	// ignore errors raised by the gcov stuff
	fclose(stderr);
	return EXIT_SUCCESS;
}
Esempio n. 22
0
/**
 * snmp_bc_open:
 * @handler_config: Pointer to hash table (passed by infrastructure)
 *
 * Open an SNMP BladeCenter/RSA plugin handler instance.
 *
 * Returns:
 * Plugin handle - normal operation.
 * NULL - on error.
 **/
void *snmp_bc_open(GHashTable *handler_config)
{
        struct oh_handler_state *handle;
        struct snmp_bc_hnd *custom_handle;
        char *hostname, *version, *sec_level, *authtype, *user, *pass, *community;
        char *root_tuple;

        root_tuple = (char *)g_hash_table_lookup(handler_config, "entity_root");
        if (!root_tuple) {
                dbg("Cannot find \"entity_root\" configuration parameter.");
                return NULL;
        }

        hostname = (char *)g_hash_table_lookup(handler_config, "host");
        if (!hostname) {
                dbg("Cannot find \"host\" configuration parameter.");
                return NULL;
        }

        handle = (struct oh_handler_state *)g_malloc0(sizeof(struct oh_handler_state));
        custom_handle = (struct snmp_bc_hnd *)g_malloc0(sizeof(struct snmp_bc_hnd));
        if (!handle || !custom_handle) {
                dbg("Out of memory.");
                return NULL;
        }

        handle->data = custom_handle;
        handle->config = handler_config;

        /* Initialize the lock */
        /* g_static_rec_mutex_init(&handle->handler_lock); */
	g_static_rec_mutex_init(&custom_handle->snmp_bc_hlock.lock);
	custom_handle->snmp_bc_hlock.count = 0;
	
        /* Initialize RPT cache */
        handle->rptcache = (RPTable *)g_malloc0(sizeof(RPTable));
        oh_init_rpt(handle->rptcache);
	 
        /* Initialize event log cache */
        handle->elcache = oh_el_create(BC_EL_MAX_SIZE);
	handle->elcache->gentimestamp = FALSE;

	/* Initialize simulator tables */
	if (is_simulator()) {
		custom_handle->ss = NULL;
		sim_init();
	}
	else {
		/* Initialize SNMP library */
		init_snmp("oh_snmp_bc");
		snmp_sess_init(&(custom_handle->session));
		custom_handle->session.peername = hostname;
		/* Set retries/timeouts - based on testing with BC/BCT MM SNMP V3 agent */
		custom_handle->session.retries = 3;
		custom_handle->session.timeout = 5000000; /* in microseconds */  
		version = (char *)g_hash_table_lookup(handle->config, "version");
		if (!version) {
			dbg("Cannot find \"version\" configuration parameter.");
			return NULL;
		}
		sec_level = (char *)g_hash_table_lookup(handle->config, "security_level");
		authtype = (char *)g_hash_table_lookup(handle->config, "auth_type");
		user = (char *)g_hash_table_lookup(handle->config, "security_name");
		pass = (char *)g_hash_table_lookup(handle->config, "passphrase");
		community = (char *)g_hash_table_lookup(handle->config, "community");
		
		/* Configure SNMP V3 session */
		if (!strcmp(version, "3")) {
			if (!user) {
				dbg("Cannot find \"security_name\" configuration parameter.");
				return NULL;
			}
			custom_handle->session.version = SNMP_VERSION_3;
			custom_handle->session.securityName = user;
			custom_handle->session.securityNameLen = strlen(user);
			custom_handle->session.securityLevel = SNMP_SEC_LEVEL_NOAUTH;
			
			if (!strncmp(sec_level, "auth", 4)) { /* If using password */
				if (!pass) {
					dbg("Cannot find \"passphrase\" configuration parameter.");
					return NULL;
				}
				
				custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
				if (!authtype || !strcmp(authtype,"MD5")) {
					custom_handle->session.securityAuthProto = usmHMACMD5AuthProtocol;
					custom_handle->session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
				} else if (!strcmp(authtype,"SHA")) {
					custom_handle->session.securityAuthProto = usmHMACSHA1AuthProtocol;
					custom_handle->session.securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
				} else {
					dbg("Unrecognized authenication type=%s.", authtype); 
					return NULL;
				}
				
				custom_handle->session.securityAuthKeyLen = USM_AUTH_KU_LEN;
				if (generate_Ku(custom_handle->session.securityAuthProto,
						custom_handle->session.securityAuthProtoLen,
						(u_char *) pass, strlen(pass),
						custom_handle->session.securityAuthKey,
						&(custom_handle->session.securityAuthKeyLen)) != SNMPERR_SUCCESS) {
					snmp_perror("snmp_bc");
					snmp_log(LOG_ERR,
						 "Error generating Ku from authentication passphrase.\n");
					dbg("Unable to establish SNMP authnopriv session.");
					return NULL;
				}
				
				if (!strcmp(sec_level, "authPriv")) { /* if using encryption */
					custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
					custom_handle->session.securityPrivProto = usmDESPrivProtocol;
					custom_handle->session.securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
					custom_handle->session.securityPrivKeyLen = USM_PRIV_KU_LEN;
					if (generate_Ku(custom_handle->session.securityAuthProto,
							custom_handle->session.securityAuthProtoLen,
							(u_char *) pass, strlen(pass),
							custom_handle->session.securityPrivKey,
							&(custom_handle->session.securityPrivKeyLen)) != SNMPERR_SUCCESS) {
						snmp_perror("snmp_bc");
						snmp_log(LOG_ERR,
							 "Error generating Ku from private passphrase.\n");
						dbg("Unable to establish SNMP authpriv session.");
						return NULL;
					}
					
				}
			}                                
                /* Configure SNMP V1 session */
		} else if (!strcmp(version, "1")) { 
			if (!community) {
				dbg("Cannot find \"community\" configuration parameter.");
				return NULL;
			}
			custom_handle->session.version = SNMP_VERSION_1;
			custom_handle->session.community = (u_char *)community;
			custom_handle->session.community_len = strlen(community);
		} else {
			dbg("Unrecognized SNMP version=%s.", version);
			return NULL;
		}
                
		/* Windows32 specific net-snmp initialization (noop on unix) */
		SOCK_STARTUP;

		custom_handle->sessp = snmp_sess_open(&(custom_handle->session));
		
		if (!custom_handle->sessp) {
			snmp_perror("ack");
			snmp_log(LOG_ERR, "Something horrible happened!!!\n");
		 	dbg("Unable to open SNMP session.");
			return NULL;
		}
		
		custom_handle->ss    = snmp_sess_session(custom_handle->sessp);

	}

	/* Determine platform type and daylight savings time */
	{
		const char *oid;
		struct snmp_value get_value;
		SaErrorT err;

		err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_RSA, &get_value, SAHPI_FALSE);
		if (err == SA_OK) {
			trace("Found RSA");
			custom_handle->platform = SNMP_BC_PLATFORM_RSA;
		}
		else {
			err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_BCT, &get_value, SAHPI_FALSE);
			if (err == SA_OK) {
				trace("Found BCT");
				custom_handle->platform = SNMP_BC_PLATFORM_BCT;
			}
			else {
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_BC, &get_value, SAHPI_FALSE);
				if (err == SA_OK) {
					trace("Found BC");
					custom_handle->platform = SNMP_BC_PLATFORM_BC;
				}
				else {
					dbg("Cannot read model type=%s; Error=%d.",
					      SNMP_BC_PLATFORM_OID_BCT, err);
					return NULL;
				}
			}
		}

		/* DST */
		if (custom_handle->platform == SNMP_BC_PLATFORM_RSA) { oid = SNMP_BC_DST_RSA; }
		else { oid = SNMP_BC_DST; }

		err = snmp_bc_snmp_get(custom_handle, oid, &get_value, SAHPI_TRUE);
		if (err == SA_OK) {
			strcpy(custom_handle->handler_timezone, get_value.string);
		}
		else {
			dbg("Cannot read DST=%s; Error=%d.", oid, get_value.type);
			return NULL;
		}
	}

	/* Initialize "String to Event" mapping hash table */
	if (errlog2event_hash_use_count == 0) {
		if (errlog2event_hash_init(custom_handle)) {
			dbg("Out of memory.");
			return NULL;
		}
	}
	errlog2event_hash_use_count++;
	
	/* Initialize "Event Number to HPI Event" mapping hash table */
	if (event2hpi_hash_init(handle)) {
		dbg("Out of memory.");
		return NULL;
	}
  
	if (is_simulator()) {
		sim_banner(custom_handle);
	}
	
        return handle;
}
Esempio n. 23
0
void gui_tick(VideoMode mode, r32 gui_time, r32 gui_dt)
{
    persist bool flag_DrawDroneGoto     = true;
    persist bool flag_DrawDrone         = true;
    persist bool flag_DrawVisibleRegion = true;
    persist bool flag_DrawTargets       = true;
    persist bool flag_DrawObstacles     = true;
    persist bool flag_Paused            = false;
    persist bool flag_Recording         = false;
    persist bool flag_SetupRecord       = false;

    persist int record_from = 0;
    persist int record_to = 0;
    persist int record_frame_skip = 1;
    persist int record_width = 0;
    persist int record_height = 0;
    persist float record_region_x = -1.0f;
    persist float record_region_y = -1.0f;
    persist float record_region_scale = 2.0f;
    persist jo_gif_t record_gif;

    persist int seek_cursor = 0;
    persist int selected_target = -1;

    persist Color color_Clear          = { 0.00f, 0.00f, 0.00f, 1.00f };
    persist Color color_Tiles          = { 0.20f, 0.35f, 0.46f, 0.66f };
    persist Color color_Grid           = { 0.00f, 0.00f, 0.00f, 1.00f };
    persist Color color_VisibleRegion  = { 0.87f, 0.93f, 0.84f, 0.50f };
    persist Color color_GreenLine      = { 0.10f, 1.00f, 0.20f, 1.00f };
    persist Color color_SelectedTarget = { 0.85f, 0.34f, 0.32f, 1.00f };
    persist Color color_Targets        = { 0.85f, 0.83f, 0.37f, 1.00f };
    persist Color color_Obstacles      = { 0.43f, 0.76f, 0.79f, 1.00f };
    persist Color color_Drone          = { 0.87f, 0.93f, 0.84f, 0.50f };
    persist Color color_DroneGoto      = { 0.87f, 0.93f, 0.84f, 0.50f };
    #define RGBA(C) C.r, C.g, C.b, C.a

    persist float send_timer = 0.0f;
    persist float send_interval = 1.0f; // In simulation time units

    NDC_SCALE_X = (mode.height / (r32)mode.width) / 12.0f;
    NDC_SCALE_Y = 1.0f / 12.0f;

    if (flag_Recording || flag_SetupRecord)
    {
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        float Ax = 2.0f / record_region_scale;
        float Bx = -1.0f - Ax*record_region_x;
        float Ay = 2.0f / record_region_scale;
        float By = -1.0f - Ay*record_region_y;
        float modelview[] = {
            Ax,   0.0f, 0.0f, 0.0f,
            0.0f, Ay,   0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            Bx,   By,   0.0f, 1.0f
        };
        glLoadMatrixf(modelview);
    }
    else
    {
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
    }

    if (!flag_Paused)
    {
        if (flag_Recording)
        {
            if (seek_cursor >= record_to)
            {
                flag_Paused = true;
                flag_Recording = false;
                seek_cursor = record_from;
                jo_gif_end(&record_gif);
            }
            else if (seek_cursor + record_frame_skip >= record_to)
            {
                // clamp to end
                seek_cursor = record_to;
            }
            else
            {
                seek_cursor += record_frame_skip;
            }
        }
        else if (seek_cursor < HISTORY_LENGTH-1)
        {
            seek_cursor++;
        }
        else
        {
            sim_Command cmd;

            if (!sim_recv_cmd(&cmd))
            {
                cmd.type = sim_CommandType_NoCommand;
                cmd.x = 0.0f;
                cmd.y = 0.0f;
                cmd.i = 0;
            }

            STATE = sim_tick(STATE, cmd);
            add_history(cmd, STATE);
            seek_cursor = HISTORY_LENGTH-1;

            send_timer -= Sim_Timestep;
            if (send_timer <= 0.0f)
            {
                sim_send_state(&STATE);
                send_timer += send_interval;
            }
        }
    }

    sim_State draw_state = HISTORY_STATE[seek_cursor];
    sim_Drone drone = draw_state.drone;
    sim_Robot *robots = draw_state.robots;
    sim_Robot *targets = draw_state.robots;
    sim_Robot *obstacles = draw_state.robots + Num_Targets;

    if (flag_Recording || flag_SetupRecord)
    {
        glViewport(0, 0, record_width, record_height);
    }
    else
    {
        glViewport(0, 0, mode.width, mode.height);
    }

    glClearColor(RGBA(color_Clear));
    glClear(GL_COLOR_BUFFER_BIT);
    glLineWidth(2.0f);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // draw grid tiles
    glBegin(GL_TRIANGLES);
    {
        color4f(color_Tiles);
        for (int yi = 0; yi < 20; yi++)
        for (int xi = 0; xi < 20; xi++)
        {
            r32 x = xi*1.0f;
            r32 y = yi*1.0f;
            fill_square(x, y, x+1.0f, y+1.0f);
        }
    }
    glEnd();

    glBegin(GL_LINES);
    {
        // draw grid lines
        color4f(color_Grid);
        for (int i = 0; i <= 20; i++)
        {
            r32 x = (r32)i;
            draw_line(x, 0.0f, x, 20.0f);
            draw_line(0.0f, x, 20.0f, x);
        }

        // draw visible region
        if (flag_DrawVisibleRegion)
        {
            color4f(color_VisibleRegion);
            draw_circle(drone.x, drone.y, 2.5f);
        }

        // draw green line
        color4f(color_GreenLine);
        draw_line(0.0f, 20.0f, 20.0f, 20.0f);

        // draw targets
        if (flag_DrawTargets)
        {
            color4f(color_Targets);
            for (int i = 0; i < Num_Targets; i++)
                draw_robot(targets[i]);
            if (selected_target >= 0)
            {
                color4f(color_SelectedTarget);
                draw_robot(targets[selected_target]);
            }
        }

        // draw obstacles
        if (flag_DrawObstacles)
        {
            color4f(color_Obstacles);
            for (int i = 0; i < Num_Obstacles; i++)
                draw_robot(obstacles[i]);
        }

        // draw drone
        if (flag_DrawDrone)
        {
            color4f(color_Drone);
            draw_line(drone.x - 0.5f, drone.y,
                      drone.x + 0.5f, drone.y);
            draw_line(drone.x, drone.y - 0.5f,
                      drone.x, drone.y + 0.5f);
        }

        // draw drone goto
        if (flag_DrawDroneGoto)
        {
            color4f(color_DroneGoto);
            draw_circle(drone.xr, drone.yr, 0.45f);
        }

        // draw indicators of magnet or bumper activations
        for (int i = 0; i < Num_Targets; i++)
        {
            r32 x = targets[i].x;
            r32 y = targets[i].y;
            if (targets[i].action.was_bumped)
            {
                glColor4f(1.0f, 0.3f, 0.1f, 1.0f);
                draw_circle(x, y, 0.5f);
            }
            else if (targets[i].action.was_top_touched)
            {
                glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
                draw_circle(x, y, 0.5f);
            }
        }
    }
    glEnd();

    // TODO: Change capture res?
    if (flag_Recording)
    {
        static unsigned char capture_data[1024*1024*4];
        Assert(sizeof(capture_data) >=
               record_width*record_height*4);
        glReadPixels(0, 0,
                     record_width,
                     record_height,
                     GL_RGBA,
                     GL_UNSIGNED_BYTE,
                     capture_data);

        jo_gif_frame(&record_gif, capture_data,
                     2, false);
    }

    ImGui_ImplSdl_NewFrame(mode.window);

    // DRAW FLAGS
    if (ImGui::CollapsingHeader("Rendering"))
    {
        ImGui::Checkbox("Drone goto", &flag_DrawDroneGoto);
        ImGui::Checkbox("Drone", &flag_DrawDrone);
        ImGui::Checkbox("Visible region", &flag_DrawVisibleRegion);
        ImGui::Checkbox("Targets", &flag_DrawTargets);
        ImGui::Checkbox("Obstacles", &flag_DrawObstacles);
    } // END DRAW FLAGS

    // COLORS
    if (ImGui::CollapsingHeader("Colors"))
    {
        ImGui::ColorEdit4("Clear", &color_Clear.r);
        ImGui::ColorEdit4("Grid", &color_Grid.r);
        ImGui::ColorEdit4("VisibleRegion", &color_VisibleRegion.r);
        ImGui::ColorEdit4("GreenLine", &color_GreenLine.r);
        ImGui::ColorEdit4("Targets", &color_Targets.r);
        ImGui::ColorEdit4("Obstacles", &color_Obstacles.r);
        ImGui::ColorEdit4("Drone", &color_Drone.r);
        ImGui::ColorEdit4("DroneGoto", &color_DroneGoto.r);
    } // END COLORS

    // REWIND HISTORY
    if (ImGui::CollapsingHeader("Seek##header"))
    {
        ImGui::Checkbox("Paused", &flag_Paused);
        ImGui::SliderInt("Seek##bar", &seek_cursor, 0, HISTORY_LENGTH-1);
        ImGui::InputInt("Seek frame", &seek_cursor);
        if (seek_cursor < 0) seek_cursor = 0;
        if (seek_cursor > HISTORY_LENGTH-1) seek_cursor = HISTORY_LENGTH-1;
        ImGui::Text("Time: %.2f seconds", (seek_cursor+1) * Sim_Timestep);
    } // END REWIND HISTORY

    // ROBOTS
    if (ImGui::CollapsingHeader("Robots"))
    {
        ImGui::Columns(4, "RobotsColumns");
        ImGui::Separator();
        ImGui::Text("ID"); ImGui::NextColumn();
        ImGui::Text("X"); ImGui::NextColumn();
        ImGui::Text("Y"); ImGui::NextColumn();
        ImGui::Text("Angle"); ImGui::NextColumn();
        ImGui::Separator();
        for (int i = 0; i < Num_Targets; i++)
        {
            char label[32];
            sprintf(label, "%02d", i);
            if (ImGui::Selectable(label, selected_target == i, ImGuiSelectableFlags_SpanAllColumns))
                selected_target = i;
            ImGui::NextColumn();
            ImGui::Text("%.2f", robots[i].x); ImGui::NextColumn();
            ImGui::Text("%.2f", robots[i].y); ImGui::NextColumn();
            ImGui::Text("%.2f", robots[i].q); ImGui::NextColumn();
        }
        ImGui::Columns(1);
        ImGui::Separator();
    }
    else
    {
        selected_target = -1;
    } // END ROBOTS

    // COMMUNICATION
    if (ImGui::CollapsingHeader("Communication"))
    {
        ImGui::TextWrapped("The rate at which the state is "
                           "sent can be changed using this slider. "
                           "The slider value represents the time "
                           "interval (in simulation time) "
                           "between each send.");
        ImGui::SliderFloat("Send interval", &send_interval,
                           Sim_Timestep, 1.0f);
        ImGui::Separator();

        ImGui::Text("Last 10 non-trivial commands received:");
        ImGui::Columns(5, "CommunicationColumns");
        ImGui::Separator();
        ImGui::Text("Time"); ImGui::NextColumn();
        ImGui::Text("type"); ImGui::NextColumn();
        ImGui::Text("x"); ImGui::NextColumn();
        ImGui::Text("y"); ImGui::NextColumn();
        ImGui::Text("i"); ImGui::NextColumn();
        ImGui::Separator();
        int count = 0;
        for (int i = 0; count < 10 && i <= seek_cursor; i++)
        {
            sim_State state_i = HISTORY_STATE[seek_cursor-i];
            sim_Command cmd_i = HISTORY_CMD[seek_cursor-i];
            if (cmd_i.type == sim_CommandType_NoCommand)
                continue;
            char label[32];
            sprintf(label, "%.2f", state_i.elapsed_time);
            ImGui::Selectable(label, false,
                              ImGuiSelectableFlags_SpanAllColumns);
            ImGui::NextColumn();
            switch (cmd_i.type)
            {
                case sim_CommandType_NoCommand:
                {
                    ImGui::Text("Nothing"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                } break;
                case sim_CommandType_LandInFrontOf:
                {
                    ImGui::Text("Land 180"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("%d", cmd_i.i); ImGui::NextColumn();
                } break;
                case sim_CommandType_LandOnTopOf:
                {
                    ImGui::Text("Land 45"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("%d", cmd_i.i); ImGui::NextColumn();
                } break;
                case sim_CommandType_Track:
                {
                    ImGui::Text("Track"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("%d", cmd_i.i); ImGui::NextColumn();
                } break;
                case sim_CommandType_Search:
                {
                    ImGui::Text("Search"); ImGui::NextColumn();
                    ImGui::Text("%.2f", cmd_i.x); ImGui::NextColumn();
                    ImGui::Text("%.2f", cmd_i.y); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                } break;
            }
            count++;
        }
        ImGui::Columns(1);
        ImGui::Separator();
    } // END COMMUNICATION

    // RECORDING GIFS
    if (ImGui::CollapsingHeader("Recording"))
    {
        flag_SetupRecord = true;
        if (ImGui::Button("Mark frame as begin"))
        {
            record_from = seek_cursor;
        }
        ImGui::SameLine();
        ImGui::Text("Record from: %d", record_from);
        if (ImGui::Button("Mark frame as end"))
        {
            record_to = seek_cursor;
        }
        ImGui::SameLine();
        ImGui::Text("Record to: %d", record_to);
        ImGui::InputInt("Frame skip", &record_frame_skip);

        ImGui::InputInt("Record width", &record_width);
        ImGui::InputInt("Record height", &record_height);
        if (record_width <= 0) record_width = mode.width;
        if (record_height <= 0) record_height = mode.height;

        ImGui::SliderFloat("Record x", &record_region_x, -1.0f, 1.0f);
        ImGui::SliderFloat("Record y", &record_region_y, -1.0f, 1.0f);
        ImGui::SliderFloat("Record scale", &record_region_scale, 0.0f, 2.0f);

        if (ImGui::Button("Start recording") && !flag_Recording)
            ImGui::OpenPopup("Save recording as?");
        if (ImGui::BeginPopupModal("Save recording as?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
        {
            persist char filename[1024];
            persist bool init_filename = true;
            if (init_filename)
            {
                sprintf(filename, "recording%u.gif", STATE.seed);
                init_filename = false;
            }
            ImGui::InputText("Filename", filename, sizeof(filename));
            ImGui::Separator();

            if (ImGui::Button("OK", ImVec2(120,0)))
            {
                flag_Recording = true;
                flag_Paused = false;
                seek_cursor = record_from-1;
                record_gif = jo_gif_start(filename, (short)record_width, (short)record_height, 0, 32);
                ImGui::CloseCurrentPopup();
            }
            ImGui::SameLine();
            if (ImGui::Button("Cancel", ImVec2(120,0)))
            {
                ImGui::CloseCurrentPopup();
            }
            ImGui::EndPopup();
        }

        if (ImGui::Button("Stop recording") && flag_Recording)
        {
            flag_Recording = false;
            flag_Paused = true;
            jo_gif_end(&record_gif);
        }

        if (record_from < 0) record_from = 0;
        if (record_from > HISTORY_LENGTH-1) record_from = HISTORY_LENGTH-1;
        if (record_to < record_from) record_to = record_from;
        if (record_to > HISTORY_LENGTH-1) record_to = HISTORY_LENGTH-1;
        if (record_frame_skip < 1) record_frame_skip = 1;
        ImGui::Separator();
    }
    else
    {
        flag_SetupRecord = false;
    } // END RECORDING GIFS

    // RESET AND SET SEED
    persist int custom_seed = 0;
    if (ImGui::Button("Reset"))
    {
        if (custom_seed > 0)
            STATE = sim_init((u32)custom_seed);
        else
            STATE = sim_init((u32)get_tick());
        HISTORY_LENGTH = 0;
        sim_Command cmd;
        cmd.type = sim_CommandType_NoCommand;
        add_history(cmd, STATE);
    }
    ImGui::SameLine();
    ImGui::InputInt("Seed", &custom_seed);
    // END RESET AND SET SEED

    // SAVE SIMULATION
    if (ImGui::Button("Save.."))
        ImGui::OpenPopup("Save as?");
    if (ImGui::BeginPopupModal("Save as?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
    {
        persist char filename[1024];
        persist bool init_filename = true;
        if (init_filename)
        {
            sprintf(filename, "simulation%u", STATE.seed);
            init_filename = false;
        }
        ImGui::InputText("Filename", filename, sizeof(filename));
        ImGui::Separator();

        if (ImGui::Button("OK", ImVec2(120,0)))
        {
            write_history(filename);
            ImGui::CloseCurrentPopup();
        }
        ImGui::SameLine();
        if (ImGui::Button("Cancel", ImVec2(120,0)))
        {
            ImGui::CloseCurrentPopup();
        }
        ImGui::EndPopup();
    } // END SAVE SIMULATION

    ImGui::SameLine();

    // SAVE SINGLE SNAPSHOT
    persist bool init_snapshot_filename = true;
    if (ImGui::Button("Save snapshot.."))
        ImGui::OpenPopup("Save snapshot as?");
    if (ImGui::BeginPopupModal("Save snapshot as?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
    {
        persist char filename[1024];
        ImGui::TextWrapped("The filename is relative to the executable,"
                           "unless you write an absolute path.");
        if (init_snapshot_filename)
        {
            sprintf(filename, "snapshot%u-%u", STATE.seed, seek_cursor);
            init_snapshot_filename = false;
        }
        ImGui::InputText("Filename", filename, sizeof(filename));
        ImGui::Separator();

        if (ImGui::Button("OK", ImVec2(120,0)))
        {
            sim_Observed_State snapshot =
                sim_observe_state(HISTORY_STATE[seek_cursor]);
            printf("%.2f\n", snapshot.obstacle_q[0]);
            sim_write_snapshot(filename, snapshot);
            ImGui::CloseCurrentPopup();
        }
        ImGui::SameLine();
        if (ImGui::Button("Cancel", ImVec2(120,0)))
        {
            ImGui::CloseCurrentPopup();
        }
        ImGui::EndPopup();
    }
    else
    {
        init_snapshot_filename = true;
    } // END SAVE SIMULATION

    ImGui::SameLine();

    // LOAD SIMULATION
    if (ImGui::Button("Load.."))
        ImGui::OpenPopup("Load file?");
    if (ImGui::BeginPopupModal("Load file?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
    {
        persist char filename[1024];
        persist bool init_filename = true;
        if (init_filename)
        {
            sprintf(filename, "simulation%u", STATE.seed);
            init_filename = false;
        }
        ImGui::InputText("Filename", filename, sizeof(filename));
        ImGui::Separator();

        if (ImGui::Button("OK", ImVec2(120,0)))
        {
            read_history(filename);
            seek_cursor = 0;
            flag_Paused = true;
            ImGui::CloseCurrentPopup();
        }
        ImGui::SameLine();
        if (ImGui::Button("Cancel", ImVec2(120,0)))
        {
            ImGui::CloseCurrentPopup();
        }
        ImGui::EndPopup();
    } // END LOAD SIMULATION

    ImGui::Render();
} // END gui_tick
Esempio n. 24
0
File: init.c Progetto: hydra/freewpc
/** Initialize the FreeWPC program. */
__noreturn__ void freewpc_init (void)
{
    extern __common__ void system_reset (void);

    /* Initialize the platform specifics first */
    VOIDCALL (platform_init);

    /* Reset the blanking and watchdog circuitry.
     * Eventually, the watchdog will be tickled every 1ms
     * by the IRQ; until interrupts are enabled, we will
     * have to do this periodically ourselves. */
    pinio_watchdog_reset ();

    /* Set init complete flag to false.  When everything is
     * ready, we'll change this to a 1. */
    sys_init_complete = 0;
    periodic_ok = 0;
    sys_init_pending_tasks = 0;

    /* Initialize all of the other kernel subsystems,
     * starting with the hardware-centric ones and moving on
     * to software features. */

    /* Initialize the real-time scheduler.  The periodic functions
    are scheduled at compile-time  using the 'gensched' utility. */
    VOIDCALL (tick_init);

    /* Initialize the hardware.
     * After each init call, tickle the watchdog (IRQ isn't enabled yet)
     * to prevent it from expiring and resetting the CPU.
     * We don't use a callset here because there are some ordering
     * dependencies -- some modules must be initialized before others --
     * and gencallset doesn't allow us to express those conditions.
     */
#ifdef DEBUGGER
    db_init ();
    bpt_init ();
    pinio_watchdog_reset ();
#endif
    ac_init ();
    pinio_watchdog_reset ();
    sol_init ();
    pinio_watchdog_reset ();
#ifdef CONFIG_GI
    gi_init ();
    pinio_watchdog_reset ();
#endif
    display_init ();
    pinio_watchdog_reset ();
    switch_init ();
    pinio_watchdog_reset ();
    flipper_init ();
    pinio_watchdog_reset ();
    lamp_init ();
    pinio_watchdog_reset ();
    device_init ();
    pinio_watchdog_reset ();
    free_timer_init ();
    pinio_watchdog_reset ();
    sound_init ();
    pinio_watchdog_reset ();
#if (MACHINE_PIC == 1)
    pic_init ();
    pinio_watchdog_reset ();
#endif

    /* task_init is somewhat special in that it transforms the system
     * from a single task into a multitasking one.  After this, tasks
     * can be spawned if need be.  A task is created for the current
     * thread of execution, too. */
    task_init ();
    pinio_watchdog_reset ();

#ifdef CONFIG_NATIVE
    /* Notify the simulator when the core OS is up and running. */
    sim_init ();
#endif

    /* Initialize the sound board early in a background
     * thread, since it involves polling for data back from it,
     * which may take unknown (or even infinite) time. */
    sys_init_pending_tasks++;
    task_create_gid (GID_SOUND_INIT, sound_board_init);

    /* Enable interrupts (IRQs and FIRQs).  Do this as soon as possible,
     * but not before all of the hardware modules are done. */
    enable_interrupts ();

    /* Initialize everything else.  Some of these are given explicitly
    to force a particular order, since callsets do not guarantee the
    order of invocation.  For most things the order doesn't matter. */
    deff_init ();
    leff_init ();
    test_init ();
    adj_init ();
    log_init ();
    callset_invoke (init);

    /* Check all adjustments and make sure that their checksums are valid.
    If problems are found, those adjustments will be made sane again. */
    csum_area_check_all ();

    /* Enable periodic processing. */
    periodic_ok = 1;
    task_sleep (TIME_16MS);

    /* The system is initialized from a hardware perspective.
     * Now, perform additional final initializations. */
    system_reset ();

    /* The system can run itself now, this task is done! */
    task_exit ();
}
Esempio n. 25
0
/* 
 * run_tty_sim - Run the simulator in TTY mode
 */
static void run_tty_sim() 
{
    int icount = 0;
    byte_t run_status = STAT_AOK;
    cc_t result_cc = 0;
    int byte_cnt = 0;
    mem_t mem0, reg0;
    state_ptr isa_state = NULL;


    /* In TTY mode, the default object file comes from stdin */
    if (!object_file) {
        object_file = stdin;
    }

    if (verbosity >= 2)
        sim_set_dumpfile(stdout);
    sim_init();

    /* Emit simulator name */
    if (verbosity >= 2)
        printf("%s\n", simname);

    byte_cnt = load_mem(mem, object_file, 1, START_PLACE);
    if (byte_cnt == 0) {
        fprintf(stderr, "No lines of code found\n");
        exit(1);
    } else if (verbosity >= 2) {
        printf("%d bytes of code read\n", byte_cnt);
    }
    fclose(object_file);
    if (do_check) {
        isa_state = new_state(0);
        free_reg(isa_state->r);
        free_mem(isa_state->m);
        isa_state->m = copy_mem(mem);
        isa_state->r = copy_reg(reg);
        isa_state->cc = cc;
    }

    if(verbosity > 0){
        mem0 = copy_mem(mem);
        reg0 = copy_reg(reg);
    }

    icount = sim_run_pipe(instr_limit, 5*instr_limit, &run_status, &result_cc);
    if (verbosity > 0) {
        printf("%d instructions executed\n", icount);
        printf("Status = %s\n", stat_name(run_status));
        printf("Condition Codes: %s\n", cc_name(result_cc));
        printf("Changed Register State:\n");
        diff_reg(reg0, reg, stdout);
        printf("Changed Memory State:\n");
        diff_mem(mem0, mem, stdout);
    }
    if (do_check) {
        exit(0);
        byte_t e = STAT_AOK;
        int step;
        bool_t match = TRUE;

        for (step = 0; step < instr_limit && e == STAT_AOK; step++) {
            e = step_state(isa_state, stdout);
        }

        if (diff_reg(isa_state->r, reg, NULL)) {
            match = FALSE;
            if (verbosity > 0) {
                printf("ISA Register != Pipeline Register File\n");
                diff_reg(isa_state->r, reg, stdout);
            }
        }
        if (diff_mem(isa_state->m, mem, NULL)) {
            match = FALSE;
            if (verbosity > 0) {
                printf("ISA Memory != Pipeline Memory\n");
                diff_mem(isa_state->m, mem, stdout);
            }
        }
        if (isa_state->cc != result_cc) {
            match = FALSE;
            if (verbosity > 0) {
                printf("ISA Cond. Codes (%s) != Pipeline Cond. Codes (%s)\n",
                        cc_name(isa_state->cc), cc_name(result_cc));
            }
        }
        if (match) {
            printf("ISA Check Succeeds\n");
        } else {
            printf("ISA Check Fails\n");
        }
    }

    /* Emit CPI statistics */
    {
        double cpi = instructions > 0 ? (double) cycles/instructions : 1.0;
        printf("%d CPI: %d cycles/%d instructions = %.2f\n", PSIM_ID,
                cycles, instructions, cpi);
    }
}
Esempio n. 26
0
int test_sim()
{
    u32 i, j;
    u8 data;
    if(sim_init() != 0) {
        DBG("sim:init failed\n");
        return -1;
    }
    // test all 0xff
    for (i = 0;i < FLASH_SIZE;i++) {
        if (sim_read_byte(i, &data) != 0 && data != 0xff) {
            DBG("sim:sim read failed or init failed(not all 0xff\n");
            return -1;
        }
    }

    // test write and read
    for (i = 0;i < FLASH_SIZE;i++) {
        if (sim_write_byte(i, 0xaa) != 0) {
            DBG("sim:write failed\n");
            return -1;
        }
    }
    
    for (i = 0;i < FLASH_SIZE;i++) {
        if (sim_read_byte(i, &data) != 0 && data != 0xaa) {
            DBG("sim:read failed or write data error\n");
            return -1;
        }
    }
    
    for (i = 0;i < FLASH_SIZE;i++) {
        if (sim_write_byte(i, 0x55) != 0) {
            DBG("sim:write failed\n");
            return -1;
        }
    }
    
    for (i = 0;i < FLASH_SIZE;i++) {
        if (sim_read_byte(i, &data) != 0 && data != 0x00) {
            DBG("sim:read failed or write data error\n");
            return -1;
        }
    }
    
    // test sector erase
    for (i = 0;i < FLASH_SECOTR_NUM;i++) {
        if (sim_erase_sector(i) != 0) {
            DBG("sim:sector erase failed\n");
            return -1;
        }

        for (j = 0; j < FLASH_SECTOR_SIZE;j++) {
            if (sim_read_byte(i * FLASH_SECTOR_SIZE + j, &data) != 0 
                && data != 0xff) 
            {
                DBG("sim:sector is not erased\n");
                return -1;
            }
        }
    }
    
    return 0;
}
Esempio n. 27
0
void Tossim::init() {
  sim_init();
  motes = (Mote**)malloc(sizeof(Mote*) * (TOSSIM_MAX_NODES + 1));
  memset(motes, 0, sizeof(Mote*) * TOSSIM_MAX_NODES);
}
Esempio n. 28
0
/**
 * snmp_bc_open:
 * @handler_config: Pointer to hash table (passed by infrastructure)
 *
 * Open an SNMP BladeCenter/RSA plugin handler instance.
 *
 * Returns:
 * Plugin handle - normal operation.
 * NULL - on error.
 **/
void *snmp_bc_open(GHashTable *handler_config)
{
        struct oh_handler_state *handle;
        struct snmp_bc_hnd *custom_handle;
        char *hostname, *version, *sec_level, 
		*authtype, *user, *pass, *community, 
		*context_name, *count_per_getbulk, 
		*privacy_passwd, *privacy_protocol;
        char *root_tuple;

	if (!handler_config) {
                dbg("INVALID PARM - NULL handler_config pointer.");
                return NULL;	
	}

        root_tuple = (char *)g_hash_table_lookup(handler_config, "entity_root");
        if (!root_tuple) {
                dbg("Cannot find \"entity_root\" configuration parameter.");
                return NULL;
        }

        hostname = (char *)g_hash_table_lookup(handler_config, "host");
        if (!hostname) {
                dbg("Cannot find \"host\" configuration parameter.");
                return NULL;
        }

        handle = (struct oh_handler_state *)g_malloc0(sizeof(struct oh_handler_state));
        custom_handle = (struct snmp_bc_hnd *)g_malloc0(sizeof(struct snmp_bc_hnd));
        if (!handle || !custom_handle) {
                dbg("Out of memory.");
                return NULL;
        }

        handle->data = custom_handle;
        handle->config = handler_config;

        /* Initialize the lock */
        /* g_static_rec_mutex_init(&handle->handler_lock); */
	g_static_rec_mutex_init(&custom_handle->snmp_bc_hlock.lock);
	custom_handle->snmp_bc_hlock.count = 0;
	
        /* Initialize resource masks */
	/* Set all masks and counts to zero's    */
	custom_handle->max_pb_supported = 0;		/* pb - processor blade */
	custom_handle->max_blower_supported = 0;	/* blower - fan/blower  */
	custom_handle->max_pm_supported = 0;		/* pm - power module    */
	custom_handle->max_sm_supported = 0;		/* sm - switch module   */
	custom_handle->max_mm_supported = 0;		/* mm - management module */
	custom_handle->max_mt_supported = 0;		/* mt - media tray        */
	
	memset(&custom_handle->installed_pb_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	memset(&custom_handle->installed_blower_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	memset(&custom_handle->installed_pm_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	memset(&custom_handle->installed_sm_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	memset(&custom_handle->installed_mm_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	custom_handle->installed_mt_mask = 0;

        /* Indicate this is the 1st discovery (T0 discovery) */
        /* Use to see if we need to create events for log entries.  */
	/* Do not report any event from event log entries, for      */
	/* entries that are created before this instance of OpenHPI */	
	custom_handle->isFirstDiscovery = SAHPI_TRUE;
	
        /* Initialize RPT cache */
        handle->rptcache = (RPTable *)g_malloc0(sizeof(RPTable));
        oh_init_rpt(handle->rptcache);
	 
        /* Initialize event log cache */
        handle->elcache = oh_el_create(BC_EL_MAX_SIZE);
	handle->elcache->gentimestamp = FALSE;

	/* Initialize simulator tables */
	if (is_simulator()) {
		custom_handle->ss = NULL;
		sim_init();
	}
	else {
		/* Initialize SNMP library */
		init_snmp("oh_snmp_bc");
		snmp_sess_init(&(custom_handle->session));
		custom_handle->session.peername = hostname;
		/* Set retries/timeouts - based on testing with BC/BCT MM SNMP V3 agent */
		custom_handle->session.retries = 3;
		custom_handle->session.timeout = 5000000; /* in microseconds */  
		version = (char *)g_hash_table_lookup(handle->config, "version");
		if (!version) {
			dbg("Cannot find \"version\" configuration parameter.");
			return NULL;
		}
		sec_level = (char *)g_hash_table_lookup(handle->config, "security_level");
		authtype = (char *)g_hash_table_lookup(handle->config, "auth_type");
		user = (char *)g_hash_table_lookup(handle->config, "security_name");
		pass = (char *)g_hash_table_lookup(handle->config, "passphrase");
		community = (char *)g_hash_table_lookup(handle->config, "community");
		context_name = (char *)g_hash_table_lookup(handle->config, "context_name");
		count_per_getbulk = (char *)g_hash_table_lookup(handle->config, "count_per_getbulk");
		privacy_passwd = (char *)g_hash_table_lookup(handle->config, "privacy_passwd");
		privacy_protocol = (char *)g_hash_table_lookup(handle->config, "privacy_protocol");
		
		
		/* Configure SNMP V3 session */
		if (!strcmp(version, "3")) {
			if (!user) {
				dbg("Cannot find \"security_name\" configuration parameter.");
				return NULL;
			}
			custom_handle->session.version = SNMP_VERSION_3;
			custom_handle->session.securityName = user;
			custom_handle->session.securityNameLen = strlen(user);
			custom_handle->session.securityLevel = SNMP_SEC_LEVEL_NOAUTH;
			
			if (!strncmp(sec_level, "auth", 4)) { /* If using password */
				if (!pass) {
					dbg("Cannot find \"passphrase\" configuration parameter.");
					return NULL;
				}
				
				custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
				if (!authtype || !strcmp(authtype,"MD5")) {
					custom_handle->session.securityAuthProto = usmHMACMD5AuthProtocol;
					custom_handle->session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
				} else if (!strcmp(authtype,"SHA")) {
					custom_handle->session.securityAuthProto = usmHMACSHA1AuthProtocol;
					custom_handle->session.securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
				} else {
					dbg("Unrecognized authenication type=%s.", authtype); 
					return NULL;
				}
				
				custom_handle->session.securityAuthKeyLen = USM_AUTH_KU_LEN;
				if (generate_Ku(custom_handle->session.securityAuthProto,
						custom_handle->session.securityAuthProtoLen,
						(u_char *) pass, strlen(pass),
						custom_handle->session.securityAuthKey,
						&(custom_handle->session.securityAuthKeyLen)) != SNMPERR_SUCCESS) {
					snmp_perror("snmp_bc");
					snmp_log(LOG_ERR,
						 "Error generating Ku from authentication passphrase.\n");
					dbg("Unable to establish SNMP authnopriv session.");
					return NULL;
				}
				
				if (!strcmp(sec_level, "authPriv")) { /* if using encryption */
				
					if (!privacy_passwd) {
						dbg("Cannot find \"privacy_passwd\" configuration parameter.");
						return NULL;
					}
				
					custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
					custom_handle->session.securityPrivProto = usmDESPrivProtocol;
					custom_handle->session.securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
					custom_handle->session.securityPrivKeyLen = USM_PRIV_KU_LEN;
					if (generate_Ku(custom_handle->session.securityAuthProto,
							custom_handle->session.securityAuthProtoLen,
							(u_char *) privacy_passwd, strlen(privacy_passwd),
							custom_handle->session.securityPrivKey,
							&(custom_handle->session.securityPrivKeyLen)) != SNMPERR_SUCCESS) {
						snmp_perror("snmp_bc");
						snmp_log(LOG_ERR,
							 "Error generating Ku from private passphrase.\n");
						dbg("Unable to establish SNMP authpriv session.");
						return NULL;
					}
					
				}
				
				if (count_per_getbulk != NULL) 
				{
					custom_handle->count_per_getbulk = atoi((char *)count_per_getbulk);
					if (custom_handle->count_per_getbulk <= 10) {
					 	custom_handle->count_per_getbulk = 10;
					}
							
				} else { 
					custom_handle->count_per_getbulk = SNMP_BC_BULK_DEFAULT;
				}

				if (context_name != NULL) 
				{
					custom_handle->session.contextName = (char *)context_name;
					custom_handle->session.contextNameLen = strlen(context_name);
				}
			}                                
                /* Configure SNMP V1 session */
		} else if (!strcmp(version, "1")) { 
			if (!community) {
				dbg("Cannot find \"community\" configuration parameter.");
				return NULL;
			}
			custom_handle->session.version = SNMP_VERSION_1;
			custom_handle->session.community = (u_char *)community;
			custom_handle->session.community_len = strlen(community);
		} else {
			dbg("Unrecognized SNMP version=%s.", version);
			return NULL;
		}
                
		/* Windows32 specific net-snmp initialization (noop on unix) */
		SOCK_STARTUP;

		custom_handle->sessp = snmp_sess_open(&(custom_handle->session));
		
		if (!custom_handle->sessp) {
			snmp_perror("ack");
			snmp_log(LOG_ERR, "Something horrible happened!!!\n");
		 	dbg("Unable to open SNMP session.");
			return NULL;
		}
		
		custom_handle->ss    = snmp_sess_session(custom_handle->sessp);

	}

	/* Determine BladeCenter chassis type */
	{
		const char *oid;
		struct snmp_value get_value;
		SaErrorT err;
		do {
			err = snmp_bc_snmp_get(custom_handle, SNMP_BC_CHASSIS_TYPE_OID, &get_value, SAHPI_FALSE);
			if (err == SA_OK) {
			        int chassis_type, chassis_subtype;
				
				chassis_type = get_value.integer;
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_CHASSIS_SUBTYPE_OID, &get_value, SAHPI_FALSE);
				if (err) {
					dbg("Cannot read model subtype");
					return NULL;
				}
				chassis_subtype = get_value.integer;

				if (chassis_type == SNMP_BC_CHASSIS_TYPE_BC &&
				    chassis_subtype == SNMP_BC_CHASSIS_SUBTYPE_ORIG) {
					trace("Found BC");
					custom_handle->platform = SNMP_BC_PLATFORM_BC;
					break;
				}

				if (chassis_type == SNMP_BC_CHASSIS_TYPE_BC &&
				    chassis_subtype == SNMP_BC_CHASSIS_SUBTYPE_H) {
					trace("Found BCH");
					custom_handle->platform = SNMP_BC_PLATFORM_BCH;
					break;
				}
				
				if (chassis_type == SNMP_BC_CHASSIS_TYPE_BCT &&
				    chassis_subtype == SNMP_BC_CHASSIS_SUBTYPE_ORIG) {
					trace("Found BCT");
					custom_handle->platform = SNMP_BC_PLATFORM_BCT;
					break;
				}

				dbg("Unknown BladeCenter model");
				return NULL;
			}
			else {  /* Older MM software doesn't support chassis type and subtype OIDs */
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_BCT, &get_value, SAHPI_FALSE);
				if (err == SA_OK) {
					trace("Found BCT");
					custom_handle->platform = SNMP_BC_PLATFORM_BCT;
					break;
				} 
				
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_BC, &get_value, SAHPI_FALSE);
				if (err == SA_OK) {
					trace("Found BC");
					custom_handle->platform = SNMP_BC_PLATFORM_BC;
					break;
				}
				
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_RSA, &get_value, SAHPI_FALSE);
				if (err == SA_OK) {
					trace("Found RSA");
					custom_handle->platform = SNMP_BC_PLATFORM_RSA;
					break;
				} 
				
				dbg("Unknown BladeCenter model");
				return NULL;
			}
		} while(0);
		
		/* Determine if daylight savings time (DST) is enabled */
		if (custom_handle->platform == SNMP_BC_PLATFORM_RSA) { oid = SNMP_BC_DST_RSA; }
		else { oid = SNMP_BC_DST; }

		err = snmp_bc_snmp_get(custom_handle, oid, &get_value, SAHPI_TRUE);
		if (err == SA_OK) {
			strcpy(custom_handle->handler_timezone, get_value.string);
		}
		else {
			dbg("Cannot read DST=%s; Error=%d.", oid, get_value.type);
			return NULL;
		}
	}

	/* Initialize "String to Event" mapping hash table */
	if (errlog2event_hash_use_count == 0) {
		if (errlog2event_hash_init(custom_handle)) {
			dbg("Out of memory.");
			return NULL;
		}
	}
	errlog2event_hash_use_count++;
	
	/* Initialize "Event Number to HPI Event" mapping hash table */
	if (event2hpi_hash_init(handle)) {
		dbg("Out of memory.");
		return NULL;
	}
  
	if (is_simulator()) {
		sim_banner(custom_handle);
	}
	
        return handle;
}
Esempio n. 29
0
int main(int argc, char *argv[])
{
	int i, n;
	
	bool wasRunning = FALSE;
	bool save_cfg = FALSE;
	bool change_settings_ui(menu_e *menu, u1_t key, bool *skip_first, cfg_t *cfg);
	bool show_ip = FALSE;
	bool config_valid, config_key = FALSE;
	bool config_ip = FALSE, config_nm = FALSE, config_gw = FALSE, config_am = FALSE;
	u4_t key;
	menu_e menu;
	int addr_mode;
	int ip[4], nm[4], gw[4], bc[4];
	
	FILE *cfp, *efp;
	char *config_file = ROOT_DIR "/.5370.config";

	cfg_t *cfg = &cfg_buf;
	
	dsp_7seg_init(FALSE);	// panic routine can't use display until bus is setup

	// silently ignores unrecognized arguments
	for (i=1; i<argc; i++) {
		if (strcmp(argv[i], "-bg") == 0) background_mode = TRUE;
		if (strcmp(argv[i], "-ip") == 0) show_ip = TRUE;
		if (strcmp(argv[i], "-no") == 0) menu_action = FALSE;

		if (strcmp(argv[i], "?")==0 || strcmp(argv[i], "-?")==0 || strcmp(argv[i], "--?")==0 || strcmp(argv[i], "-h")==0 ||
			strcmp(argv[i], "h")==0 || strcmp(argv[i], "-help")==0 || strcmp(argv[i], "--h")==0 || strcmp(argv[i], "--help")==0) {
			printf( "-rcl|-recall [name]    load key settings from named profile\n"
					"-hpib-hard    use the original HPIB hardware interface, assuming installed\n"
					"-hpib-sim     simulate the HPIB interface in software (debug mode)\n"
					"-hpib-net     simulate and re-direct transfers over an Ethernet connection\n"
					"-ip           show IP address of Ethernet interface and exit\n"
			);
			xit(0);
		}
	}
	
	lprintf("HP%s v%d.%d\n", INST_STR, FIRMWARE_VER_MAJ, FIRMWARE_VER_MIN);
    lprintf("compiled: %s %s\n", __DATE__, __TIME__);

	sim_args(TRUE, argc, argv);
	hpib_args(TRUE, argc, argv);

	sim_init();
	web_server_init();
	
	if (!menu_action) printf("menu action disabled\n");

reset:
	// To support the action of the 'reset' key most code files have a reset routine that zeros static variables.
	// This is similar to the C runtime idea of zeroing the bss when a program is first run.
	
	if (wasRunning) {
		wasRunning = FALSE;
		net_reset(NET_HPIB);
		net_reset(NET_TELNET);
		web_server_stop();
		skip_first = save_cfg = config_key = config_ip = config_nm = config_gw = config_am = FALSE;
	}

	sim_reset();

	if (!(bus_read(RREG_LDACSR) & DSR_VOK)) {
		lprintf("waiting for 5370 power\n");
		usleep(1000000);
		while (!(bus_read(RREG_LDACSR) & DSR_VOK)) {
			sched_yield();
			usleep(250000);
		}
		lprintf("5370 power on\n");
		usleep(1000000);
	} else {
		lprintf("5370 is powered on\n");
	}
	
	// display firmware version
	dsp_7seg_init(TRUE);
	dsp_7seg_str(DSP_LEFT, INST_STR, DSP_CLEAR);
	dsp_7seg_chr(POS(10), 'v');
	dsp_7seg_num(POS(11), POS_IS_LSD, FIRMWARE_VER_MAJ, DEFAULT_WIDTH, SPACE_FILL);
	dsp_7seg_num(POS(12), POS_IS_MSD, FIRMWARE_VER_MIN, FIELD_WIDTH(0), ZERO_FILL);
	dsp_7seg_dp(POS(12));
	dsp_leds_clr_all();
	delay(2000);

	if ((cfp = fopen(config_file, "r")) == NULL) {
		if (errno != ENOENT) sys_panic(config_file);
		config_valid = FALSE;
	} else {
		while (fgets(lbuf, LBUF, cfp)) {
			if ((sscanf(lbuf, "key 0x%x", &key) == 1) && (key == 0xcafe5370)) config_key = TRUE; else
			if (sscanf(lbuf, "am %d", &addr_mode) == 1) config_am = TRUE; else
			if (sscanf(lbuf, "ip %d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]) == 4) config_ip = TRUE; else
			if (sscanf(lbuf, "nm %d.%d.%d.%d", &nm[0], &nm[1], &nm[2], &nm[3]) == 4) config_nm = TRUE; else
			if (sscanf(lbuf, "gw %d.%d.%d.%d", &gw[0], &gw[1], &gw[2], &gw[3]) == 4) config_gw = TRUE; else
				;
		}
		assert((addr_mode == 0) || (addr_mode == 1));
		menu = cfg->menu = (addr_mode == 0)? M_DHCP : M_IP;
		
		if (config_key && config_ip && config_nm && config_gw && config_am) {
			printf("valid config file %s\n", config_file);
			config_valid = TRUE;

			if (menu == M_IP) {
				printf("setting interface address\n");
				sprintf(lbuf, "ifconfig eth0 %d.%d.%d.%d netmask %d.%d.%d.%d",
					ip[0], ip[1], ip[2], ip[3], nm[0], nm[1], nm[2], nm[3]);
				if (menu_action) system(lbuf);
				sprintf(lbuf, "route add default %d.%d.%d.%d", gw[0], gw[1], gw[2], gw[3]);
				if (menu_action) system(lbuf);
			}
		} else {
			printf("invalid config file %s\n", config_file);
			config_valid = FALSE;
		}
		fclose(cfp);
	}

	if (!config_valid) {
		menu = cfg->menu = M_DHCP;		// try DHCP first if not valid config
	}

#define ENET_RETRY 20

	if (menu == M_DHCP) {	// see if interface configured by DHCP
		gw[3]=gw[2]=gw[1]=gw[0]=0;	// ifconfig doesn't tell us the gateway, only the broadcast which we don't care about
		
		// sometimes the link is slow to come up, so retry a few times
		for (i=0; i<ENET_RETRY; i++) {
			if ((efp = popen("ifconfig eth0", "r")) == NULL) sys_panic("ifconfig eth0");
			char *lp = lbuf;
		
			n=0;
			while (fgets(lp, LBUF, efp)) {
				if ((n = sscanf(lp, "%*[ ]inet addr:%d.%d.%d.%d Bcast:%d.%d.%d.%d Mask:%d.%d.%d.%d",
					&ip[0], &ip[1], &ip[2], &ip[3],
					&bc[0], &bc[1], &bc[2], &bc[3],
					&nm[0], &nm[1], &nm[2], &nm[3])) == 12)
					break;
			}
			pclose(efp);
			if (n == 12) break;
			delay(1000);
		}
	} else {
		i=0;	// interface configured manually above
	}

	if (i != ENET_RETRY) {
		for (i=0; i<4; i++) {
			cfg->ip[i] = ip[i]; cfg->nm[i] = nm[i]; cfg->gw[i] = gw[i];
		}

		if (menu == M_DHCP) lprintf("via DHCP ");
		lprintf("eth0: ip %d.%d.%d.%d mask %d.%d.%d.%d ",
			ip[0], ip[1], ip[2], ip[3], nm[0], nm[1], nm[2], nm[3]);
		if (menu != M_DHCP) lprintf("gw %d.%d.%d.%d", gw[0], gw[1], gw[2], gw[3]);
		lprintf("\n");
		dsp_7seg_str(DSP_LEFT, "ip", DSP_CLEAR);
		display_ipaddr(cfg->ip);
	} else {
		lprintf("eth0: not configured from DHCP?");
		dsp_7seg_str(DSP_LEFT, "no dhcp?", DSP_CLEAR);
	}
	
	if (!config_valid && (i == ENET_RETRY)) {		// configuration not valid, DHCP failed, so set some defaults
		menu = cfg->menu = M_IP;
		bcopy(default_ipinfo, cfg->if_ipinfo, sizeof(default_ipinfo));
		save_cfg = TRUE;
	}

	if (show_ip) xit(0);
	delay(2000);	// show ip on display for a moment before continuing

	net_connect(NET_HPIB, SERVER, NULL, HPIB_TCP_PORT);
	net_connect(NET_TELNET, SERVER, NULL, TELNET_TCP_PORT);
	web_server_start();

	// place a call here to setup your measurement extension code
	meas_extend_example_init();

	// reset key held down during a reboot -- drop into menu mode
	preempt_reset_key(TRUE);

	// while in the boot routine the reset key either starts the app or saves the changed config
	app_state = S_MENU;

	while (1) {
		u1_t key;

		sim_input();	// for remote debugging of menu mode
		key = handler_dev_display_read(RREG_KEY_SCAN);	// called instead of bus_read() so simulated keys will be returned

		switch(app_state) {
	
		case S_MENU:
			if (key != KEY(RESET)) {
				app_state = S_START;
				break;
			}

			dsp_7seg_str(DSP_LEFT, "ready", DSP_CLEAR);
			printf("ready\n");
			dsp_led_set(RESET);
			wait_key_release();
			dsp_led_clr(RESET);
			dsp_7seg_str(DSP_LEFT, "chg settings", DSP_CLEAR);
			printf("menu mode\n");
			skip_first = TRUE;
			menu = M_HALT;		// first menu item displayed
			
			// light up the keys valid during menu mode
			for (i=0; settings_keys[i].key; i++) {
				dsp_led_set(settings_keys[i].key);
			}

			app_state = S_MENU_POLL;
			break;

		case S_MENU_POLL:
			if (key == KEY(RESET)) {
				dsp_led_set(RESET);
				wait_key_release();
				dsp_led_clr(RESET);
				app_state = S_MENU_DONE;
				break;
			}

			if (change_settings_ui(&menu, key, &skip_first, cfg)) save_cfg = TRUE;
			break;

		case S_MENU_DONE:
			if (!skip_first && (menu == M_HALT)) {
			
					// Debian takes a while to halt, but nicely clears the GPIOs so the
					// display goes blank right when halted.
					// Angstrom with Gnome disabled halts very fast, but doesn't
					// clear the GPIOs like Debian. So we get the PRU to poll the LEDs
					// until they go off, then blank the display.
					dsp_7seg_str(DSP_LEFT, " halting...", DSP_CLEAR);
					printf("halting...\n");
					
					#ifdef DIST_DEBIAN
						if (menu_action) system("halt");
						exit(0);
					#endif

					#ifdef DIST_ANGSTROM
						dsp_7seg_chr(POS(0), ' ');		 // preload address & data
						send_pru_cmd(PRU_HALT);
						if (menu_action) system("halt");
						exit(0);
					#endif
			} else
			if (menu == M_CANCEL || (skip_first && (menu == M_HALT))) {
				app_state = S_START;
				break;
			} else {
				if (menu != M_DHCP) menu = M_IP;
				if (menu != cfg->menu) save_cfg = TRUE;
			}

			if (save_cfg) {
				dsp_7seg_str(DSP_LEFT, "config changed", DSP_CLEAR);
				delay(2000);
				cfg->menu = menu;
			
				if (menu == M_DHCP) {
					dsp_7seg_str(DSP_LEFT, "using dhcp mode", DSP_CLEAR);
				} else {
					dsp_7seg_str(DSP_LEFT, "using ip mode", DSP_CLEAR);
				}

				delay(2000);
				dsp_7seg_str(DSP_LEFT, "saving config", DSP_CLEAR);
				if ((cfp = fopen(config_file, "w")) == NULL) sys_panic(config_file);
				printf("writing config file %s\n", config_file);
				fprintf(cfp, "key 0xcafe5370\n");
				fprintf(cfp, "am %d\n", (cfg->menu == M_DHCP)? 0:1);
				fprintf(cfp, "ip %d.%d.%d.%d\n", cfg->ip[0], cfg->ip[1], cfg->ip[2], cfg->ip[3]);
				fprintf(cfp, "nm %d.%d.%d.%d\n", cfg->nm[0], cfg->nm[1], cfg->nm[2], cfg->nm[3]);
				fprintf(cfp, "gw %d.%d.%d.%d\n", cfg->gw[0], cfg->gw[1], cfg->gw[2], cfg->gw[3]);
				fclose(cfp);

				delay(2000);
			}
			
			app_state = S_START;
			break;
		
		case S_START:
			if (wasRunning) {		// if previous sim was interrupted must reset before starting new one
				goto reset;
			}
			
			preempt_reset_key(FALSE);
			sim_main();
			preempt_reset_key(TRUE);
			handler_dev_display_read(RREG_KEY_SCAN);	// flush extra sim reset key, if any
			delay(1000);
			
			// this sim was interrupted, so can't restart a new sim without doing a reset first
			wasRunning = TRUE;

			// if key still down after one second delay enter menu mode, else treat as simple reset
			if (handler_dev_display_read(RREG_KEY_SCAN) == KEY(RESET)) {
				app_state = S_MENU;
			} else {
				goto reset;
			}
			break;
		}
	}

	return 0;
}
Esempio n. 30
0
int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        Printf("Failed to initialize SDL: %s\n", SDL_GetError());
        return -1;
    }

    VideoMode mode = {};
    mode.width = 800;
    mode.height = 600;
    mode.gl_major = 1;
    mode.gl_minor = 5;
    mode.double_buffer = 1;
    mode.depth_bits = 24;
    mode.stencil_bits = 8;
    mode.multisamples = 4;
    mode.swap_interval = 1;

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, mode.gl_major);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, mode.gl_minor);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,          mode.double_buffer);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,            mode.depth_bits);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,          mode.stencil_bits);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,    mode.multisamples>0?1:0);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,    mode.multisamples);

    mode.window = SDL_CreateWindow(
        "World Simulator",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        mode.width, mode.height,
        SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);

    if (!mode.window)
    {
        Printf("Failed to create a window: %s\n", SDL_GetError());
        return -1;
    }

    SDL_GLContext context = SDL_GL_CreateContext(mode.window);

    // Note: This must be set on a valid context
    SDL_GL_SetSwapInterval(mode.swap_interval);

    SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &mode.gl_major);
    SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &mode.gl_minor);
    SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER,          &mode.double_buffer);
    SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE,            &mode.depth_bits);
    SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE,          &mode.stencil_bits);
    SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES,    &mode.multisamples);
    mode.swap_interval = SDL_GL_GetSwapInterval();

    sim_init_msgs(false);

    ImGui_ImplSdl_Init(mode.window);

    STATE = sim_init((u32)get_tick());
    HISTORY_LENGTH = 0;

    bool running = true;
    u64 initial_tick = get_tick();
    u64 last_frame_t = initial_tick;
    r32 elapsed_time = 0.0f;
    r32 delta_time = 1.0f / 60.0f;
    while (running)
    {
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            ImGui_ImplSdl_ProcessEvent(&event);
            switch (event.type)
            {
                case SDL_WINDOWEVENT:
                {
                    switch (event.window.event)
                    {
                        case SDL_WINDOWEVENT_SIZE_CHANGED:
                        {
                            Printf("Window %d size changed to %dx%d\n",
                                    event.window.windowID,
                                    event.window.data1,
                                    event.window.data2);
                            mode.width = event.window.data1;
                            mode.height = event.window.data2;
                        } break;
                    }
                } break;

                case SDL_QUIT:
                {
                    running = false;
                } break;
            }
        }
        gui_tick(mode, elapsed_time, delta_time);
        SDL_GL_SwapWindow(mode.window);

        delta_time = time_since(last_frame_t);
        if (mode.fps_lock > 0)
        {
            r32 target_time = 1.0f / (r32)mode.fps_lock;
            r32 sleep_time = target_time - delta_time;
            if (sleep_time >= 0.01f)
                SDL_Delay((u32)(sleep_time * 1000.0f));
            delta_time = time_since(last_frame_t);
        }
        last_frame_t = get_tick();
        elapsed_time = time_since(initial_tick);

        GLenum error = glGetError();
        if (error != GL_NO_ERROR)
        {
            Printf("An error occurred: %s\n", gl_error_message(error));
            running = false;
        }
    }

    ImGui_ImplSdl_Shutdown();
    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(mode.window);
    SDL_Quit();

    return 0;
}