Ejemplo n.º 1
0
	// timer callback; used to wrest control of the system
	virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
	{
		static const UINT32 sample_instructions[] =
		{
			0x3d40f900,     // li r10,0xf9000000
			0x394af000,     // addi r10,r10,-0x1000
			0x38600146,     // li r3,0x00000146
			0x38800004,     // li r4,0x00000004
			0x7c64572c,     // sthbrx r3,r4,r10
			0x38600000,     // li r3,0x00000000
			0x986a0070      // stb r3,0x0070(r10)
		};

		// iterate over instructions
		for (int instnum = 0; instnum < ARRAY_LENGTH(sample_instructions); instnum++)
		{
			// write the instruction to execute, followed by a BLR which will terminate the
			// basic block in the DRC
			m_space->write_dword(RAM_BASE, sample_instructions[instnum]);
			m_space->write_dword(RAM_BASE + 4, 0x4e800020);

			// initialize the register state
			m_cpu->set_state_int(PPC_PC, RAM_BASE);
			for (int regnum = 0; regnum < 32; regnum++)
				m_cpu->set_state_int(PPC_R0 + regnum, regnum | (regnum << 8) | (regnum << 16) | (regnum << 24));
			m_cpu->set_state_int(PPC_CR, 0);
			m_cpu->set_state_int(PPC_LR, 0x12345678);
			m_cpu->set_state_int(PPC_CTR, 0x1000);
			m_cpu->set_state_int(PPC_XER, 0);
			for (int regnum = 0; regnum < 32; regnum++)
			{
				double value = double(regnum | (regnum << 8) | (regnum << 16) | (regnum << 24));
				m_cpu->set_state_int(PPC_F0 + regnum, d2u(value));
			}

			// output initial state
			printf("==================================================\n");
			printf("Initial state:\n");
			dump_state(true);

			// execute one instruction
			*m_cpu->m_icountptr = 0;
			m_cpu->run();

			// dump the final register state
			printf("Final state:\n");
			dump_state(false);
		}

		// all done; just bail
		throw emu_fatalerror(0, "All done");
	}
Ejemplo n.º 2
0
random_source::~random_source()
{
	if (state_file.length() > 0)
		dump_state(state_file);

	delete rng;
}
Ejemplo n.º 3
0
int _tiffCloseProc(thandle_t hdata) {
    TIFFSTATE *state = (TIFFSTATE *)hdata;

    TRACE(("_tiffCloseProc \n"));
    dump_state(state);

    return 0;
}
Ejemplo n.º 4
0
	void CServer::dump_libintegra_state()
	{
		std::cout << std::endl;
		std::cout << "Print State:" << std::endl;
		std::cout << "************" << std::endl;
		std::cout << std::endl;
		dump_state( get_nodes(), 0 );
	}
Ejemplo n.º 5
0
toff_t _tiffSizeProc(thandle_t hdata) {
    TIFFSTATE *state = (TIFFSTATE *)hdata;

    TRACE(("_tiffSizeProc \n"));
    dump_state(state);

    return (toff_t)state->size;
}
Ejemplo n.º 6
0
toff_t _tiffSeekProc(thandle_t hdata, toff_t off, int whence) {
    TIFFSTATE *state = (TIFFSTATE *)hdata;

    TRACE(("_tiffSeekProc: off: %u whence: %d \n", (uint)off, whence));
    dump_state(state);
    switch (whence) {
    case 0:
        state->loc = off;
        break;
    case 1:
        state->loc += off;
        break;
    case 2:
        state->loc = state->eof + off;
        break;
    }
    dump_state(state);
    return state->loc;
}
Ejemplo n.º 7
0
int cmd(object user, string str) {
  if (str && str != "") {
       user -> message("Usage: statedump\n");
       return FALSE;
   }

   dump_state();
   user -> message("Statedump initiated.\n");
   return TRUE;
}
Ejemplo n.º 8
0
int _tiffMapProc(thandle_t hdata, tdata_t* pbase, toff_t* psize) {
    TIFFSTATE *state = (TIFFSTATE *)hdata;

    TRACE(("_tiffMapProc input size: %u, data: %p\n", (uint)*psize, *pbase));
    dump_state(state);

    *pbase = state->data;
    *psize = state->size;
    TRACE(("_tiffMapProc returning size: %u, data: %p\n", (uint)*psize, *pbase));
    return (1);
}
Ejemplo n.º 9
0
void
dump_mbi (PMEMORY_BASIC_INFORMATION mbi)
{
  fprintf (fp, "0x%08x ", mbi->AllocationBase);
  dump_protect_flags (mbi->AllocationProtect);
  fprintf (fp, "0x%08x ", mbi->BaseAddress);
  fprintf (fp, "0x%08x ", mbi->RegionSize);
  dump_state (mbi->State);
  dump_protect_flags (mbi->Protect);
  dump_type (mbi->Type);
  fprintf (fp, "\n");
}
Ejemplo n.º 10
0
tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) {
    TIFFSTATE *state = (TIFFSTATE *)hdata;
    tsize_t to_write;

    TRACE(("_tiffWriteProc: %d \n", (int)size));
    dump_state(state);

    to_write = min(size, state->size - (tsize_t)state->loc);
    if (state->flrealloc && size>to_write) {
        tdata_t new_data;
        tsize_t newsize=state->size;
        while (newsize < (size + state->size)) {
            if (newsize > INT_MAX - 64*1024){
                return 0;
            }
            newsize += 64*1024;
            // newsize*=2; // UNDONE, by 64k chunks?
        }
        TRACE(("Reallocing in write to %d bytes\n", (int)newsize));
        /* malloc check ok, overflow checked above */
        new_data = realloc(state->data, newsize);
        if (!new_data) {
            // fail out
            return 0;
        }
        state->data = new_data;
        state->size = newsize;
        to_write = size;
    }

    TRACE(("to_write: %d\n", (int)to_write));

    _TIFFmemcpy((UINT8 *)state->data + state->loc, buf, to_write);
    state->loc += (toff_t)to_write;
    state->eof = max(state->loc, state->eof);

    dump_state(state);
    return to_write;
}
Ejemplo n.º 11
0
void *info_thrd(void *arg)
{
	sigset_t sigmask;
	struct timespec timespec = { .tv_sec = 1, .tv_nsec = 0 };
	int sig, waiting = 0;

	sigemptyset(&sigmask);
	sigaddset(&sigmask, SIGQUIT);
	sigaddset(&sigmask, SIGHUP);

	while(1) {
		if(waiting)
			sig = sigtimedwait(&sigmask, NULL, &timespec);
		else
			sig = sigwaitinfo(&sigmask, NULL);

		if(sig == -1) {
			switch(errno) {
			case EAGAIN:
				/* interval timed out */
				waiting = 0;
				/* FALLTHROUGH */
			case EINTR:
				/* if waiting, the wait will be longer, but
				   that's OK */
				continue;
			default:
				BAD_ERROR("sigtimedwait/sigwaitinfo failed "
					"because %s\n", strerror(errno));
			}
		}

		if(sig == SIGQUIT && !waiting) {
			if(pathname)
				INFO("%s\n", pathname);

			/* set one second interval period, if ^\ received
			   within then, dump queue and cache status */
			waiting = 1;
		} else
			dump_state();
	}
}


void init_info()
{
	pthread_create(&info_thread, NULL, info_thrd, NULL);
}
Ejemplo n.º 12
0
tsize_t _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) {
    TIFFSTATE *state = (TIFFSTATE *)hdata;
    tsize_t to_read;

    TRACE(("_tiffReadProc: %d \n", (int)size));
    dump_state(state);

    to_read = min(size, min(state->size, (tsize_t)state->eof) - (tsize_t)state->loc);
    TRACE(("to_read: %d\n", (int)to_read));

    _TIFFmemcpy(buf, (UINT8 *)state->data + state->loc, to_read);
    state->loc += (toff_t)to_read;

    TRACE( ("location: %u\n", (uint)state->loc));
    return to_read;
}
Ejemplo n.º 13
0
	void CServer::dump_state( const node_map &nodes, int indentation ) const 
	{
		for( node_map::const_iterator i = nodes.begin(); i != nodes.end(); i++ )
		{
			const INode *node = i->second;

			for( int i = 0; i < indentation; i++ )
			{
				std::cout << "  |";
			}

			const IInterfaceDefinition &interface_definition = node->get_interface_definition();
			string module_id_string = CGuidHelper::guid_to_string( interface_definition.get_module_guid() );
			std::cout << "  Node: \"" << node->get_name() << "\".\t module name: " << interface_definition.get_interface_info().get_name() << ".\t module id: " << module_id_string << ".\t Path: " << node->get_path().get_string() << std::endl;

			bool has_children = !node->get_children().empty();

			const node_endpoint_map &node_endpoints = node->get_node_endpoints();
			for( node_endpoint_map::const_iterator node_endpoint_iterator = node_endpoints.begin(); node_endpoint_iterator != node_endpoints.end(); node_endpoint_iterator++ )
			{
				const INodeEndpoint *node_endpoint = node_endpoint_iterator->second;
				const CValue *value = node_endpoint->get_value();
				if( !value ) continue;

				for( int i = 0; i < indentation; i++ )
				{
					std::cout << "  |";
				}

				std::cout << ( has_children ? "  |" : "   " );

				string value_string = value->get_as_string();

				std::cout << "   -Attribute:  " << node_endpoint->get_endpoint_definition().get_name() << " = " << value_string << std::endl;
			}
		
			if( has_children )
			{
				dump_state( node->get_children(), indentation + 1 );
			}
		}
	}
Ejemplo n.º 14
0
/**
 * assign data points to current centroids
 */
void update_assignments()
{
  uint      i, j, d;
  uint      nearest_centroid;
  uint64    min_dist;
  centroid  *cp, *cp_last;

  dbg("*** assigning points to centroids...\n\n");

  // clear out centroids
  for (cp = centroids, cp_last = centroids + num_clusters; cp < cp_last; cp++) {
    cp->num_points = 0;
    cp->sum_x = 0;
    cp->sum_y = 0;
  }

  // for each data point...
  for (i = 0; i < num_points; i++) {
    // find nearest centroid
    for (j = 0; j < num_clusters; j++) {
      d = distance(i, centroids[j].point_id);
      if (j == 0 || min_dist > d) {
        min_dist = d;
        nearest_centroid = j;
      }
    }

    // assign point to centroid
    point_assignments[i].centroid_id = nearest_centroid;
    point_assignments[i].distance = min_dist;

    // update centroid stats
    centroids[nearest_centroid].sum_x += datax(i);
    centroids[nearest_centroid].sum_y += datay(i);
    centroids[nearest_centroid].num_points++;
  }

  dump_state();
}
Ejemplo n.º 15
0
void CLG_(check_command)()
{
    /* check for dumps needed */
    static Char buf[512];
    static Char cmdBuffer[512];
    Char *cmdPos = 0, *cmdNextLine = 0;
    Int fd, bytesRead = 0, do_kill = 0;
    SysRes res;
    Int currentPID;
    static Int check_counter = 0;

    /* Check for PID change, i.e. whether we run as child after a fork.
     * If yes, we setup interactive control for the new process
     */
    currentPID = VG_(getpid)();
    if (thisPID != currentPID) {
	thisPID = currentPID;
	setup_control();
    }

    /* Toggle between 2 command files, with/without ".pid" postfix
     * (needed for compatibility with KCachegrind, which wants to trigger
     *  a dump by writing into a command file without the ".pid" postfix)
     */
    check_counter++;
    if (check_counter % 2) {
	current_command_file = command_file;
	current_result_file  = result_file;
    }
    else {
	current_command_file = command_file2;
	current_result_file  = result_file2;
    }
    
    res = VG_(open)(current_command_file, VKI_O_RDONLY,0);
    if (!res.isError) {
	fd = (Int) res.res;
	bytesRead = VG_(read)(fd,cmdBuffer,500);
	cmdBuffer[500] = 0; /* no command overrun please */
	VG_(close)(fd);
	/* don't delete command file on read error (e.g. EAGAIN) */
	if (bytesRead>0) {
	    cmdPos = cmdBuffer;
	}
    }

    /* force creation of result file if needed */
    fd = -2;

    while((bytesRead>0) && *cmdPos) {
      
	/* Calculate pointer for next line */
	cmdNextLine = cmdPos+1;
	while((bytesRead>0) && *cmdNextLine && (*cmdNextLine != '\n')) {
	  cmdNextLine++;
	  bytesRead--;
	}
	if ((bytesRead>0) && (*cmdNextLine == '\n')) {
	  *cmdNextLine = 0;
	  cmdNextLine++;
	  bytesRead--;
	} 

	/* Command with integer option */
	if ((*cmdPos >= '0') && (*cmdPos <='9')) {
	  int value = *cmdPos-'0';
	  cmdPos++;
	  while((*cmdPos >= '0') && (*cmdPos <='9')) {
	    value = 10*value + (*cmdPos-'0');
	    cmdPos++;
	  }
	  while((*cmdPos == ' ') || (*cmdPos == '\t')) cmdPos++;
	  
	  switch(*cmdPos) {
#if CLG_ENABLE_DEBUG
	    /* verbosity */
	  case 'V':
	  case 'v':
	    CLG_(clo).verbose = value;
	    break;
#endif
	  default:
	    break;	      
	  }

	  cmdPos = cmdNextLine;
	  continue;
	}  

	/* Command with boolean/switch option */
	if ((*cmdPos=='+') || 
	    (*cmdPos=='-')) {
	  int value = (cmdPos[0] == '+');
	  cmdPos++;
	  while((*cmdPos == ' ') || (*cmdPos == '\t')) cmdPos++;
	  
	  switch(*cmdPos) {
	  case 'I':
	  case 'i':
	    CLG_(set_instrument_state)("Command", value);
	    break;

	  default:
	    break;
	  }

	  cmdPos = cmdNextLine;
	  continue;
	}

	/* regular command */
	switch(*cmdPos) {
	case 'D':
	case 'd':
	  /* DUMP */

	  /* skip command */
	  while(*cmdPos && (*cmdPos != ' ')) cmdPos++;
	  if (*cmdPos)
	    VG_(sprintf)(buf, "Dump Command:%s", cmdPos);
	  else
	    VG_(sprintf)(buf, "Dump Command");
	  CLG_(dump_profile)(buf, False);
	  break;
	    
	case 'Z':
	case 'z':
	    CLG_(zero_all_cost)(False);
	    break;

	case 'K':
	case 'k':
	    /* Kill: Delay to be able to remove command file before. */
	    do_kill = 1;
	    break;

	case 'I':
	case 'i':
	    fd = dump_info(fd);
	    break;

	case 's':
	case 'S':
	    fd = dump_state(fd);
	    break;

	case 'O':
	case 'o':
	    /* Options Info */
	    if ( (fd = createRes(fd)) <0) break;

	    VG_(sprintf)(buf, "\ndesc: Option: --skip-plt=%s\n",
			 CLG_(clo).skip_plt ? "yes" : "no");
	    VG_(write)(fd, (void*)buf, VG_(strlen)(buf));	    
	    VG_(sprintf)(buf, "desc: Option: --collect-jumps=%s\n",
			 CLG_(clo).collect_jumps ? "yes" : "no");
	    VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
	    VG_(sprintf)(buf, "desc: Option: --separate-recs=%d\n",
			 CLG_(clo).separate_recursions);
	    VG_(write)(fd, (void*)buf, VG_(strlen)(buf));
	    VG_(sprintf)(buf, "desc: Option: --separate-callers=%d\n",
			 CLG_(clo).separate_callers);
	    VG_(write)(fd, (void*)buf, VG_(strlen)(buf));

	    break;

	default:
	  break;
	}

	cmdPos = cmdNextLine;
    }

    /* If command executed, delete command file */
    if (cmdPos) VG_(unlink)(current_command_file);
    if (fd>=0) VG_(close)(fd);	    

    if (do_kill) {
      VG_(message)(Vg_UserMsg,
		   "Killed because of command from %s", current_command_file);
      CLG_(fini)(0);
      VG_(exit)(1);
    }
}
Ejemplo n.º 16
0
int main(int argc, char const *argv[])
{
#ifdef _MEM_PROFILER
  uint8_t checkpoint_set = 0;
#endif
  fd_set rfds;
  char buffer[PIPE_BUFFER_SIZE];
  int i, n;
  Plugin plugins[MAX_PLUGINS];
  int plugins_count = 0;
  mrb_state *mrb;
  mrb_value r_output, r_plugins_list;
  mrb_sym output_gv_sym, plugins_to_load_gv_sym;
  
  printf("Version: %s\n", PROBE_VERSION);
  
  if( argc != 2 ){
    printf("Usage: %s <config_path>\n", argv[0]);
    exit(1);
  }
  
#ifdef _MEM_PROFILER
  init_profiler();
#endif
  
  config_path = argv[1];
  
  printf("Initializing core...\n");
  mrb = mrb_open_allocf(profiler_allocf, "main");
  output_gv_sym = mrb_intern_cstr(mrb, "$output");
  plugins_to_load_gv_sym = mrb_intern_cstr(mrb, "$plugins_to_load");
  setup_api(mrb);
  execute_file(mrb, "plugins/main.rb");
  execute_file(mrb, config_path);
  
  printf("Loading plugins...\n");
  r_plugins_list = mrb_gv_get(mrb, plugins_to_load_gv_sym);
  for(i = 0; i< mrb_ary_len(mrb, r_plugins_list); i++){
    char *path, tmp[100];
    int ssize;
    
    mrb_value r_plugin_name = mrb_ary_ref(mrb, r_plugins_list, i);
    const char *plugin_name = mrb_string_value_cstr(mrb, &r_plugin_name);
    
    snprintf(tmp, sizeof(tmp) - 1, "plugins/%s.rb", plugin_name);
    ssize = strlen(tmp);
    
    path = malloc(ssize + 1);
    strncpy(path, tmp, ssize);
    path[ssize] = '\0';
    
    if( access(path, F_OK) == -1 ){
      printf("cannot open plugin file \"%s\": %s\n", path, strerror(errno));
      exit(1);
    }
    
    init_plugin_from_file(&plugins[plugins_count], path, plugin_name); plugins_count++;
  }
  
  printf("Instanciating output class...\n");
  r_output = mrb_gv_get(mrb, output_gv_sym);
  interval = mrb_fixnum(mrb_funcall(mrb, r_output, "interval", 0));
  
  printf("Interval set to %dms\n", (int)interval);
  
  printf("Sending initial report...\n");
  mrb_funcall(mrb, r_output, "send_report", 0);
  
  if (mrb->exc) {
    mrb_print_error(mrb);
    
    exit(1);
  }

  
  // start all the threads
  for(i= 0; i< plugins_count; i++){
    // printf("== plugin %d\n", i);
    n = pthread_create(&plugins[i].thread, NULL, plugin_thread, (void *)&plugins[i]);
    if( n < 0 ){
      fprintf(stderr, "create failed\n");
    }
  }
  
  if( signal(SIGINT, clean_exit) == SIG_ERR){
    perror("signal");
    exit(1);
  }
  
  while(running){
    int fds[MAX_PLUGINS];
    int maxfd = 0, ai;
    struct timeval tv;
    mrb_value r_buffer;
    struct timeval cycle_started_at, cycle_completed_at;
    
    gettimeofday(&cycle_started_at, NULL);
    
    bzero(fds, sizeof(int) * MAX_PLUGINS);
    
    // ask every plugin to send their data
    for(i= 0; i< plugins_count; i++){
      strcpy(buffer, "request");
      if( send(plugins[i].host_pipe, buffer, strlen(buffer), 0) == -1 ){
        printf("send error when writing in pipe connected to plugin '%s'\n", plugins[i].name);
      }
      fds[i] = plugins[i].host_pipe;
      // printf("sent request to %d\n", i);
    }
    
    // printf("waiting answers...\n");
    // and now wait for each answer
    while(1){
      int left = 0;
      
      FD_ZERO(&rfds);
      
      for(i = 0; i< MAX_PLUGINS; i++){
        if( fds[i] != NOPLUGIN_VALUE ){
          FD_SET(fds[i], &rfds);
          left++;
          if( fds[i] > maxfd )
            maxfd = fds[i];
        }
      }
      
      // printf("left: %d %d\n", left, left <= 0);
      
      if( !running || (0 == left) )
        break;
      
      // substract 20ms to stay below the loop delay
      fill_timeout(&tv, cycle_started_at, interval - 20);
      // printf("before select\n");
      n = select(maxfd + 1, &rfds, NULL, NULL, &tv);
      // printf("after select: %d\n", n);
      if( n > 0 ){
        // find out which pipes have data
        for(i = 0; i< MAX_PLUGINS; i++){
          if( (fds[i] != NOPLUGIN_VALUE) && FD_ISSET(fds[i], &rfds) ){
            while (1){
              struct timeval answered_at;
              n = read(fds[i], buffer, sizeof(buffer));
              if( n == -1 ){
                if( errno != EAGAIN )
                  perror("read");
                break;
              }
              
              if( n == PIPE_BUFFER_SIZE ){
                printf("PIPE_BUFFER_SIZE is too small, increase it ! (value: %d)\n", PIPE_BUFFER_SIZE);
                continue;
              }
              
              gettimeofday(&answered_at, NULL);
              // printf("received answer from %s in %u ms\n", (const char *) plugins[i].mrb->ud,
              //     (uint32_t)((answered_at.tv_sec - cycle_started_at.tv_sec) * 1000 +
              //     (answered_at.tv_usec - cycle_started_at.tv_usec) / 1000)
              //   );
              
              buffer[n] = 0x00;
              
              ai = mrb_gc_arena_save(mrb);
              r_buffer = mrb_str_buf_new(mrb, n);
              mrb_str_buf_cat(mrb, r_buffer, buffer, n);
              
              // mrb_funcall(mrb, r_output, "tick", 0);
              mrb_funcall(mrb, r_output, "add", 1, r_buffer);
              check_exception("add", mrb);
              
              // pp(mrb, r_output, 0);
              
              mrb_gc_arena_restore(mrb, ai);
            }
            
            fds[i] = 0;
          }
        }
      }
      else if( n == 0 )  {
        printf("no responses received from %d plugins.\n", left);
        break;
        // timeout
      }
      else {
        perror("select");
      }
    }
    
    int idx = mrb_gc_arena_save(mrb);
    mrb_funcall(mrb, r_output, "flush", 0);
    check_exception("flush", mrb);
    mrb_gc_arena_restore(mrb, idx);
    
    // and now sleep until the next cycle
    gettimeofday(&cycle_completed_at, NULL);
    
  #ifdef _MEM_PROFILER
    if( checkpoint_set ){
      print_allocations();
    }
  #endif
    
    // force a gc run at the end of each cycle
    mrb_full_gc(mrb);
    // printf("[main] capa: %d / %d\n", mrb->arena_idx, mrb->arena_capa);
    // for(i= 0; i< plugins_count; i++){
    //   printf("[%s] capa: %d / %d\n", plugins[i].name, plugins[i].mrb->arena_idx, plugins[i].mrb->arena_capa);
    // }
  
  #ifdef _MEM_PROFILER
    checkpoint_set = 1;
    // and set starting point
    profiler_set_checkpoint();
  #endif

    
  #ifdef _MEM_PROFILER_RUBY
    // dump VMS state
    dump_state(mrb);
    for(i= 0; i< plugins_count; i++){
      dump_state(plugins[i].mrb);
    }
  #endif
    
    fflush(stdout);
    sleep_delay(&cycle_started_at, &cycle_completed_at, interval);
  }
  
  printf("Sending exit signal to all plugins...\n");
  strcpy(buffer, "exit");
  for(i= 0; i< plugins_count; i++){
    C_CHECK("send", send(plugins[i].host_pipe, buffer, strlen(buffer), 0) );
  }
  
  printf("Giving some time for threads to exit...\n\n");
  really_sleep(2000);
  
  
  for(i= 0; i< plugins_count; i++){
    int ret = pthread_kill(plugins[i].thread, 0);
    
    // if a success is returned then the thread is still alive
    // which means the thread did not acknoledged the exit message
    // kill it.
    if( ret == 0 ){
      printf("    - plugin \"%s\" failed to exit properly, killing it...\n", (const char *) plugins[i].mrb->ud);
      pthread_cancel(plugins[i].thread);
    }
    else {
      printf("    - plugin \"%s\" exited properly.\n", (const char *) plugins[i].mrb->allocf_ud);
    }
    
    if( pthread_join(plugins[i].thread, NULL) < 0){
      fprintf(stderr, "join failed\n");
    }
    
    mrb_close(plugins[i].mrb);
  }
  
  mrb_close(mrb);
  
  printf("Exited !\n");
  return 0;
}
Ejemplo n.º 17
0
void Dump_lines( const uint_8 *input, uint length )
/*************************************************/
{
    const uint_8                *p;
    const uint_8                *stmt_start;
    uint                        opcode_base;
    uint                        *opcode_lengths;
    uint                        u;
    uint                        file_index;
    const uint_8                *name;
    uint_32                     mod_time;
    uint_32                     file_length;
    uint_32                     directory;
    uint_8                      op_code;
    uint_32                     op_len;
    uint_32                     tmp;
    uint                        line_range;
    int                         line_base;
    int_32                      itmp;
    int                         default_is_stmt;
    state_info                  state;
    uint                        min_instr;
    uint_32                     unit_length;
    const uint_8                *unit_base;

    p = input;
    while( p - input < length ) {

        unit_length = get_u32( (uint_32 *)p );
        p += sizeof( uint_32 );
        unit_base = p;

        Wdputs( "total_length: " );
        Puthex( unit_length, 8 );

        Wdputslc( "\nversion: " );
        Puthex( get_u16( (uint_16 *)p ), 4 );
        p += sizeof( uint_16 );

        Wdputslc( "\nprologue_length: " );
        Puthex( get_u32( (uint_32 *)p ), 8 );
        stmt_start = p;
        stmt_start += get_u32( (uint_32 *)p );
        p += sizeof( uint_32 );
        stmt_start += sizeof( uint_32 );
        min_instr = *p;
        Wdputslc( "\nminimum_instruction_length: " );
        Puthex( min_instr, 2 );
        p += 1;

        default_is_stmt = *p;
        Wdputslc( "\ndefault_is_stmt: " );
        Puthex( default_is_stmt, 2 );
        p += 1;

        line_base = *(int_8 *)p;
        Wdputslc( "\nline_base: " );
        Puthex( line_base, 2 );
        p += 1;

        line_range = *(uint_8 *)p;
        Wdputslc( "\nline_range: " );
        Puthex( line_range, 2 );
        p += 1;

        opcode_base = *p;
        Wdputslc( "\nopcode_base: " );
        Puthex( opcode_base, 2 );
        Wdputslc( "\n" );
        p += 1;
        opcode_lengths = malloc( sizeof( uint ) * opcode_base );
        Wdputslc( "standard_opcode_lengths:\n" );
        for( u = 0; u < opcode_base - 1; ++u ) {
            opcode_lengths[ u ] = *p;
            ++p;
            Putdecl( u, 4 );
            Wdputs( ": " );
            Putdec( opcode_lengths[ u ] );
            Wdputslc( "\n" );
        }

        Wdputs( "-- current_offset = " );
        Puthex( p - input, 8 );
        Wdputslc( "\n" );

        if( p - input >= length ) return;

        Wdputslc( "include directories\n" );
        file_index = 0;
        while( *p != 0 ) {
            ++file_index;
            name = p;
            p += strlen( (char *)p ) + 1;
            Wdputs( "path " );
            Putdec( file_index );
            Wdputs( ": '" );
            Wdputs( (char *)name );
            Wdputslc( "'\n" );
            if( p - input >= length ) return;
        }
        p++;
        Wdputslc( "file names\n" );
        file_index = 0;
        while( *p != 0 ) {
            ++file_index;
            name = p;
            p += strlen( (char *)p ) + 1;
            p = DecodeULEB128( p, &directory );
            p = DecodeULEB128( p, &mod_time );
            p = DecodeULEB128( p, &file_length );
            Wdputs( "file " );
                Putdec( file_index );
            Wdputs( ": '" );
                Wdputs( (char *)name );
            Wdputs( "' directory " );
                Putdec( directory );
            Wdputs( " mod_time " );
                Puthex( mod_time, 8 );
            Wdputs( " length " );
                Puthex( file_length, 8 );
            Wdputslc( "\n" );
            if( p - input >= length ) return;
        }
        p++;
        init_state( &state, default_is_stmt );
        Wdputs( "-- current_offset = " );
        Puthex( p - input, 8 );
        if( p != stmt_start ) {
            Wdputs( ":***Prologue length off***" );
        }
        Wdputslc( "\n" );
        while( p - unit_base < unit_length ) {
            op_code = *p;
            ++p;
            if( op_code == 0 ) {
                /* extended op_code */
                p = DecodeULEB128( p, &op_len );
                Wdputs( "len: " );
                Putdecl( op_len, 3 );
                Wdputc( ' ' );
                op_code = *p;
                ++p;
                --op_len;
                switch( op_code ) {
                case DW_LNE_end_sequence:
                    Wdputslc( "END_SEQUENCE\n" );
                    state.end_sequence = 1;
                    dump_state( &state );
                    init_state( &state, default_is_stmt );
                    p+= op_len;
                    break;
                case DW_LNE_set_address:
                    Wdputs( "SET_ADDRESS " );
                    if( op_len == 4 ) {
                        tmp = get_u32( (uint_32 *)p );
                    } else if( op_len == 2 ) {
                        tmp = get_u16( (uint_16 *)p );
                    } else {
                        tmp = 0xffffffff;
                    }
                    state.address = tmp;
                    Puthex( tmp, op_len*2 );
                    Wdputslc( "\n" );
                    p += op_len;
                    break;
                case DW_LNE_set_segment:
                    Wdputs( "SET_SEGMENT " );
                    if( op_len == 4 ) {
                        tmp = get_u32( (uint_32 *)p );
                    } else if( op_len == 2 ) {
                        tmp = get_u16( (uint_16 *)p );
                    } else {
                        tmp = 0xffffffff;
                    }
                    state.segment = tmp;
                    Puthex( tmp, op_len*2 );
                    Wdputslc( "\n" );
                    p += op_len;
                    break;
                case DW_LNE_define_file:
                    ++file_index;
                    name = p;
                    p += strlen( (char *)p ) + 1;
                    p = DecodeULEB128( p, &directory );
                    p = DecodeULEB128( p, &mod_time );
                    p = DecodeULEB128( p, &file_length );
                    Wdputs( "DEFINE_FILE " );
                    Putdec( file_index );
                    Wdputs( ": '" );
                    Wdputs( (char *)name );
                    Wdputs( "' directory " );
                    Putdec( directory );
                    Wdputs( " mod_time " );
                    Puthex( mod_time, 8 );
                    Wdputs( " length " );
                    Puthex( file_length, 8 );
                    break;
                default:
                    Wdputs( "** unknown extended opcode: " );
                    Puthex( op_code, 2 );
                    Wdputslc( "\n" );
                    p += op_len;
                    break;
                }
            } else if( op_code < opcode_base ) {
                get_standard_op( op_code );
                switch( op_code ) {
                case DW_LNS_copy:
                    dump_state( &state );
                    state.basic_block = 0;
                    break;
                case DW_LNS_advance_pc:
                    p = DecodeLEB128( p, &itmp );
                    Putdec( itmp );
                    state.address += itmp * min_instr;
                    break;
                case DW_LNS_advance_line:
                    p = DecodeLEB128( p, &itmp );
                    Putdec( itmp );
                    state.line += itmp;
                    break;
                case DW_LNS_set_file:
                    p = DecodeLEB128( p, &itmp );
                    Putdec( itmp );
                    state.file = itmp;
                    break;
                case DW_LNS_set_column:
                    p = DecodeLEB128( p, &itmp );
                    Putdec( itmp );
                    state.column = itmp;
                    break;
                case DW_LNS_negate_stmt:
                    state.is_stmt = !state.is_stmt;
                    break;
                case DW_LNS_set_basic_block:
                    state.basic_block = 1;
                    break;
                case DW_LNS_const_add_pc:
                    state.address += ( ( 255 - opcode_base ) / line_range ) * min_instr;
                    break;
                case DW_LNS_fixed_advance_pc:
                    tmp = get_u16( (uint_16 *)p );
                    p += sizeof( uint_16 );
                    Puthex( tmp, 4 );
                    state.address += tmp;
                    break;
                default:
                    for( u = 0; u < opcode_lengths[ op_code - 1 ]; ++u ) {
                        p = DecodeLEB128( p, &itmp );
                        Puthex( itmp, 8 );
                    }
                }
            } else {
                Wdputs( "SPECIAL " );
                Puthex( op_code, 2 );
                op_code -= opcode_base;
                Wdputs( ": addr incr: " );
                Putdec( op_code / line_range );
                Wdputs( "  line incr: " );
                Putdec( line_base + op_code % line_range );
                state.line += line_base + op_code % line_range;
                state.address += ( op_code / line_range ) * min_instr;
                dump_state( &state );
                state.basic_block = 0;
            }
            Wdputslc( "\n" );
        }
        free( opcode_lengths  );
        Wdputs( "-- current_offset = " );
        Puthex( p - input, 8 );
        Wdputslc( "\n" );
    }
}
Ejemplo n.º 18
0
int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) {
    TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
    char *filename = "tempfile.tif";
    char *mode = "r";
    TIFF *tiff;

    /* buffer is the encoded file, bytes is the length of the encoded file */
    /*     it all ends up in state->buffer, which is a uint8* from Imaging.h */

    TRACE(("in decoder: bytes %d\n", bytes));
    TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state,
           state->x, state->y, state->ystep));
    TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize,
           state->xoff, state->yoff));
    TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes));
    TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3]));
    TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3]));
    TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n",
           im->mode, im->type, im->bands, im->xsize, im->ysize));
    TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n",
           im->image8, im->image32, im->image, im->block));
    TRACE(("Image: pixelsize: %d, linesize %d \n",
           im->pixelsize, im->linesize));

    dump_state(clientstate);
    clientstate->size = bytes;
    clientstate->eof = clientstate->size;
    clientstate->loc = 0;
    clientstate->data = (tdata_t)buffer;
    clientstate->flrealloc = 0;
    dump_state(clientstate);

    TIFFSetWarningHandler(NULL);
    TIFFSetWarningHandlerExt(NULL);

    if (clientstate->fp) {
        TRACE(("Opening using fd: %d\n",clientstate->fp));
        lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end.
        tiff = TIFFFdOpen(clientstate->fp, filename, mode);
    } else {
        TRACE(("Opening from string\n"));
        tiff = TIFFClientOpen(filename, mode,
                              (thandle_t) clientstate,
                              _tiffReadProc, _tiffWriteProc,
                              _tiffSeekProc, _tiffCloseProc, _tiffSizeProc,
                              _tiffMapProc, _tiffUnmapProc);
    }

    if (!tiff){
        TRACE(("Error, didn't get the tiff\n"));
        state->errcode = IMAGING_CODEC_BROKEN;
        return -1;
    }

    if (clientstate->ifd){
        int rv;
        uint32 ifdoffset = clientstate->ifd;
        TRACE(("reading tiff ifd %u\n", ifdoffset));
        rv = TIFFSetSubDirectory(tiff, ifdoffset);
        if (!rv){
            TRACE(("error in TIFFSetSubDirectory"));
            return -1;
        }
    }

    if (TIFFIsTiled(tiff)) {
        UINT32 x, y, tile_y, row_byte_size;
        UINT32 tile_width, tile_length, current_tile_width;
        UINT8 *new_data;

        TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width);
        TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length);

        // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size
        row_byte_size = (tile_width * state->bits + 7) / 8;
        state->bytes = row_byte_size * tile_length;

        /* overflow check for malloc */
        if (state->bytes > INT_MAX - 1) {
            state->errcode = IMAGING_CODEC_MEMORY;
            TIFFClose(tiff);
            return -1;
        }

        /* realloc to fit whole tile */
        new_data = realloc (state->buffer, state->bytes);
        if (!new_data) {
            state->errcode = IMAGING_CODEC_MEMORY;
            TIFFClose(tiff);
            return -1;
        }

        state->buffer = new_data;

        TRACE(("TIFFTileSize: %d\n", state->bytes));

        for (y = state->yoff; y < state->ysize; y += tile_length) {
            for (x = state->xoff; x < state->xsize; x += tile_width) {
                if (ReadTile(tiff, x, y, (UINT32*) state->buffer) == -1) {
                    TRACE(("Decode Error, Tile at %dx%d\n", x, y));
                    state->errcode = IMAGING_CODEC_BROKEN;
                    TIFFClose(tiff);
                    return -1;
                }

                TRACE(("Read tile at %dx%d; \n\n", x, y));

                current_tile_width = min(tile_width, state->xsize - x);

                // iterate over each line in the tile and stuff data into image
                for (tile_y = 0; tile_y < min(tile_length, state->ysize - y); tile_y++) {
                    TRACE(("Writing tile data at %dx%d using tile_width: %d; \n", tile_y + y, x, current_tile_width));

                    // UINT8 * bbb = state->buffer + tile_y * row_byte_size;
                    // TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));

                    state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize,
                       state->buffer + tile_y * row_byte_size,
                       current_tile_width
                    );
                }
            }
        }
    } else {
        UINT32 strip_row, row_byte_size;
        UINT8 *new_data;
        UINT32 rows_per_strip;

        TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip);
        TRACE(("RowsPerStrip: %u \n", rows_per_strip));

        // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size
        row_byte_size = (state->xsize * state->bits + 7) / 8;
        state->bytes = rows_per_strip * row_byte_size;

        TRACE(("StripSize: %d \n", state->bytes));

        /* realloc to fit whole strip */
        new_data = realloc (state->buffer, state->bytes);
        if (!new_data) {
            state->errcode = IMAGING_CODEC_MEMORY;
            TIFFClose(tiff);
            return -1;
        }

        state->buffer = new_data;

        for (; state->y < state->ysize; state->y += rows_per_strip) {
            if (ReadStrip(tiff, state->y, (UINT32 *)state->buffer) == -1) {
                TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0)));
                state->errcode = IMAGING_CODEC_BROKEN;
                TIFFClose(tiff);
                return -1;
            }

            TRACE(("Decoded strip for row %d \n", state->y));

            // iterate over each row in the strip and stuff data into image
            for (strip_row = 0; strip_row < min(rows_per_strip, state->ysize - state->y); strip_row++) {
                TRACE(("Writing data into line %d ; \n", state->y + strip_row));

                // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip);
                // TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3]));

                state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] +
                               state->xoff * im->pixelsize,
                               state->buffer + strip_row * row_byte_size,
                               state->xsize);
            }
        }
    }

    TIFFClose(tiff);
    TRACE(("Done Decoding, Returning \n"));
    // Returning -1 here to force ImageFile.load to break, rather than
    // even think about looping back around.
    return -1;
}
Ejemplo n.º 19
0
// return true if current position in record is valid and usable
bool
site_crawler::
process_record_line(char* line)
{
    static const unsigned MAX_WORD(50);

    // do a low-level tab parse:
    {
        char* p(line);
        _word[0]=p;
        _n_word=1;
        while (true) {
            if ((*p == '\n') || (*p == '\0')) break;
            if (*p == sep) {
                *p = '\0';
                _word[_n_word++] = p+1;
                if (_n_word == MAX_WORD) break;
            }
            ++p;
        }
        // allow for optional extra columns in each file format:
        if (_n_word<_opt.sti().col_count()) {
            log_os << "ERROR: Consensus record has " << _n_word << " column(s) but expecting at least " << _opt.sti().col_count() << "\n";
            dump_state(log_os);
            exit(EXIT_FAILURE);
        }
    }

    const vcf_pos last_vpos(vpos());
    _chrom=_opt.sti().chrom(_word);
    _vpos.pos=_opt.sti().pos(_word);

    _is_site_allele_current=false;
    _is_indel_allele_current=false;

    _vpos.is_indel=(_opt.sti().get_is_indel(_word));

    if (pos()<1) {
        log_os << "ERROR: gvcf record position less than 1. position: " << pos() << " ";
        dump_state(log_os);
        exit(EXIT_FAILURE);
    }

    if (_opt.is_region()) {
        // deal with vcf records after the region of interest:
        if (pos()>_opt.region_end) {
            _is_sample_begin_state = false;
            _is_sample_end_state = true;
            return true;
        }
    } else {
        if (pos()>static_cast<pos_t>(_ref_seg.end())) {
            log_os << "ERROR: allele file position exceeds final position in reference sequence segment . position: "
                   << pos() << " ref_contig_end: " << _ref_seg.end() << "\n";
            dump_state(log_os);
            exit(EXIT_FAILURE);
        }
    }

    if (! _opt.sti().get_nonindel_ref_length(pos(),is_indel(),_word,_locus_size)) {
        //log_os << "ERROR: failed to parse locus at pos: "  << pos << "\n";
        log_os << "WARNING: failed to parse locus at: "  << vpos() << "\n";
        dump_state(log_os);
        //exit(EXIT_FAILURE);
        _locus_size=0;
    }

    _locus_offset=0;

    // deal with vcf records which fully proceed the region of interest:
    if (_opt.is_region()) {
        if ((pos()+_locus_size-1)<_opt.region_begin) return false;
    }

    //const bool last_is_call(is_call);
    _is_call = _opt.sti().get_is_call(_word,pos(),_skip_call_begin_pos,_skip_call_end_pos);

    _n_total = _opt.sti().total(_word);

    if (is_indel()) {
        if (! _is_return_indels)
        {
            _vpos.pos=last_vpos.pos;
            _locus_size=0;
            return false;
        }
        else
        {
            _locus_size=0;
        }
    }

    if (is_any_call()) {
        _is_call=update_allele();
    }

    // don't allow failed block read-through, so that we can get through indel-overlap errors
    //if(! is_call) {
    //    if(_locus_size>1) _locus_size=1;
    //}

    if (! _is_sample_begin_state) {
        if (! (last_vpos < vpos()) ) {
            if (_opt.is_murdock_mode) {
                _vpos=last_vpos;
                _locus_size=0;
                return false;
            } else {
                log_os << "ERROR: unexpected position order in variant file. current_pos: "
                       << pos() << " last " << last_vpos << "\n";
                dump_state(log_os);
                exit(EXIT_FAILURE);
            }
        }
    } else {
        _is_sample_begin_state=false;
    }

    // deal with vcf records which partially overlap the region of interest:
    if (_opt.is_region()) {
        if (pos()<_opt.region_begin) return false;
    }

    return true;
}
Ejemplo n.º 20
0
void test_inv_tbox()
{
	tbox_mixing_bijections_t tbox_mixing_bijections, inv_tbox_mixing_bijections;
	tbox_t tbox;
	uint32_t expanded_key[(NR + 1) * 4];
	uint8_t state[4][4];
	uint8_t state2[4][4];
	int round, row, col, i;

	make_tbox_mixing_bijections(tbox_mixing_bijections,
			inv_tbox_mixing_bijections);

	for (i = 0; i < (NR + 1) * 4; ++i)
		expanded_key[i] = (uint8_t) rand(); /*  identity key expansion */
	make_inv_tbox(tbox, ISBox, expanded_key, tbox_mixing_bijections);

	for (round = NR - 1; round != 1; --round) {
		printf("round: %d \n", round);
		randomize_state(state);
		memcpy(&state2[0][0], &state[0][0], 16); /*  for validation */

		dump_state("State before ", state);
		inv_shift_rows(state);
		for (row = 0; row < 4; ++row) {
			for (col = 0; col < 4; ++col) {
				state[row][col] = tbox[round][row][col][(state[row][col])];
			}
		}
		dump_state("State after TBox ", state);
		/*  validation */
		/*  The above should be equal to: */
		/*  0. mix */
		/* 	1. addroundkey */
		/*  2. subbytes */
		/* 	3. shiftrows */

		for (row = 0; row < 4; ++row) {
			for (col = 0; col < 4; ++col) {
				mul_byte_by_matrix(&state2[row][col],
						tbox_mixing_bijections[round][row][col],
						state2[row][col]);
			}
		}
		add_round_key(state2, expanded_key, round+1);
		inv_sub_bytes(state2, ISBox);
		inv_shift_rows(state2);

		dump_state("Validation State ", state2);
		ASSERT(comp_states(state, state2));
	}
	/*  validation for the last round is different */
	round = 0;
	{
		printf("rounds 9 and 10\n");
		randomize_state(state);
		memcpy(&state2[0][0], &state[0][0], 16); /*  for validation */

		dump_state("State before ", state);
		inv_shift_rows(state);
		for (row = 0; row < 4; ++row) {
			for (col = 0; col < 4; ++col) {
				state[row][col] = tbox[round][row][col][(state[row][col])];
			}
		}
		dump_state("State after TBox ", state);
		/*  validation */
		/*  The above should be equal to: */
		/*  0. mix */
		/* 	1. addroundkey */
		/*  2. subbytes */
		/* 	3. shiftrows */
		/* 	4. addroundkey */

		for (row = 0; row < 4; ++row) {
			for (col = 0; col < 4; ++col) {
				mul_byte_by_matrix(&state2[row][col],
						tbox_mixing_bijections[round][row][col],
						state2[row][col]);
			}
		}
		add_round_key(state2, expanded_key, 1);
		inv_sub_bytes(state2, ISBox);
		inv_shift_rows(state2);
		add_round_key(state2, expanded_key, 0); /*  the last key */

		dump_state("Validation State ", state2);
		ASSERT(comp_states(state, state2));
	}
	free_tbox_mixing_bijections(tbox_mixing_bijections);
	free_tbox_mixing_bijections(inv_tbox_mixing_bijections);
}
Ejemplo n.º 21
0
void
site_crawler::
update(bool is_store_header) {
    if (_is_sample_end_state) return;


    // move on to a new locus:
    while (true) {
        // continue crawling through a multibase locus:
        //
        // at present (201202) this only means compressed block
        // entries in gVCF -- long indels should be skipped over
        // rather than walked
        //
        _locus_offset++;
        if (_locus_offset < _locus_size) {
            // check for pos moving past the end of region of interest:
            if (_opt.is_region()) {
                if ((pos()+1)>(_opt.region_end)) {
                    _is_sample_begin_state = false;
                    _is_sample_end_state = true;
                    return;
                }
            }

            _vpos.pos++;

            if (_opt.is_region()) {
                // check for pos preceding the start of region of interest in a multi-base record:
                if (pos()<_opt.region_begin) {
                    continue;
                }
            }

            if (pos()>static_cast<pos_t>(_ref_seg.end())) {
                log_os << "ERROR: allele file position exceeds final position in reference sequence segment. position: "
                       << pos() << " ref_contig_end: " << _ref_seg.end() << "\n";
                dump_state(log_os);
                exit(EXIT_FAILURE);
            }

            if (is_site_call()) {
                const char ref_base=_ref_seg.get_base(pos()-1);
                if (! _opt.sti().get_site_allele(_site_allele,_word,_locus_offset,ref_base)) {
                    log_os << "ERROR: Failed to read site genotype from record:\n";
                    dump_state(log_os);
                    exit(EXIT_FAILURE);
                }
            }
            return;
        }

        // start new/next file:
        if (NULL == _tabs) {
            if (_next_file >= 1) {
                _is_sample_begin_state = false;
                _is_sample_end_state = true;
                return;
            }
            const std::string& afile(_si.file);
            if (0 == _next_file) {
                // open a separate header streamer to get sample_name and optional header capture:
                tabix_header_streamer ths(afile.c_str());
                while (ths.next()) {
                    const char* line(ths.getline());
                    if (NULL == line) break;
                    if (is_store_header) {
                        _header.push_back(line);
                    }
                    if (_sample_name.empty() && boost::starts_with(line,"#CHROM")) {
                        std::vector<std::string> words;
                        split_string(line,'\t',words);
                        if (words.size()>VCFID::SAMPLE) {
                            _sample_name = words[VCFID::SAMPLE];
                        } else {
                            _sample_name = "UNKNOWN";
                        }
                    }
                }
            }
            _tabs=new tabix_streamer(afile.c_str(),_chr_region);
            if (! _tabs) {
                log_os << "ERROR:: Can't open gvcf file: " << afile << "\n";
                exit(EXIT_FAILURE);
            }
            _next_file++;
        }

        // read through file to get to a data line:
        bool is_eof(true);
        char* line(NULL);
        while (_tabs->next()) {
            line=_tabs->getline();
            if (NULL == line) break;
            assert(strlen(line));
            if (line[0] == '#') continue;
            is_eof=false;
            break;
        }

        if (! is_eof) {
            const bool is_valid=process_record_line(line);
            if (is_valid) return;
        } else {
            // if eof, go to next file or terminate:
            delete _tabs;
            _tabs=NULL;
        }
    }
}
Ejemplo n.º 22
0
int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) {
    /* One shot encoder. Encode everything to the tiff in the clientstate.
       If we're running off of a FD, then run once, we're good, everything
       ends up in the file, we close and we're done.

       If we're going to memory, then we need to write the whole file into memory, then
       parcel it back out to the pystring buffer bytes at a time.

    */

    TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
    TIFF *tiff = clientstate->tiff;

    TRACE(("in encoder: bytes %d\n", bytes));
    TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state,
           state->x, state->y, state->ystep));
    TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize,
           state->xoff, state->yoff));
    TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes));
    TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3]));
    TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3]));
    TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n",
           im->mode, im->type, im->bands, im->xsize, im->ysize));
    TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n",
           im->image8, im->image32, im->image, im->block));
    TRACE(("Image: pixelsize: %d, linesize %d \n",
           im->pixelsize, im->linesize));

    dump_state(clientstate);

    if (state->state == 0) {
        TRACE(("Encoding line bt line"));
        while(state->y < state->ysize){
            state->shuffle(state->buffer,
                           (UINT8*) im->image[state->y + state->yoff] +
                           state->xoff * im->pixelsize,
                           state->xsize);

            if (TIFFWriteScanline(tiff, (tdata_t)(state->buffer), (uint32)state->y, 0) == -1) {
                TRACE(("Encode Error, row %d\n", state->y));
                state->errcode = IMAGING_CODEC_BROKEN;
                TIFFClose(tiff);
                if (!clientstate->fp){
                    free(clientstate->data);
                }
                return -1;
            }
            state->y++;
        }

        if (state->y == state->ysize) {
            state->state=1;

            TRACE(("Flushing \n"));
            if (!TIFFFlush(tiff)) {
                TRACE(("Error flushing the tiff"));
                // likely reason is memory.
                state->errcode = IMAGING_CODEC_MEMORY;
                TIFFClose(tiff);
                if (!clientstate->fp){
                    free(clientstate->data);
                }
                return -1;
            }
            TRACE(("Closing \n"));
            TIFFClose(tiff);
            // reset the clientstate metadata to use it to read out the buffer.
            clientstate->loc = 0;
            clientstate->size = clientstate->eof; // redundant?
        }
    }

    if (state->state == 1 && !clientstate->fp) {
        int read = (int)_tiffReadProc(clientstate, (tdata_t)buffer, (tsize_t)bytes);
        TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3]));
        if (clientstate->loc == clientstate->eof) {
            TRACE(("Hit EOF, calling an end, freeing data"));
            state->errcode = IMAGING_CODEC_END;
            free(clientstate->data);
        }
        return read;
    }

    state->errcode = IMAGING_CODEC_END;
    return 0;
}
Ejemplo n.º 23
0
int main(int argc, const char * argv[])
{
    if(2 != argc) {
        printf("Usage: ./chip8 filename\n");
        return 1;
    }

    // This should be the file to load
    const char* filename = argv[1];

    // Init the system
    chip8* cpu = (chip8 *) malloc(sizeof(chip8));
    initialize(cpu);
    initialize_sdl();

    SDL_Window* window;
    SDL_Renderer* renderer;
    if(SDL_CreateWindowAndRenderer(640, 320, SDL_WINDOW_SHOWN, &window, &renderer) == -1) {
        printf("Failed to generate SDL video, %s", SDL_GetError());
        SDL_Quit();
    }

    // Load the specified game
    load_game(cpu, filename);

    int quit = 0;
    Uint32 delay = 2;
    while(!quit) {
        Uint32 timeout = SDL_GetTicks() + 16;
        while (!SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) {

            // Debugging to dump the state of the emulator
            dump_state(cpu);

            SDL_Event event;
            // Consume key queue
            while (SDL_PollEvent(&event) != 0) {
                //User requests quit
                if (event.type == SDL_QUIT) {
                    quit = 1;
                } else if(event.type == SDL_KEYDOWN) {
                    switch(event.key.keysym.sym) {
                        case SDLK_RIGHT:
                            delay += 10;
                            break;
                        case SDLK_LEFT:
                            if(delay<11) {
                                delay = 1;
                            } else {
                                delay-=10;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }

            process_delayRegister(cpu);
            process_soundRegister(cpu);

            // Execute the next instruction
            uint16_t opcode = fetch(cpu);
            execute(cpu, opcode);

            SDL_Delay(delay);
            printf("Delay=%d\n", delay);
        }

        // Draw the state of the world
        if(cpu->shouldDraw) {
            render(cpu, window, renderer);
            cpu->shouldDraw = false;
        }

    }

    deinitialize_sdl();

    return 0;
}
Ejemplo n.º 24
0
/**
 * pick new centroids based on mean coordinates in the cluster
 */
void update_centroids()
{
  uint        i, a, b;
  uint        *dp;
  uint64      d;
  float       k;
  assignment  *ap;
  centroid    *cp, *cp_last;

  dbg("*** updating centroids...\n\n");

  // initialize
  for (cp = centroids, cp_last = centroids + num_clusters; cp < cp_last; cp++) {
    cp->target_x = cp->sum_x / cp->num_points;
    cp->target_y = cp->sum_y / cp->num_points;
    cp->prev_distance = cp->best_distance;
    cp->best_distance = BIG_NUM;
  }

  #ifdef DEBUG
  for (i = 0, cp = centroids, cp_last = centroids + num_clusters; cp < cp_last; i++, cp++) {
    a = datax(cp->point_id) - cp->target_x;
    b = datay(cp->point_id) - cp->target_y;
    dbg("old centroid %d (%d, %d), target = (%.1lf, %.1lf), distance = %d\n", i, datax(cp->point_id), datay(cp->point_id), cp->target_x, cp->target_y, a * a + b * b);
  }
  #endif

  // go through points; for each respective centroid, find the
  // point closest to the target new centroid
  for (i = 0, ap = point_assignments, dp = data_points; i < num_points; i++, ap++, dp += 2) {
    // get my centroid
    cp = centroids + ap->centroid_id;

    // calculate distance to target
    a = *dp - cp->target_x;
    b = *(dp + 1) - cp->target_y;
    d = a * a + b * b;

    // new closest point?
    if (cp->best_distance > d) {
      cp->best_distance = d;
      cp->point_id = i;
    }
  }

  // check improvement
  improved = 0;
  improvement = 0.0;
  for (i = 0, cp = centroids; i < num_clusters; i++, cp++) {
    dbg("new centroid %d (%d, %d), distance: %ld => %ld", i, datax(cp->point_id), datay(cp->point_id), cp->prev_distance, cp->best_distance);
    if (cp->prev_distance) {
      k = ((float)cp->best_distance - (float)cp->prev_distance) / (float)cp->prev_distance;
      improvement += fabs(k);
      improved++;
      dbg(" (%.3f%%)", 100.0 * k);
    }
    dbg("\n");
  }
  dbg("\n");

  dump_state();
}
Ejemplo n.º 25
0
int
main(int argc, char *argv[])
{
  struct QOP_MDWF_State *mdwf_state = NULL;
  QMP_thread_level_t qt = QMP_THREAD_SINGLE;
  int status = 1;
  int vx[4];
  int i;

  if (QMP_init_msg_passing(&argc, &argv, qt, &qt) != QMP_SUCCESS) {
    fprintf(stderr, "QMP_init() failed\n");
    return 1;
  }

  for (i = 0; i < NELEM(b5); i++) {
    b5[i] = 0.1 * i * (NELEM(b5) - i);
    c5[i] = 0.1 * i * i * (NELEM(b5) - i);
  }

  self = QMP_get_node_number();
  primary = QMP_is_primary_node();
  for (i = 0; i < argc; i++)
    zprint("arg[%d]=%s", i, argv[i]);
  if (argc != 14) {
    zprint("14 arguments expected, found %d", argc);
    QMP_finalize_msg_passing();
    return 1;
  }

  for (i = 0; i < 4; i++) {
    mynetwork[i] = atoi(argv[i+1]);
    mylocal[i] = atoi(argv[i+5]);
    vx[i] = atoi(argv[i+10]);
    mylattice[i] = mylocal[i] * mynetwork[i];
  }
  mylocal[4] = mylattice[4] = atoi(argv[9]);

  zshowv4("network", mynetwork);
  zshowv5("local lattice", mylocal);
  zshowv5("lattice", mylattice);

  getv(mynode, 0, 4, vx);

  xshowv("node", mynode);

  if (QOP_MDWF_init(&mdwf_state,
		    mylattice, mynetwork, mynode, primary,
		    getsub, NULL)) {
    zprint("MDWF_init() failed");
    goto end;
  }

  zprint("MDWF_init() done");

  dump_state(mdwf_state);

  QOP_MDWF_fini(&mdwf_state);

  status = 0;
 end:
  QMP_finalize_msg_passing();
  return status;
}
Ejemplo n.º 26
0
int main(int argc, char **argv)
{
  uint        i, j, x, y;
  double      distance_mean, distance_sum;
  float       average_improvement;
  assignment  *ap, *ap_last;
  centroid    *cp;

  // usage: ./kmeans /path/to/file num_points num_clusters max_iterations
  input_file_name = argv[1];
  num_points = atoi(argv[2]);
  num_clusters = atoi(argv[3]);
  max_iterations = (argc > 4 ? atoi(argv[4]) : 20);
  dbg("file: %s, num_points: %d, num_clusters: %d\n\n", argv[1], num_points, num_clusters);

  setup_data_points();
  setup_assignments();
  setup_centroids();

  dump_state();

  for (uint i = 0; i < max_iterations; i++) {
    dbg("================ ITERATION %d ================\n\n", i);
    update_assignments();
    update_centroids();
    if (improved) {
      average_improvement = improvement / improved;
      dbg("average improvement: %.1f\n\n", 100.0 * average_improvement);

      // done if average improvement is less than 0.1%
      if (average_improvement < 0.001)
        break;
    }
  }

  dbg("================ DONE! ================\n\n");
  dump_state();

  // dump final centroids, FORMAT: x, y, num points, p:c distance std dev
  // calculate standard deviation of point-to-centroid distances
  for (i = 0, cp = centroids; i < num_clusters; i++, cp++) {
    // centroid coords
    x = datax(cp->point_id);
    y = datay(cp->point_id);

    if (cp->num_points <= 1) {
      printf("%d\t%d\t%d\t0.0\n", x, y, cp->num_points);
    } else {
      // calculate mean distance
      distance_sum = 0.0;
      for (j = 0, ap = point_assignments, ap_last = point_assignments + num_points; ap < ap_last; j++, ap++) {
        if (ap->centroid_id != i) continue;
        distance_sum += sqrt(ap->distance);
      }
      distance_mean = distance_sum / cp->num_points;

      // calculate summation for sample variance
      distance_sum = 0.0;
      for (ap = point_assignments, ap_last = point_assignments + num_points; ap < ap_last; ap++) {
        if (ap->centroid_id != i) continue;
        distance_sum += pow2(sqrt(ap->distance) - distance_mean);
      }

      printf("%d\t%d\t%d\t%.1lf\n", x, y, cp->num_points, sqrt(distance_sum / (cp->num_points - 1)));
    }
  }

  return 0;
}
Ejemplo n.º 27
0
void test_decryption()
{
	gf2matrix *mix_columns_mixing_bijection, *inv_mix_columns_mixing_bijection;
	tbox_mixing_bijections_t tbox_mixing_bijections, inv_tbox_mixing_bijections;
	gf2matrix *initial_encoding, *initial_decoding;
	gf2matrix *final_encoding, *final_decoding;
	tbox_t tbox;
	typeIA_t typeIAs;
	typeII_t typeIIs;
	typeIII_t typeIIIs;
	typeIB_t typeIBs;
	typeIV_IA_t typeIV_IAs;
	typeIV_IB_t typeIV_IBs;
	typeIV_II_round_t typeIV_IIs[NR - 1];
	typeIV_III_round_t typeIV_IIIs[NR - 1];
	uint32_t mixed_key_schedule[4 * (NR + 1)];
	uint8_t key[KEY_SIZE] = {
			0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
			0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c};
	sboxes_8bit_t typeIA_input_sbox, typeIA_input_sbox_inv;
	sboxes_128bit_t typeIA_interim_sbox, typeIA_interim_sbox_inv;
	sboxes_8bit_t typeII_input_sbox[NR], typeII_input_sbox_inv[NR];
	sboxes_32bit_t typeII_interim_sbox[NR - 1], typeII_interim_sbox_inv[NR - 1];
	sboxes_8bit_t typeII_output_sbox[NR - 1], typeII_output_sbox_inv[NR - 1];
	sboxes_32bit_t typeIII_interim_sbox[NR - 1], typeIII_interim_sbox_inv[NR
			- 1];
	sboxes_128bit_t typeIB_interim_sbox, typeIB_interim_sbox_inv;
	sboxes_8bit_t typeIB_output_sbox, typeIB_output_sbox_inv;
	uint8_t state[4][4];
	uint8_t in[16];
	uint8_t out[16], out2[16];
	_4bit_strip32_t strips32;
	_4bit_strip128_t strips128;
	int round, row, col, i;

	int tries = 3;
	for (; tries != 0; --tries) {
		randomize_key(key);
		make_block_invertible_matrix_pair(&mix_columns_mixing_bijection,
				&inv_mix_columns_mixing_bijection, 32);
/* 		mix_columns_mixing_bijection = make_identity_matrix(32); */
/* 		inv_mix_columns_mixing_bijection = make_identity_matrix(32); */
		make_tbox_mixing_bijections(tbox_mixing_bijections,
				inv_tbox_mixing_bijections);
/* 		make_identity_tbox_mixing_bijections(tbox_mixing_bijections); */
/* 		make_identity_tbox_mixing_bijections(inv_tbox_mixing_bijections); */

		make_block_invertible_matrix_pair(&initial_encoding, &initial_decoding, 128);
/* 		initial_encoding = make_identity_matrix(128); */
/* 		initial_decoding = make_identity_matrix(128); */
		make_block_invertible_matrix_pair(&final_encoding, &final_decoding, 128);
/* 		final_encoding = make_identity_matrix(128); */
/* 		final_decoding = make_identity_matrix(128); */

		expand_key(key, SBox, mixed_key_schedule, 4);
		mix_expanded_key(mixed_key_schedule);
		make_inv_tbox(tbox, ISBox, mixed_key_schedule, tbox_mixing_bijections);

		make_sbox_pair_8(typeIA_input_sbox, typeIA_input_sbox_inv);
/* 		make_identity_sboxes8(typeIA_input_sbox); */
/* 		make_identity_sboxes8(typeIA_input_sbox_inv); */
		make_sbox_pair_128(typeIA_interim_sbox, typeIA_interim_sbox_inv);
/* 		make_identity_sboxes128(typeIA_interim_sbox); */
/* 		make_identity_sboxes128(typeIA_interim_sbox_inv); */
		make_rounds_sbox_pair_8(typeII_input_sbox, typeII_input_sbox_inv, NR);
/* 		for(i =0; i < NR; ++i) { */
/* 			make_identity_sboxes8(typeII_input_sbox[i]); */
/* 			make_identity_sboxes8(typeII_input_sbox_inv[i]); */
/* 		} */
		make_rounds_sbox_pair_32(typeII_interim_sbox, typeII_interim_sbox_inv,
				NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes32(typeII_interim_sbox[i]); */
/* 			make_identity_sboxes32(typeII_interim_sbox_inv[i]); */
/* 		} */
		make_rounds_sbox_pair_8(typeII_output_sbox, typeII_output_sbox_inv, NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes8(typeII_output_sbox[i]); */
/* 			make_identity_sboxes8(typeII_output_sbox_inv[i]); */
/* 		} */

		make_rounds_sbox_pair_32(typeIII_interim_sbox, typeIII_interim_sbox_inv,
				NR - 1);
/* 		for(i =0; i < NR-1; ++i) { */
/* 			make_identity_sboxes32(typeIII_interim_sbox[i]); */
/* 			make_identity_sboxes32(typeIII_interim_sbox_inv[i]); */
/* 		} */
		make_sbox_pair_128(typeIB_interim_sbox, typeIB_interim_sbox_inv);
/* 		make_identity_sboxes128(typeIB_interim_sbox); */
/* 		make_identity_sboxes128(typeIB_interim_sbox_inv); */
		make_sbox_pair_8(typeIB_output_sbox, typeIB_output_sbox_inv);
/* 		make_identity_sboxes8(typeIB_output_sbox); */
/* 		make_identity_sboxes8(typeIB_output_sbox_inv); */


		make_typeIA(typeIAs, inv_tbox_mixing_bijections[NR - 1], initial_decoding,
				typeIA_input_sbox_inv, typeIA_interim_sbox);
		make_typeIV_IA(typeIV_IAs, typeIA_interim_sbox_inv,
				typeII_input_sbox[NR - 1], typeII_input_sbox_inv[NR-1]);
		make_inv_typeII(typeIIs, tbox, mix_columns_mixing_bijection,
				&typeII_input_sbox_inv[1], typeII_interim_sbox);
		make_typeIV_II(typeIV_IIs, typeII_interim_sbox_inv, typeII_output_sbox,
				typeII_output_sbox_inv);
		make_typeIII(typeIIIs, inv_mix_columns_mixing_bijection,
				inv_tbox_mixing_bijections, typeII_output_sbox_inv,
				typeIII_interim_sbox);
		make_typeIV_III(typeIV_IIIs, typeIII_interim_sbox_inv,
				typeII_input_sbox, typeII_input_sbox_inv);
		make_inv_typeIB(typeIBs, tbox[0], final_encoding,
				typeII_input_sbox_inv[0], typeIB_interim_sbox);
		make_typeIV_IB(typeIV_IBs, typeIB_interim_sbox_inv, typeIB_output_sbox,
				typeIB_output_sbox_inv);

		for (i = 0; i < 16; ++i) {
			in[i] = rand();
		}
		dump_hex("input: ", in, 16);
		printf("White-box inverse cipher:\n");
		do_input(state, in, initial_encoding, typeIA_input_sbox);

		dump_state("State before ", state);
		do_typeIA(strips128, state, typeIAs);
		do_typeIV_IA(state, strips128, typeIV_IAs);
		for (round = NR - 2; round != -1; --round) {
			printf("round %d: ", round + 2);
			dump_state("", state);
			inv_shift_rows(state);
			do_typeII(strips32, state, typeIIs[round]);
			do_typeIV_II(state, strips32, typeIV_IIs[round]);
			do_typeIII(strips32, state, typeIIIs[round]);
			do_typeIV_III(state, strips32, typeIV_IIIs[round]);
		}
		inv_shift_rows(state);
		dump_state("rounds 1 and 0: ", state);
		do_typeIB(strips128, state, typeIBs);
		do_typeIV_IB(state, strips128, typeIV_IBs);

		do_output(out, state, final_decoding, typeIB_output_sbox_inv);

		printf("Original AES Equivalent Inverse Cipher on same input using same key:\n");
		eqv_decipher(in, out2, ISBox, mixed_key_schedule);
		dump_hex("WB Output ", out, 16);
		dump_hex("AES Output ", out2, 16);
		ASSERT(memcmp(out, out2, 16) == 0);
		free_matrix(mix_columns_mixing_bijection);
		free_matrix(inv_mix_columns_mixing_bijection);
		free_tbox_mixing_bijections(tbox_mixing_bijections);
		free_tbox_mixing_bijections(inv_tbox_mixing_bijections);
		free_matrix(final_decoding);
		free_matrix(final_encoding);
		free_matrix(initial_decoding);
		free_matrix(initial_encoding);
	}
}
Ejemplo n.º 28
0
int
main(int ac, char **av, char **ep)
{
	int rc;
	cpu_t *cpu;
	xec_guest_info_t guest_info;
	xec_mem_if_t *mem_if;
	xec_monitor_t *monitor;
	xec_us_syscall_if_t *us_syscall;
	m88k_uintptr_t stack_top;
	nix_env_t *env;
	bool debugging = false;

	aspace_lock();

	if (ac < 2) {
		fprintf(stderr, "usage: %s <executable> [args...]\n", *av);
		exit(EXIT_FAILURE);
	}

	/* Initialize xec, nix and loader. */
	xec_init();
	obsd41_init();
	loader_init();

	/* Create CPU */
	cpu = cpu_new(CPU_ARCH_M88K, CPU_FLAG_ENDIAN_BIG, 0);
	if (cpu == NULL) {
		fprintf(stderr, "error: failed initializing M88K architecture.\n");
		exit(EXIT_FAILURE);
	}

	/* Create XEC bridge mem-if */
	mem_if = run88_new_mem_if();

	/* Create the XEC US Syscall */
	us_syscall = obsd41_us_syscall_create(mem_if);
	if (us_syscall == NULL) {
		fprintf(stderr, "error: failed creating xec userspace syscall.\n");
		exit(EXIT_FAILURE);
	}

	/* Create NIX env */
	env = nix_env_create(mem_if);
	if (env == NULL) {
		fprintf(stderr, "error: failed creating nix environment.\n");
		exit(EXIT_FAILURE);
	}

	/* Load the executable */
	rc = loader_load(mem_if, av[1]);
	if (rc != LOADER_SUCCESS) {
		fprintf(stderr, "error: cannot load executable '%s', error=%d.\n", av[1], rc);
		exit(EXIT_FAILURE);
	}

	/* Setup arguments */
	g_uframe_log = xec_log_register("uframe");

#ifndef DEBUGGER
	xec_log_disable("nix");
	xec_log_disable("openbsd41");
	xec_log_disable("uframe");
	xec_log_disable(NULL);
#endif

	openbsd_m88k_setup_uframe(cpu, mem_if, ac - 1, av + 1, ep, &stack_top);

	/* Setup the CPU */
	cpu_set_flags_codegen(cpu, CPU_CODEGEN_OPTIMIZE|CPU_CODEGEN_TAG_LIMIT);
	cpu_set_flags_debug(cpu, CPU_DEBUG_NONE);
	//cpu_set_flags_debug(cpu, CPU_DEBUG_SINGLESTEP_BB);
	cpu_set_flags_hint(cpu, CPU_HINT_TRAP_RETURNS_TWICE);
	cpu_set_ram(cpu, RAM);

	/* Create XEC bridge monitor */
	guest_info.name = cpu->info.name;
	guest_info.endian = (cpu->info.common_flags & CPU_FLAG_ENDIAN_MASK)
		== CPU_FLAG_ENDIAN_BIG ? XEC_ENDIAN_BIG : XEC_ENDIAN_LITTLE;
	guest_info.byte_size = cpu->info.byte_size;
	guest_info.word_size = cpu->info.word_size;
	guest_info.page_size = cpu->info.default_page_size;
	monitor = xec_monitor_create(&guest_info, mem_if, cpu->rf.grf, NULL);
	if (monitor == NULL) {
		fprintf(stderr, "error: failed createc xec monitor.\n");
		exit(EXIT_FAILURE);
	}

	/* Setup registers for execution */
	PC = g_ahdr.entry;

	R[31] = stack_top; // Stack Pointer
	R[1]  = -1;        // Return Address

	cpu->code_start = g_ahdr.tstart;
	cpu->code_end   = g_ahdr.tstart + g_ahdr.tsize;
	cpu->code_entry = g_ahdr.entry;

	cpu_tag(cpu, cpu->code_entry);

	dump_state(RAM, (m88k_grf_t*)cpu->rf.grf);

#ifdef DEBUGGER
	debugging = true;
#else
	fprintf(stderr, "Translating..."); fflush(stderr);
	cpu_translate(cpu);
	fprintf(stderr, "done.\n");
#endif

	aspace_unlock();

	for (;;) {
		if (debugging) {
			rc = cpu_debugger(cpu, debug_function);
			if (rc < 0) {
				debugging = false;
				continue;
			}
		} else {
			rc = cpu_run(cpu, debug_function);
		}

		switch (rc) {
			case JIT_RETURN_NOERR: /* JIT code wants us to end execution */
				break;

			case JIT_RETURN_FUNCNOTFOUND:
#ifndef DEBUGGER
				fprintf(stderr, "%s: error: 0x%llX not found!\n", __func__, (unsigned long long)PC);
				fprintf(stderr, "Translating..."); fflush(stderr);
				cpu_tag(cpu, PC);
				cpu_flush(cpu);
				cpu_translate(cpu);
				fprintf(stderr, "done.\n");
#else
				dump_state(RAM, (m88k_grf_t*)cpu->rf.grf);

				if (PC == (uint32_t)(-1U))
					goto exit_loop;

				// bad :(
				fprintf(stderr, "%s: warning: 0x%llX not found!\n", __func__, (unsigned long long)PC);
				fprintf(stderr, "PC: ");
				for (size_t i = 0; i < 16; i++)
					fprintf(stderr, "%02X ", RAM[PC+i]);
				fprintf(stderr, "\n");
				exit(EXIT_FAILURE);
#endif
				break;

			case JIT_RETURN_TRAP:
//				printf("TRAP %u / %u!\n", TRAPNO, R[13]);
				if (TRAPNO == 0x80 && R[13] == 1) // exit
					goto exit_loop;

//				printf("BEFORE:\n");
//				dump_state(RAM, (m88k_grf_t*)cpu->rf.grf);
				xec_us_syscall_dispatch(us_syscall, monitor);
//				printf("AFTER:\n");
//				dump_state(RAM, (m88k_grf_t*)cpu->rf.grf);
				break;

			case JIT_RETURN_SINGLESTEP:
				break;

			default:
				fprintf(stderr, "unknown return code: %d\n", rc);
				goto exit_loop;
		}

		if (cpu->flags_debug & (CPU_DEBUG_SINGLESTEP | CPU_DEBUG_SINGLESTEP_BB))
			cpu_flush(cpu);
	}

exit_loop:
	cpu_free(cpu);

	fprintf(stderr, ">> run88 success\n");
	exit(EXIT_SUCCESS);
}
Ejemplo n.º 29
0
/* The key event handler. */
int handle_keystroke_event(nbstate *state, GR_EVENT_KEYSTROKE *ev)
{
	/* If the event is a "key up" event and the key is either the left or
	 * right cursor key, cancel bat movement in that direction. Otherwise
	 * we don't care about the event. */
	if(ev->type == GR_EVENT_TYPE_KEY_UP) {
		switch(ev->ch) {
			case MWKEY_LEFT:
				state->flags.left = 0;
				break;
			case MWKEY_RIGHT:
				state->flags.right = 0;
				break;
			default:
				/* Ignore the event. */
				break;
		}
		return 0; /* Normal return. */
	}

	/* If we get to here, it's a "key down" event. Perform various
	 * different actions depending on which key was pressed: */
	switch(ev->ch) {
		case ' ': /* The space bar is the "action" key: */
			action_pressed(state);
			break;
		case MWKEY_F1: /* F1 is the "pause" key: */
			state->flags.paused ^= 1; /* Set the pause flag. */
			break;
		case MWKEY_F2: /* F2 is the "suicide" key: */
			lost_ball(state); /* Throw away the current ball. */
			break;
#ifdef DEBUG_POWERS
		/* If DEBUG_POWERS is defined in nbreaker.h, keys F3-F8 are
		 * used to trigger the power ups and power downs without
		 * needing to catch a falling power box. */
		case MWKEY_F3: /* WideBat */
			activate_widebat(state);
			break;
		case MWKEY_F4: /* SlowMotion */
			activate_slowmotion(state);
			break;
		case MWKEY_F5: /* StickyBat */
			activate_stickybat(state);
			break;
		case MWKEY_F6: /* PowerBall */
			activate_powerball(state);
			break;
		case MWKEY_F7: /* NarrowBat */
			activate_narrowbat(state);
			break;
		case MWKEY_F8: /* FastMotion */
			activate_fastmotion(state);
			break;
#endif
		case MWKEY_LEFT: /* The left cursor key: */
			/* Set the "moving left" flag and cancel the
			 * "moving right" one. */
			state->flags.left = 1;
			state->flags.right = 0;
			break;
		case MWKEY_RIGHT: /* The right cursor key: */
			/* Set the "moving right" flag and cancel the
			 * "moving left" one. */
			state->flags.left = 0;
			state->flags.right = 1;
			break;
#ifdef NB_DEBUG
		/* If NB_DEBUG is set in nbreaker.h, dump the game state when
		 * F10 is pressed. */
		case MWKEY_F10:
			dump_state(state);
			break;
#endif
		/* If the escape key is pressed, return 1 which means "exit
		 * the game". */
		case MWKEY_ESCAPE:
			return 1;

		/* Feed all other key presses to the cheat recogniser engine: */
		default:
			do_cheat(state, ev->ch);
			break;
	}

	return 0; /* Normal return. */
}
Ejemplo n.º 30
0
void init_physics()
{
	ions[0] = proton();
	ions[1] = electron();
	ions[0].location = (struct vector) {0,0,0};
	ions[0].velocity=(struct vector){0,0,0};
	ions[1].location = (struct vector) {0,20,0};
	ions[1].velocity=(struct vector){0.15,0,0};
}

/*
void init_physics()
{
#define RANDO ((rand()%100)-50)
	int i;
	for(i=0;i<N_IONS;i++){
		switch(rand()%8){
			case 0:
				ions[i] = nuclion(rand()%9);
				break;
			default:
				ions[i] = electron();
				break;
		}
		ions[i].location = (struct vector) {RANDO,RANDO,RANDO};
		ions[i].velocity=(struct vector){0,0,0};
	}
}
*/

void dump_state()
{
	int i;
	printf("--- IONS ---\n");
	for(i=0;i<N_IONS;i++){
		printf("[%i]\n",i);
		printf("charge %Lf \n",ions[i].charge);
		printf("mass %Lf \n",ions[i].mass);
		v_print("location",ions[i].location);
		v_printe("velocity",ions[i].velocity);
		v_printe("acceleration",ions[i].accel);
	}
	printf("-----------\n");
}

void calculate_acceleration(struct particle * p,double dt)
{
	struct vector fv = {0,0,0};
	int i;
	for(i=0;i<N_IONS;i++){
		fv = v_add(fv,gravitation(ions[i],*p));
		fv = v_add(fv,coulombs(ions[i],*p));
//		fv = v_add(fv,biotsavart(ions[i],*p));
	}
	/* because f/m=a */
	fv.x/=p->mass;
	fv.y/=p->mass;
	fv.z/=p->mass;
	p->accel = v_scalar_mul(dt,fv);
}

void apply_vel(struct particle * p)
{
	p->velocity = v_add(p->accel,p->velocity);
	p->location = v_add(p->location,p->velocity);
}

void physics_tick(double dt)
{
	int i;
	for(i=0;i<N_IONS;i++)
		calculate_acceleration(&ions[i],dt);
	for(i=0;i<N_IONS;i++)
		apply_vel(&ions[i]);
	if(keys['P'])
		dump_state();
}