Example #1
0
DWORD Q4_ConnectToMasterServer(GAME_INFO *pGI, int iMasterIdx)
{
	size_t packetlen=0;
	char sendbuf[40];
	ZeroMemory(sendbuf,sizeof(sendbuf));
	
	int len = 0;
	len = UTILZ_ConvertEscapeCodes(pGI->szMasterQueryString,sendbuf,sizeof(sendbuf));
	char szIP[260];
	strcpy(szIP,pGI->szMasterServerIP[iMasterIdx]);
	
	SplitIPandPORT(szIP,pGI->dwMasterServerPORT);

	dbg_print("Master server %s:%d",szIP,(unsigned short)pGI->dwMasterServerPORT);

	SOCKET ConnectSocket = getsockudp(szIP,(unsigned short)pGI->dwMasterServerPORT);
   
	if(INVALID_SOCKET==ConnectSocket)
	{
		dbg_print("Error connecting to socket!");
		return 1001;
	}
	dbg_print("Sending command %s Len: %d",sendbuf,len);
	if(send(ConnectSocket, sendbuf, len, 0)==SOCKET_ERROR) 
	{
		closesocket(ConnectSocket);		
		dbg_print("Error sending packet!");
		return 1002;
	}

	int i = 0;
	unsigned char *packet[iMAX_PACKETS];
	size_t packlen[iMAX_PACKETS];

	DWORD Q4_dwNewTotalServers=0;
	// Let's retrieve all packets as fast as possible, that's the reason for splitting up int two for loop.
	for(i=0; i<iMAX_PACKETS;i++)
	{
		packet[i] = NULL;
		packet[i]=(unsigned char*)getpacket(ConnectSocket, &packlen[i]);
		if(packet[i]==NULL) //End of transfer
			break;  	
	}
	//Now parse all server IP's from recieved packets
	for(i=0; i<iMAX_PACKETS;i++)
	{
		if(packet[i]==NULL) //End of packets
			break;  	
		Q4_dwNewTotalServers += Q4_ParseServers((char*)packet[i],packlen[i],pGI,Q4_InsertServerItem);
		SetStatusText(pGI->iIconIndex,g_lang.GetString("StatusReceivingMaster"),Q4_dwNewTotalServers,pGI->szGAME_NAME);		
		free(packet[i]);
	}
	
	closesocket(ConnectSocket);
	pGI->dwTotalServers = pGI->vSI.size();
	return 	0;
}
Example #2
0
int Client::handle_packet(uintptr_t * params)
{
	Decoder dec = getpacket();

	switch(dec.get_packet_action()) {
	case A_REG_FIRST:
		return kHPFirstPlayer;

	case A_START_GAME:
		return kHPStartGame;

	case A_GAME_STATE:
		_handle_game_state(dec, params);
		return kHPGameState;

	case A_ROLL_DICE:
		_handle_roll_dice(dec, params);
		return kHPRolledDice;

	case A_YOU_DIED:
		return kHPDead;

	case A_BUY_PROP:
		return kHPBuyProp;

	case A_CARD:
		_handle_card(dec, params);
		return kHPCard;

	case A_CASINO:
		return kHPCasino;

	case A_FREE_PARKING:
		return kHPFreeParking;

	case A_TRADE:
		_handle_trade(dec, params);
		return kHPTrade;

	case A_JAIL:
		return kHPJail;

	case A_ACTION:
		_handle_action(dec, params);
		return kHPAction;

	default:
		throw std::runtime_error("Unknown packet.");
		return kHPBad;
	}
}
Example #3
0
int
main(int argc, char *argv[])
{
	unsigned int sport = 0;
	unsigned int dport = 0;
	char *destination = NULL;
	char *source = NULL;
	int fd;

	int i = 1;
	while(i<argc) {
		
		if(!strcmp(argv[i], "--listen-port") || !strcmp(argv[i], "-i")) {
			sport = atoi(argv[i+1]);
		}
		else if(!strcmp(argv[i], "--broadcast-port") || !strcmp(argv[i], "-o")) {
			dport = atoi(argv[i+1]);
		}
		else if(!strcmp(argv[i], "--broadcast-address") || !strcmp(argv[i], "-b")) {
			destination = argv[i+1];
		}
		else if(!strcmp(argv[i], "--source-address") || !strcmp(argv[i], "-s")) {
			source = argv[i+1];
		}

		i += 2;
	}

	if (sport < 1 || sport > 65535)
		usage(argv[0]);		
	if (dport < 1 || dport > 65535)
		usage(argv[0]);			

	/* Workaround to avoid loop */
	if(dport == sport)
		usage(argv[0]);

	nozombies();

	fd = listenon(sport);
	for (;;) {
		getpacket(fd, sport, destination, dport, source);
	}

	/* NOTREACHED */
	return 0;
}
Example #4
0
int Client::initialize(const std::string & name)
{
	// initialize sends a register packet to the server
	// and gets a response back. the server will either send:
	// 1) a simple packet with 'A_START_GAME' action
	// 2) a duplicate of the register packet you sent

	// if #1 is true, then this client is 'first' client,
	// and will subsequently control the game start

	// if #2 is true, then this client is not the first,
	// but has successfully registered.

	// any other response would indicate an error, such as
	// 1) too many players.
	// 2) game has already started
	// 3) nick name is being used

	assert(!name.empty());

	ActionPacket reg(kAPRegister);
	reg.add_sparam(name);
	sendpacket(&reg);
	
	// may throw an exception (should be handled in caller)
	Decoder dec = getpacket();

	switch( dec.get_packet_action() ) {
	case A_REG_FIRST: 
		return 1;

	case A_REG_GOOD:
		return 0;

	case A_REG_FAIL:
		return -1;
		
	default:
		throw std::runtime_error("Server responded with invalid packet");
		return -1;
	}
 	
	return -1;
}
Example #5
0
unsigned char* Warsow_patch(SOCKET pSocket,SERVER_INFO *pSI, DWORD *dwStartTick,size_t *packetlen)
{

	unsigned char *packet=NULL;
	char szWarsow042[] = {"\xFF\xFF\xFF\xFFgetinfo"};
	*packetlen = send(pSocket, szWarsow042, sizeof(szWarsow042), 0);	
	*dwStartTick = GetTickCount();
	packet=(unsigned char*)getpacket(pSocket, packetlen);
	if(packet!=NULL)
		return packet;

	if(*packetlen==SOCKET_ERROR) 
	{
		dbg_print("Error at send()\n");
		closesocket(pSocket);		
		pSI->cPurge++;

	}
	return NULL;
}
Example #6
0
static int
serial_image_reader(Camera *camera,CameraFile *file,int nr,unsigned char ***imagebufs,int *sizes, GPContext *context) {
    int	picnum,curread,ret=0;
    GPPort *port = camera->port;
    unsigned int id;

    jd11_select_image(port,nr);
    *imagebufs = (unsigned char**)malloc(3*sizeof(char**));
    for (picnum=0;picnum<3;picnum++) {
	curread=0;
	sizes[picnum] = jd11_imgsize(port);
	(*imagebufs)[picnum]=(unsigned char*)malloc(sizes[picnum]+400);
	_send_cmd(port,0xfff1);
	id = gp_context_progress_start (context, sizes[picnum],
			_("Downloading data..."));
	while (curread<sizes[picnum]) {
	    int readsize = sizes[picnum]-curread;
	    if (readsize > 200) readsize = 200;
	    ret=getpacket(port,(*imagebufs)[picnum]+curread,readsize);
	    if (ret==0)
		break;
	    curread+=ret;
	    if (ret<200)
		break;
	    gp_context_progress_update (context, id, curread);
	    if (gp_context_cancel (context) == GP_CONTEXT_FEEDBACK_CANCEL) {
		int j;
		/* What to do ... Just free the stuff we allocated for now. */
		for (j=0;j<picnum;j++)
		    free((*imagebufs)[picnum]);
		free(*imagebufs);
		return GP_ERROR_CANCEL;
	    }
	    _send_cmd(port,0xfff1);
	}
	gp_context_progress_stop (context, id);
    }
    return GP_OK;
}
Example #7
0
long initmultiplayerscycle(void)
{
	long i, k;

	getpacket(&i,0);

	tims = GetTickCount();
	if (myconnectindex == connecthead)
	{
		for(i=numplayers-1;i>0;i--)
			if (!otherip[i]) break;
		if (!i) {
			netready = 1;
			return 0;
		}
	}
	else
	{
		if (netready) return 0;
		if (tims < lastsendtims[connecthead]) lastsendtims[connecthead] = tims;
		if (tims >= lastsendtims[connecthead]+250) //1000/PAKRATE)
		{
			lastsendtims[connecthead] = tims;

				//   short crc16ofs;       //offset of crc16
				//   long icnt0;           //-1 (special packet for MMULTI.C's player collection)
				//   ...
				//   unsigned short crc16; //CRC16 of everything except crc16
			k = 2;
			*(long *)&pakbuf[k] = -1; k += 4;
			pakbuf[k++] = 0xaa;
			*(unsigned short *)&pakbuf[0] = (unsigned short)k;
			*(unsigned short *)&pakbuf[k] = getcrc16(pakbuf,k); k += 2;
			netsend(connecthead,pakbuf,k);
		}
	}

	return 1;
}
Example #8
0
DWORD Q4_Get_ServerStatus(SERVER_INFO *pSI,long (*UpdatePlayerListView)(PLAYERDATA *q4players),long (*UpdateRulesListView)(SERVER_RULES *pServRules))
{

	if(pSI==NULL)
	{
		dbg_print("Invalid pointer argument @Get_ServerStatus!\n");
		return -1;
	}

	SOCKET pSocket =  getsockudp(pSI->szIPaddress ,(unsigned short)pSI->usPort); 
 
	if(pSocket==INVALID_SOCKET)
	{
	  dbg_print("Error at getsockudp()\n");
	  return -1;
	}
  
	char sendbuf[]={"\xFF\xFFgetInfo\x00\x01\x00\x00\x00"};
	

	size_t packetlen = 0;

	//Some default values
	pSI->dwPing = 9999;

	//If country shortname is EU or zz (Unknown) try to find a country based on the IP address.
	if( ((pSI->szShortCountryName[0]=='E') && (pSI->szShortCountryName[1]=='U')) || ((pSI->szShortCountryName[0]=='z') && (pSI->szShortCountryName[1]=='z')))
	{
		char szShortName[4];			
		g_IPtoCountry.IPtoCountry(pSI->dwIP,szShortName);
		strncpy_s(pSI->szShortCountryName,sizeof(pSI->szShortCountryName),szShortName,_TRUNCATE);
	}
	DWORD dwRetries=0;
retry:
	packetlen = send(pSocket, sendbuf, 14, 0);
	if(packetlen==SOCKET_ERROR) 
	{
		dbg_print("Error at send()\n");
		closesocket(pSocket);
		pSI->cPurge++;
	//	pSI->bLocked = FALSE;
		return -1;
	}

	unsigned char *packet=NULL;
	DWORD dwStartTick=0;

	
	dwStartTick = GetTickCount();

	packet=(unsigned char*)getpacket(pSocket, &packetlen);
	if(packet==NULL)
	{
		if(dwRetries<AppCFG.dwRetries)
		{
			dwRetries++;
			goto retry;
		}
	}

	if(packet) 
	{
		pSI->dwPing = (GetTickCount() - dwStartTick);
		//pSI->cPure=0;

		//dbg_dumpbuf("dump.bin", packet, packetlen);
		SERVER_RULES *pServRules=NULL;
		char *end = (char*)((packet)+packetlen);
		
		GetServerLock(pSI);

		CleanUp_ServerInfo(pSI);

		char *pCurrPointer=NULL; //will contain the start address for the player data
		pCurrPointer = Q4_ParseServerRules(pSI,pServRules,(char*)packet,packetlen);
		pSI->pServerRules = pServRules;
		if(pServRules!=NULL)
		{		
			char *szVarValue = NULL;

			pSI->szServerName = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_SERVERNAME).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szMap = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_MAP).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szMod = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_MOD).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szGameTypeName = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_GAMETYPE).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szVersion = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_VERSION).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szFS_GAME = Get_RuleValue("fs_game",pSI->pServerRules);


			szVarValue= Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_PRIVATE).sRuleValue.c_str(),pSI->pServerRules);
			if(szVarValue!=NULL)
				pSI->bPrivate = (char)atoi(szVarValue);

			if(Get_RuleValue("net_serverPunkbusterEnabled",pServRules)!=NULL)
				pSI->bPunkbuster = (char)atoi(Get_RuleValue("net_serverPunkbusterEnabled",pServRules));
			else if(Get_RuleValue("sv_punkbuster",pServRules)!=NULL)
				pSI->bPunkbuster = (char)atoi(Get_RuleValue("sv_punkbuster",pServRules));


			PLAYERDATA *pQ4Players=NULL;
			DWORD nPlayers=0;
			//---------------------------------
			//Retrieve players if any exsist...
			//---------------------------------
			pQ4Players = Q4_ParsePlayers(pSI,pCurrPointer,end,&nPlayers);
			pSI->pPlayerData = pQ4Players;


			//-----------------------------------
			//Update server info from rule values
			//-----------------------------------
			time(&pSI->timeLastScan);
			pSI->bUpdated = 1;
			pSI->nPlayers = nPlayers;
			pSI->cPurge = 0;

			
			if(Get_RuleValue("si_maxPlayers",pServRules)!=NULL)
				pSI->nMaxPlayers = atoi(Get_RuleValue("si_maxPlayers",pServRules));

	//		if(Get_RuleValue("si_tv",pServRules)!=NULL)
	//			pSI->bTV = atoi(Get_RuleValue("si_tv",pServRules));		
			
			if(Get_RuleValue("si_privatePlayers",pServRules)!=NULL)
				pSI->nPrivateClients = atoi(Get_RuleValue("si_privatePlayers",pServRules));
			else if(Get_RuleValue("si_privateClients",pServRules)!=NULL) 			//ETQW
			{
				pSI->nPrivateClients = atoi(Get_RuleValue("si_privateClients",pServRules));
				pSI->nMaxPlayers -=	pSI->nPrivateClients;
			}

		} //end if(pServRules!=NULL)

		ReleaseServerLock(pSI);
		if(Q4_Callback_CheckForBuddy!=NULL)
			Q4_Callback_CheckForBuddy(pSI->pPlayerData,pSI);

		free(packet);

	} //end if(packet)
	else
		pSI->cPurge++;

	if(UpdatePlayerListView!=NULL) 
		UpdatePlayerListView(pSI->pPlayerData);
		
	if(UpdateRulesListView!=NULL)
		UpdateRulesListView(pSI->pServerRules);

	//pSI->bLocked = FALSE;
	closesocket(pSocket);
	return 0;
}
Example #9
0
void packet_size_breakdown(struct OPTIONS *options, char *ifname,
                           int facilitytime, struct filterstate *ofilter)
{
    WINDOW *win;
    PANEL *panel;
    WINDOW *borderwin;
    PANEL *borderpanel;

    struct ifstat_brackets brackets[20];
    unsigned int interval;

    int ch;

    int fd;

    char buf[MAX_PACKET_SIZE];
    int br;
    char *ipacket;
    char iface[10];
    unsigned int mtu;

    struct sockaddr_ll fromaddr;
    unsigned short linktype;
    int pkt_result;

    struct timeval tv;
    unsigned long starttime, startlog, timeint;
    unsigned long now;
    unsigned long long unow;
    unsigned long updtime = 0;
    unsigned long long updtime_usec = 0;

    int logging = options->logging;
    FILE *logfile = NULL;

    struct promisc_states *promisc_list;

    char msgstring[80];

    if (!facility_active(PKTSIZEIDFILE, ifname))
        mark_facility(PKTSIZEIDFILE, "Packet size breakdown", ifname);
    else {
        snprintf(msgstring, 80,
                 "Packet sizes already being monitored on %s", ifname);
        write_error(msgstring, daemonized);
        return;
    }

    if (!iface_supported(ifname)) {
        err_iface_unsupported();
        unmark_facility(PKTSIZEIDFILE, ifname);
        return;
    }
    if (!iface_up(ifname)) {
        err_iface_down();
        unmark_facility(PKTSIZEIDFILE, ifname);
        return;
    }
    borderwin = newwin(LINES - 2, COLS, 1, 0);
    borderpanel = new_panel(borderwin);

    wattrset(borderwin, BOXATTR);
    tx_box(borderwin, ACS_VLINE, ACS_HLINE);
    mvwprintw(borderwin, 0, 1, " Packet Distribution by Size ");

    win = newwin(LINES - 4, COLS - 2, 2, 1);
    panel = new_panel(win);

    tx_stdwinset(win);
    wtimeout(win, -1);
    wattrset(win, STDATTR);
    tx_colorwin(win);

    move(LINES - 1, 1);
    stdexitkeyhelp();

    initialize_brackets(ifname, brackets, &interval, &mtu, win);

    mvwprintw(win, 1, 1, "Packet size brackets for interface %s", ifname);
    wattrset(win, BOXATTR);

    mvwprintw(win, 4, 1, "Packet Size (bytes)");
    mvwprintw(win, 4, 26, "Count");
    mvwprintw(win, 4, 36, "Packet Size (bytes)");
    mvwprintw(win, 4, 60, "Count");
    wattrset(win, HIGHATTR);

    if (logging) {
        if (strcmp(current_logfile, "") == 0) {
            snprintf(current_logfile, 80, "%s-%s.log", PKTSIZELOG, ifname);

            if (!daemonized)
                input_logfile(current_logfile, &logging);
        }
    }

    if (logging) {
        opentlog(&logfile, current_logfile);

        if (logfile == NULL)
            logging = 0;
    }
    if (logging)
        signal(SIGUSR1, rotate_size_log);

    writelog(logging, logfile,
             "******** Packet size distribution facility started ********");

    exitloop = 0;
    gettimeofday(&tv, NULL);
    starttime = startlog = timeint = tv.tv_sec;

    open_socket(&fd);

    if (fd < 0) {
        unmark_facility(PKTSIZEIDFILE, ifname);
        return;
    }

    if ((first_active_facility()) && (options->promisc)) {
        init_promisc_list(&promisc_list);
        save_promisc_list(promisc_list);
        srpromisc(1, promisc_list);
        destroy_promisc_list(&promisc_list);
    }

    adjust_instance_count(PROCCOUNTFILE, 1);
    active_facility_countfile[0] = '\0';

    do {
        gettimeofday(&tv, NULL);
        now = tv.tv_sec;
        unow = tv.tv_sec * 1e+6 + tv.tv_usec;

        if (((options->updrate != 0)
             && (now - updtime >= options->updrate))
            || ((options->updrate == 0)
                && (unow - updtime_usec >= DEFAULT_UPDATE_DELAY))) {
            update_panels();
            doupdate();
            updtime = now;
            updtime_usec = unow;
        }
        if (now - timeint >= 5) {
            printelapsedtime(starttime, now, LINES - 3, 1, borderwin);
            timeint = now;
        }
        if ((now - startlog >= options->logspan) && (logging)) {
            write_size_log(brackets, now - starttime, ifname, mtu,
                           logfile);
            startlog = now;
        }
        check_rotate_flag(&logfile, logging);

        if ((facilitytime != 0)
            && (((now - starttime) / 60) >= facilitytime))
            exitloop = 1;

        getpacket(fd, buf, &fromaddr, &ch, &br, iface, win);

        if (ch != ERR) {
            switch (ch) {
            case 12:
            case 'l':
            case 'L':
                tx_refresh_screen();
                break;
            case 'x':
            case 'X':
            case 'q':
            case 'Q':
            case 27:
            case 24:
                exitloop = 1;
            }
        }
        if (br > 0) {
            pkt_result =
                processpacket(buf, &ipacket, &br, NULL, NULL, NULL,
                              &fromaddr, &linktype, ofilter,
                              MATCH_OPPOSITE_USECONFIG, iface, ifname);

            if (pkt_result != PACKET_OK)
                continue;

            update_size_distrib(br, brackets, interval, win);
        }
    } while (!exitloop);

    if (logging) {
        signal(SIGUSR1, SIG_DFL);
        write_size_log(brackets, now - starttime, ifname, mtu, logfile);
        writelog(logging, logfile,
                 "******** Packet size distribution facility stopped ********");
        fclose(logfile);
    }
    close(fd);

    if ((options->promisc) && (is_last_instance())) {
        load_promisc_list(&promisc_list);
        srpromisc(0, promisc_list);
        destroy_promisc_list(&promisc_list);
    }

    adjust_instance_count(PROCCOUNTFILE, -1);

    del_panel(panel);
    delwin(win);
    del_panel(borderpanel);
    delwin(borderwin);
    unmark_facility(PKTSIZEIDFILE, ifname);
    strcpy(current_logfile, "");
}
/*
 * 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);
    }
}
Example #11
0
File: gdb.c Project: JanmanX/KUDOS
/* 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);
    }

}
Example #12
0
void
gdb_event_loop(int sigval, unsigned long *registers)
{
  int addr;
  int length;
  unsigned char *ptr;
  ptr = packet_out_buf;

  DEBUG (1, "In gdb_event_loop");

  while (1) {
    packet_out_buf[0] = 0;
    
    getpacket(packet_in_buf);      
    ptr = &packet_in_buf[1];

    switch (packet_in_buf[0]) {
    case '?':		/* get the last known signal */
      gdb_last_signal(sigval);
      break;
      
    case 'd':		/* toggle debug messages from the stub */
      gdb_toggle();
      break;
      
    case 'g':		/* return the value of the CPU registers */
      target_read_registers(registers);
      break;
      
    case 'G':	   /* set the value of the CPU registers - return OK */
      target_write_registers(registers);
      break;
      
    case 'm':	  /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
      /* Try to read %x,%x.  */
      if (hex2int((char **)&ptr, &addr)
	  && *ptr++ == ','
	  && hex2int((char **)&ptr, &length)) {
	gdb_read_memory(addr, length);
      } else {
	make_return_packet(1);
      }
      break;
      
    case 'M': /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
      /* Try to read '%x,%x:'.  */
      if (hex2int((char **)&ptr, &addr)
	  && *ptr++ == ','
	  && hex2int((char **)&ptr, &length)
	  && *ptr++ == ':') {
	gdb_write_memory (addr, length, ptr);
      } else {
	make_return_packet(2);
      }
      break;
      
    case 'c':    /* cAA..AA    Continue at address AA..AA(optional) */
      /* try to read optional parameter, pc unchanged if no parm */
      if (hex2int((char **)&ptr, &addr)) {
	write_pc(registers, addr);
      }
      
      /*
       * we 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. 
       */
      
      flush_i_cache();
      /* by returning, we pick up execution where we left off */
      return;

      /* kill the program */
    case 'k' :
      gdb_kill();
      break;
    case 'r':		/* Reset */
      target_reset();
      break;
    }			/* switch */
    
    /* reply to the request */
    putpacket(packet_out_buf);
  }
  DEBUG (1, "Leaving handle_exception()");
}
Example #13
0
DWORD BFBC2_Get_ServerStatus(SERVER_INFO *pSI,long (*UpdatePlayerListView)(PLAYERDATA *Q3players),long (*UpdateRulesListView)(SERVER_RULES *pServerRules))
{
	SOCKET pSocket = NULL;
	unsigned char *packet=NULL;
	DWORD dwStartTick=0;

	if(pSI==NULL)
	{
		dbg_print("Invalid pointer argument @Get_ServerStatus!\n");
		return (DWORD)0xdead;
	}
	pSI->usQueryPort = 48888;

	pSocket =  getsockudp(pSI->szIPaddress ,(unsigned short)pSI->usQueryPort);  
	if(pSocket==INVALID_SOCKET)
	{
	  dbg_print("Error at getsockudp()\n");
	  return 0x000002;
	}

	size_t packetlen = 0;

	//Some default values
	pSI->dwPing = 9999;

	if( ((pSI->szShortCountryName[0]=='E') && (pSI->szShortCountryName[1]=='U')) || ((pSI->szShortCountryName[0]=='z') && (pSI->szShortCountryName[1]=='z')))
	{	
		char szShortName[4];			
		g_IPtoCountry.IPtoCountry(pSI->dwIP,szShortName);//optimized since v1.31 
		strncpy_s(pSI->szShortCountryName,sizeof(pSI->szShortCountryName),szShortName,_TRUNCATE);
	}
	DWORD dwRetries=0;
	int len = 0; //(int)strlen(sendbuf);
	char sendbuf[80];
	ZeroMemory(sendbuf,sizeof(sendbuf));

	//memcpy( buf, "\x00\x00\x00\x00\x1b\x00\x00\x00\x01\x00\x00\x00\x0a\x00\x00\x00serverInfo\x00", size );
	//memcpy( buf, "\x01\x00\x00\x00\x15\x00\x00\x00\x01\x00\x00\x00\x04\x00\x00\x00quit\x00", size );

	len = UTILZ_ConvertEscapeCodes(gm.GamesInfo[pSI->cGAMEINDEX].szServerRequestInfo,sendbuf,sizeof(sendbuf));
retry:


	//if(gm.GamesInfo[pSI->cGAMEINDEX].szServerRequestInfo!=NULL)
		packetlen = send(pSocket, "\x00\x00\x00\x00\x1b\x00\x00\x00\x01\x00\x00\x00\x0a\x00\x00\x00serverInfo\x00", 27, 0);
//	else
//		packetlen=SOCKET_ERROR;

		
	if(packetlen==SOCKET_ERROR) 
	{
		dbg_print("Error at send()\n");
		closesocket(pSocket);		
		pSI->cPurge++;
		return -1;
	}

	dwStartTick = GetTickCount();
	packet=(unsigned char*)getpacket(pSocket, &packetlen);

	if(packet==NULL)
	{
		if(dwRetries<AppCFG.dwRetries)
		{
			dwRetries++;
			goto retry;
		}
	}

	if(packet) 
	{
		pSI->dwPing = (GetTickCount() - dwStartTick);

		GetServerLock(pSI);
		if(pSI->pPlayerData!=NULL)
			CleanUp_PlayerList(pSI->pPlayerData);
		pSI->pPlayerData = NULL;

		if(pSI->pServerRules!=NULL)
			CleanUp_ServerRules(pSI->pServerRules);
		pSI->pServerRules = NULL;


		//dbg_dumpbuf("dump.bin", packet, packetlen);
		SERVER_RULES *pServRules=NULL;
		char *end = (char*)((packet)+packetlen);
		
		char *pCurrPointer=NULL; //will contain the start address for the player data

		//pCurrPointer = Q3_ParseServerRules(pServRules,(char*)packet,packetlen);
		pSI->pServerRules = pServRules;
		if(pServRules!=NULL)
		{		

			char *szVarValue=NULL;
			GAME_INFO *pGI = &gm.GamesInfo[pSI->cGAMEINDEX];
//			pSI->szServerName = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_SERVERNAME).sRuleValue.c_str(),pSI->pServerRules);
//			pSI->szMap = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_MAP).sRuleValue.c_str(),pSI->pServerRules);
//			pSI->szMod = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_MOD).sRuleValue.c_str(),pSI->pServerRules);
//			pSI->szGameTypeName = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_GAMETYPE).sRuleValue.c_str(),pSI->pServerRules);
//			pSI->szVersion = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_VERSION).sRuleValue.c_str(),pSI->pServerRules);

			PLAYERDATA *pQ3Players=NULL;
			DWORD nPlayers=0;
			//---------------------------------
			//Retrieve players if any exsist...
			//---------------------------------
//			pQ3Players = Q3_ParsePlayers2(pSI,pCurrPointer,end,&nPlayers,szP_ET);
			
			pSI->pPlayerData = pQ3Players;

			//-----------------------------------
			//Update server info from rule values
			//-----------------------------------
			pSI->bUpdated = 1;
			pSI->cPurge = 0;
			pSI->nPlayers = nPlayers;
			


			szVarValue= Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_PRIVATE).sRuleValue.c_str(),pSI->pServerRules);
			if(szVarValue!=NULL)
				pSI->bPrivate = (char)atoi(szVarValue);

			szVarValue = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_PB).sRuleValue.c_str(),pServRules);		
			if(szVarValue!=NULL)
				pSI->bPunkbuster = (char)atoi(szVarValue);

			szVarValue = Get_RuleValue("sv_privateClients",pServRules);
			if(szVarValue!=NULL)
				pSI->nPrivateClients = atoi(szVarValue);

			time(&pSI->timeLastScan);

	

		} //end if(pServRules!=NULL)
	
		ReleaseServerLock(pSI);
		if(Callback_CheckForBuddy!=NULL)
			Callback_CheckForBuddy(pSI->pPlayerData,pSI);

		free(packet);

	} //end if(packet)
	else
		pSI->cPurge++;   //increase purge counter when the server is not responding

	if(UpdatePlayerListView!=NULL) 
		UpdatePlayerListView(pSI->pPlayerData);
		
	if(UpdateRulesListView!=NULL)
		UpdateRulesListView(pSI->pServerRules);

	closesocket(pSocket);
//	pSI->bLocked = FALSE;
	return 0;
}
/*
 * This function does all command processing for interfacing to gdb.  It
 * returns 1 if you should skip the instruction at the trap address, 0
 * otherwise.
 */
void gdb_stub_handle_exception(gdb_pt_regs *regs,int sigval)
{
	int trap;			/* Trap type */
	int addr;
	int length;
	char *ptr;
	unsigned long *stack;

	
	/*
	 * reply to host that an exception has occurred
	 */
	send_signal(sigval);

	/*
	 * Wait for input from remote GDB
	 */
	while (1) {
		output_buffer[0] = 0;
		getpacket(input_buffer);

		switch (input_buffer[0])
		{
		case '?':
			send_signal(sigval);
			continue;

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

		/*
		 * Return the value of the CPU registers
		 */
		case 'g':
			gdb_stub_get_non_pt_regs(regs);
			ptr = output_buffer;
			ptr=  mem2hex((char *)regs,ptr,sizeof(s390_regs_common),FALSE);
			ptr=  mem2hex((char *)&regs->crs[0],ptr,NUM_CRS*CR_SIZE,FALSE);
			ptr = mem2hex((char *)&regs->fp_regs, ptr,sizeof(s390_fp_regs));
			break;
	  
		/*
		 * set the value of the CPU registers - return OK
		 * FIXME: Needs to be written
		 */
		case 'G':
			ptr=input_buffer;
			hex2mem (ptr, (char *)regs,sizeof(s390_regs_common), FALSE);
			ptr+=sizeof(s390_regs_common)*2;
			hex2mem (ptr, (char *)regs->crs[0],NUM_CRS*CR_SIZE, FALSE);
			ptr+=NUM_CRS*CR_SIZE*2;
			hex2mem (ptr, (char *)regs->fp_regs,sizeof(s390_fp_regs), FALSE);
			gdb_stub_set_non_pt_regs(regs);
			strcpy(output_buffer,"OK");
		break;

		/*
		 * mAA..AA,LLLL  Read LLLL bytes at address AA..AA
		 */
		case 'm':
			ptr = &input_buffer[1];

			if (hexToInt(&ptr, &addr)
				&& *ptr++ == ','
				&& hexToInt(&ptr, &length)) {
				if (mem2hex((char *)addr, output_buffer, length, 1))
					break;
				strcpy (output_buffer, "E03");
			} else
				strcpy(output_buffer,"E01");
			break;

		/*
		 * MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK
		 */
		case 'M': 
			ptr = &input_buffer[1];

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

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

			ptr = &input_buffer[1];
			if (hexToInt(&ptr, &addr))
				regs->cp0_epc = addr;
	  
			/*
			 * 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.
			 * NB: We flush both caches, just to be sure...
			 */

			flush_cache_all();
			return;
			/* NOTREACHED */
			break;


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


		/*
		 * Reset the whole machine (FIXME: system dependent)
		 */
		case 'r':
			break;


		/*
		 * Step to next instruction
		 */
		case 's':
			/*
			 * There is no single step insn in the MIPS ISA, so we
			 * use breakpoints and continue, instead.
			 */
			single_step(regs);
			flush_cache_all();
			return;
			/* NOTREACHED */

		}
		break;

		}			/* switch */

		/*
		 * reply to the request
		 */

		putpacket(output_buffer);

	} /* while */
Example #15
0
long netgetpacket(long *ind, char *buf)
{
	int i;
	long len;
	PACKET_PROXYp prx;

	len = getpacket(ind, buf);
	if ((unsigned)len < sizeof(PACKET_PROXY) || buf[0] != PACKET_TYPE_PROXY) {
		if (len > 0) {
			initprintf("netgetpacket() gets normal from %d\nContents:",*ind);
			for (i=0; i<len; i++)
				initprintf(" %02x", buf[i]);
			initprintf("\n");
		}
		return len;
	}

	prx = (PACKET_PROXYp)buf;

	initprintf("netgetpacket() got proxy from %d\nPlayerIndex=%d Contents:",*ind,prx->PlayerIndex);
	for (i=0; i<len-sizeof(PACKET_PROXY); i++)
		initprintf(" %02x", *(((char*)&prx[1])+i));
	initprintf("\n");

	if (myconnectindex == connecthead) {
		// I am the master

		if (prx->PlayerIndex == (BYTE)(-1)) {
			// broadcast

			// Rewrite the player index to be the sender's connection number
			prx->PlayerIndex = (BYTE)*ind;

			// Transmit to all the other players except ourselves and the sender
			for (i = connecthead; i >= 0; i = connectpoint2[i]) {
				if (i == myconnectindex || i == *ind) continue;
				initprintf("netgetpacket(): distributing to %d\n", i);
				sendpacket(i, buf, len);
			}
			
			// Return the packet payload to the caller
			len -= sizeof(PACKET_PROXY);
			memmove(buf, &prx[1], len);
			return len;
		} else {
			// proxy send to a specific player

			i = prx->PlayerIndex;

			// Rewrite the player index to be the sender's connection number
			prx->PlayerIndex = (BYTE)*ind;

			// Transmit to the intended recipient
			if (i == myconnectindex) {
				len -= sizeof(PACKET_PROXY);
				memmove(buf, &prx[1], len);
				return len;
			}

			initprintf("netgetpacket(): forwarding to %d\n", i);
			sendpacket(i, buf, len);
			return 0;	// nothing for us to do
		}
	} else if (*ind == connecthead) {
		// I am a slave, and the proxy message came from the master
		*ind = prx->PlayerIndex;
		len -= sizeof(PACKET_PROXY);
		memmove(buf, &prx[1], len);
		return len;
	} else {
		initprintf("netgetpacket(): Got a proxy message from %d instead of %d\n",*ind,connecthead);
	}
	return 0;
}
Example #16
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);
    }
}
Example #17
0
    int main(int argc, char **argv)
    {
        struct user_opt opt;
        struct crack_data cdata;
        struct capture_data capdata;
        struct wpa_eapol_key *eapkeypacket;
        u8 eapolkey_nomic[99];
        struct timeval start, end;
        int ret;
        char passphrase[MAXPASSLEN + 1];

        printf("%s %s - WPA-PSK dictionary attack. <*****@*****.**>\n",
               PROGNAME, VER);

        memset(&opt, 0, sizeof(struct user_opt));
        memset(&capdata, 0, sizeof(struct capture_data));
        memset(&cdata, 0, sizeof(struct crack_data));
        memset(&eapolkey_nomic, 0, sizeof(eapolkey_nomic));

        /* Collect and test command-line arguments */
        parseopts(&opt, argc, argv);
        testopts(&opt);
        printf("\n");

        /* Populate capdata struct */
        strncpy(capdata.pcapfilename, opt.pcapfile,
            sizeof(capdata.pcapfilename));
        if (openpcap(&capdata) != 0) {
            printf("Unsupported or unrecognized pcap file.\n");
            exit(-1);
        }

        /* populates global *packet */
        while (getpacket(&capdata) > 0) {
            if (opt.verbose > 2) {
                lamont_hdump(packet, h->len);
            }
            /* test packet for data that we are looking for */
            if (memcmp(&packet[capdata.l2type_offset], DOT1X_LLCTYPE, 2) ==
                0 && (h->len >
                capdata.l2type_offset + sizeof(struct wpa_eapol_key))) {
                /* It's a dot1x frame, process it */
                handle_dot1x(&cdata, &capdata, &opt);
                if (cdata.aaset && cdata.spaset && cdata.snonceset &&
                    cdata.anonceset && cdata.keymicset
                    && cdata.eapolframeset) {
                    /* We've collected everything we need. */
                    break;
                }
            }
        }

        if (!(cdata.aaset && cdata.spaset && cdata.snonceset &&
              cdata.anonceset && cdata.keymicset && cdata.eapolframeset)) {

                cdata.aaset = 0;
                cdata.spaset = 0;
                cdata.snonceset = 0;
                cdata.anonceset = 0;
                cdata.keymicset = 0;
                cdata.eapolframeset = 0;

                opt.nonstrict = 1;

                memset(&capdata, 0, sizeof(struct capture_data));
                memset(&cdata, 0, sizeof(struct crack_data));
                memset(&eapolkey_nomic, 0, sizeof(eapolkey_nomic));

                /* Populate capdata struct */
                strncpy(capdata.pcapfilename, opt.pcapfile,
                    sizeof(capdata.pcapfilename));
                if (openpcap(&capdata) != 0) {
                    printf("Unsupported or unrecognized pcap file.\n");
                    exit(-1);
                }

                /* populates global *packet */
                while (getpacket(&capdata) > 0) {
                    if (opt.verbose > 2) {
                        lamont_hdump(packet, h->len);
                    }
                    /* test packet for data that we are looking for */
                    if (memcmp(&packet[capdata.l2type_offset], DOT1X_LLCTYPE, 2) ==
                        0 && (h->len >capdata.l2type_offset + sizeof(struct wpa_eapol_key))) {
                        /* It's a dot1x frame, process it */
                        handle_dot1x(&cdata, &capdata, &opt);

                        if (cdata.aaset && cdata.spaset && cdata.snonceset
			 && cdata.anonceset && cdata.keymicset
                         && cdata.eapolframeset) {

			    if (cdata.replay_counter1 != 0 
                             && cdata.replay_counter2 != 0) {

                              if (memcmp (cdata.replay_counter1,
				          cdata.replay_counter2, 8) == 0) {

				   cdata.counters = 1;
	                           /* We've collected everything we need. */
        	                   break;

			      } 

			    } 

			    if (cdata.replay_counter3 != 0
			     && cdata.replay_counter4 != 0) {

			      if (memcmp (cdata.replay_counter3,
			                  cdata.replay_counter4, 8) == 0) {

				    cdata.counters = 1;
				    /* We've collected everything we need. */
				    break;

			      }

			    }
						
                        }
                    }
                }
        }

        closepcap(&capdata);

        if (!(cdata.aaset && cdata.spaset && cdata.snonceset &&
              cdata.anonceset && cdata.keymicset && cdata.eapolframeset && cdata.counters)) {
            printf("End of pcap capture file, incomplete four-way handshake "
                   "exchange.  Try using a\ndifferent capture.\n");
            exit(-1);
        } else {
            if (cdata.ver == WPA_KEY_INFO_TYPE_HMAC_SHA1_AES) {
                printf("Collected all necessary data to mount crack"
                            " against WPA2/PSK passphrase.\n");
             } else if (cdata.ver == WPA_KEY_INFO_TYPE_HMAC_MD5_RC4) {
                printf("Collected all necessary data to mount crack"
                            " against WPA/PSK passphrase.\n");
            }
        }

        if (opt.verbose > 1) {
            dump_all_fields(cdata, &opt);
        }

        if (opt.checkonly) {
            /* Don't attack the PSK, just return non-error return code */
            return 0;
        }

	/* Zero mic and length data for hmac-md5 calculation */
	eapkeypacket =
	    (struct wpa_eapol_key *)&cdata.eapolframe[EAPDOT1XOFFSET];
	memset(&eapkeypacket->key_mic, 0, sizeof(eapkeypacket->key_mic));
	if (opt.nonstrict == 0) {
		eapkeypacket->key_data_length = 0;
	}

	printf("Starting dictionary attack.  Please be patient.\n");
	fflush(stdout);

	signal(SIGINT, cleanup);
	signal(SIGTERM, cleanup);
	signal(SIGQUIT, cleanup);

	gettimeofday(&start, 0);

	if (!IsBlank(opt.hashfile)) {
		ret = hashfile_attack(&opt, passphrase, &cdata);
	} else if (!IsBlank(opt.dictfile)) {
		ret = dictfile_attack(&opt, passphrase, &cdata);
	} else {
		usage("Must specify dictfile or hashfile (-f or -d)");
		exit(-1);
	}

	if (ret == 0) {
		printf("\nThe PSK is \"%s\".\n", passphrase);
		gettimeofday(&end, 0);
		printstats(start, end, wordstested);
		return 0;
	} else {
		printf("Unable to identify the PSK from the dictionary file. " 
	       		"Try expanding your\npassphrase list, and double-check"
		        " the SSID.  Sorry it didn't work out.\n");
		gettimeofday(&end, 0);
		printstats(start, end, wordstested);
		return 1;
	}

	return 1;

}
Example #18
0
/* This function reads all thumbnails at once and initializes the whole
 * camera filesystem. This can be done, because finding out how much 
 * pictures are on the camera is done by reading the whole preview picture
 * stream anyway.
 * And since the file infos are static mostly, why not just set them too at
 * the same time.
 */
int
jd11_index_reader(GPPort *port, CameraFilesystem *fs, GPContext *context) {
    int		i, id, count, xsize, curread=0, ret=0;
    unsigned char	*indexbuf;

    ret = jd11_select_index(port);
    if (ret != GP_OK)
	return ret;
    xsize = jd11_imgsize(port);
    if (!xsize) { /* shortcut, no reading needed */
	return GP_OK;
    }
    count = xsize/(64*48);
    xsize = count * (64*48);
    indexbuf = malloc(xsize);
    if (!indexbuf) return GP_ERROR_NO_MEMORY;
    id = gp_context_progress_start (context, xsize,
				    _("Downloading thumbnail..."));
    _send_cmd(port,0xfff1);
    while (curread < xsize) {
	    int readsize = xsize-curread;
	    if (readsize>200) readsize = 200;
	    ret=getpacket(port,indexbuf+curread,readsize);
	    if (ret==0)
		    break;
	    curread+=ret;
	    if (ret<200)
		    break;
	    gp_context_progress_update (context, id, curread);
	    if (gp_context_cancel (context) == GP_CONTEXT_FEEDBACK_CANCEL) {
		/* What to do...Just free the stuff we allocated for now.*/
		free(indexbuf);
		return GP_ERROR_CANCEL;
	    }
	    _send_cmd(port,0xfff1);
    }
    gp_context_progress_stop (context, id);
    for (i=0;i<count;i++) {
	CameraFile	*file;
	char		fn[20];
	unsigned char *src;
	unsigned char thumb[64*48];
	int y;
	CameraFileInfo	info;
	
	ret = gp_file_new(&file);
	if (ret!=GP_OK) {
	    free(indexbuf);
	    return ret;
	}
	sprintf(fn,"image%02i.pgm",i);
	gp_file_set_mime_type(file, GP_MIME_PGM);
	gp_file_append(file, THUMBHEADER, strlen(THUMBHEADER));
	src = indexbuf+(i*64*48);
	for (y=0;y<48;y++) {
	    int x,off = 64*y;
	    for (x=0;x<64;x++)
		thumb[47*64-off+(63-x)] = src[off+x];
	}
	ret = gp_file_append(file,(char*)thumb,sizeof(thumb));
	if (ret != GP_OK) {
		gp_file_free (file);
		return ret;
	}
	ret = gp_filesystem_append(fs, "/", fn, context);
	if (ret != GP_OK) {
		/* should perhaps remove the entry again */
		gp_file_free (file);
		return ret;
	}
	ret = gp_filesystem_set_file_noop(fs, "/", fn, GP_FILE_TYPE_PREVIEW, file, context);
	if (ret != GP_OK) return ret;

	/* we also get the fs info for free, so just set it */
	info.file.fields = GP_FILE_INFO_TYPE |
			GP_FILE_INFO_WIDTH | GP_FILE_INFO_HEIGHT | 
			GP_FILE_INFO_SIZE;
	strcpy(info.file.type,GP_MIME_PNM);
	info.file.width		= 640;
	info.file.height	= 480;
	info.file.size		= 640*480*3+strlen(IMGHEADER);
	info.preview.fields = GP_FILE_INFO_TYPE |
			GP_FILE_INFO_WIDTH | GP_FILE_INFO_HEIGHT | 
			GP_FILE_INFO_SIZE;
	strcpy(info.preview.type,GP_MIME_PGM);
	info.preview.width	= 64;
	info.preview.height	= 48;
	info.preview.size	= 64*48+strlen(THUMBHEADER);
	ret = gp_filesystem_set_info_noop(fs, "/", fn, info, context);
    }
    free(indexbuf);
    return GP_OK;
}
Example #19
0
DWORD COD4_Get_ServerStatus(SERVER_INFO *pSI,long (*UpdatePlayerListView)(PLAYERDATA *Q3players),long (*UpdateRulesListView)(SERVER_RULES *pServerRules))
{
	SOCKET pSocket = NULL;
	unsigned char *packet=NULL;
	DWORD dwStartTick=0;

	if(pSI==NULL)
	{
		dbg_print("Invalid pointer argument @Get_ServerStatus!\n");
		return (DWORD)0x000001;
	}

	pSocket =  getsockudp(pSI->szIPaddress ,(unsigned short)pSI->usPort); 
 
	if(pSocket==INVALID_SOCKET)
	{
	  dbg_print("Error at getsockudp()\n");
	  return 0x000002;
	}

	size_t packetlen = 0;

	//Some default values
	pSI->dwPing = 9999;

	if( ((pSI->szShortCountryName[0]=='E') && (pSI->szShortCountryName[1]=='U')) || ((pSI->szShortCountryName[0]=='z') && (pSI->szShortCountryName[1]=='z')))
	{
	
		char szShortName[4];			
		g_IPtoCountry.IPtoCountry(pSI->dwIP,szShortName);//optimized since v1.31 
		strncpy_s(pSI->szShortCountryName,sizeof(pSI->szShortCountryName),szShortName,_TRUNCATE);
	}
	DWORD dwRetries=0;
	int len = 0; //(int)strlen(sendbuf);
	char sendbuf[80];
	ZeroMemory(sendbuf,sizeof(sendbuf));
	len = UTILZ_ConvertEscapeCodes(gm.GamesInfo[pSI->cGAMEINDEX].szServerRequestInfo,sendbuf,sizeof(sendbuf));
retry:
	if(gm.GamesInfo[pSI->cGAMEINDEX].szServerRequestInfo!=NULL)
		packetlen = send(pSocket, sendbuf, len+1, 0);
	else
		packetlen=SOCKET_ERROR;

		
	if(packetlen==SOCKET_ERROR) 
	{
		dbg_print("Error at send()\n");
		closesocket(pSocket);		
		pSI->cPurge++;
	//	pSI->bLocked = FALSE;
		return -1;
	}

	dwStartTick = GetTickCount(); //ping data start 
	packet=(unsigned char*)getpacket(pSocket, &packetlen);
	if(packet==NULL)
	{
		if(dwRetries<AppCFG.dwRetries)
		{
			dwRetries++;
			goto retry;
		}
	}

	if(packet) 
	{
		pSI->dwPing = (GetTickCount() - dwStartTick); //ping data stop
		//dbg_dumpbuf("dump.bin", packet, packetlen);

		GetServerLock(pSI);

		CleanUp_ServerInfo(pSI);

		SERVER_RULES *pServRules=NULL;
		char *end = (char*)((packet)+packetlen);
		
		char *pCurrPointer=NULL; //will contain the start address for the player data

		pCurrPointer = Q3_ParseServerRules(pServRules,(char*)packet,packetlen);
		pSI->pServerRules = pServRules;

		if(pServRules!=NULL)
		{		
		
			PLAYERDATA *pQ3Players=NULL;
			DWORD nPlayers=0;
			//---------------------------------
			//Retrieve players if any exsist...
			//---------------------------------

			pSI->szServerName = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_SERVERNAME).sRuleValue.c_str(),pSI->pServerRules,1);
			pSI->szMap = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_MAP).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szMod = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_MOD).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szGameTypeName = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_GAMETYPE).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szVersion = Get_RuleValue((TCHAR*)gm.GamesInfo[pSI->cGAMEINDEX].vGAME_SPEC_COL.at(COL_VERSION).sRuleValue.c_str(),pSI->pServerRules);

			pQ3Players = Q3_ParsePlayers2(pSI,pCurrPointer,end,&nPlayers);

	
			pSI->pPlayerData = pQ3Players;

			//-----------------------------------
			//Update server info from rule values
			//-----------------------------------

			pSI->bUpdated = 1;
			pSI->cPurge = 0;
			pSI->nPlayers = nPlayers;
			char *szVarValue=NULL;
			char *pVarValue = NULL;
	
			szVarValue = Get_RuleValue("pswrd",pServRules);  //CoD & Cod2
			if(szVarValue!=NULL)
				pSI->bPrivate = atoi(szVarValue);


			szVarValue = Get_RuleValue("sv_punkbuster",pServRules);
			if(szVarValue!=NULL)
				pSI->bPunkbuster = (char)atoi(szVarValue);


			szVarValue = Get_RuleValue("sv_privateClients",pServRules);
			if(szVarValue!=NULL)
				pSI->nPrivateClients = atoi(szVarValue);

			szVarValue = Get_RuleValue("sv_maxclients",pServRules);
			if(szVarValue!=NULL)
			{
				unsigned int maxClient = atoi(szVarValue);
				if(maxClient>pSI->nPrivateClients)
					pSI->nMaxPlayers = maxClient-pSI->nPrivateClients;
				else
					pSI->nMaxPlayers = pSI->nPrivateClients-maxClient;

			}
			free(packet);
			packet =NULL;
		//	pCurrPointer = Q3_ParseServerRules(pServRules,(char*)packet,packetlen);

			ZeroMemory(sendbuf,sizeof(sendbuf));
			len = UTILZ_ConvertEscapeCodes("\xFF\xFF\xFF\xFFgetinfo x73",sendbuf,sizeof(sendbuf));
		//	Sleep(50);		
			packetlen = send(pSocket, sendbuf, len+1, 0);
			packet=(unsigned char*)getpacket(pSocket, &packetlen);

			if(packet) 
			{
				//dbg_dumpbuf("dump.bin", packet, packetlen);
				SERVER_RULES *pServRulestemp=NULL;
				SERVER_RULES *pServRules2=NULL;
				char *end = (char*)((packet)+packetlen);
				
				char *pCurrPointer2=NULL; //will contain the start address for the player data

				pCurrPointer2 = Q3_ParseServerRules(pServRules2,(char*)packet,packetlen);
				pServRulestemp = pSI->pServerRules ;
				while(pServRulestemp!=NULL)
				{
					if(pServRulestemp->pNext==NULL)
						break;
					pServRulestemp = pServRulestemp->pNext;

				}
				
				pServRulestemp->pNext = pServRules2;
	
				free(packet);
				packet = NULL;
			}
			time(&pSI->timeLastScan);

		} //end if(pServRules!=NULL)

		ReleaseServerLock(pSI);
		
		if(Callback_CheckForBuddy!=NULL)  //This has to be done after the lock to avoid deadlock
			Callback_CheckForBuddy(pSI->pPlayerData,pSI);	

	} //end if(packet)
	else
		pSI->cPurge++;   //increase purge counter when the server is not responding



	if(UpdatePlayerListView!=NULL) 
		UpdatePlayerListView(pSI->pPlayerData);
		
	if(UpdateRulesListView!=NULL)
		UpdateRulesListView(pSI->pServerRules);

	
	closesocket(pSocket);
//	pSI->bLocked = FALSE;
	return 0;
}
Example #20
0
File: gdb.c Project: vocho/openqnx
/*
 * This function does all command procesing for interfacing to gdb.
 */
static boolean
do_gdb_interface(struct kdebug_entry *entry, CPU_REGISTERS *ctx, ulong_t signal) {
    int    length;

struct kdebug_info		*kinfo;
const struct kdebug_private	*kprivate;
THREAD *thread;

    /* 
     * Indicate that we've gone back to debug mode
     */
    for (length = 0; length < 4; length++) dbg_putc('|');
	if(protocol == 0) {
		// generic GDB 4.16 wants the response to the continue/step
		// command sent before it transmits anything else.
		ksprintf(outbuf,"S%02xk", (unsigned)signal);
		putpacket();
	}

	while(getpacket()) {
		connected = TRUE;

		outbuf[0] = 0;

#ifdef DEBUG_GDB
kprintf("Processing packet '%s'\n", inbuf);		
#endif
        switch(inbuf[0]) {

		/* Tell the gdb client our signal number */
		case '?' :
			if(gdb_test_reloc_sem()) {
				paddr_t					base;
				char					*str = SYSPAGE_ENTRY(strings)->data;
				struct asinfo_entry		*as = SYSPAGE_ENTRY(asinfo);
		
				while(strcmp(&str[as->name], "imagefs") != 0) {
					++as;
				}
				base = gdb_image_base(as->start);
				gdb_clear_reloc_sem();
				ksprintf(outbuf,"N%02x%P;%P;%P",
					(unsigned)signal, base, base, (paddr_t)(base + as->end - as->start + 1));
			} else {
				ksprintf(outbuf,"S%02xk", (unsigned)signal);
			}
	
			for(length=1;outbuf[length];length++) {
				if((outbuf[length] >= 'A') && 
					(outbuf[length] <='Z'))
					outbuf[length]=outbuf[length]+('a'-'A');
			}
			if(gdb_debug) gdb_printf("%s", outbuf);
	
			break;
	
		/* toggle debug flag */
		case 'd' :
			gdb_debug = !(gdb_debug);
			break; 
		
		/* return the value of the CPU registers */
		case 'g' :
/* temp solution, need to add an offset item in kdebug_private for fpu data	*/
			if((kinfo = private->kdebug_info)== NULL || (kprivate = kinfo->kdbg_private) == NULL ||
				(thread = ((void **)kprivate->actives)[0]) == NULL) {
				gdb_get_cpuregs(ctx,NULL);
			} else {
				gdb_get_cpuregs(ctx,thread->fpudata);
			}
			break;
	
		/* set the value of the CPU registers - return OK */
		case 'G' : 
/* temp solution, need to add an offset item in kdebug_private for fpu data	*/
			if((kinfo = private->kdebug_info)== NULL || (kprivate = kinfo->kdbg_private) == NULL ||
				(thread = ((void **)kprivate->actives)[0]) == NULL) {
				gdb_set_cpuregs(ctx,NULL);
			} else {
				gdb_set_cpuregs(ctx,thread->fpudata);
			}
			strcpy(outbuf,"OK");
			break;

		/* get target information */
		case 'i':
			gdb_get_info();
			break;
		  
		/* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
		case 'm' : 
			gdb_read_membytes(ctx);
			break;
		  
		/* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
		case 'M' : 
			gdb_write_membytes(ctx);
			break;
		 
		/* cAA..AA    Continue at address AA..AA(optional) */
		case 'c' : 
			gdb_proc_continue(ctx, 0);	/* continue the process */
			return(TRUE);
	
		/* sAA..AA   Step one instruction from AA..AA(optional) */
		case 's' : 
			gdb_proc_continue(ctx, 1);	/* step one instruction */
			return(TRUE);

		/* q???? Generic query */	

		case 'q': 
			if(memcmp(&inbuf[1], "Rcmd,", 5) == 0) {
				// remote command
				char	*p;

				p = &inbuf[6];
				hex2mem(p, scratch, strlen(p));
				#define MEM_CMD	"mem "
				if(memcmp(scratch, MEM_CMD, sizeof(MEM_CMD)-1) == 0) {
					monitor_mem(&scratch[sizeof(MEM_CMD)-1]);
				}
			}
			break;

		/* k		Kill program */
		case 'k' :
			putpacket(); /*ACK the packet early (since we're going bye-bye) */
			gdb_prep_reboot();
			SYSPAGE_ENTRY(callout)->reboot(_syspage_ptr, 0);
			break;

		/* D		Detach from host */
		case 'D' :
			connected = FALSE;
			return(FALSE);
			  
		} /* switch */ 
Example #21
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;
  long   addr, length;
  char * ptr;
  struct alpharegs {
    u_int64_t r[32];
    u_int64_t f[32];
    u_int64_t pc, vfp;
  };
  static struct alpharegs registers;
  int i;

  clear_single_step(raw_regs);

  bzero(&registers, sizeof registers);

  /*
   * Map trapframe to registers.
   * Ignore float regs for now.
   */
  for (i = 0; i < FRAME_SIZE; i++)
    if (tf2gdb[i] >= 0)
      registers.r[tf2gdb[i]] = raw_regs->tf_regs[i];
  registers.pc = raw_regs->tf_regs[FRAME_PC];

  /* reply to host that an exception has occurred */
  sigval = computeSignal (type, code);
  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.pc, ptr, 8);
  *ptr++ = ';';

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

  *ptr++ = hexchars[SP >> 4];
  *ptr++ = hexchars[SP & 0xf];
  *ptr++ = ':';
  ptr = mem2hex ((vm_offset_t)&registers.r[SP], ptr, 8);
  *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 'k':
	  prom_halt();
	  /*NOTREACHED*/
	  break;

	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 */
	  {
	    long regno;

	    ptr = &remcomInBuffer[1];

	    if (hexToInt (&ptr, &regno)
		&& *ptr++ == '='
		&& regno < NUM_REGS)
	      {
		hex2mem (ptr, (vm_offset_t)&registers + regno * 8, 8);
		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.pc = addr;

	  /*
	   * Map gdb registers back to trapframe (ignoring fp regs).
	   */
	  for (i = 0; i < NUM_REGS; i++)
	    if (gdb2tf[i] >= 0)
	      raw_regs->tf_regs[gdb2tf[i]] = registers.r[i];
	  raw_regs->tf_regs[FRAME_PC] = registers.pc;

	  if (remcomInBuffer[0] == 's')
	    if (!set_single_step(raw_regs))
	      printf("Can't set single step breakpoint\n");

	  return;

	} /* switch */

      /* reply to the request */
      putpacket (remcomOutBuffer);
    }
}
Example #22
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);
	}
}
Example #23
0
DWORD Q3_Get_ServerStatus(SERVER_INFO *pSI,long (*UpdatePlayerListView)(PLAYERDATA *Q3players),long (*UpdateRulesListView)(SERVER_RULES *pServerRules))
{
	SOCKET pSocket = NULL;
	unsigned char *packet=NULL;
	DWORD dwStartTick=0;

	if(pSI==NULL)
	{
		dbg_print("Invalid pointer argument @Get_ServerStatus!\n");
		return (DWORD)0xdead;
	}
	pSocket =  getsockudp(pSI->szIPaddress ,(unsigned short)pSI->usPort);  
	if(pSocket==INVALID_SOCKET)
	{
	  dbg_print("Error at getsockudp()\n");
	  return 0x000002;
	}

	size_t packetlen = 0;

	//Some default values
	pSI->dwPing = 9999;

	if( ((pSI->szShortCountryName[0]=='E') && (pSI->szShortCountryName[1]=='U')) || ((pSI->szShortCountryName[0]=='z') && (pSI->szShortCountryName[1]=='z')))
	{	
		char szShortName[4];			
		g_IPtoCountry.IPtoCountry(pSI->dwIP,szShortName);//optimized since v1.31 
		strncpy_s(pSI->szShortCountryName,sizeof(pSI->szShortCountryName),szShortName,_TRUNCATE);
	}
	DWORD dwRetries=0;
	int len = 0; //(int)strlen(sendbuf);
	char sendbuf[80];
	ZeroMemory(sendbuf,sizeof(sendbuf));
	len = UTILZ_ConvertEscapeCodes(gm.GamesInfo[pSI->cGAMEINDEX].szServerRequestInfo,sendbuf,sizeof(sendbuf));
retry:


	if(gm.GamesInfo[pSI->cGAMEINDEX].szServerRequestInfo!=NULL)
		packetlen = send(pSocket, sendbuf, len+1, 0);
	else
		packetlen=SOCKET_ERROR;

		
	if(packetlen==SOCKET_ERROR) 
	{
		dbg_print("Error at send()\n");
		closesocket(pSocket);		
		pSI->cPurge++;
		return -1;
	}

	dwStartTick = GetTickCount();
	packet=(unsigned char*)getpacket(pSocket, &packetlen);
	if(pSI->cGAMEINDEX==WARSOW_SERVERLIST && packet==NULL)
		packet = Warsow_patch(pSocket,pSI,&dwStartTick,&packetlen);

	if(packet==NULL)
	{
		
		if(dwRetries<AppCFG.dwRetries)
		{
			

			dwRetries++;
			goto retry;
		}
	}

	if(packet) 
	{
		pSI->dwPing = (GetTickCount() - dwStartTick);

		GetServerLock(pSI);

		CleanUp_ServerInfo(pSI);


		//dbg_dumpbuf("dump.bin", packet, packetlen);
		SERVER_RULES *pServRules=NULL;
		char *end = (char*)((packet)+packetlen);
		
		char *pCurrPointer=NULL; //will contain the start address for the player data

		pCurrPointer = Q3_ParseServerRules(pServRules,(char*)packet,packetlen);
		pSI->pServerRules = pServRules;
		if(pServRules!=NULL)
		{		
		
			char szP_ET[150];
			if(pSI->cGAMEINDEX == ET_SERVERLIST)
			{			
				ZeroMemory(&szP_ET,sizeof(szP_ET));			
				char *szPVarValue=NULL;
				szPVarValue = Get_RuleValue("P",pServRules);
				if(szPVarValue!=NULL)
					strcpy(szP_ET,szPVarValue);
			}
			char *szVarValue=NULL;
			GAME_INFO *pGI = &gm.GamesInfo[pSI->cGAMEINDEX];
			pSI->szServerName = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_SERVERNAME).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szMap = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_MAP).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szMod = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_MOD).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szGameTypeName = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_GAMETYPE).sRuleValue.c_str(),pSI->pServerRules);
			pSI->szVersion = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_VERSION).sRuleValue.c_str(),pSI->pServerRules);

			PLAYERDATA *pQ3Players=NULL;
			DWORD nPlayers=0;
			//---------------------------------
			//Retrieve players if any exsist...
			//---------------------------------
			switch(pSI->cGAMEINDEX)
			{
				case WARSOW_SERVERLIST:
					{
						const char *szTVvalue = Get_RuleValue((TCHAR*)"tv",pSI->pServerRules);
						if(szTVvalue!=NULL)
						{
							if(strcmp("1",szTVvalue)==0)
								pSI->szServerName = Get_RuleValue((TCHAR*)"tv_name",pSI->pServerRules);
							
							const char* szClients = Get_RuleValue((TCHAR*)"clients",pSI->pServerRules);
							if(szClients!=NULL)
								nPlayers =  atoi(szClients);

						} else
						{
							pQ3Players = Q3_ParsePlayers2(pSI,pCurrPointer,end,&nPlayers);
						}

					}
					break;
				case QW_SERVERLIST:
				case Q2_SERVERLIST:
					pQ3Players = QW_ParsePlayers(pSI,pCurrPointer,end,&nPlayers);
					break;
				default:
					pQ3Players = Q3_ParsePlayers2(pSI,pCurrPointer,end,&nPlayers,szP_ET);
				break;
			}
			
			pSI->pPlayerData = pQ3Players;

			//-----------------------------------
			//Update server info from rule values
			//-----------------------------------
			pSI->bUpdated = 1;
			pSI->cPurge = 0;
			pSI->nPlayers = nPlayers;
			


			szVarValue= Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_PRIVATE).sRuleValue.c_str(),pSI->pServerRules);
			if(szVarValue!=NULL)
				pSI->bPrivate = (char)atoi(szVarValue);

			szVarValue = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_PB).sRuleValue.c_str(),pServRules);		
			if(szVarValue!=NULL)
				pSI->bPunkbuster = (char)atoi(szVarValue);


			//getting status value
			switch(pSI->cGAMEINDEX)
			{	
				case QW_SERVERLIST:
						pSI->szSTATUS = Get_RuleValue("status",pSI->pServerRules);
				break;
				case Q2_SERVERLIST:
					{
						//Lets enumerate through vars for the best match to sue as a status...
						pSI->szSTATUS = Get_RuleValue("time_remaining",pSI->pServerRules);
						if(pSI->szSTATUS==NULL)						
						{
							pSI->szSTATUS = Get_RuleValue("#time_left",pSI->pServerRules);
							if(pSI->szSTATUS==NULL)
							{
								pSI->szSTATUS = Get_RuleValue("gamestats",pSI->pServerRules);
							}
						}
					}
				break;
				case Q3_SERVERLIST:
						pSI->szSTATUS = Get_RuleValue((TCHAR*)pGI->vGAME_SPEC_COL.at(COL_STATUS).sRuleValue.c_str(),pSI->pServerRules);
					break;
			}

			szVarValue = Get_RuleValue("sv_privateClients",pServRules);
			if(szVarValue!=NULL)
				pSI->nPrivateClients = atoi(szVarValue);

			szVarValue = Get_RuleValue("sv_maxclients",pServRules);
			if(szVarValue!=NULL)
			{
				unsigned int maxClient = atoi(szVarValue);
				if(maxClient>pSI->nPrivateClients)
					pSI->nMaxPlayers = maxClient-pSI->nPrivateClients;
				else
					pSI->nMaxPlayers = pSI->nPrivateClients-maxClient;

			}
			else
			{ //for QW
				szVarValue = Get_RuleValue("maxclients",pServRules);
				if(szVarValue!=NULL)
					pSI->nMaxPlayers = atoi(szVarValue)-pSI->nPrivateClients;
			}

			time(&pSI->timeLastScan);

	

		} //end if(pServRules!=NULL)
	
		ReleaseServerLock(pSI);
		if(Callback_CheckForBuddy!=NULL)
			Callback_CheckForBuddy(pSI->pPlayerData,pSI);

		free(packet);

	} //end if(packet)
	else
		pSI->cPurge++;   //increase purge counter when the server is not responding

	if(UpdatePlayerListView!=NULL) 
		UpdatePlayerListView(pSI->pPlayerData);
		
	if(UpdateRulesListView!=NULL)
		UpdateRulesListView(pSI->pServerRules);

	closesocket(pSocket);
//	pSI->bLocked = FALSE;
	return 0;
}
Example #24
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);
    }
}
Example #25
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;
	}
}
Example #26
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) */
}
Example #27
0
/* All expected commands are sent from remote.c. Send a response according
   to the description in remote.c. */
static void
handle_exception (int sigval)
{
	/* Avoid warning of not used. */

	USEDFUN(handle_exception);
	USEDVAR(internal_stack[0]);

	/* Send response. */

	stub_is_stopped (sigval);

	for (;;) {
		remcomOutBuffer[0] = '\0';
		getpacket (remcomInBuffer);
		switch (remcomInBuffer[0]) {
			case 'g':
				/* Read registers: g
				   Success: Each byte of register data is described by two hex digits.
				   Registers are in the internal order for GDB, and the bytes
				   in a register  are in the same order the machine uses.
				   Failure: void. */
				
				{
#ifdef PROCESS_SUPPORT
					/* Use the special register content in the executing thread. */
					copy_registers (&reg_g, &reg, sizeof(registers));
					/* Replace the content available on the stack. */
					if (current_thread_g != executing_task) {
						copy_registers_from_stack (current_thread_g, &reg_g);
					}
					mem2hex ((unsigned char *)remcomOutBuffer, (unsigned char *)&reg_g, sizeof(registers));
#else
					mem2hex(remcomOutBuffer, (char *)&reg, sizeof(registers));
#endif
				}
				break;
				
			case 'G':
				/* Write registers. GXX..XX
				   Each byte of register data  is described by two hex digits.
				   Success: OK
				   Failure: void. */
#ifdef PROCESS_SUPPORT
				hex2mem ((unsigned char *)&reg_g, &remcomInBuffer[1], sizeof(registers));
				if (current_thread_g == executing_task) {
					copy_registers (&reg, &reg_g, sizeof(registers));
				}
				else {
					copy_registers_to_stack(current_thread_g, &reg_g);
				}
#else
				hex2mem((char *)&reg, &remcomInBuffer[1], sizeof(registers));
#endif
				gdb_cris_strcpy (remcomOutBuffer, "OK");
				break;
				
			case 'P':
				/* Write register. Pn...=r...
				   Write register n..., hex value without 0x, with value r...,
				   which contains a hex value without 0x and two hex digits
				   for each byte in the register (target byte order). P1f=11223344 means
				   set register 31 to 44332211.
				   Success: OK
				   Failure: E02, E05 */
				{
					char *suffix;
					int regno = gdb_cris_strtol (&remcomInBuffer[1], &suffix, 16);
					int status;
#ifdef PROCESS_SUPPORT
					if (current_thread_g != executing_task)
						status = write_stack_register (current_thread_g, regno, suffix+1);
					else
#endif
						status = write_register (regno, suffix+1);

					switch (status) {
						case E02:
							/* Do not support read-only registers. */
							gdb_cris_strcpy (remcomOutBuffer, error_message[E02]);
							break;
						case E05:
							/* Do not support non-existing registers. */
							gdb_cris_strcpy (remcomOutBuffer, error_message[E05]);
							break;
						case E07:
							/* Do not support non-existing registers on the stack. */
							gdb_cris_strcpy (remcomOutBuffer, error_message[E07]);
							break;
						default:
							/* Valid register number. */
							gdb_cris_strcpy (remcomOutBuffer, "OK");
							break;
					}
				}
				break;
				
			case 'm':
				/* Read from memory. mAA..AA,LLLL
				   AA..AA is the address and LLLL is the length.
				   Success: XX..XX is the memory content.  Can be fewer bytes than
				   requested if only part of the data may be read. m6000120a,6c means
				   retrieve 108 byte from base address 6000120a.
				   Failure: void. */
				{
                                        char *suffix;
					unsigned char *addr = (unsigned char *)gdb_cris_strtol(&remcomInBuffer[1],
                                                                                               &suffix, 16);                                        int length = gdb_cris_strtol(suffix+1, 0, 16);
                                        
                                        mem2hex(remcomOutBuffer, addr, length);
                                }
				break;
				
			case 'X':
				/* Write to memory. XAA..AA,LLLL:XX..XX
				   AA..AA is the start address,  LLLL is the number of bytes, and
				   XX..XX is the binary data.
				   Success: OK
				   Failure: void. */
			case 'M':
				/* Write to memory. MAA..AA,LLLL:XX..XX
				   AA..AA is the start address,  LLLL is the number of bytes, and
				   XX..XX is the hexadecimal data.
				   Success: OK
				   Failure: void. */
				{
					char *lenptr;
					char *dataptr;
					unsigned char *addr = (unsigned char *)gdb_cris_strtol(&remcomInBuffer[1],
										      &lenptr, 16);
					int length = gdb_cris_strtol(lenptr+1, &dataptr, 16);
					if (*lenptr == ',' && *dataptr == ':') {
						if (remcomInBuffer[0] == 'M') {
							hex2mem(addr, dataptr + 1, length);
						}
						else /* X */ {
							bin2mem(addr, dataptr + 1, length);
						}
						gdb_cris_strcpy (remcomOutBuffer, "OK");
					}
					else {
						gdb_cris_strcpy (remcomOutBuffer, error_message[E06]);
					}
				}
				break;
				
			case 'c':
				/* Continue execution. cAA..AA
				   AA..AA is the address where execution is resumed. If AA..AA is
				   omitted, resume at the present address.
				   Success: return to the executing thread.
				   Failure: will never know. */
				if (remcomInBuffer[1] != '\0') {
					reg.pc = gdb_cris_strtol (&remcomInBuffer[1], 0, 16);
				}
				enableDebugIRQ();
				return;
				
			case 's':
				/* Step. sAA..AA
				   AA..AA is the address where execution is resumed. If AA..AA is
				   omitted, resume at the present address. Success: return to the
				   executing thread. Failure: will never know.
				   
				   Should never be invoked. The single-step is implemented on
				   the host side. If ever invoked, it is an internal error E04. */
				gdb_cris_strcpy (remcomOutBuffer, error_message[E04]);
				putpacket (remcomOutBuffer);
				return;
				
			case '?':
				/* The last signal which caused a stop. ?
				   Success: SAA, where AA is the signal number.
				   Failure: void. */
				remcomOutBuffer[0] = 'S';
				remcomOutBuffer[1] = hex_asc_hi(sigval);
				remcomOutBuffer[2] = hex_asc_lo(sigval);
				remcomOutBuffer[3] = 0;
				break;
				
			case 'D':
				/* Detach from host. D
				   Success: OK, and return to the executing thread.
				   Failure: will never know */
				putpacket ("OK");
				return;
				
			case 'k':
			case 'r':
				/* kill request or reset request.
				   Success: restart of target.
				   Failure: will never know. */
				kill_restart ();
				break;
				
			case 'C':
			case 'S':
			case '!':
			case 'R':
			case 'd':
				/* Continue with signal sig. Csig;AA..AA
				   Step with signal sig. Ssig;AA..AA
				   Use the extended remote protocol. !
				   Restart the target system. R0
				   Toggle debug flag. d
				   Search backwards. tAA:PP,MM
				   Not supported: E04 */
				gdb_cris_strcpy (remcomOutBuffer, error_message[E04]);
				break;
#ifdef PROCESS_SUPPORT

			case 'T':
				/* Thread alive. TXX
				   Is thread XX alive?
				   Success: OK, thread XX is alive.
				   Failure: E03, thread XX is dead. */
				{
					int thread_id = (int)gdb_cris_strtol (&remcomInBuffer[1], 0, 16);
					/* Cannot tell whether it is alive or not. */
					if (thread_id >= 0 && thread_id < number_of_tasks)
						gdb_cris_strcpy (remcomOutBuffer, "OK");
				}
				break;
								
			case 'H':
				/* Set thread for subsequent operations: Hct
				   c = 'c' for thread used in step and continue;
				   t can be -1 for all threads.
				   c = 'g' for thread used in other  operations.
				   t = 0 means pick any thread.
				   Success: OK
				   Failure: E01 */
				{
					int thread_id = gdb_cris_strtol (&remcomInBuffer[2], 0, 16);
					if (remcomInBuffer[1] == 'c') {
						/* c = 'c' for thread used in step and continue */
						/* Do not change current_thread_c here. It would create a mess in
						   the scheduler. */
						gdb_cris_strcpy (remcomOutBuffer, "OK");
					}
					else if (remcomInBuffer[1] == 'g') {
						/* c = 'g' for thread used in other  operations.
						   t = 0 means pick any thread. Impossible since the scheduler does
						   not allow that. */
						if (thread_id >= 0 && thread_id < number_of_tasks) {
							current_thread_g = thread_id;
							gdb_cris_strcpy (remcomOutBuffer, "OK");
						}
						else {
							/* Not expected - send an error message. */
							gdb_cris_strcpy (remcomOutBuffer, error_message[E01]);
						}
					}
					else {
						/* Not expected - send an error message. */
						gdb_cris_strcpy (remcomOutBuffer, error_message[E01]);
					}
				}
				break;
				
			case 'q':
			case 'Q':
				/* Query of general interest. qXXXX
				   Set general value XXXX. QXXXX=yyyy */
				{
					int pos;
					int nextpos;
					int thread_id;
					
					switch (remcomInBuffer[1]) {
						case 'C':
							/* Identify the remote current thread. */
							gdb_cris_strcpy (&remcomOutBuffer[0], "QC");
							remcomOutBuffer[2] = hex_asc_hi(current_thread_c);
							remcomOutBuffer[3] = hex_asc_lo(current_thread_c);
							remcomOutBuffer[4] = '\0';
							break;
						case 'L':
							gdb_cris_strcpy (&remcomOutBuffer[0], "QM");
							/* Reply with number of threads. */
							if (os_is_started()) {
								remcomOutBuffer[2] = hex_asc_hi(number_of_tasks);
								remcomOutBuffer[3] = hex_asc_lo(number_of_tasks);
							}
							else {
								remcomOutBuffer[2] = hex_asc_hi(0);
								remcomOutBuffer[3] = hex_asc_lo(1);
							}
							/* Done with the reply. */
							remcomOutBuffer[4] = hex_asc_lo(1);
							pos = 5;
							/* Expects the argument thread id. */
							for (; pos < (5 + HEXCHARS_IN_THREAD_ID); pos++)
								remcomOutBuffer[pos] = remcomInBuffer[pos];
							/* Reply with the thread identifiers. */
							if (os_is_started()) {
								/* Store the thread identifiers of all tasks. */
								for (thread_id = 0; thread_id < number_of_tasks; thread_id++) {
									nextpos = pos + HEXCHARS_IN_THREAD_ID - 1;
									for (; pos < nextpos; pos ++)
										remcomOutBuffer[pos] = hex_asc_lo(0);
									remcomOutBuffer[pos++] = hex_asc_lo(thread_id);
								}
							}
							else {
								/* Store the thread identifier of the boot task. */
								nextpos = pos + HEXCHARS_IN_THREAD_ID - 1;
								for (; pos < nextpos; pos ++)
									remcomOutBuffer[pos] = hex_asc_lo(0);
								remcomOutBuffer[pos++] = hex_asc_lo(current_thread_c);
							}
							remcomOutBuffer[pos] = '\0';
							break;
						default:
							/* Not supported: "" */
							/* Request information about section offsets: qOffsets. */
							remcomOutBuffer[0] = 0;
							break;
					}
				}
				break;
#endif /* PROCESS_SUPPORT */
				
			default:
				/* The stub should ignore other request and send an empty
				   response ($#<checksum>). This way we can extend the protocol and GDB
				   can tell whether the stub it is talking to uses the old or the new. */
				remcomOutBuffer[0] = 0;
				break;
		}
		putpacket(remcomOutBuffer);
	}
}
Example #28
0
int dictfile_attack(struct user_opt *opt, char *passphrase, 
	struct crack_data *cdata)
{
	
	FILE *fp;
	int fret;
	u8 pmk[32];
	u8 ptk[64];
	u8 keymic[16];
	struct wpa_ptk *ptkset;

#ifdef FPGA
//	int i;
	opt_g = opt;
	cdata_g = cdata;
	if(usefpga)
		initfpga();
#endif

	/* Open the dictionary file */
	if (*opt->dictfile == '-') {
		printf("Using STDIN for words.\n");
		fp = stdin;
	} else {
		fp = fopen(opt->dictfile, "r");
		if (fp == NULL) {
			perror("fopen");
			exit(-1);
		}
	}


	while (feof(fp) == 0 && sig == 0) {

		/* Populate "passphrase" with the next word */
		fret = nextdictword(passphrase, fp);
		if (fret < 0) {
			break;
		}

		if (opt->verbose > 1) {
			printf("Testing passphrase: %s\n", passphrase);
		}

		/*
		 * Test length of word.  IEEE 802.11i indicates the passphrase
		 * must be at least 8 characters in length, and no more than 63 
		 * characters in length. 
		 */
		if (fret < 8 || fret > 63) {
			if (opt->verbose) {
				printf("Invalid passphrase length: %s (%d).\n",
				       passphrase, strlen(passphrase));
			}
			continue;
		} else {
			/* This word is good, increment the words tested
			counter */
			wordstested++;
		}

		/* Status display */
#ifdef FPGA
		if ((wordstested % 100) == 0) {
#else
		if ((wordstested % 1000) == 0) {
#endif
			printf("key no. %ld: %s\n", wordstested, passphrase);
			fflush(stdout);
		}

		if (opt->verbose > 1) {
			printf("Calculating PMK for \"%s\".\n", passphrase);
		}
		
		pbkdf2_sha1(passphrase, opt->ssid, strlen(opt->ssid), 4096,
			    pmk, sizeof(pmk), USECACHED);

#ifdef FPGA
		if (!usefpga) {
#endif
		if (opt->verbose > 2) {
			printf("PMK is");
			lamont_hdump(pmk, sizeof(pmk));
		}

		if (opt->verbose > 1) {
			printf("Calculating PTK with collected data and "
			       "PMK.\n");
		}

#ifdef FPGA
/*
		for(i = 0; i < 32; i++)
			printf("%02x ", pmk[i]);
		printf("\n");
*/
#endif

		wpa_pmk_to_ptk(pmk, cdata->aa, cdata->spa, cdata->anonce,
			       cdata->snonce, ptk, sizeof(ptk));

		if (opt->verbose > 2) {
			printf("Calculated PTK for \"%s\" is", passphrase);
			lamont_hdump(ptk, sizeof(ptk));
		}

		ptkset = (struct wpa_ptk *)ptk;

		if (opt->verbose > 1) {
			printf("Calculating hmac-MD5 Key MIC for this "
			       "frame.\n");
		}

		hmac_md5(ptkset->mic_key, 16, cdata->eapolframe,
			 sizeof(cdata->eapolframe), keymic);

		if (opt->verbose > 2) {
			printf("Calculated MIC with \"%s\" is", passphrase);
			lamont_hdump(keymic, sizeof(keymic));
		}

		if (memcmp(&cdata->keymic, &keymic, sizeof(keymic)) == 0) {
			return 0;
		} else {
			continue;
		}
#ifdef FPGA
		}
#endif
	}

#ifdef FPGA
	if(usefpga) {	
		printf("waiting..."); fflush(stdout);
		finishreg();
		printf("\ndone\n");
	}
#endif

	return 1;
}

int main(int argc, char **argv)
{
	struct user_opt opt;
	struct crack_data cdata;
	struct capture_data capdata;
	struct wpa_eapol_key *eapkeypacket;
	u8 eapolkey_nomic[99];
	struct timeval start, end;
	int ret;
	char passphrase[MAXPASSLEN + 1];

	printf("%s %s - WPA-PSK dictionary attack. <*****@*****.**>\n",
	       PROGNAME, VER);

	memset(&opt, 0, sizeof(struct user_opt));
	memset(&capdata, 0, sizeof(struct capture_data));
	memset(&cdata, 0, sizeof(struct crack_data));
	memset(&eapolkey_nomic, 0, sizeof(eapolkey_nomic));

	/* Collect and test command-line arguments */
	parseopts(&opt, argc, argv);
	testopts(&opt);
	printf("\n");

	/* Populate capdata struct */
	strncpy(capdata.pcapfilename, opt.pcapfile,
		sizeof(capdata.pcapfilename));
	if (openpcap(&capdata) != 0) {
		printf("Unsupported or unrecognized pcap file.\n");
		exit(1);
	}

	/* populates global *packet */
	while (getpacket(&capdata) > 0) {
		if (opt.verbose > 2) {
			lamont_hdump(packet, h->len);
		}
		/* test packet for data that we are looking for */
		if (memcmp(&packet[capdata.l2type_offset], DOT1X_LLCTYPE, 2) ==
		    0 && (h->len >
			capdata.l2type_offset + sizeof(struct wpa_eapol_key))) {
			/* It's a dot1x frame, process it */
			handle_dot1x(&cdata, &capdata);
			if (cdata.aaset && cdata.spaset && cdata.snonceset &&
			    cdata.anonceset && cdata.keymicset
			    && cdata.eapolframeset) {
				/* We've collected everything we need. */
				break;
			}
		}
	}

	closepcap(&capdata);

	if (!(cdata.aaset && cdata.spaset && cdata.snonceset &&
	      cdata.anonceset && cdata.keymicset && cdata.eapolframeset)) {
		printf("End of pcap capture file, incomplete TKIP four-way "
		       "exchange.  Try using a\ndifferent capture.\n");
		exit(1);
	} else {
		printf("Collected all necessary data to mount crack against "
		       "passphrase.\n");
	}

	if (opt.verbose > 1) {
		dump_all_fields(cdata);
	}

	/* Zero mic and length data for hmac-md5 calculation */
	eapkeypacket =
	    (struct wpa_eapol_key *)&cdata.eapolframe[EAPDOT1XOFFSET];
	memset(&eapkeypacket->key_mic, 0, sizeof(eapkeypacket->key_mic));
	eapkeypacket->key_data_length = 0;

	printf("Starting dictionary attack.  Please be patient.\n");
	fflush(stdout);

//	signal(SIGINT, cleanup);
//	signal(SIGTERM, cleanup);
//	signal(SIGQUIT, cleanup);

	gettimeofday(&start, NULL);
#ifdef FPGA
	start_g = start;
#endif

	if (!IsBlank(opt.hashfile)) {
		ret = hashfile_attack(&opt, passphrase, &cdata);
	} else if (!IsBlank(opt.dictfile)) {
		ret = dictfile_attack(&opt, passphrase, &cdata);
	} else {
		usage("Must specify dictfile or hashfile (-f or -d)");
		exit(1);
	}

	if (ret == 0) {
		printf("\nThe PSK is \"%s\".\n", passphrase);
	} else {
		printf("Unable to identify the PSK from the dictionary file. " 
	       		"Try expanding your\npassphrase list, and double-check"
		        " the SSID.  Sorry it didn't work out.\n");
	}

	gettimeofday(&end, NULL);
	printstats(start, end, wordstested);
	return (1);
}
Example #29
0
void c_debug_handler(frame_context *frame)
{
    char *ptr;
    s32 addr,len;
    s32 thread,current_thread;
    s32 host_has_detached;
    frame_context *regptr;

    thread = gdbstub_getcurrentthread();
    current_thread = thread;

    if(current_device->open(current_device)<0) return;

    if(dbg_active) {
        gdbstub_report_exception(frame,thread);
        putpacket(remcomOutBuffer);
    }

    if(frame->SRR0==(u32)__breakinst) frame->SRR0 += 4;

    host_has_detached = 0;
    while(!host_has_detached) {
        remcomOutBuffer[0]= 0;
        getpacket(remcomInBuffer);
        switch(remcomInBuffer[0]) {
        case '?':
            gdbstub_report_exception(frame,thread);
            break;
        case 'D':
            dbg_instep = 0;
            dbg_active = 0;
            frame->SRR1 &= ~MSR_SE;
            strcpy(remcomOutBuffer,"OK");
            host_has_detached = 1;
            break;
        case 'k':
            dbg_instep = 0;
            dbg_active = 0;
            frame->SRR1 &= ~MSR_SE;
            frame->SRR0 = 0x80001800;
            host_has_detached = 1;
            goto exit;
        case 'g':
            regptr = frame;
            ptr = remcomOutBuffer;
            if(current_thread!=thread) regptr = &current_thread_registers;

            ptr = mem2hstr(ptr,(char*)regptr->GPR,32*4);
            ptr = mem2hstr(ptr,(char*)regptr->FPR,32*8);
            ptr = mem2hstr(ptr,(char*)&regptr->SRR0,4);
            ptr = mem2hstr(ptr,(char*)&regptr->SRR1,4);
            ptr = mem2hstr(ptr,(char*)&regptr->CR,4);
            ptr = mem2hstr(ptr,(char*)&regptr->LR,4);
            ptr = mem2hstr(ptr,(char*)&regptr->CTR,4);
            ptr = mem2hstr(ptr,(char*)&regptr->XER,4);
            ptr = mem2hstr(ptr,(char*)&regptr->FPSCR,4);
            break;
        case 'm':
            ptr = &remcomInBuffer[1];
            if(hexToInt(&ptr,&addr) && ((addr&0xC0000000)==0xC0000000 || (addr&0xC0000000)==0x80000000)
                    && *ptr++==','
                    && hexToInt(&ptr,&len) && len<=((BUFMAX - 4)/2))
                mem2hstr(remcomOutBuffer,(void*)addr,len);
            else
                strcpy(remcomOutBuffer,"E00");
            break;
        case 'q':
            process_query(remcomInBuffer,remcomOutBuffer,thread);
            break;
        case 'c':
            dbg_instep = 0;
            dbg_active = 1;
            frame->SRR1 &= ~MSR_SE;
            current_device->wait(current_device);
            goto exit;
        case 's':
            dbg_instep = 1;
            dbg_active = 1;
            frame->SRR1 |= MSR_SE;
            current_device->wait(current_device);
            goto exit;
        case 'z':
        {
            s32 ret,type,len;
            char *addr;

            ret = parsezbreak(remcomInBuffer,&type,&addr,&len);
            if(!ret) {
                strcpy(remcomOutBuffer,"E01");
                break;
            }
            if(type!=0) break;

            if(len<4) {
                strcpy(remcomOutBuffer,"E02");
                break;
            }

            ret = remove_bp(addr);
            if(!ret) {
                strcpy(remcomOutBuffer,"E03");
                break;
            }
            strcpy(remcomOutBuffer,"OK");
        }
        break;
        case 'H':
            if(remcomInBuffer[1]=='g')
            {
                s32 tmp,ret;

                if(vhstr2thread(&remcomInBuffer[2],&tmp)==NULL) {
                    strcpy(remcomOutBuffer,"E01");
                    break;
                }
                if(!tmp) tmp = thread;
                if(tmp==current_thread) {
                    strcpy(remcomOutBuffer,"OK");
                    break;
                }

                if(current_thread!=thread) ret = gdbstub_setthreadregs(current_thread,&current_thread_registers);
                if(tmp!=thread) {
                    ret = gdbstub_getthreadregs(tmp,&current_thread_registers);
                    if(!ret) {
                        strcpy(remcomOutBuffer,"E02");
                        break;
                    }
                }
                current_thread= tmp;
            }
            strcpy(remcomOutBuffer,"OK");
            break;
        case 'T':
        {
            s32 tmp;

            if(vhstr2thread(&remcomInBuffer[1],&tmp)==NULL) {
                strcpy(remcomOutBuffer,"E01");
                break;
            }
            if(gdbstub_indextoid(tmp)==NULL) strcpy(remcomOutBuffer,"E02");
            else strcpy(remcomOutBuffer,"OK");
        }
        break;
        case 'Z':
        {
            s32 ret,type,len;
            char *addr;

            ret = parsezbreak(remcomInBuffer,&type,&addr,&len);
            if(!ret) {
                strcpy(remcomOutBuffer,"E01");
                break;
            }
            if(type!=0) {
                strcpy(remcomOutBuffer,"E02");
                break;
            }
            if(len<4) {
                strcpy(remcomOutBuffer,"E03");
                break;
            }

            ret = insert_bp(addr);
            if(!ret) {
                strcpy(remcomOutBuffer,"E04");
                break;
            }
            strcpy(remcomOutBuffer,"OK");
        }
        break;
        }
        putpacket(remcomOutBuffer);
    }
    current_device->close(current_device);
exit:
    return;
}