Пример #1
0
/*calcul de la checkSum -> least significant byte de la somme de tous les octets sauf les octets de SYNC */
void calculateCheckSum(struct trame* trameAEnv) { 
  char* checkSum = (char*) malloc(sizeof (char[2]));
  char* lSB = (char*) malloc(sizeof (char[2]));
  int sum = 0, i;
  memset(lSB, '\0', 2);
  for (i = 0; i < 8; i = i + 2) {
    checkSum[0] = trameAEnv->DATA[i];
    checkSum[1] = trameAEnv->DATA[i + 1];
    sum += hexToInt(checkSum);
  }

  for (i = 0; i < 8; i = i + 2) {
    checkSum[0] = trameAEnv->ID[i];
    checkSum[1] = trameAEnv->ID[i + 1];
    sum += hexToInt(checkSum);
  }
  checkSum[0] = trameAEnv->HEADER[0];
  checkSum[1] = trameAEnv->LENGHT[0];
  sum += hexToInt(checkSum);
  for (i = 0; i < 2; i = i + 2) {
    checkSum[0] = trameAEnv->ORG[i];
    checkSum[1] = trameAEnv->ORG[i + 1];
    sum += hexToInt(checkSum);
  }
  for (i = 0; i < 2; i = i + 2) {
    checkSum[0] = trameAEnv->STATUS[i];
    checkSum[1] = trameAEnv->STATUS[i + 1];
    sum += hexToInt(checkSum);
  }
  itochar(sum, checkSum, 16);
  lSB[0] = checkSum[1];
  lSB[1] = checkSum[0];
  trameAEnv->CHECKSUM = lSB;
  free(checkSum);
}
Пример #2
0
int main (void) 
{

	char *input;
	int output = 0;

	//Get input in HEX
	input = (char *)malloc(sizeof(char)*10);
	scanf ("%s",input);

	//Alpha
	output+=255;
	output = output<<8;

	//Red
	output+=hexToInt( *(input+0), *(input+1) );
	output = output<<8;

	//Green
	output+=hexToInt( *(input+2), *(input+3) );
	output = output<<8;
	
	//Blue
	output+=hexToInt( *(input+4), *(input+5) );

	//Print output
	printf("%d\n",output);
}
Пример #3
0
int Lexer::hexToInt (int c0, int c1, int c2, int c3) const
{
  return (hexToInt (c0) << 12) +
         (hexToInt (c1) << 8)  +
         (hexToInt (c2) << 4)  +
          hexToInt (c3);
}
int byteToInt(string byteString){

    // String length should be exactly 2
    if (byteString.length() != 2){
        throw std::length_error("String length error");
    }

    int value = 0;

    for (int i=0; i<2; i++){
        value += i % 2 == 0 ? hexToInt(byteString[i]) << 4 : hexToInt(byteString[i]);
    }
    return value;
}
/*
** Taken from SQLite source code.
** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
** value.  Return a pointer to its binary value.  Space to hold the
** binary value has been obtained from malloc and must be freed by
** the calling routine.
*/
static void *hexToBlob(const char *z, int n){
  char *zBlob;
  int i;

  zBlob = (char *)malloc(n/2 + 1);
  n--;
  if( zBlob ){
    for(i=0; i<n; i+=2){
      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
    }
    zBlob[i/2] = 0;
  }
  return zBlob;
}
Пример #6
0
language_c::language_c(char * setupLang, SystemDefault_c * SystemDefault) : collection_c() {
  current = -1;
  langDir = new char[MAX_PATH];
  strcpy(langDir,SystemDefault->PrgPath);
  strcat(langDir,"lang\\");
  char * SerPath = new char[MAX_PATH];
  strcpy(SerPath,langDir);
  strcat(SerPath,"*.xml");
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind;
  hFind = FindFirstFile(SerPath, &FindFileData);
  if (hFind != INVALID_HANDLE_VALUE) {
    LoadLanguageFile(FindFileData.cFileName);
    while (FindNextFile(hFind,&FindFileData )) {
      LoadLanguageFile(FindFileData.cFileName);
    }
    FindClose(hFind);
  }
  delete[] SerPath;
//////////////////////////////
// Detect Systemdefault
//////////////////////////////
//  setup = aSetup;
  int ConfigLang = hexToInt(setupLang);
  current = getLangID(ConfigLang);
  if (current == -1) {
    int UserLang = GetUserDefaultUILanguage();
    if (current == -1) {current = getLangID(UserLang);}
    if (current == -1) {current = getLangIDMain(PRIMARYLANGID(UserLang));}
    int SysLang = GetSystemDefaultUILanguage();
    if (current == -1) {current = getLangID(SysLang);}
    if (current == -1) {current = getLangIDMain(PRIMARYLANGID(SysLang));}
  }
}
Пример #7
0
static p_str*
parseHexString(const uint8_t *buf, const unsigned int len) {
  unsigned int i,j;
  p_str *ret;

  ret = malloc(sizeof(p_str));
  ret->content = malloc(sizeof(uint8_t)*(len/2));
  ret->len = (len/2);

  for(i=0, j=0; i<len; i += 2) {
    ret->content[j] = hexToInt(buf[i]) * 16;
    ret->content[j] += hexToInt(buf[i+1]);
    j++;
  }

  return ret;
}
Пример #8
0
void traiterDataGPS(void){
	int i,j,chk;

	i = 0;
	while(i<lengthWaitBuffer){
		//avencée vers le premier $
		while(i<lengthWaitBuffer && waitBuffer[i]!='$') i++;
		// waitBuffer[i+1] contient le début des données de la trames

		//calcul du checksum
		j = i+1;
		chk = 0;
		while(j<lengthWaitBuffer && waitBuffer[j]!='*'){
			chk ^= waitBuffer[j];
			j++;
		}

		//trame valide ?
		if((j+3 < lengthWaitBuffer) && (chk == hexToInt(waitBuffer+j+1,2))){
			waitBuffer[j+3] = 0;
			if(!strCmp(waitBuffer+i,"$GPGGA")){
				i += 7;
				i += strCpy(gps_UTCPos, waitBuffer+i, 10) + 1;

				i += strCpy(gps_Latitude, waitBuffer+i, 9) + 1;
				i += strCpy(gps_NSind, waitBuffer+i, 1) + 1;
				i += strCpy(gps_Longitude, waitBuffer+i, 10) + 1;
				i += strCpy(gps_EWind, waitBuffer+i, 1) + 1;

				i += strCpy(gps_PosFixInd, waitBuffer+i, 1) + 1;
				i += strCpy(gps_SatUsed, waitBuffer+i, 2) + 1;
				i += strCpy(gps_HDOP, waitBuffer+i, 16) + 1;

				i += strCpy(gps_Altitude, waitBuffer+i, 16) + 1;
				i += strCpy(gps_AltUnit, waitBuffer+i, 16) + 1;
			}
			else if(!strCmp(waitBuffer+i,"$GPRMC")){
				i += 7;
				i += strCpy(gps_UTCPos, waitBuffer+i, 10) + 1;
				i += strCpy(gps_Status, waitBuffer+i, 1) + 1;

				i += strCpy(gps_Latitude, waitBuffer+i, 9) + 1;
				i += strCpy(gps_NSind, waitBuffer+i, 1) + 1;
				i += strCpy(gps_Longitude, waitBuffer+i, 10) + 1;
				i += strCpy(gps_EWind, waitBuffer+i, 1) + 1;

				i += strCpy(gps_SpeedOverGround, waitBuffer+i, 16) + 1;
				i += strCpy(gps_CourseOverGround, waitBuffer+i, 16) + 1;
				i += strCpy(gps_Date, waitBuffer+i, 6) + 1;
			}
		}
		i++;
	}

	lengthWaitBuffer = 0;
}
Пример #9
0
void hexString::setIntValue(){
	//Internal function.  Convert hex to int using non-recursive method.
	unsigned long long int pow = 1;
	intValue = 0;
	
	for (int i = hexValue.length(); i > 0; i--) {
		intValue += pow * hexToInt(hexValue[i-1]);
		pow *= 16;
	}	
}
Пример #10
0
int nextFourBytesAsInt(char* str, int startLocation)
{
    int i = 0;
    char fourBytes[5] = "";
    fourBytes[4] = '\0';
    for (i = 0; i < 4; i++)
    {
        fourBytes[i] = str[startLocation+i];
    }
    return hexToInt(fourBytes);
}
Пример #11
0
int hexString::getBit(int whichBit, char hexChar){
	//Internal function to set the value of bits mathematically.
	//Returns the requested bit.
	int value = hexToInt(hexChar);
	int bit[4] = {0,0,0,0};
	if (value > 7){bit[3] = 1; value -= 8;}
	if (value > 3){bit[2] = 1; value -= 4;}
	if (value > 1){bit[1] = 1; value -= 2;}
	bit[0] = value;
	return bit[whichBit];	
}
Пример #12
0
int language_c::getLangID(int lang) {
  int id = -1;
  languagefile_c * file;
  int i=0;
  while ((i<Count) & (id == -1)) {
    file = (languagefile_c*)getByIndex(i);
    if (lang == hexToInt(file->getId())) {id = i;}
    i = i + 1;
  }
  return id;
}
Пример #13
0
    void fromString(const std::string &string) override
    {
        uint8_t rgba[4] = { 0, 0, 0, 255 };

        for (int i = 0; i < string.length() && i < 8; ++i)
        {
            if (!(i % 2))
                rgba[i / 2] = 0;
            rgba[i / 2] |= (hexToInt(string[i]) << ((i % 2) ? 0 : 4));
        }

        rgba_t next{};
        next.r = float(rgba[0]) / 255.f;
        next.g = float(rgba[1]) / 255.f;
        next.b = float(rgba[2]) / 255.f;
        next.a = float(rgba[3]) / 255.f;
        setInternal(next);
    }
Пример #14
0
/*converts user input string into a base 10 number, will 
 * return 1 if number conversion leads to somethign bigger
 * than 32 bit. Calls on seperate functions based on the type
 * of input*/
int convertToInt(number* ptr) {
		if (ptr -> type == 'd' || ptr -> type == 'D' || ptr -> type == 'o' || ptr -> type == 'O' || ptr -> type == 'b' || ptr -> type == 'B') {
			if (strToInt(ptr) == 1) {
				return 1;
			}
			else {
				return 0;
			}
		}
		else if (ptr -> type == 'x' || ptr -> type == 'X') {
			if (hexToInt(ptr) == 1) {
				return 1;
			}
			else {
				return 0;
			}
		}
	return 0;
}
Пример #15
0
static int textToPointer(const char *z, void **pp){
  sqlite3_uint64 n = 0;
  int i;
  unsigned int u;
  for(i=0; i<sizeof(void*)*2 && z[0]; i++){
    int v;
    v = hexToInt(*z++);
    if( v<0 ) return TCL_ERROR;
    n = n*16 + v;
  }
  if( *z!=0 ) return TCL_ERROR;
  if( sizeof(n)==sizeof(*pp) ){
    memcpy(pp, &n, sizeof(n));
  }else if( sizeof(u)==sizeof(*pp) ){
    u = (unsigned int)n;
    memcpy(pp, &u, sizeof(u));
  }else{
    assert( 0 );
  }
  return TCL_OK;
}
Пример #16
0
void Terminal::writeColoredString(const char* data)
{
	Color originalColor = getColor();
	while (*data != 0)
	{
		if (*data == '$' && *(data + 1) != 0)
		{
			data++;
			char c = *(data++);
			uint8_t ic = hexToInt(c);
			if (ic != 255)
				setColor(
					static_cast<Color>((
						static_cast<uint8_t>(originalColor) & 0xF0) | ic));
		}
		else
		{
			putChar(*(data++));
		}
	}
	setColor(originalColor);
}
Пример #17
0
/**
 * Returns -1 if there is a socket error.
 */
static int
processPacket_gdb( SOCKET_TYPE sock, const uint8_t *packet,
		   struct gdb_stub_state *stub) {
  //  uint8_t remcomOutBuffer[BUFMAX_GDB];
  struct debug_out_packet *out_packet = getOutPacket();
  uint8_t *out_ptr = out_packet->start_ptr;
  int send_reply = 1;
  uint32_t send_size = 0;

  DEBUG_LOG("Processing packet %c\n", packet[0]);
  gdbstub_mutex_lock();

  switch( packet[0]) {
  case 3:
    /* The break command */
    //stub->running_state = gdb_stub_state::STOPPED_GDB_STATE;
    //*ptr++ = 'S';
    //*ptr++ = hexchars[0x2 >> 4];
    //*ptr++ = hexchars[0x2 & 0xf];
    //*ptr++ = 0;
    send_reply = 0;
    break;

  case '?':
    send_size = make_stop_packet( out_ptr, stub->stop_type, stub->stop_address);
    /**ptr++ = 'S';
    *ptr++ = hexchars[stub->stop_reason >> 4];
    *ptr++ = hexchars[stub->stop_reason & 0xf];
    send_size = 3;*/
    break;

  case 'c':
  case 'k':
	stub->emu_stub_state = gdb_stub_state::RUNNING_EMU_GDB_STATE;
    stub->ctl_stub_state = gdb_stub_state::START_RUN_GDB_STATE;
    stub->main_stop_flag = 0;
    send_reply = 0;
    /* remove the cpu stall */
    stub->cpu_ctrl->unstall( stub->cpu_ctrl->data);
	NDS_debug_continue();
    break;

  case 's': {
    uint32_t instr_addr = stub->cpu_ctrl->read_reg( stub->cpu_ctrl->data, 15);
    /* Determine where the next instruction will take the CPU.
     * Execute the instruction using a copy of the CPU with a zero memory interface.
     */
    DEBUG_LOG( "Stepping instruction at %08x\n", instr_addr);

    /* install the post execution function */
    stub->step_instr_address = instr_addr;
    stub->cpu_ctrl->install_post_ex_fn( stub->cpu_ctrl->data,
                                        step_instruction_watch,
                                        stub);

    stub->emu_stub_state = gdb_stub_state::RUNNING_EMU_GDB_STATE;
    stub->ctl_stub_state = gdb_stub_state::START_RUN_GDB_STATE;
    stub->main_stop_flag = 0;
    send_reply = 0;

    /* remove the cpu stall */
    stub->cpu_ctrl->unstall( stub->cpu_ctrl->data);
	//NDS_debug_step();
	NDS_debug_continue();
    break;
  }

    /*
     * Register set
     */
  case 'P': {
    uint32_t reg;
    uint32_t value;
    const uint8_t *rx_ptr = &packet[1];

    DEBUG_LOG("Processing packet %s\n", packet);
    if ( hexToInt( &rx_ptr, &reg)) {
      if ( *rx_ptr++ == '=') {
        uint8_t tmp_mem[4];

        rx_ptr = hex2mem( rx_ptr, tmp_mem, 4);
        value = LITTLE_ENDIAN_TO_UINT32_T( tmp_mem);
        DEBUG_LOG("Setting reg %d to %08x\n", reg, value);
        if ( reg < 16)
          stub->cpu_ctrl->set_reg( stub->cpu_ctrl->data, reg, value);
        if ( reg == 25) {
          stub->cpu_ctrl->set_reg( stub->cpu_ctrl->data, 16, value);
        }

        strcpy( (char *)out_ptr, "OK");
        send_size = 2;
      }
    }
    break;
  }

  case 'm': {
    uint32_t addr = 0;
    uint32_t length = 0;
    int error01 = 1;
    const uint8_t *rx_ptr = &packet[1];

    if ( hexToInt( &rx_ptr, &addr)) {
      if ( *rx_ptr++ == ',') {
        if ( hexToInt( &rx_ptr, &length)) {
          //DEBUG_LOG("mem read from %08x (%d)\n", addr, length);
          if ( !mem2hex( stub->direct_memio, addr, out_ptr, length)) {
            strcpy ( (char *)out_ptr, "E03");
            send_size = 3;
          }
          else {
            send_size = length * 2;
          }
          error01 = 0;
        }
      }
    }
    if ( error01)
      strcpy( (char *)out_ptr,"E01");
    break;
  }

    /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
  case 'M': {
    /* Try to read '%x,%x:'.  */
    const uint8_t *rx_ptr = &packet[1];
    uint32_t addr = 0;
    uint32_t length = 0;
    int error01 = 1;
    DEBUG_LOG("Memory write %s\n", rx_ptr);
    if ( hexToInt(&rx_ptr, &addr)) {
      if ( *rx_ptr++ == ',') {
        if ( hexToInt(&rx_ptr, &length)) {
          if ( *rx_ptr++ == ':') {
            uint8_t write_byte;
            unsigned int i;
            DEBUG_LOG("Memory write of %d bytes to %08x\n",
                      length, addr);

            for ( i = 0; i < length; i++) {
              rx_ptr = hex2mem( rx_ptr, &write_byte, 1);

              stub->direct_memio->write8( stub->direct_memio->data,
                                         addr++, write_byte);
            }

            strcpy( (char *)out_ptr, "OK");
            error01 = 0;
          }
        }
        else {
          DEBUG_LOG("Failed to find length (addr %08x)\n", addr);
        }
      }
      else {
        DEBUG_LOG("expected ',' got '%c' (addr = %08x)\n", *rx_ptr, addr);
      }
    }
    else {
      DEBUG_LOG("Failed to find addr\n");
    }

    if ( error01) {
      strcpy( (char *)out_ptr, "E02");
    }
    break;
  }

  case 'Z':
  case 'z': {
    const uint8_t *rx_ptr = &packet[2];
    int remove_flag = 0;

    if ( packet[0] == 'z')
      remove_flag = 1;

    DEBUG_LOG( "%c%c packet %s (remove? %d)\n", packet[0], packet[1],
               rx_ptr, remove_flag);

    switch ( packet[1]) {

      /* all instruction breakpoints are treated the same */
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
      {
	uint32_t addr = 0;
	uint32_t length = 0;
	int error01 = 1;
        struct breakpoint_gdb **bpoint_list;

        switch ( packet[1]) {
        case '0':
        case '1':
          bpoint_list = &stub->instr_breakpoints;
          break;

        case '2':
          bpoint_list = &stub->write_breakpoints;
          break;

        case '3':
          bpoint_list = &stub->read_breakpoints;
          break;

        case '4':
          bpoint_list = &stub->access_breakpoints;
          break;
        }

        if ( *rx_ptr++ == ',') {
          DEBUG_LOG("%s\n", rx_ptr);

          if ( hexToInt( &rx_ptr, &addr)) {
            if ( *rx_ptr++ == ',') {
              DEBUG_LOG("addr %08x %s\n", addr, rx_ptr);

              if ( hexToInt( &rx_ptr, &length)) {
                if ( remove_flag) {
                  int removed = 0;
                  struct breakpoint_gdb *last_bpoint = NULL;
                  struct breakpoint_gdb *bpoint = *bpoint_list;

                  while ( bpoint != NULL && !removed) {
                    if ( bpoint->addr == addr) {
                      DEBUG_LOG("Breakpoint(%c) at %08x removed\n", packet[1], addr);
                      removed = 1;

                      if ( last_bpoint == NULL) {
                        *bpoint_list = bpoint->next;
                      }
                      else {
                        last_bpoint->next = bpoint->next;
                      }
                      bpoint->next = stub->free_breakpoints;
                      stub->free_breakpoints = bpoint;
                    }
                    last_bpoint = bpoint;
                    bpoint = bpoint->next;
                  }

                  strcpy( (char *)out_ptr, "OK");
                  send_size = 2;
                  error01 = 0;
                }
                else {
                  /* get a breakpoint descriptor from the free pool and add it to
                   * the current stub instruction breakpoint list */
                  struct breakpoint_gdb *bpoint = stub->free_breakpoints;

                  if ( bpoint != NULL) {
                    DEBUG_LOG( "Breakpoint(%c) added at %08x length %d\n",
                               packet[1],  addr, length);
                    stub->free_breakpoints = bpoint->next;

                    bpoint->addr = addr;
                    bpoint->size = length;

                    bpoint->next = *bpoint_list;
                    *bpoint_list = bpoint;

                    strcpy( (char *)out_ptr, "OK");
                    send_size = 2;
                    error01 = 0;
                  }
		}
	      }
	    }
	  }
	}

	if ( error01) {
	  strcpy( (char *)out_ptr, "E01");
	  send_size = 3;
	}
      }
      break;

    default:
      break;
    }
    break;
  }

    /*
     * Set the register values
     */
  case 'G':
    {
      int i;
      const uint8_t *rx_ptr = &packet[1];
      uint32_t reg_values[16];
      uint32_t cpsr;
      uint8_t tmp_mem[4];
      DEBUG_LOG("'G' command %s\n", rx_ptr);

      /* general purpose regs 0 to 15 */
      for ( i = 0; i < 16; i++) {
	rx_ptr = hex2mem( rx_ptr, tmp_mem, 4);

        reg_values[i] = LITTLE_ENDIAN_TO_UINT32_T( tmp_mem);
        DEBUG_LOG("Setting reg %d to %08x\n", i, reg_values[i]);
      }

      /* skip the floaing point registers and floating point status register */
      rx_ptr += 8 * (96 / 8 * 2);
      rx_ptr += 8;

      /* the CPSR register is last */
      rx_ptr = hex2mem( rx_ptr, tmp_mem, 4);
      cpsr = LITTLE_ENDIAN_TO_UINT32_T( tmp_mem);
      DEBUG_LOG("Setting cpsr to %08x\n", cpsr);

      strcpy( (char *)out_ptr, "OK");
      send_size = 2;
      break;
    }

  case 'g':		/* return the value of the CPU registers */
    {
      int i;
      int out_index = 0;
      uint32_t pc_value = stub->cpu_ctrl->read_reg( stub->cpu_ctrl->data, 15);
      uint32_t cpsr_value = stub->cpu_ctrl->read_reg( stub->cpu_ctrl->data, 16);

      DEBUG_LOG("'g' command PC = %08x\n", pc_value);

      /* general purpose regs 0 to 14 */
      for ( i = 0; i < 15; i++) {
        uint32_t reg = stub->cpu_ctrl->read_reg( stub->cpu_ctrl->data, i);
	out_ptr[out_index++] = hexchars[(reg >> 4) & 0xf];
	out_ptr[out_index++] = hexchars[(reg >> 0) & 0xf];
	out_ptr[out_index++] = hexchars[(reg >> 12) & 0xf];
	out_ptr[out_index++] = hexchars[(reg >> 8) & 0xf];
	out_ptr[out_index++] = hexchars[(reg >> 20) & 0xf];
	out_ptr[out_index++] = hexchars[(reg >> 16) & 0xf];
	out_ptr[out_index++] = hexchars[(reg >> 28) & 0xf];
	out_ptr[out_index++] = hexchars[(reg >> 24) & 0xf];
      }

      out_ptr[out_index++] = hexchars[(pc_value >> 4) & 0xf];
      out_ptr[out_index++] = hexchars[(pc_value >> 0) & 0xf];
      out_ptr[out_index++] = hexchars[(pc_value >> 12) & 0xf];
      out_ptr[out_index++] = hexchars[(pc_value >> 8) & 0xf];
      out_ptr[out_index++] = hexchars[(pc_value >> 20) & 0xf];
      out_ptr[out_index++] = hexchars[(pc_value >> 16) & 0xf];
      out_ptr[out_index++] = hexchars[(pc_value >> 28) & 0xf];
      out_ptr[out_index++] = hexchars[(pc_value >> 24) & 0xf];

      /* floating point registers (8 96bit) */
      for ( i = 0; i < 8; i++) {
	int j;
	for ( j = 0; j < (96/4); j++) {
	  out_ptr[out_index++] = '0';
	}
      }

      /* floating point status register? */
      for ( i = 0; i < 1; i++) {
	int j;
	for ( j = 0; j < 8; j++) {
	  out_ptr[out_index++] = '0';
	}
      }

      /* The CPSR */
      for ( i = 0; i < 1; i++) {
	out_ptr[out_index++] = hexchars[(cpsr_value >> 4) & 0xf];
	out_ptr[out_index++] = hexchars[(cpsr_value >> 0) & 0xf];
	out_ptr[out_index++] = hexchars[(cpsr_value >> 12) & 0xf];
	out_ptr[out_index++] = hexchars[(cpsr_value >> 8) & 0xf];
	out_ptr[out_index++] = hexchars[(cpsr_value >> 20) & 0xf];
	out_ptr[out_index++] = hexchars[(cpsr_value >> 16) & 0xf];
	out_ptr[out_index++] = hexchars[(cpsr_value >> 28) & 0xf];
	out_ptr[out_index++] = hexchars[(cpsr_value >> 24) & 0xf];
      }
      send_size = out_index;
    }
    break;
  }

  gdbstub_mutex_unlock();

  if ( send_reply) {
    return putpacket( sock, out_packet, send_size);
  }

  return 0;
}
Пример #18
0
/*
 * This function does all command processing for interfacing to gdb.
 */
static int
handle_exception (struct pt_regs *regs)
{
	int addr;
	int length;
	char *ptr;
	kgdb_data kd;
	int i;

	if (!initialized) {
		printf("kgdb: exception before kgdb is initialized! huh?\n");
		return (0);
	}

	/* probably should check which exception occured as well */
	if (longjmp_on_fault) {
		longjmp_on_fault = 0;
		kgdb_longjmp(error_jmp_buf, KGDBERR_MEMFAULT);
		panic("kgdb longjump failed!\n");
	}

	if (kgdb_active) {
		printf("kgdb: unexpected exception from within kgdb\n");
		return (0);
	}
	kgdb_active = 1;

	kgdb_interruptible(0);

	printf("kgdb: handle_exception; trap [0x%x]\n", kgdb_trap(regs));

	if (kgdb_setjmp(error_jmp_buf) != 0)
		panic("kgdb: error or fault in entry init!\n");

	kgdb_enter(regs, &kd);

	if (first_entry) {
		/*
		 * the first time we enter kgdb, we save the processor
		 * state so that we can return to the monitor if the
		 * remote end quits gdb (or at least, tells us to quit
		 * with the 'k' packet)
		 */
		entry_regs = *regs;
		first_entry = 0;
	}

	ptr = remcomOutBuffer;

	*ptr++ = 'T';

	*ptr++ = hexchars[kd.sigval >> 4];
	*ptr++ = hexchars[kd.sigval & 0xf];

	for (i = 0; i < kd.nregs; i++) {
		kgdb_reg *rp = &kd.regs[i];

		*ptr++ = hexchars[rp->num >> 4];
		*ptr++ = hexchars[rp->num & 0xf];
		*ptr++ = ':';
		ptr = (char *)mem2hex((char *)&rp->val, ptr, 4);
		*ptr++ = ';';
	}

	*ptr = 0;

#ifdef KGDB_DEBUG
	if (kdebug)
		printf("kgdb: remcomOutBuffer: %s\n", remcomOutBuffer);
#endif

	putpacket((unsigned char *)&remcomOutBuffer);

	while (1) {
		volatile int errnum;

		remcomOutBuffer[0] = 0;

		getpacket(remcomInBuffer);
		ptr = &remcomInBuffer[1];

#ifdef KGDB_DEBUG
		if (kdebug)
			printf("kgdb:  remcomInBuffer: %s\n", remcomInBuffer);
#endif

		errnum = kgdb_setjmp(error_jmp_buf);

		if (errnum == 0) switch (remcomInBuffer[0]) {

		case '?':               /* report most recent signal */
			remcomOutBuffer[0] = 'S';
			remcomOutBuffer[1] = hexchars[kd.sigval >> 4];
			remcomOutBuffer[2] = hexchars[kd.sigval & 0xf];
			remcomOutBuffer[3] = 0;
			break;

#ifdef KGDB_DEBUG
		case 'd':
			/* toggle debug flag */
			kdebug ^= 1;
			break;
#endif

		case 'g':	/* return the value of the CPU registers. */
			length = kgdb_getregs(regs, remcomRegBuffer, BUFMAX);
			mem2hex(remcomRegBuffer, remcomOutBuffer, length);
			break;

		case 'G':   /* set the value of the CPU registers */
			length = strlen(ptr);
			if ((length & 1) != 0) kgdb_error(KGDBERR_BADPARAMS);
			hex2mem(ptr, remcomRegBuffer, length/2);
			kgdb_putregs(regs, remcomRegBuffer, length/2);
			strcpy(remcomOutBuffer,"OK");
			break;

		case 'm':	/* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
				/* Try to read %x,%x.  */

			if (hexToInt(&ptr, &addr)
			    && *ptr++ == ','
			    && hexToInt(&ptr, &length))	{
				mem2hex((char *)addr, remcomOutBuffer, length);
			} else {
				kgdb_error(KGDBERR_BADPARAMS);
			}
			break;

		case 'M': /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
			/* Try to read '%x,%x:'.  */

			if (hexToInt(&ptr, &addr)
			    && *ptr++ == ','
			    && hexToInt(&ptr, &length)
			    && *ptr++ == ':') {
				hex2mem(ptr, (char *)addr, length);
				strcpy(remcomOutBuffer, "OK");
			} else {
				kgdb_error(KGDBERR_BADPARAMS);
			}
			break;


		case 'k':    /* kill the program, actually return to monitor */
			kd.extype = KGDBEXIT_KILL;
			*regs = entry_regs;
			first_entry = 1;
			goto doexit;

		case 'C':    /* CSS  continue with signal SS */
			*ptr = '\0';	/* ignore the signal number for now */
			/* fall through */

		case 'c':    /* cAA..AA  Continue; address AA..AA optional */
			/* try to read optional parameter, pc unchanged if no parm */
			kd.extype = KGDBEXIT_CONTINUE;

			if (hexToInt(&ptr, &addr)) {
				kd.exaddr = addr;
				kd.extype |= KGDBEXIT_WITHADDR;
			}

			goto doexit;

		case 'S':    /* SSS  single step with signal SS */
			*ptr = '\0';	/* ignore the signal number for now */
			/* fall through */

		case 's':
			kd.extype = KGDBEXIT_SINGLE;

			if (hexToInt(&ptr, &addr)) {
				kd.exaddr = addr;
				kd.extype |= KGDBEXIT_WITHADDR;
			}

		doexit:
/* Need to flush the instruction cache here, as we may have deposited a
 * breakpoint, and the icache probably has no way of knowing that a data ref to
 * some location may have changed something that is in the instruction cache.
 */
			kgdb_flush_cache_all();
			kgdb_exit(regs, &kd);
			kgdb_active = 0;
			kgdb_interruptible(1);
			return (1);

		case 'r':		/* Reset (if user process..exit ???)*/
			panic("kgdb reset.");
			break;

		case 'P':    /* Pr=v  set reg r to value v (r and v are hex) */
			if (hexToInt(&ptr, &addr)
			    && *ptr++ == '='
			    && ((length = strlen(ptr)) & 1) == 0) {
				hex2mem(ptr, remcomRegBuffer, length/2);
				kgdb_putreg(regs, addr,
					remcomRegBuffer, length/2);
				strcpy(remcomOutBuffer,"OK");
			} else {
				kgdb_error(KGDBERR_BADPARAMS);
			}
			break;
		}			/* switch */

		if (errnum != 0)
			sprintf(remcomOutBuffer, "E%02d", errnum);

#ifdef KGDB_DEBUG
		if (kdebug)
			printf("kgdb: remcomOutBuffer: %s\n", remcomOutBuffer);
#endif

		/* reply to the request */
		putpacket((unsigned char *)&remcomOutBuffer);

	} /* while(1) */
}
Пример #19
0
////////////////////////////////////////////////////////////////////////////////
// Lexer::Type::string
//   '|"
//   [ U+XXXX | \uXXXX | \" | \' | \\ | \/ | \b | \f | \n | \r | \t | . ]
//   '|"
bool Lexer::isString (std::string& token, Lexer::Type& type, int quote)
{
  std::size_t marker = _cursor;

  if (_text[marker] == quote)
  {
    token = _text.substr (marker++, 1);

    int c;
    while ((c = _text[marker]))
    {
      // EOS.
      if (c == quote)
        break;

      // Unicode U+XXXX or \uXXXX codepoint.
      else if (_eos - marker >= 6 &&
               ((_text[marker + 0] == 'U' && _text[marker + 1] == '+') ||
                (_text[marker + 0] == '\\' && _text[marker + 1] == 'u')) &&
               isHexDigit (_text[marker + 2]) &&
               isHexDigit (_text[marker + 3]) &&
               isHexDigit (_text[marker + 4]) &&
               isHexDigit (_text[marker + 5]))
      {
        token += utf8_character (
                   hexToInt (
                     _text[marker + 2],
                     _text[marker + 3],
                     _text[marker + 4],
                     _text[marker + 5]));
        marker += 6;
      }

      // An escaped thing.
      else if (c == '\\')
      {
        c = _text[++marker];

        switch (c)
        {
        case '"':  token += (char) 0x22; ++marker; break;
        case '\'': token += (char) 0x27; ++marker; break;
        case '\\': token += (char) 0x5C; ++marker; break;
        case 'b':  token += (char) 0x08; ++marker; break;
        case 'f':  token += (char) 0x0C; ++marker; break;
        case 'n':  token += (char) 0x0A; ++marker; break;
        case 'r':  token += (char) 0x0D; ++marker; break;
        case 't':  token += (char) 0x09; ++marker; break;
        case 'v':  token += (char) 0x0B; ++marker; break;

        // This pass-through default case means that anythign can be escaped
        // harmlessly. In particular 'quote' is included, if it not one of the
        // above characters.
        default:   token += (char) c;    ++marker; break;
        }
      }

      // Ordinary character.
      else
        token += utf8_character (utf8_next_char (_text, marker));
    }

    if (_text[marker] == quote)
    {
      token += _text.substr (marker++, 1);
      type = Lexer::Type::string;
      _cursor = marker;
      return true;
    }
  }

  return false;
}
Пример #20
0
int handle_exception(arch & archi, int sigval)
{
	char *ptr;
	int addr, length;
	static int ThreadInfoFirst=0;

	ptr = remcomOutBuffer;

	writeTPacket(remcomOutBuffer, archi, sigval);

	if(putpacket(remcomOutBuffer))
		return 2;

	while(1)
	{
		remcomOutBuffer[0] = 0;

		if(!(ptr = getpacket()))
			return 2;
		switch (*ptr++)
		{
			case '?':
				remcomOutBuffer[0] = 'S';
				sprintf(&(remcomOutBuffer[1]), "%02X", sigval);
				break;

			case 'd':	/* toggle debug flag */
				break;

			case 'g':	/* return the value of the CPU registers */
				ptr = remcomOutBuffer;
				writegRepPacket(&ptr, archi);
				break;

			case 'G':	/* set the value of the CPU registers - return OK */
				writeGPacketToReg(ptr, archi);

				strcpy(remcomOutBuffer, "OK");
				break;

			case 'm':	/* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
				/* Try to read %x,%x.  */
				if(hexToInt(&ptr, &addr) && *ptr++ == ','
				  && hexToInt(&ptr, &length))
				{
					mem2hex(addr, remcomOutBuffer, length, archi);
					break;
				}
				else
					strcpy(remcomOutBuffer, "E01");	/* Pas réussi à lire la trame */
				break;

			case 'M':	/* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
				if(hexToInt(&ptr, &addr) && *ptr++ == ','
				  && hexToInt(&ptr, &length) && *ptr++ == ':')
				{
					if(hex2mem(ptr, addr, length, archi))
						strcpy(remcomOutBuffer, "OK");
					else
						strcpy(remcomOutBuffer, "E03");	/* écriture fail */
				}
				else
					strcpy(remcomOutBuffer, "E02");	/*Pas capable de décoder */
				break;

			case 'c':	/* cAA..AA    Continue at address AA..AA(optional) */
				if(hexToInt(&ptr, &addr))
				{
					archi.setProgramCounter(addr);
				}
				return 0;

			case 'C':	/* cAA..AA    Continue at address AA..AA(optional) */
				return 0;

			case 's':	/*sAA..AA Execute one instruction from AA..AA (optional) */
				if(hexToInt(&ptr, &addr))
				{
					archi.setProgramCounter(addr);
					printf("{step from addr %d}", addr);
				}

#ifdef DEBUG
				printf("%s", (archi.disassemble(archi.programCounter(), 2)).c_str());	/* print instruction to execute */
#endif
				printf("{%d}", archi.execInst(1));
				writeTPacket(remcomOutBuffer, archi, 5);

				break;
			case 'Z':
				switch (*ptr++)
				{
					case '0':
					case '1':
						if(*ptr++ == ',' && hexToInt(&ptr, &addr)
						  && *ptr++ == ',' && hexToInt(&ptr, &length))
						{
							archi.addBreakpoint(addr);
							strcpy(remcomOutBuffer, "OK");
						}
						else
							strcpy(remcomOutBuffer, "E01");	/* Pas réussi à lire la trame */
						break;

					case '2':	/* Read breakpoint */
					case '3':	/* Write breakpoint */
					case '4':	/* Acces breakpoint */
						remcomOutBuffer[0] = '\0';	/* Not suported */
						break;
				}
				break;

			case 'z':
				switch (*ptr++)
				{
					case '0':
					case '1':
						if(*ptr++ == ',' && hexToInt(&ptr, &addr)
						  && *ptr++ == ',' && hexToInt(&ptr, &length))
						{
							archi.removeBreakpoint(addr);
							strcpy(remcomOutBuffer, "OK");
						}
						else
							strcpy(remcomOutBuffer, "E01");	/* Pas réussi à lire la trame */
						break;

					case '2':	/* Read  breakpoint */
					case '3':	/* Write breakpoint */
					case '4':	/* Acces breakpoint */
						remcomOutBuffer[0] = '\0';	/* Not suported */
						break;
				}
				break;

				/* kill the program */
			case 'k':

#ifdef DEBUG
				printf("{[Stub] KILL!}");
#endif
				return -1;

			case 'r':	/* Reset */
#ifdef DEBUG
				printf("{[Stub] Reset!}");
#endif
				archi.reset();
				break;
			case 'D':
#ifdef DEBUG
				printf("{[Stub] Detach}");
#endif
				return 1;
			case 'q':	/*General query packet */
				switch (*ptr++)
				{
					case 'f':
						if(strcmp(ptr, "ThreadInfo") == 0)
						{
							ThreadInfoFirst = 1;
							strcpy(remcomOutBuffer, "m0");
						}
						break;

					case 's':
						if(strcmp(ptr, "ThreadInfo") == 0)
						{
							if(ThreadInfoFirst)
							{
								ThreadInfoFirst = 0;
								strcpy(remcomOutBuffer, "l");
							}
							else
							{
								ThreadInfoFirst = 1;
								strcpy(remcomOutBuffer, "m0");
							}
						}
						break;

					case 'C':
						strcpy(remcomOutBuffer, "QC0");
						break;
				}

		}	/* switch */

		/* reply to the request */
		if(putpacket(remcomOutBuffer))
			return 2;
	}
}
Пример #21
0
int Lexer::hexToInt (int c0, int c1) const
{
  return (hexToInt (c0) << 4) + hexToInt (c1);
}
Пример #22
0
/*
 * This function does all command procesing for interfacing to gdb.
 */
void
gdb_handle_exception (db_regs_t *raw_regs, int type, int code)
{
  int    sigval;
  int    addr, length;
  char * ptr;
  struct i386regs {
    unsigned int eax;
    unsigned int ecx;
    unsigned int edx;
    unsigned int ebx;
    unsigned int esp;
    unsigned int ebp;
    unsigned int esi;
    unsigned int edi;
    unsigned int eip;
    unsigned int eflags;
    unsigned int cs;
    unsigned int ss;
    unsigned int ds;
    unsigned int es;
  };
  struct i386regs registers;

  registers.eax = raw_regs->tf_eax;
  registers.ebx = raw_regs->tf_ebx;
  registers.ecx = raw_regs->tf_ecx;
  registers.edx = raw_regs->tf_edx;

  registers.esp = raw_regs->tf_esp;
  registers.ebp = raw_regs->tf_ebp;
  registers.esi = raw_regs->tf_esi;
  registers.edi = raw_regs->tf_edi;

  registers.eip = raw_regs->tf_eip;
  registers.eflags = raw_regs->tf_eflags;

  registers.cs = raw_regs->tf_cs;
  registers.ss = raw_regs->tf_ss;
  registers.ds = raw_regs->tf_ds;
  registers.es = raw_regs->tf_es;

  /* reply to host that an exception has occurred */
  sigval = computeSignal (type);
  ptr = remcomOutBuffer;

  *ptr++ = 'T';
  *ptr++ = hexchars[sigval >> 4];
  *ptr++ = hexchars[sigval & 0xf];

  *ptr++ = hexchars[PC >> 4];
  *ptr++ = hexchars[PC & 0xf];
  *ptr++ = ':';
  ptr = mem2hex ((vm_offset_t)&registers.eip, ptr, 4);
  *ptr++ = ';';

  *ptr++ = hexchars[FP >> 4];
  *ptr++ = hexchars[FP & 0xf];
  *ptr++ = ':';
  ptr = mem2hex ((vm_offset_t)&registers.ebp, ptr, 4);
  *ptr++ = ';';

  *ptr++ = hexchars[SP >> 4];
  *ptr++ = hexchars[SP & 0xf];
  *ptr++ = ':';
  ptr = mem2hex ((vm_offset_t)&registers.esp, ptr, 4);
  *ptr++ = ';';

  *ptr++ = 0;

  putpacket (remcomOutBuffer);

  while (1)
    {
      remcomOutBuffer[0] = 0;

      getpacket (remcomInBuffer);
      switch (remcomInBuffer[0]) 
	{
	case '?':
	  remcomOutBuffer[0] = 'S';
	  remcomOutBuffer[1] = hexchars[sigval >> 4];
	  remcomOutBuffer[2] = hexchars[sigval % 16];
	  remcomOutBuffer[3] = 0;
	  break;

	case 'D':		/* detach; say OK and turn off gdb */
	  putpacket(remcomOutBuffer);
	  boothowto &= ~RB_GDB;
	  return;

	case 'g':		/* return the value of the CPU registers */
	  mem2hex ((vm_offset_t)&registers, remcomOutBuffer, NUMREGBYTES);
	  break;

	case 'G':		/* set the value of the CPU registers - return OK */
	  hex2mem (&remcomInBuffer[1], (vm_offset_t)&registers, NUMREGBYTES);
	  strcpy (remcomOutBuffer, "OK");
	  break;

	case 'P':		/* Set the value of one register */
	  {
	    int regno;

	    ptr = &remcomInBuffer[1];

	    if (hexToInt (&ptr, &regno)
		&& *ptr++ == '='
		&& regno < NUM_REGS)
	      {
		hex2mem (ptr, (vm_offset_t)&registers + regno * 4, 4);
		strcpy(remcomOutBuffer,"OK");
	      }
	    else
	      strcpy (remcomOutBuffer, "P01");
	    break;
	  }
	case 'm':	/* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
	  /* Try to read %x,%x.  */

	  ptr = &remcomInBuffer[1];

	  if (hexToInt (&ptr, &addr)
	      && *(ptr++) == ','
	      && hexToInt (&ptr, &length))
	    {
	      if (mem2hex((vm_offset_t) addr, remcomOutBuffer, length) == NULL)
		strcpy (remcomOutBuffer, "E03");
	      break;
	    }
	  else
	    strcpy (remcomOutBuffer, "E01");
	  break;

	case 'M': /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */

	  /* Try to read '%x,%x:'.  */

	  ptr = &remcomInBuffer[1];

	  if (hexToInt(&ptr,&addr)
	      && *(ptr++) == ','
	      && hexToInt(&ptr, &length)
	      && *(ptr++) == ':')
	    {
	      if (hex2mem(ptr, (vm_offset_t) addr, length) == NULL)
		strcpy (remcomOutBuffer, "E03");
	      else
		strcpy (remcomOutBuffer, "OK");
	    }
	  else
	    strcpy (remcomOutBuffer, "E02");
	  break;

	  /* cAA..AA    Continue at address AA..AA(optional) */
	  /* sAA..AA   Step one instruction from AA..AA(optional) */
	case 'c' :
	case 's' :
	  /* try to read optional parameter, pc unchanged if no parm */

	  ptr = &remcomInBuffer[1];
	  if (hexToInt(&ptr,&addr))
	    registers.eip = addr;


	  /* set the trace bit if we're stepping */
	  if (remcomInBuffer[0] == 's')
	    registers.eflags |= PSL_T;
	  else
	    registers.eflags &= ~PSL_T;

	  raw_regs->tf_eax = registers.eax;
	  raw_regs->tf_ebx = registers.ebx;
	  raw_regs->tf_ecx = registers.ecx;
	  raw_regs->tf_edx = registers.edx;

	  raw_regs->tf_esp = registers.esp;
	  raw_regs->tf_ebp = registers.ebp;
	  raw_regs->tf_esi = registers.esi;
	  raw_regs->tf_edi = registers.edi;

	  raw_regs->tf_eip = registers.eip;
	  raw_regs->tf_eflags = registers.eflags;

	  raw_regs->tf_cs = registers.cs;
	  raw_regs->tf_ss = registers.ss;
	  raw_regs->tf_ds = registers.ds;
	  raw_regs->tf_es = registers.es;
	  return;

	} /* switch */

      /* reply to the request */
      putpacket (remcomOutBuffer);
    }
}
Пример #23
0
/*
 * This function does all command procesing for interfacing to gdb.
 */
void handle_exception (int exceptionVector)
{
    int sigval, stepping;
    int addr, length;
    char *ptr;
    int newPC;
    Frame *frame;

    if (remote_debug)
        printf ("vector=%d, sr=0x%x, pc=0x%x\n",
                exceptionVector, registers[PS], registers[PC]);

    /* reply to host that an exception has occurred */
    sigval = computeSignal (exceptionVector);
    remcomOutBuffer[0] = 'S';
    remcomOutBuffer[1] = hexchars[sigval >> 4];
    remcomOutBuffer[2] = hexchars[sigval % 16];
    remcomOutBuffer[3] = 0;

    putpacket (remcomOutBuffer);

    stepping = 0;

    while (1 == 1)
    {
        remcomOutBuffer[0] = 0;
        ptr = getpacket ();
        switch (*ptr++)
        {
        case '?':
            remcomOutBuffer[0] = 'S';
            remcomOutBuffer[1] = hexchars[sigval >> 4];
            remcomOutBuffer[2] = hexchars[sigval % 16];
            remcomOutBuffer[3] = 0;
            break;
        case 'd':
            remote_debug = !(remote_debug);	/* toggle debug flag */
            break;
        case 'g':		/* return the value of the CPU registers */
            mem2hex ((char *) registers, remcomOutBuffer, NUMREGBYTES);
            break;
        case 'G':		/* set the value of the CPU registers - return OK */
            hex2mem (ptr, (char *) registers, NUMREGBYTES);
            strcpy (remcomOutBuffer, "OK");
            break;

        /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
        case 'm':
            if (setjmp (remcomEnv) == 0)
            {
                exceptionHandler (2, handle_buserror);

                /* TRY TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
                if (hexToInt (&ptr, &addr))
                    if (*(ptr++) == ',')
                        if (hexToInt (&ptr, &length))
                        {
                            ptr = 0;
                            mem2hex ((char *) addr, remcomOutBuffer, length);
                        }

                if (ptr)
                {
                    strcpy (remcomOutBuffer, "E01");
                }
            }
            else
            {
                exceptionHandler (2, _catchException);
                strcpy (remcomOutBuffer, "E03");
                debug_error ("%s","bus error");
            }

            /* restore handler for bus error */
            exceptionHandler (2, _catchException);
            break;

        /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
        case 'M':
            if (setjmp (remcomEnv) == 0)
            {
                exceptionHandler (2, handle_buserror);

                /* TRY TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
                if (hexToInt (&ptr, &addr))
                    if (*(ptr++) == ',')
                        if (hexToInt (&ptr, &length))
                            if (*(ptr++) == ':')
                            {
                                hex2mem (ptr, (char *) addr, length);
                                ptr = 0;
                                strcpy (remcomOutBuffer, "OK");
                            }
                if (ptr)
                {
                    strcpy (remcomOutBuffer, "E02");
                }
            }
            else
            {
                exceptionHandler (2, _catchException);
                strcpy (remcomOutBuffer, "E03");
                debug_error ("%s","bus error");
            }

            /* restore handler for bus error */
            exceptionHandler (2, _catchException);
            break;

        /* cAA..AA    Continue at address AA..AA(optional) */
        /* sAA..AA   Step one instruction from AA..AA(optional) */
        case 's':
            stepping = 1;
        case 'c':
            /* try to read optional parameter, pc unchanged if no parm */
            if (hexToInt (&ptr, &addr))
                registers[PC] = addr;

            newPC = registers[PC];

            /* clear the trace bit */
            registers[PS] &= 0x7fff;

            /* set the trace bit if we're stepping */
            if (stepping)
                registers[PS] |= 0x8000;

            /*
             * look for newPC in the linked list of exception frames.
             * if it is found, use the old frame it.  otherwise,
             * fake up a dummy frame in returnFromException().
             */
            if (remote_debug)
                printf ("new pc = 0x%x\n", newPC);
            frame = lastFrame;
            while (frame)
            {
                if (remote_debug)
                    printf ("frame at 0x%x has pc=0x%x, except#=%d\n",
                            frame, frame->exceptionPC, frame->exceptionVector);
                if (frame->exceptionPC == newPC)
                    break;		/* bingo! a match */
                /*
                 * for a breakpoint instruction, the saved pc may
                 * be off by two due to re-executing the instruction
                 * replaced by the trap instruction.  Check for this.
                 */
                if ((frame->exceptionVector == 33) &&
                        (frame->exceptionPC == (newPC + 2)))
                    break;
                if (frame == frame->previous)
                {
                    frame = 0;	/* no match found */
                    break;
                }
                frame = frame->previous;
            }

            /*
             * If we found a match for the PC AND we are not returning
             * as a result of a breakpoint (33),
             * trace exception (9), nmi (31), jmp to
             * the old exception handler as if this code never ran.
             */
            if (frame)
            {
                if ((frame->exceptionVector != 9) &&
                        (frame->exceptionVector != 31) &&
                        (frame->exceptionVector != 33))
                {
                    /*
                     * invoke the previous handler.
                     */
                    if (oldExceptionHook)
                        (*oldExceptionHook) (frame->exceptionVector);
                    newPC = registers[PC];	/* pc may have changed  */
                    if (newPC != frame->exceptionPC)
                    {
                        if (remote_debug)
                            printf ("frame at 0x%x has pc=0x%x, except#=%d\n",
                                    frame, frame->exceptionPC,
                                    frame->exceptionVector);
                        /* re-use the last frame, we're skipping it (longjump?) */
                        frame = (Frame *) 0;
                        _returnFromException (frame);	/* this is a jump */
                    }
                }
            }

            /* if we couldn't find a frame, create one */
            if (frame == 0)
            {
                frame = lastFrame - 1;

                /* by using a bunch of print commands with breakpoints,
                   it's possible for the frame stack to creep down.  If it creeps
                   too far, give up and reset it to the top.  Normal use should
                   not see this happen.
                 */
                if ((unsigned int) (frame - 2) < (unsigned int) &gdbFrameStack)
                {
                    initializeRemcomErrorFrame ();
                    frame = lastFrame;
                }
                frame->previous = lastFrame;
                lastFrame = frame;
                frame = 0;	/* null so _return... will properly initialize it */
            }

            _returnFromException (frame);	/* this is a jump */

            break;

        /* kill the program */
        case 'k':		/* do nothing */
            break;
        }			/* switch */

        /* reply to the request */
        putpacket (remcomOutBuffer);
    }
}
Пример #24
0
	void HandleSignal(int signal)
	{
		static const std::string INVALID_LINE_INDICATOR = "#####";
		const std::string logFileName = logOutput.GetFilename();

		std::string error;
		std::queue<std::string> paths;
		std::queue<uintptr_t> addresses;
		std::map<std::string,uintptr_t> binPath_baseMemAddr;

		logOutput.RemoveAllSubscribers();
		{
			LogObject log;
			if (signal == SIGSEGV) {
				error = "Segmentation fault (SIGSEGV)";
			} else if (signal == SIGILL) {
				error = "Illegal instruction (SIGILL)";
			} else if (signal == SIGPIPE) {
				error = "Broken pipe (SIGPIPE)";
			} else if (signal == SIGIO) {
				error = "IO-Error (SIGIO)";
			} else if (signal == SIGABRT) {
				error = "Aborted (SIGABRT)";
			} else {
				// we should never get here
				error = "Unknown signal";
			}
			log << error << " in spring " << SpringVersion::GetFull() << "\nStacktrace:\n";

			std::vector<void*> buffer(128);
			const int numLines = backtrace(&buffer[0], buffer.size());    // stack pointers
			char** lines       = backtrace_symbols(&buffer[0], numLines); // give them meaningfull names
			if (lines == NULL) {
				log << "Unable to create stacktrace\n";
			} else {
				for (int l = 0; l < numLines; l++) {
					const std::string line(lines[l]);
					log << line;

					// example paths: "./spring" "/usr/lib/AI/Skirmish/NTai/0.666/libSkirmishAI.so"
					std::string path;
					size_t begin = 0;
					size_t end   = line.find_last_of('('); // if there is a function name
					if (end == std::string::npos) {
						end      = line.find_last_of('['); // if there is only the memory address
						if ((end != std::string::npos) && (end > 0)) {
							end--; // to get rid of the ' ' before the '['
						}
					}
					if (end == std::string::npos) {
						path = INVALID_LINE_INDICATOR;
					} else {
						path = line.substr(begin, end-begin);
					}

					// example address: "0x89a8206"
					std::string addr;
					begin = line.find_last_of('[');
					end = std::string::npos;
					if (begin != std::string::npos) {
						end = line.find_last_of(']');
					}
					if ((begin == std::string::npos) || (end == std::string::npos)) {
						addr = INVALID_LINE_INDICATOR;
					} else {
						addr = line.substr(begin+1, end-begin-1);
					}

					if (path == "") {
						log << " # NOTE: no path -> not translating";
					} else if ((path == INVALID_LINE_INDICATOR)
							|| (addr == INVALID_LINE_INDICATOR)) {
						log << " # NOTE: invalid stack-trace line -> not translating";
					} else {
						const std::string absPath = createAbsolutePath(path);
						binPath_baseMemAddr[absPath] = 0;
						paths.push(absPath);
						const uintptr_t addr_num = hexToInt(addr.c_str());
						addresses.push(addr_num);
					}
					log << "\n";
				}
				delete lines;
				lines = NULL;
			}
			log << "Translated Stacktrace:\n";
		}
		logOutput.End(); // Stop writing to log.

		findBaseMemoryAddresses(binPath_baseMemAddr);

		std::string lastPath;
		while (!paths.empty()) {
			std::ostringstream buf;
			lastPath = paths.front();
			const std::string symbolFile = locateSymbolFile(lastPath);
			const uintptr_t baseAddress = binPath_baseMemAddr[lastPath];
			buf << "addr2line " << "--exe=\"" << symbolFile << "\"";
			// add addresses as long as the path stays the same
			while (!paths.empty() && (lastPath == paths.front())) {
				uintptr_t addr_num = addresses.front();
				if (paths.front() != Platform::GetBinaryFile() && (addr_num > baseAddress)) {
					// shift the stack trace address by the value of
					// the libraries base address in process memory
					// for all binaries that are not the processes main binary
					// (which could be spring or spring-dedicated for example)
					addr_num -= baseAddress;
				}
				buf << " 0x" << intToHexString(addr_num);
				lastPath = paths.front();
				paths.pop();
				addresses.pop();
			}
			buf << " >> " << logFileName; // pipe to infolog (which will be in CWD)
			system(buf.str().c_str());
		}

		ErrorMessageBox(error, "Spring crashed", 0);
	}
Пример #25
0
void gdbstub_loop(void) {
	int addr;
	int length;
	char *ptr, *ptr1;
	void *ramaddr;
	unsigned long regbuf[NUMREGS];
	bool reply, set;
	
	while (1)	{
		remcomOutBuffer[0] = 0;

		ptr = getpacket();
		if (!ptr) {
			gdbstub_disconnect();
			return;
		}
		reply = true;
		switch (*ptr++) 	{
			case '?':
				send_stop_reply(SIGNAL_TRAP, NULL, 0);
				reply = false; // already done
				break;

			case 'g':  /* return the value of the CPU registers */
				get_registers(regbuf);
				ptr = remcomOutBuffer;
				ptr = mem2hex(regbuf, ptr, NUMREGS * sizeof(unsigned long)); 
				break;
		
			case 'G':  /* set the value of the CPU registers - return OK */
				hex2mem(ptr, regbuf, NUMREGS * sizeof(unsigned long));
				set_registers(regbuf);
				strcpy(remcomOutBuffer,"OK");
				break;
				
			case 'p': /* pn Read the value of register n */
				if (hexToInt(&ptr, &addr) && (size_t)addr < sizeof(regbuf)) {
					mem2hex(get_registers(regbuf) + addr, remcomOutBuffer, sizeof(unsigned long));
				} else {
					strcpy(remcomOutBuffer,"E01");
				}
				break;
				
			case 'P': /* Pn=r Write register n with value r */
				ptr = strtok(ptr, "=");
				if (hexToInt(&ptr, &addr)
					  && (ptr=strtok(NULL, ""))
					  && (size_t)addr < sizeof(regbuf)
					  // TODO hex2mem doesn't check the format
					  && hex2mem((char*)ptr, &get_registers(regbuf)[addr], sizeof(u32))
					  ) {
					set_registers(regbuf);
					strcpy(remcomOutBuffer, "OK");
				} else {
					strcpy(remcomOutBuffer,"E01");
				}
				break;
		
			case 'm':  /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
				/* Try to read %x,%x */
				if (hexToInt(&ptr, &addr)
				    && *ptr++ == ','
				    && hexToInt(&ptr, &length)) {
					ramaddr = virt_mem_ptr(addr, length);
					if (!ramaddr || mem2hex(ramaddr, remcomOutBuffer, length))
						break;
					strcpy(remcomOutBuffer, "E03");
				}	else
					strcpy(remcomOutBuffer,"E01");
				break;
		
			case 'M': /* MAA..AA,LLLL: Write LLLL bytes at address AA..AA  */
				/* Try to read '%x,%x:' */
				if (hexToInt(&ptr, &addr)
				    && *ptr++ == ','
				    && hexToInt(&ptr, &length)
				    && *ptr++ == ':')	{
				  ramaddr = virt_mem_ptr(addr, length);
				  if (!ramaddr) {
				  	strcpy(remcomOutBuffer, "E03");
				  	break;
				  }
				  if (range_translated((u32)ramaddr, (u32)((char *)ramaddr + length)))
				  	flush_translations();
					if (hex2mem(ptr, ramaddr, length))
						strcpy(remcomOutBuffer, "OK");
					else
						strcpy(remcomOutBuffer, "E03");
				}	else
					strcpy(remcomOutBuffer, "E02");
				break;
		
			case 'S': /* Ssig[;AA..AA] Step with signal at address AA..AA(optional). Same as 's' for us. */
				ptr = strchr(ptr, ';'); /* skip the signal */
				if (ptr)
					ptr++;
			case 's': /* s[AA..AA]  Step at address AA..AA(optional) */
				cpu_events |= EVENT_DEBUG_STEP;
				goto parse_new_pc;
			case 'C': /* Csig[;AA..AA] Continue with signal at address AA..AA(optional). Same as 'c' for us. */
				ptr = strchr(ptr, ';'); /* skip the signal */
				if (ptr)
					ptr++;
			case 'c':    /* c[AA..AA]    Continue at address AA..AA(optional) */
parse_new_pc:
				if (ptr && hexToInt(&ptr, &addr)) {
					arm.reg[15] = addr;
				}
				return;
			case 'q':
				if (!strcmp("Offsets", ptr)) {
					sprintf(remcomOutBuffer, "Text=%x;Data=%x;Bss=%x",
						ndls_debug_alloc_block, ndls_debug_alloc_block,	ndls_debug_alloc_block);
				}
				break;
			case 'Z': /* 0|1|2|3|4,addr,kind  */
				set = true;
				goto z;
			case 'z': /* 0|1|2|3|4,addr,kind  */
				set = false;
			// kinds other than 4 aren't supported
z:
				ptr1 = ptr++;
				ptr = strtok(ptr, ","); 
				if (ptr && hexToInt(&ptr, &addr) && (ramaddr = virt_mem_ptr(addr & ~3, 4))) {
					u32 *flags = &RAM_FLAGS(ramaddr);
					switch (*ptr1) {
						case '0': // mem breakpoint
						case '1': // hw breakpoint
							if (set) {
								if (*flags & RF_CODE_TRANSLATED) flush_translations();
								*flags |= RF_EXEC_BREAKPOINT;
							} else
								*flags &= ~RF_EXEC_BREAKPOINT;
							break;
						case '2': // write watchpoint
						case '4': // access watchpoint
							if (set) *flags |= RF_WRITE_BREAKPOINT;
							else *flags &= ~RF_WRITE_BREAKPOINT;
							if (*ptr1 != 4)
								break;
						case '3': // read watchpoint, access watchpoint
							if (set) *flags |= RF_READ_BREAKPOINT;
							else *flags &= ~RF_READ_BREAKPOINT;
							break;
						default:
							goto reply;
					}
					strcpy(remcomOutBuffer, "OK");
				} else
					strcpy(remcomOutBuffer, "E01");
				break;
		}			/* switch */

reply:
		/* reply to the request */
		if (reply)
			putpacket(remcomOutBuffer);
	}
}
Пример #26
0
int NmeaParser::receiveData(const uint8 *indata, int len)
{
  char databyte;  /* Byte being examined */
  int numDecodedPackets = 0;

  if (state == state_pre_system_startup) {
#ifdef DRIV_NMEA_DEBUG_ALL_INPUT
     m_log->debug("Dropped data since not initialized: %i bytes", len);
#endif
     return -1;
  }

  while (len) {
    databyte=*indata;
#ifdef DRIV_NMEA_DEBUG_ALL_INPUT
    m_log->debug("rd: 0x%08x, 0x%02x", int(state), databyte);
#endif
    switch (state)  {
      case state_idle:
        if (databyte=='$') {
          state=state_in_packet;
          reassembly_ptr = reassmebled_pkt;
          calculated_checksum = 0;
        }
        break;
      case state_in_packet_after_star:
        /* Calculate the checksum */
        if (databyte == '\r' || databyte == '\n') {
           // Checksum done, handle the packet
           ++numDecodedPackets;
           if ( !checksum_present || (checksum_from_pkt == calculated_checksum) ) {
              interpret_packet();
           } else {
              DEBUG_BAD_PACKETS("Broken nmea checksum, %02x!=%02x\n", checksum_from_pkt, calculated_checksum);
           }
           state=state_idle;
        } else {
           checksum_from_pkt = (checksum_from_pkt << 4) + hexToInt(databyte);
           checksum_present=1;
        }
        break;
      case state_in_packet:
        if (databyte=='*') {
           state=state_in_packet_after_star;
           checksum_from_pkt = 0;
           checksum_present=0;
          break;
        }
        if ((reassembly_ptr - reassmebled_pkt) >= 
            int(sizeof(reassmebled_pkt)) ) {
          state=state_idle;  /* Oversized packet, drop it */
          DEBUG_BAD_PACKETS("%s","Oversized packet!\n");
          break;
        }
        *(reassembly_ptr++)=databyte;
        calculated_checksum ^= databyte;
        break;
    case state_pre_system_startup:
       m_log->error("receiveData: state should never be pre_system_startup");
       return 0; //XXX dom something meningful here.
    }
    indata++;
    len--;
  }
  
  return numDecodedPackets;
}
Пример #27
0
int main(int argc, char *argv[]) {
	if (argc != 3) {
		printf("Usage: convbdf [input] [fontname]\n");
		return 1;
	}

	std::ifstream in(argv[1]);
	std::string line;

	std::getline(in, line);
	if (in.fail() || in.eof())
		error("Premature end of file");

	int verMajor, verMinor;
	if (sscanf(line.c_str(), "STARTFONT %d.%d", &verMajor, &verMinor) != 2)
		error("File '%s' is no BDF file", argv[1]);

	if (verMajor != 2 || (verMinor != 1 && verMinor != 2))
		error("File '%s' does not use a supported BDF version (%d.%d)", argv[1], verMajor, verMinor);

	std::string fontName;
	std::string copyright;
	BdfFont font;
	memset(&font, 0, sizeof(font));
	font.ascent = -1;
	font.defaultCharacter = -1;

	int charsProcessed = 0, charsAvailable = 0, descent = -1;

	while (true) {
		std::getline(in, line);
		if (in.fail() || in.eof())
			error("Premature end of file");

		if (hasPrefix(line, "SIZE ")) {
			// Ignore
		} else if (hasPrefix(line, "FONT ")) {
			fontName = line.substr(5);
		} else if (hasPrefix(line, "COPYRIGHT ")) {
			copyright = line.substr(10);
		} else if (hasPrefix(line, "COMMENT ")) {
			// Ignore
		} else if (hasPrefix(line, "FONTBOUNDINGBOX ")) {
			if (sscanf(line.c_str(), "FONTBOUNDINGBOX %d %d %d %d",
			           &font.defaultBox.width, &font.defaultBox.height,
			           &font.defaultBox.xOffset, &font.defaultBox.yOffset) != 4)
				error("Invalid FONTBOUNDINGBOX");
		} else if (hasPrefix(line, "CHARS ")) {
			if (sscanf(line.c_str(), "CHARS %d", &charsAvailable) != 1)
				error("Invalid CHARS");

			font.numCharacters = 256;
			font.bitmaps = new unsigned char *[font.numCharacters];
			memset(font.bitmaps, 0, sizeof(unsigned char *) * font.numCharacters);
			font.advances = new unsigned char[font.numCharacters];
			font.boxes = new BdfBoundingBox[font.numCharacters];
		} else if (hasPrefix(line, "FONT_ASCENT ")) {
			if (sscanf(line.c_str(), "FONT_ASCENT %d", &font.ascent) != 1)
				error("Invalid FONT_ASCENT");
		} else if (hasPrefix(line, "FONT_DESCENT ")) {
			if (sscanf(line.c_str(), "FONT_DESCENT %d", &descent) != 1)
				error("Invalid FONT_ASCENT");
		} else if (hasPrefix(line, "DEFAULT_CHAR ")) {
			if (sscanf(line.c_str(), "DEFAULT_CHAR %d", &font.defaultCharacter) != 1)
				error("Invalid DEFAULT_CHAR");
		} else if (hasPrefix(line, "STARTCHAR ")) {
			++charsProcessed;
			if (charsProcessed > charsAvailable)
				error("Too many characters defined (only %d specified, but %d existing already)",
				      charsAvailable, charsProcessed);

			bool hasWidth = false, hasBitmap = false;

			int encoding = -1;
			int xAdvance;
			unsigned char *bitmap = 0;
			BdfBoundingBox bbox = font.defaultBox;

			while (true) {
				std::getline(in, line);
				if (in.fail() || in.eof())
					error("Premature end of file");

				if (hasPrefix(line, "ENCODING ")) {
					if (sscanf(line.c_str(), "ENCODING %d", &encoding) != 1)
						error("Invalid ENCODING");
				} else if (hasPrefix(line, "DWIDTH ")) {
					int yAdvance;
					if (sscanf(line.c_str(), "DWIDTH %d %d", &xAdvance, &yAdvance) != 2)
						error("Invalid DWIDTH");
					if (yAdvance != 0)
						error("Character %d uses a DWIDTH y advance of %d", encoding, yAdvance);
					if (xAdvance < 0)
						error("Character %d has a negative x advance", encoding);

					if (xAdvance > font.maxAdvance)
						font.maxAdvance = xAdvance;

					hasWidth = true;
				} else if (hasPrefix(line, "BBX" )) {
					if (sscanf(line.c_str(), "BBX %d %d %d %d",
					           &bbox.width, &bbox.height,
					           &bbox.xOffset, &bbox.yOffset) != 4)
						error("Invalid BBX");
				} else if (line == "BITMAP") {
					hasBitmap = true;

					const size_t bytesPerRow = ((bbox.width + 7) / 8);

					// Since we do not load all characters, we only create a
					// buffer for the ones we actually load.
					if (encoding < font.numCharacters)
						bitmap = new unsigned char[bbox.height * bytesPerRow];

					for (int i = 0; i < bbox.height; ++i) {
						std::getline(in, line);
						if (in.fail() || in.eof())
							error("Premature end of file");
						if (line.size() != bytesPerRow * 2)
							error("Glyph bitmap line too short");

						if (!bitmap)
							continue;

						for (size_t j = 0; j < bytesPerRow; ++j) {
							unsigned char nibble1 = line[j * 2 + 0];
							hexToInt(nibble1);
							unsigned char nibble2 = line[j * 2 + 1];
							hexToInt(nibble2);
							bitmap[i * bytesPerRow + j] = (nibble1 << 4) | nibble2;
						}
					}
				} else if (line == "ENDCHAR") {
					if (encoding == -1 || !hasWidth || !hasBitmap)
						error("Character not completly defined");

					if (encoding < font.numCharacters) {
						font.advances[encoding] = xAdvance;
						font.boxes[encoding] = bbox;
						font.bitmaps[encoding] = bitmap;
					}
					break;
				}
			}
		} else if (line == "ENDFONT") {
			break;
		} else {
			// Silently ignore other declarations
			//warning("Unsupported declaration: \"%s\"", line.c_str());
		}
	}

	if (font.ascent < 0)
		error("No ascent specified");
	if (descent < 0)
		error("No descent specified");

	font.height = font.ascent + descent;

	int firstCharacter = font.numCharacters;
	int lastCharacter = -1;
	bool hasFixedBBox = true;
	bool hasFixedAdvance = true;

	for (int i = 0; i < font.numCharacters; ++i) {
		if (!font.bitmaps[i])
			continue;

		if (i < firstCharacter)
			firstCharacter = i;

		if (i > lastCharacter)
			lastCharacter = i;

		if (font.advances[i] != font.maxAdvance)
			hasFixedAdvance = false;

		const BdfBoundingBox &bbox = font.boxes[i];
		if (bbox.width != font.defaultBox.width
		    || bbox.height != font.defaultBox.height
		    || bbox.xOffset != font.defaultBox.xOffset
		    || bbox.yOffset != font.defaultBox.yOffset)
			hasFixedBBox = false;
	}

	if (lastCharacter == -1)
		error("No glyphs found");

	// Free the advance table, in case all glyphs use the same advance
	if (hasFixedAdvance) {
		delete[] font.advances;
		font.advances = 0;
	}

	// Free the box table, in case all glyphs use the same box
	if (hasFixedBBox) {
		delete[] font.boxes;
		font.boxes = 0;
	}

	// Adapt for the fact that we never use encoding 0.
	if (font.defaultCharacter < firstCharacter
	    || font.defaultCharacter > lastCharacter)
		font.defaultCharacter = -1;

	font.firstCharacter = firstCharacter;

	charsAvailable = lastCharacter - firstCharacter + 1;
	// Try to compact the tables
	if (charsAvailable < font.numCharacters) {
		unsigned char **bitmaps = new unsigned char *[charsAvailable];
		BdfBoundingBox *boxes = 0;
		if (!hasFixedBBox)
			boxes = new BdfBoundingBox[charsAvailable];
		unsigned char *advances = 0;
		if (!hasFixedAdvance)
			advances = new unsigned char[charsAvailable];

		for (int i = 0; i < charsAvailable; ++i) {
			const int encoding = i + firstCharacter;
			if (font.bitmaps[encoding]) {
				bitmaps[i] = font.bitmaps[encoding];

				if (!hasFixedBBox)
					boxes[i] = font.boxes[encoding];
				if (!hasFixedAdvance)
					advances[i] = font.advances[encoding];
			} else {
				bitmaps[i] = 0;
			}
		}

		delete[] font.bitmaps;
		font.bitmaps = bitmaps;
		delete[] font.advances;
		font.advances = advances;
		delete[] font.boxes;
		font.boxes = boxes;

		font.numCharacters = charsAvailable;
	}

	char dateBuffer[256];
	time_t curTime = time(0);
	snprintf(dateBuffer, sizeof(dateBuffer), "%s", ctime(&curTime));

	// Finally output the cpp source file to stdout
	printf("// Generated by convbdf on %s"
	       "#include \"graphics/fonts/bdf.h\"\n"
	       "\n"
	       "// Font information:\n"
	       "//  Name: %s\n"
	       "//  Size: %dx%d\n"
	       "//  Box: %d %d %d %d\n"
	       "//  Ascent: %d\n"
	       "//  First character: %d\n"
	       "//  Default character: %d\n"
	       "//  Characters: %d\n"
	       "//  Copyright: %s\n"
	       "\n",
	       dateBuffer, fontName.c_str(), font.maxAdvance, font.height,
	       font.defaultBox.width, font.defaultBox.height, font.defaultBox.xOffset,
	       font.defaultBox.yOffset, font.ascent, font.firstCharacter,
	       font.defaultCharacter, font.numCharacters, copyright.c_str());

	printf("namespace Graphics {\n"
	       "\n");

	for (int i = 0; i < font.numCharacters; ++i) {
		if (!font.bitmaps[i])
			continue;

		BdfBoundingBox box = hasFixedBBox ? font.defaultBox : font.boxes[i];
		printf("// Character %d (0x%02X)\n"
		       "// Box: %d %d %d %d\n"
		       "// Advance: %d\n"
		       "//\n", i + font.firstCharacter, i + font.firstCharacter,
		       box.width, box.height, box.xOffset, box.yOffset,
		       hasFixedAdvance ? font.maxAdvance : font.advances[i]);

		printf("// +");
		for (int x = 0; x < box.width; ++x)
			printf("-");
		printf("+\n");

		const unsigned char *bitmap = font.bitmaps[i];

		for (int y = 0; y < box.height; ++y) {
			printf("// |");
			unsigned char data = 0;
			for (int x = 0; x < box.width; ++x) {
				if (!(x % 8))
					data = *bitmap++;

				printf("%c", (data & 0x80) ? '*' : ' ');
				data <<= 1;
			}
			printf("|\n");
		}

		printf("// +");
		for (int x = 0; x < box.width; ++x)
			printf("-");
		printf("+\n");

		const int bytesPerRow = (box.width + 7) / 8;
		bitmap = font.bitmaps[i];
		printf("static const byte glyph%d[] = {\n", i);
		for (int y = 0; y < box.height; ++y) {
			printf("\t");

			for (int x = 0; x < bytesPerRow; ++x) {
				if (x)
					printf(", ");
				printf("0x%02X", *bitmap++);
			}

			if (y != box.height - 1)
				printf(",");
			printf("\n");
		}
		printf("};\n"
		       "\n");
	}

	printf("// Bitmap pointer table\n"
	       "const byte *const bitmapTable[] = {\n");
	for (int i = 0; i < font.numCharacters; ++i) {
		if (font.bitmaps[i])
			printf("\tglyph%d", i);
		else
			printf("\t0");

		if (i != font.numCharacters - 1)
			printf(",");
		printf("\n");
	}
	printf("};\n"
	       "\n");

	if (!hasFixedAdvance) {
		printf("// Advance table\n"
		       "static const byte advances[] = {\n");
		for (int i = 0; i < font.numCharacters; ++i) {
			if (font.bitmaps[i])
				printf("\t%d", font.advances[i]);
			else
				printf("\t0");

			if (i != font.numCharacters - 1)
				printf(",");
			printf("\n");
		}
		printf("};\n"
		       "\n");
	}

	if (!hasFixedBBox) {
		printf("// Bounding box table\n"
		       "static const BdfBoundingBox boxes[] = {\n");
		for (int i = 0; i < font.numCharacters; ++i) {
			if (font.bitmaps[i]) {
				const BdfBoundingBox &box = font.boxes[i];
				printf("\t{ %d, %d, %d, %d }", box.width, box.height, box.xOffset, box.yOffset);
			} else {
				printf("\t{ 0, 0, 0, 0 }");
			}

			if (i != font.numCharacters - 1)
				printf(",");
			printf("\n");
		}
		printf("};\n"
		       "\n");
	}

	printf("// Font structure\n"
	       "static const BdfFontData desc = {\n"
	       "\t%d, // Max advance\n"
	       "\t%d, // Height\n"
	       "\t{ %d, %d, %d, %d }, // Bounding box\n"
	       "\t%d, // Ascent\n"
	       "\n"
	       "\t%d, // First character\n"
	       "\t%d, // Default character\n"
	       "\t%d, // Characters\n"
	       "\n"
	       "\tbitmapTable, // Bitmaps\n",
	       font.maxAdvance, font.height, font.defaultBox.width,
	       font.defaultBox.height, font.defaultBox.xOffset, font.defaultBox.yOffset,
	       font.ascent, font.firstCharacter, font.defaultCharacter, font.numCharacters);

	if (hasFixedAdvance)
		printf("\t0, // Advances\n");
	else
		printf("\tadvances, // Advances\n");

	if (hasFixedBBox)
		printf("\t0 // Boxes\n");
	else
		printf("\tboxes // Boxes\n");

	printf("};\n"
	       "\n"
	       "DEFINE_FONT(%s)\n"
	       "\n"
	       "} // End of namespace Graphics\n",
	       argv[2]);
}
/*
 * This function does all command procesing for interfacing to gdb.
 */
void
handle_exception (int exceptionVector)
{
  int sigval;
  int addr, length, reg;
  char *ptr;
  int newPC;

  gdb_i386vector = exceptionVector;

  if (remote_debug)
    printf ("vector=%d, sr=0x%x, pc=0x%x\n",
	    exceptionVector,
	    registers[PS],
	    registers[PC]);

  /* Reply to host that an exception has occurred.  Always return the
     PC, SP, and FP, since gdb always wants them.  */
  ptr = remcomOutBuffer;
  *ptr++ = 'T';
  sigval = computeSignal (exceptionVector);
  *ptr++ = hexchars[sigval >> 4];
  *ptr++ = hexchars[sigval % 16];

  *ptr++ = hexchars[ESP];
  *ptr++ = ':';
  mem2hex ((char *) &registers[ESP], ptr, REGBYTES, 0);
  ptr += REGBYTES * 2;
  *ptr++ = ';';

  *ptr++ = hexchars[EBP];
  *ptr++ = ':';
  mem2hex ((char *) &registers[EBP], ptr, REGBYTES, 0);
  ptr += REGBYTES * 2;
  *ptr++ = ';';

  *ptr++ = hexchars[PC];
  *ptr++ = ':';
  mem2hex ((char *) &registers[PC], ptr, REGBYTES, 0);
  ptr += REGBYTES * 2;
  *ptr++ = ';';

  *ptr = '\0';

  putpacket (remcomOutBuffer);

  while (1 == 1)
    {
      error = 0;
      remcomOutBuffer[0] = 0;
      getpacket (remcomInBuffer);
      switch (remcomInBuffer[0])
	{
	case '?':
	  remcomOutBuffer[0] = 'S';
	  remcomOutBuffer[1] = hexchars[sigval >> 4];
	  remcomOutBuffer[2] = hexchars[sigval % 16];
	  remcomOutBuffer[3] = 0;
	  break;
	case 'd':
	  remote_debug = !(remote_debug);	/* toggle debug flag */
	  break;
	case 'g':		/* return the value of the CPU registers */
	  mem2hex ((char *) registers, remcomOutBuffer, NUMREGBYTES, 0);
	  break;
	case 'G':		/* set the value of the CPU registers - return OK */
	  hex2mem (&remcomInBuffer[1], (char *) registers, NUMREGBYTES, 0);
	  strcpy (remcomOutBuffer, "OK");
	  break;

	case 'P':		/* Set specific register */
	  ptr = &remcomInBuffer[1];
	  if (hexToInt (&ptr, &reg)
	      && *ptr++ == '=')
	    {
	      hex2mem (ptr, (char *) &registers[reg], REGBYTES, 0);
	      strcpy (remcomOutBuffer, "OK");
	    }
	  else
	    {
	      strcpy (remcomOutBuffer, "E01");
	      debug_error ("malformed register set command; %s",
			   remcomInBuffer);
	    }
	  break;

	  /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
	case 'm':
	  /* TRY TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
	  ptr = &remcomInBuffer[1];
	  if (hexToInt (&ptr, &addr))
	    if (*(ptr++) == ',')
	      if (hexToInt (&ptr, &length))
		{
		  ptr = 0;
		  mem_err = 0;
		  mem2hex ((char *) addr, remcomOutBuffer, length, 1);
		  if (mem_err)
		    {
		      strcpy (remcomOutBuffer, "E03");
		      debug_error ("memory fault", 0);
		    }
		}

	  if (ptr)
	    {
	      strcpy (remcomOutBuffer, "E01");
	      debug_error ("malformed read memory command: %s", remcomInBuffer);
	    }
	  break;

	  /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
	case 'M':
	  /* TRY TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
	  ptr = &remcomInBuffer[1];
	  if (hexToInt (&ptr, &addr))
	    if (*(ptr++) == ',')
	      if (hexToInt (&ptr, &length))
		if (*(ptr++) == ':')
		  {
		    mem_err = 0;
		    hex2mem (ptr, (char *) addr, length, 1);

		    if (mem_err)
		      {
			strcpy (remcomOutBuffer, "E03");
			debug_error ("memory fault", 0);
		      }
		    else
		      {
			strcpy (remcomOutBuffer, "OK");
		      }

		    ptr = 0;
		  }
	  if (ptr)
	    {
	      strcpy (remcomOutBuffer, "E02");
	      debug_error ("malformed write memory command: %s", remcomInBuffer);
	    }
	  break;

	  /* cAA..AA    Continue at address AA..AA(optional) */
	  /* sAA..AA   Step one instruction from AA..AA(optional) */
	case 'c':
	case 's':
	  /* try to read optional parameter, pc unchanged if no parm */
	  ptr = &remcomInBuffer[1];
	  if (hexToInt (&ptr, &addr))
	    registers[PC] = addr;

	  newPC = registers[PC];

	  /* clear the trace bit */
	  registers[PS] &= 0xfffffeff;

	  /* set the trace bit if we're stepping */
	  if (remcomInBuffer[0] == 's')
	    registers[PS] |= 0x100;

	  _returnFromException ();	/* this is a jump */

	  break;

	  /* Detach.  */
	case 'D':
	  putpacket (remcomOutBuffer);
	  registers[PS] &= 0xfffffeff;
	  _returnFromException ();	/* this is a jump */

	  break;

	  /* kill the program */
	case 'k':		/* do nothing */
	  break;
	}			/* switch */

      /* reply to the request */
      putpacket (remcomOutBuffer);
    }
}
void PIC32F42::opcodeFunction() {
    int opcodeValue, address;
    string hexStr;
    opcodeValue = hexToInt('0', '0', memory[PC], memory[PC + 1]);

    switch (opcodeValue) {

            //Move Value to W
        case 80:
            hasOpcode = true;
            W[0] = memory[PC + 2];
            W[1] = memory[PC + 3];
            PC = PC + 4;
            opcodeFunction();
            break;

            //Move W to memory
        case 81:
            hasOpcode = true;
            address = hexToInt(memory[PC + 2], memory[PC + 3], memory[PC + 4], memory[PC + 5])*2;
            memory[address] = W[0];
            memory[address + 1] = W[1];
            PC = PC + 6;
            opcodeFunction();
            break;

            //Add Value to W
        case 90:
        {
            int value;
            string hex_value;
            hasOpcode = true;
            value = hexToInt('0', '0', memory[PC + 2], memory[PC + 3]);
            value = value + hexToInt('0', '0', W[0], W[1]);
            hex_value = intToHex(value);
            W[0] = hex_value[hex_value.size() - 2];
            W[1] = hex_value[hex_value.size() - 1];
            PC = PC + 4;
            opcodeFunction();
        }
            break;

            //Subtract Value from W
        case 91:
        {
            int value;
            string hex_value;
            hasOpcode = true;
            value = hexToInt('0', '0', memory[PC + 2], memory[PC + 3]);
            value = hexToInt('0', '0', W[0], W[1]) - value;
            hex_value = intToHex(value);
            W[0] = hex_value[hex_value.size() - 2];
            W[1] = hex_value[hex_value.size() - 1];
            PC = PC + 4;
            opcodeFunction();
        }
            break;

            //Goto address
        case 110:
            hasOpcode = true;
            int tmp;
            address = hexToInt(memory[PC + 2], memory[PC + 3], memory[PC + 4], memory[PC + 5]);
            PC = address * 2;
            if (PC > (size - 1)) {
                cout << "SIGWEED. Program executed past top of memory\n";
                PC = tmp;
                break;
            }
            opcodeFunction();
            break;

            //Branch if not equal
        case 112:
            hasOpcode = true;
            int comparision, value;
            comparision = hexToInt('0', '0', memory[PC + 2], memory[PC + 3]);
            value = hexToInt('0', '0', W[0], W[1]);
            if (comparision == value) {
                PC = PC + 8;
            } else {
                PC = hexToInt(memory[PC + 4], memory[PC + 5], memory[PC + 6], memory[PC + 7])*2;
            }
            opcodeFunction();
            break;

            //Halt opcode
        case 255:
            cout << "Program halted\n";
            break;

        default:
            if (hasOpcode == true) {
                hexStr = intToHex(PC / 2);
                cout << "Program Counter = 0x" << hexStr << "\n";
                hasOpcode = false;
            } else {
                hexStr = intToHex(PC / 2);
                cout << "SIGOP. Invalid opcode. Program Counter = 0x" << hexStr << "\n";
            }
            break;
    }
}
Пример #30
0
/* return value: 0 if the simulator is to be killed,
 *               1 if the simulator is to be continued.
 */
static int process_gdb_loop(void)
{
  int addr;
  int length;
  int cpu_id;
  int step_cpu, other_cpu = 0;
  char *ptr;
  char type;
  int regnum;
  uint32_t val;

  regnum = regnum;
  step_cpu = other_cpu = 0;

  /* if the hardware is running, we dropped here because the user has
   * hit break in gdb, so we send a signal to GDB indicating that */
  if (hardware->running == 1) {
      remcomOutBuffer[0] = 'S';
      remcomOutBuffer[1] = '0';
      remcomOutBuffer[2] = '5';
      remcomOutBuffer[3] = 0;
      putpacket((unsigned char *)remcomOutBuffer);
  }

  while (1)
    {
      remcomOutBuffer[0] = 0;

      ptr = (char*)getpacket();
      if (ptr == NULL) {
          /* we didn't receive a valid packet, assume that
             the connection has been terminated */
          gdb_interface_close();

          return 1;
      }

      if (debug_packets) printf("from gdb:%s\n", ptr);
      switch (*ptr++) {
      case '?': /* `?' -- last signal */
          remcomOutBuffer[0] = 'S';
          remcomOutBuffer[1] = '0';
          remcomOutBuffer[2] = '1';
          remcomOutBuffer[3] = 0;
          break;
      case 'c':    /* cAA..AA    Continue at address AA..AA(optional) */
          if (hexToInt(&ptr, &addr))
              set_pc(step_cpu, addr);
          hardware->running = 1;
          return 1;
          break;
      case 'd': /* `d' -- toggle debug *(deprecated)* */
          debug_packets = (debug_packets + 1) % 2;
          break;
      case 'g':		/* return the value of the CPU registers */
          read_registers(other_cpu, remcomOutBuffer);
          break;
      case 'G':	   /* set the value of the CPU registers - return OK */
          write_registers(other_cpu, ptr);
          strcpy(remcomOutBuffer,"OK");
	  break;
      case 'H': /* `H'CT... -- set thread */
          type = *ptr++;
          if (hexToInt(&ptr, &cpu_id)) {
              if (cpu_id == -1 || cpu_id == 0) /* XXX all threads */
                  cpu_id = 1;
              if (type == 'c') {
                  step_cpu = cpu_id - 1; /* minus one because
                                            gdb threats start from 1
                                            and yams cpu's from 0. */
                  strcpy(remcomOutBuffer, "OK");
              } else if (type == 'g') {
                  other_cpu = cpu_id - 1; /* same here */
                  strcpy(remcomOutBuffer, "OK");
              } else
                  strcpy(remcomOutBuffer, "E01");
          } else
              strcpy(remcomOutBuffer, "E01");
          break;
      case 'k' : 	  /* kill the program */
          return 0;
          break;
      case 'm':	  /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
          if (hexToInt(&ptr,&addr) &&*ptr++==','&& hexToInt(&ptr,&length)) {
              if (read_mem(addr, length, remcomOutBuffer))
                  strcpy(remcomOutBuffer, "E03");
          } else
              strcpy(remcomOutBuffer, "E01");
          break;
      case 'M': /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA */
          if (hexToInt(&ptr, &addr) && *ptr++ == ','
              && hexToInt(&ptr, &length) && *ptr++ == ':') {
              if (!write_mem(addr, length, ptr))
                  strcpy(remcomOutBuffer, "OK");
              else
                  strcpy(remcomOutBuffer, "E03");
          }
          else
              strcpy(remcomOutBuffer, "E02");
          break;
      case 'p': /* `p'HEX NUMBER OF REGISTER -- read register packet */
          if (hexToInt(&ptr, &regnum) && regnum <= 73)
              sprintf(remcomOutBuffer, "%08x",
                      read_register(other_cpu, regnum));
          else
              sprintf(remcomOutBuffer, "E01");
          break;
      case 'P': /* `P'N...`='R... -- write register */
          if (hexToInt(&ptr, (int*)&regnum) && *ptr++=='=' && hexToInt(&ptr, (int*)&val)) {
              write_register(other_cpu, regnum, val);
              sprintf(remcomOutBuffer, "OK");
          } else
              sprintf(remcomOutBuffer, "E01");
      case 'q': /* `q'QUERY -- general query */
          if (!strcmp(ptr, "fThreadInfo")) {
              int i;
              char *ptr = remcomOutBuffer;
              ptr += sprintf(ptr, "m01");
              if (hardware->num_cpus > 1)
                  for (i = 1; i < hardware->num_cpus; i++)
                      ptr += sprintf(ptr, ",%02x", i + 1);
              sprintf(ptr, "l");
          }
          break;
      case 's': /* `s'ADDR -- step */
          command_step(1);
          sprintf(remcomOutBuffer, "S01");
          break;
      case 'T': /* `T'XX -- thread alive */
          if (hexToInt(&ptr, &cpu_id) && --cpu_id < hardware->num_cpus)
              strcpy(remcomOutBuffer, "OK");
          else
              strcpy(remcomOutBuffer, "E01");
          break;
      case 'z':   /* remove breakpoint: `Z'TYPE`,'ADDR`,'LENGTH */
          type = *ptr++;
          if (*ptr++== ',' && hexToInt(&ptr, &addr)
              && *ptr++ == ',' && hexToInt(&ptr, &length)) {
              if (type == '1') { /* hardware breakpoint */
                  command_breakpoint(0xFFFFFFFF);
                  strcpy(remcomOutBuffer, "OK");
              } else /* all others are unsupported */
                  strcpy(remcomOutBuffer, "E01");
          } else
              strcpy(remcomOutBuffer, "E02");
          break;
      case 'Z':  /* insert breakpoint: `Z'TYPE`,'ADDR`,'LENGTH */
          type = *ptr++;
          if (*ptr++== ',' && hexToInt(&ptr, &addr)
              && *ptr++ == ',' && hexToInt(&ptr, &length)) {
              if (type == '1') { /* hardware breakpoint */
                  command_breakpoint(addr);
                  strcpy(remcomOutBuffer, "OK");
              } else /* all others are unsupported */
                  strcpy(remcomOutBuffer, "E01");

          } else
              strcpy(remcomOutBuffer, "E02");
          break;
      default:
          break;
      }			/* switch */

      /* reply to the request */
      putpacket((unsigned char *)remcomOutBuffer);
      if (debug_packets) printf("to gdb: %s\n", remcomOutBuffer);
    }

}