int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
                    const Vector<SizedFile> &CorporaFiles) {
  Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
         DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
  MkDir(DirPath);
  auto Temp = TempPath(".dft");
  for (auto &F : CorporaFiles) {
    // For every input F we need to collect the data flow and the coverage.
    // Data flow collection may fail if we request too many DFSan tags at once.
    // So, we start from requesting all tags in range [0,Size) and if that fails
    // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
    // Function number => DFT.
    std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
    std::unordered_set<std::string> Cov;
    std::queue<std::pair<size_t, size_t>> Q;
    Q.push({0, F.Size});
    while (!Q.empty()) {
      auto R = Q.front();
      Printf("\n\n\n********* Trying: [%zd, %zd)\n", R.first, R.second);
      Q.pop();
      Command Cmd;
      Cmd.addArgument(DFTBinary);
      Cmd.addArgument(std::to_string(R.first));
      Cmd.addArgument(std::to_string(R.second));
      Cmd.addArgument(F.File);
      Cmd.addArgument(Temp);
      Printf("CMD: %s\n", Cmd.toString().c_str());
      if (ExecuteCommand(Cmd)) {
        // DFSan has failed, collect tags for two subsets.
        if (R.second - R.first >= 2) {
          size_t Mid = (R.second + R.first) / 2;
          Q.push({R.first, Mid});
          Q.push({Mid, R.second});
        }
      } else {
        Printf("********* Success: [%zd, %zd)\n", R.first, R.second);
        std::ifstream IF(Temp);
        std::string L;
        while (std::getline(IF, L, '\n')) {
          // Data flow collection has succeeded.
          // Merge the results with the other runs.
          if (L.empty()) continue;
          if (L[0] == 'C') {
            // Take coverage lines as is, they will be the same in all attempts.
            Cov.insert(L);
          } else if (L[0] == 'F') {
            size_t FunctionNum = 0;
            std::string DFTString;
            if (ParseDFTLine(L, &FunctionNum, &DFTString)) {
              auto &DFT = DFTMap[FunctionNum];
              if (DFT.empty()) {
                // Haven't seen this function before, take DFT as is.
                DFT = DFTStringToVector(DFTString);
              } else if (DFT.size() == DFTString.size()) {
                // Have seen this function already, merge DFTs.
                DFTStringAppendToVector(&DFT, DFTString);
              }
            }
          }
        }
      }
    }
    auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
    // Dump combined DFT to disk.
    Printf("Producing DFT for %s\n", OutPath.c_str());
    std::ofstream OF(OutPath);
    for (auto &DFT: DFTMap)
      OF << "F" << DFT.first << " " << DFT.second << std::endl;
    for (auto &C : Cov)
      OF << C << std::endl;
  }
  RemoveFile(Temp);
  // Write functions.txt.
  Command Cmd;
  Cmd.addArgument(DFTBinary);
  Cmd.setOutputFile(DirPlusFile(DirPath, "functions.txt"));
  ExecuteCommand(Cmd);
  return 0;
}
// ---------------------------------------------------------------------------
// CATNetworkInfo::StartRequestL
// other items were commented in a header
// ---------------------------------------------------------------------------
void CATNetworkInfo::StartRequest()
	{
	ExecuteCommand();
	}
// ---------------------------------------------------------------------------
// CATGetManufacturer::StartRequestL
// other items were commented in a header
// ---------------------------------------------------------------------------
void CATGetManufacturer::StartRequest()
	{
	ExecuteCommand();
	}
void ServerCliant::ProcessCommand(QByteArray ClientCommand)
{
    ExecuteCommand(ClientCommand);


}
    //-------------------------------------------------------------------------
    static INT_PTR CALLBACK MainDialogProc(
        HWND hWnd,
        UINT message,
        WPARAM wParam,
        LPARAM lParam)
    {
        switch (message)
        {
            case WM_INITDIALOG:
            {
                ResetPermissionDialog::hDlg = hWnd;

                SendDlgItemMessage(
                    hDlg,
                    IDCHK_RESETPERM,
                    BM_SETCHECK,
                    BST_CHECKED,
                    0);

                SendDlgItemMessage(
                    hDlg,
                    IDCHK_DONTFOLLOWLINKS,
                    BM_SETCHECK,
                    BST_CHECKED,
                    0);

                SendDlgItemMessage(
                    hDlg,
                    IDCHK_RECURSE,
                    BM_SETCHECK,
                    BST_CHECKED,
                    0);

                HICON t = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SMALL));
                SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)t);

                LPCTSTR Arg = GetArgs();

                if (Arg != NULL)
                    SetFolderText(Arg);
    #ifdef _DEBUG
                //else
                //    SetFolderText(_TEXT("C:\\Temp\\perm"));
    #endif
                if (Arg != NULL)
                    UpdateCommandText();
                return (INT_PTR)TRUE;
            }

            case WM_MENUCOMMAND:
                break;
            case WM_COMMAND:
            {
    #ifdef _DEBUG
                TCHAR b[1024];
                _sntprintf_s(b, _countof(b), _TEXT("WM_COMMAND: wmParam=%08X lParam=%08X\n"), wParam, lParam);
                OutputDebugString(b);
    #endif
                UINT wmId = LOWORD(wParam);
                UINT wmEvent = HIWORD(wParam);

                switch (wmId)
                {
                    case IDCHK_RECURSE:
                    case IDCHK_DONTFOLLOWLINKS:
                    case IDCHK_TAKEOWN:
                    case IDCHK_RESETPERM:
                    case IDCHK_RM_HS:
                    {
                        if (wmEvent == BN_CLICKED)
                        {
                            UpdateCommandText();
                            return TRUE;
                        }
                        break;
                    }
                    case IDM_ADDTOEXPLORERFOLDERRIGHT:
                    case IDM_REMOVEFROMEXPLORERFOLDERCONTEXTMENU:
                    {
                        AddToExplorerContextMenu(wmId == IDM_ADDTOEXPLORERFOLDERRIGHT);
                        break;
                    }
                    case IDBTN_ABOUT:
                    {
                        DialogBox(
                            hInstance,
                            MAKEINTRESOURCE(IDD_ABOUTBOX),
                            hDlg,
                            AboutDlgProc);

                        return TRUE;
                    }
                    case IDBTN_CHOOSE_FOLDER:
                    {
                        stringT out;
                        if (BrowseFolder(hDlg, STR_SELECT_FOLDER, out))
                        {
                            SetFolderText(out.c_str());
                            UpdateCommandText();
                        }
                        return TRUE;
                    }
                    case IDBTN_MORE_ACTIONS:
                    {
                        ShowMoreActionsMenu();
                        return TRUE;
                    }
                    case IDOK:
                    {
                        ExecuteCommand();
                        return TRUE;
                    }
                }
                break;
            }
            // Close dialog
            case WM_CLOSE:
            {
                EndDialog(hDlg, 0);
                return TRUE;
            }
        }
        return FALSE;
    }
int main()
{
	printf("This sample creates two Lobby2Clients.\n");
	printf("They both connect to the server and performs queued operations on startup.");
	printf("(RANKING AND CLANS NOT YET DONE).\n");
	printf("Difficulty: Advanced\n\n");

	RakNet::Lobby2ResultCodeDescription::Validate();

	/// Do all these operations in this order once we are logged in.
	/// This is for easier testing.
	/// This plan will create the database, register two users, and log them both in
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_System_CreateDatabase), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_System_CreateTitle), _FILE_AND_LINE_ );

	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_CDKey_Add), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_System_RegisterProfanity), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_RegisterAccount), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Client_RegisterAccount), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_System_SetEmailAddressValidated), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_System_SetEmailAddressValidated), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_Login), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Client_Login), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Emails_Send), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Emails_Get), _FILE_AND_LINE_ );
// 	/// Create 2 clans
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_Create), _FILE_AND_LINE_ );
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_Create), _FILE_AND_LINE_ );
// 	// Invite to both
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation), _FILE_AND_LINE_ );
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation), _FILE_AND_LINE_ );
// 	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_RejectJoinInvitation), _FILE_AND_LINE_ );
// 	// Download invitations this clan has sent
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_DownloadInvitationList), _FILE_AND_LINE_ );

	/*

	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Client_SetPresence), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Client_GetAccountDetails), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_PerTitleIntegerStorage), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_PerTitleIntegerStorage), _FILE_AND_LINE_ );

	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_StartIgnore), _FILE_AND_LINE_ );
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Client_GetIgnoreList), _FILE_AND_LINE_ );

	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Friends_SendInvite), _FILE_AND_LINE_);
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Friends_AcceptInvite), _FILE_AND_LINE_);

	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_SubmitMatch));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_SubmitMatch));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_UpdateRating));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_GetRating));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Ranking_WipeRatings));
	*/
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_Create), _FILE_AND_LINE_ );
// 	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_Get), _FILE_AND_LINE_ );
	/*
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SetProperties));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SetMyMemberProperties));
	*/
	/*
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_WithdrawJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_DownloadInvitationList));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_RejectJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SendJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_AcceptJoinInvitation));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SetSubleaderStatus));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_SetMemberRank));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_GrantLeader));
	*/

	/*
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_WithdrawJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_AcceptJoinRequest));
	*/

//	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
//	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_DownloadRequestList));
	// TODO - test from here
	/*
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_RejectJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_AcceptJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_AcceptJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_KickAndBlacklistUser));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_GetBlacklist));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_UnblacklistUser));
	executionPlan.Push(AutoExecutionPlanNode(1, RakNet::L2MID_Clans_SendJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_AcceptJoinRequest));
	executionPlan.Push(AutoExecutionPlanNode(0, RakNet::L2MID_Clans_GetMembers));
	*/

	/*
	// TODO
	L2MID_Clans_CreateBoard,
		L2MID_Clans_DestroyBoard,
		L2MID_Clans_CreateNewTopic,
		L2MID_Clans_ReplyToTopic,
		L2MID_Clans_RemovePost,
		L2MID_Clans_GetBoards,
		L2MID_Clans_GetTopics,
		L2MID_Clans_GetPosts,
		*/
	

	char ip[64], serverPort[30], clientPort[30];
	int i;
	for (i=0; i < NUM_CONNECTIONS; i++)
		rakPeer[i]=RakNet::RakPeerInterface::GetInstance();
	puts("Enter the rakPeer1 port to listen on");
	clientPort[0]=0;
	RakNet::SocketDescriptor socketDescriptor(atoi(clientPort),0);
	Gets(clientPort,sizeof(clientPort));
	if (clientPort[0]==0)
		strcpy(clientPort, "0");

	puts("Enter IP to connect to");;
	ip[0]=0;
	Gets(ip,sizeof(ip));
	if (ip[0]==0)
		strcpy(ip, "127.0.0.1");

	puts("Enter the port to connect to");
	serverPort[0]=0;
	Gets(serverPort,sizeof(serverPort));
	if (serverPort[0]==0)
		strcpy(serverPort, "61111");

	for (i=0; i < NUM_CONNECTIONS; i++)
	{
		rakPeer[i]->Startup(1,&socketDescriptor, 1);
		rakPeer[i]->Connect(ip, atoi(serverPort), 0,0);

		rakPeer[i]->AttachPlugin(&lobby2Client[i]);
		lobby2Client[i].SetMessageFactory(&messageFactory);
		lobby2Client[i].SetCallbackInterface(&callback[i]);
		testUserName[i]=RakNet::RakString("user%i", i);
	}

	RakNet::Packet *packet;
	// Loop for input
	while (1)
	{
		for (i=0; i < NUM_CONNECTIONS; i++)
		{
			RakNet::RakPeerInterface *peer = rakPeer[i];
			for (packet=peer->Receive(); packet; peer->DeallocatePacket(packet), packet=peer->Receive())
			{
				switch (packet->data[0])
				{
				case ID_DISCONNECTION_NOTIFICATION:
					// Connection lost normally
					printf("ID_DISCONNECTION_NOTIFICATION\n");
					break;
				case ID_ALREADY_CONNECTED:
					// Connection lost normally
					printf("ID_ALREADY_CONNECTED\n");
					break;
				case ID_CONNECTION_BANNED: // Banned from this server
					printf("We are banned from this server.\n");
					break;			
				case ID_CONNECTION_ATTEMPT_FAILED:
					printf("Connection attempt failed\n");
					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS:
					// Sorry, the server is full.  I don't do anything here but
					// A real app should tell the user
					printf("ID_NO_FREE_INCOMING_CONNECTIONS\n");
					break;
				case ID_INVALID_PASSWORD:
					printf("ID_INVALID_PASSWORD\n");
					break;
				case ID_CONNECTION_LOST:
					// Couldn't deliver a reliable packet - i.e. the other system was abnormally
					// terminated
					printf("ID_CONNECTION_LOST\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					// This tells the rakPeer1 they have connected
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
					int j;
					for (j=0; j < NUM_CONNECTIONS; j++)
						lobby2Client[j].SetServerAddress(packet->systemAddress);
					if (i==NUM_CONNECTIONS-1)
					{
						PrintCommands(&messageFactory);
						printf("Enter instance number 1 to %i followed by command number.\n", NUM_CONNECTIONS);

						if (executionPlan.Size())
						{
							/// Execute the first command now that both clients have connected.
							AutoExecutionPlanNode aepn = executionPlan.Pop();
							ExecuteCommand(aepn.operation, RakNet::RakString("user%i", aepn.instanceNumber), aepn.instanceNumber);
						}
					}
					break;
				case ID_LOBBY2_SERVER_ERROR:
					{
						RakNet::BitStream bs(packet->data,packet->length,false);
						bs.IgnoreBytes(2); // ID_LOBBY2_SERVER_ERROR and error code
						printf("ID_LOBBY2_SERVER_ERROR: ");
						if (packet->data[1]==RakNet::L2SE_UNKNOWN_MESSAGE_ID)
						{
							unsigned int messageId;
							bs.Read(messageId);
							printf("L2SE_UNKNOWN_MESSAGE_ID %i", messageId);
						}
						else
							printf("Unknown");
						printf("\n");				
					}

					break;
				}
			}
		}
		
		
		// This sleep keeps RakNet responsive
		RakSleep(30);

		if (kbhit())
		{
			char ch = getch();
			if (ch <= '0' || ch > '9')
			{
				printf("Bad instance number\n");
				continue;
			}
			int instanceNumber = ch - 1 - '0';
			if (instanceNumber >= NUM_CONNECTIONS)
			{
				printf("Enter between 1 and %i to pick the instance of RakPeer to run\n", 1+NUM_CONNECTIONS);
				continue;
			}

			printf("Enter message number or 'quit' to quit.\n");
			char str[128];
			Gets(str, sizeof(str));
			if (_stricmp(str, "quit")==0)
			{
				printf("Quitting.\n");
				break;
			}
			else
			{
				int command = atoi(str);
				if (command <=0 || command > RakNet::L2MID_COUNT)
				{
					printf("Invalid message index %i. Commands:\n", command);
					PrintCommands(&messageFactory);
				}
				else
				{
					ExecuteCommand((RakNet::Lobby2MessageID)(command-1), RakNet::RakString("user%i", instanceNumber), instanceNumber);
				}
			}
		}
	}

	for (i=0; i < NUM_CONNECTIONS; i++)
		RakNet::RakPeerInterface::DestroyInstance(rakPeer[i]);
	return 0;
}
Example #7
0
BOOL CCLITerminal::InputStream(CLISESSION *pSession, const unsigned char *pszBuffer, int nLength)
{
	unsigned char	cc;
 	int				i, nVKey;

	if (pSession->pWorker != NULL)
	{
		// 이미 수행중인 작업이 있는 경우
		return TRUE;
	}

	for(i=0; i<nLength; i++)
	{
		cc = pszBuffer[i];

retry_loop:
		switch(pSession->nState) {
		  case TS_CR :
			   if (cc == '\n')
				  break;

			   // Do not break
			   pSession->nState = TS_DATA;

		  case TS_DATA :
			   switch(cc) {
				 case 0x00 :
					  break;
				 case IAC :
				      pSession->nState = TS_IAC;
					  break;
				 case KEY_BS :
					  ExecuteBackspace(pSession);
					  break;
				 case KEY_DEL :
					  ExecuteDelete(pSession);
					  break;
				 case KEY_TAB :
					  if (!pSession->bLogined)
						  break;
					  ExecuteTab(pSession);
					  break;
				 case '?' :
					  if (!pSession->bLogined)
						  break;
					  ExecuteInlineHelp(pSession);
					  break;
				 case KEY_ESC :
					  pSession->nState = TS_ESC;
					  break;
				 case KEY_CTRL_D :
//					  exit(0);
					  return FALSE;
				 default :
//				   	  if (!pSession->nLocalOptions[TELOPT_BINARY] && (cc == '\r'))
				   	  if (cc == '\r')
				   	  {
					      if (!ExecuteCommand(pSession))
							  return FALSE;
					   	  pSession->nState = TS_CR;
					   	  break;
				   	  }
					  if (IsPrintable(cc) && ((pSession->nCmdLength+1)<=CLIMAX_COMMAND_SIZE))
					  {
					  	  pSession->szCommand[pSession->nCmdLength] = cc;
					  	  pSession->nCmdLength++;
						  if (pSession->bNeedUser)
					  	  	   WriteChar(pSession, cc);
					  	  else WriteChar(pSession, pSession->bLogined ? cc : '*');
					  }
					  break;
			   }
			   break;

		  case TS_ESC :
			   if ((cc != '[') && (cc != 'O'))
			   {
				  pSession->nState = TS_DATA;
 				  goto retry_loop;
			   }
			   pSession->nVKeyCount = 0;
			   pSession->nState = TS_ESCSEQ;

		  case TS_ESCSEQ :
			   if (pSession->nVKeyCount >= MAX_VIRTUAL_KEY_SIZE)
			   {
				   pSession->nState = TS_DATA;
				   goto retry_loop;
			   }

			   pSession->szVKeyBuffer[pSession->nVKeyCount] = cc;
			   pSession->nVKeyCount++;
			   pSession->szVKeyBuffer[pSession->nVKeyCount] = '\0';

			   nVKey = FindVirtualKey(pSession);
			   if (nVKey >= 0)
			   {
				   ExecuteVirtualKey(pSession, nVKey);
			   	   pSession->nState = TS_DATA;
			   }
			   else if (nVKey == -1)
			   {
				   pSession->nState = TS_DATA;
				   goto retry_loop;
			   }
			   break;

		  case TS_IAC :
			   switch(cc) {
				 case BREAK :
				 case IP :
					  pSession->nState = TS_DATA;
					  break;
				 case AYT :
					  WriteStream(pSession, (char *)aytreply, strlen((char *)aytreply));
					  pSession->nState = TS_DATA;
					  break;
				 case AO :
					  WriteStream(pSession, (char *)aoreply, 2);
					  pSession->nState = TS_DATA;
					  break;
				 case EC :
					  WriteStream(pSession, "\b", 1);
					  pSession->nState = TS_DATA;
					  break;
				 case EL :
					  WriteStream(pSession, "\025", 1);
					  pSession->nState = TS_DATA;
					  break;
				 case DM :
					  pSession->nState = TS_DATA;
					  break;
				 case SB :
					  pSession->nState = TS_SB;
					  break;
				 case WILL :
					  pSession->nState = TS_WILL;
					  break;
				 case WONT :
					  pSession->nState = TS_WONT;
					  break;
				 case DO :
					  pSession->nState = TS_DO;
					  break;
				 case DONT :
					  pSession->nState = TS_DONT;
					  break;
				 case IAC :
					  WriteChar(pSession, cc);
					  pSession->nState = TS_DATA;
					  break;
				 default :
					  pSession->nState = TS_DATA;
					  break;
			   }
			   break;

		  case TS_SB :
			   if (cc == IAC)
				   pSession->nState = TS_SE;
			   break;

		  case TS_SE :
			   pSession->nState = (cc == SE) ? TS_DATA : TS_SB;
			   break; 

		  case TS_WILL :
			   //printf("IAC WILL %0d\n", cc);
			   RemoteDoOption(pSession, (int)cc, TRUE, TRUE);
			   pSession->nState = TS_DATA;
			   break;

		  case TS_WONT :
			   //printf("IAC WONT %0d\n", cc);
			   RemoteDoOption(pSession, (int)cc, FALSE, TRUE);
			   pSession->nState = TS_DATA;
			   break;

		  case TS_DO :
			   //printf("IAC DO %0d\n", cc);
			   LocalDoOption(pSession, (int)cc, TRUE, TRUE);
			   pSession->nState = TS_DATA;
			   break;

		  case TS_DONT :
			   //printf("IAC DONT %0d\n", cc);
			   LocalDoOption(pSession, (int)cc, FALSE, TRUE);
			   pSession->nState = TS_DATA;
			   break;
		}
	}

	return TRUE;
}
Example #8
0
BOOL CConsoleDlg::PreTranslateMessage(MSG* pMsg)
{

	if (pMsg->hwnd == editInput.GetSafeHwnd()) {
		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE ) {
			Select_Deselect();
			g_pParentWnd->SetFocus ();
			return TRUE;
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN ) {
			ExecuteCommand();
			return TRUE;
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE ) {
			if (pMsg->wParam == VK_ESCAPE) {
				g_pParentWnd->GetCamera()->SetFocus();
				Select_Deselect();
			}

			return TRUE;
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_UP ) {
			//save off the current in-progress command so we can get back to it
			if ( saveCurrentCommand == true ) {
				CString str;
				editInput.GetWindowText ( str );
				currentCommand = str.GetBuffer ( 0 );
				saveCurrentCommand = false;
	}

			if ( consoleHistory.Num () > 0 ) {
				editInput.SetWindowText ( consoleHistory[currentHistoryPosition] );

				int selLocation = consoleHistory[currentHistoryPosition].Length ();
				editInput.SetSel ( selLocation , selLocation + 1);
}

			if ( currentHistoryPosition > 0) {
				--currentHistoryPosition;
			}

			return TRUE;
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_DOWN ) {
			int selLocation = 0;
			if ( currentHistoryPosition < consoleHistory.Num () - 1 ) {
				++currentHistoryPosition;
				editInput.SetWindowText ( consoleHistory[currentHistoryPosition] );
				selLocation = consoleHistory[currentHistoryPosition].Length ();
			}
			else {
				editInput.SetWindowText ( currentCommand );
				selLocation = currentCommand.Length ();
				currentCommand.Clear ();
				saveCurrentCommand = true;
			}

			editInput.SetSel ( selLocation , selLocation + 1);

			return TRUE;
		}
		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_TAB ) {
			common->Printf ( "Command History\n----------------\n" );
			for ( int i = 0 ; i < consoleHistory.Num ();i++ )
{
				common->Printf ( "[cmd %d]:  %s\n" , i , consoleHistory[i].c_str() );
			}
			common->Printf ( "----------------\n" );
		}
		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_NEXT) {
			editConsole.LineScroll ( 10 );
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_PRIOR ) {
			editConsole.LineScroll ( -10 );
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_HOME ) {
			editConsole.LineScroll ( -editConsole.GetLineCount() );
		}

		if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_END ) {
			editConsole.LineScroll ( editConsole.GetLineCount() );
		}
	}

	return CDialog::PreTranslateMessage(pMsg);
}
void MemoryCardDriverThreaded_Linux::GetUSBStorageDevices( vector<UsbStorageDevice>& vDevicesOut )
{
	LOG->Trace( "GetUSBStorageDevices" );
	
	vDevicesOut.clear();

	{
		vector<RString> asDevices;
		RString sBlockDevicePath = "/sys/block/";
		GetFileList( sBlockDevicePath, asDevices );

		for( unsigned i = 0; i < asDevices.size(); ++i )
		{
			const RString &sDevice = asDevices[i];
			if( sDevice == "." || sDevice == ".." )
				continue;

			UsbStorageDevice usbd;

			RString sPath = sBlockDevicePath + sDevice + "/";
			usbd.sSysPath = sPath;

			/* Ignore non-removable devices. */
			RString sBuf;
			if( !ReadFile( sPath + "removable", sBuf ) )
				continue; // already warned
			if( atoi(sBuf) != 1 )
				continue;

			/*
			 * The kernel isn't exposing all of /sys atomically, so we end up missing
			 * the partition due to it not being shown yet.  It won't show up until the
			 * kernel has scanned the partition table, which can take a variable amount
			 * of time, sometimes over a second.  Watch for the "queue" sysfs directory,
			 * which is created after this, to tell when partition directories are created.
			 */
			RageTimer WaitUntil;
			WaitUntil += 5;
			RString sQueueFilePath = usbd.sSysPath + "queue";
			while(1)
			{
				if( WaitUntil.Ago() >= 0 )
				{
					LOG->Warn( "Timed out waiting for %s", sQueueFilePath.c_str() );
					break;
				}

				if( access(usbd.sSysPath, F_OK) == -1 )
				{
					LOG->Warn( "Block directory %s went away while we were waiting for %s",
							usbd.sSysPath.c_str(), sQueueFilePath.c_str() );
					break;
				}

				if( access(sQueueFilePath, F_OK) != -1 )
					break;

				usleep(10000);
			}

			/* Wait for udev to finish handling device node creation */
			ExecuteCommand( "udevadm settle" );

			/* If the first partition device exists, eg. /sys/block/uba/uba1, use it. */
			if( access(usbd.sSysPath + sDevice + "1", F_OK) != -1 )
			{
				LOG->Trace("OK");
				usbd.sDevice = "/dev/" + sDevice + "1";
			}
			else
			{
				LOG->Trace("error %s", strerror(errno));
				usbd.sDevice = "/dev/" + sDevice;
			}

			/*
			 * sPath/device should be a symlink to the actual device.  For USB
			 * devices, it looks like this:
			 *
			 * device -> ../../devices/pci0000:00/0000:00:02.1/usb2/2-1/2-1:1.0
			 *
			 * "2-1" is "bus-port".
			 */
			char szLink[256];
			int iRet = readlink( sPath + "device", szLink, sizeof(szLink) );
			if( iRet == -1 )
			{
				LOG->Warn( "readlink(\"%s\"): %s", (sPath + "device").c_str(), strerror(errno) );
			}
			else
			{
				/*
				 * The full path looks like
				 *
				 *   ../../devices/pci0000:00/0000:00:02.1/usb2/2-2/2-2.1/2-2.1:1.0
				 *
				 * In newer kernels, it looks like:
				 *
				 * ../../../3-2.1:1.0
				 *
				 * Each path element refers to a new hop in the chain.
				 *  "usb2" = second USB host
				 *  2-            second USB host,
				 *   -2           port 1 on the host,
				 *     .1         port 1 on an attached hub
				 *       .2       ... port 2 on the next hub ...
				 * 
				 * We want the bus number and the port of the last hop.  The level is
				 * the number of hops.
				 */
				szLink[iRet] = 0;
				vector<RString> asBits;
				split( szLink, "/", asBits );

				RString sHostPort = asBits[asBits.size()-1];
				if( !sHostPort.empty() )
				{
					/* Strip off the endpoint information after the colon. */
					size_t pos = sHostPort.find(':');
					if( pos != string::npos )
						sHostPort.erase( pos );
					
					/* sHostPort is eg. 2-2.1. */
					sHostPort.Replace( "-", "." );
					asBits.clear();
					split( sHostPort, ".", asBits );
					if( asBits.size() > 1 )
					{
						usbd.iBus = atoi( asBits[0] );
						usbd.iPort = atoi( asBits[asBits.size()-1] );
						usbd.iLevel = asBits.size() - 1;
					}
				}
			}

			if( ReadFile( sPath + "device/../idVendor", sBuf ) )
				sscanf( sBuf, "%x", &usbd.idVendor );

			if( ReadFile( sPath + "device/../idProduct", sBuf ) )
				sscanf( sBuf, "%x", &usbd.idProduct );

			if( ReadFile( sPath + "device/../serial", sBuf ) )
			{
				usbd.sSerial = sBuf;
				TrimRight( usbd.sSerial );
			}
			if( ReadFile( sPath + "device/../product", sBuf ) )
			{
				usbd.sProduct = sBuf;
				TrimRight( usbd.sProduct );
			}
			if( ReadFile( sPath + "device/../manufacturer", sBuf ) )
			{
				usbd.sVendor = sBuf;
				TrimRight( usbd.sVendor );
			}

			vDevicesOut.push_back( usbd );
		}
	}

	{
		// Find where each device is mounted. Output looks like:
		
		// /dev/sda1               /mnt/flash1             auto    noauto,owner 0 0
		// /dev/sdb1               /mnt/flash2             auto    noauto,owner 0 0
		// /dev/sdc1               /mnt/flash3             auto    noauto,owner 0 0
		
		RString fn = "/rootfs/etc/fstab";
		RageFile f;
		if( !f.Open(fn) )
		{
			LOG->Warn( "can't open '%s': %s", fn.c_str(), f.GetError().c_str() );
			return;
		}
		
		RString sLine;
		while( !f.AtEOF() )
		{
			switch( f.GetLine(sLine) )
			{
			case 0: continue; /* eof */
			case -1:
				LOG->Warn( "error reading '%s': %s", fn.c_str(), f.GetError().c_str() );
				return;
			}

			char szScsiDevice[1024];
			char szMountPoint[1024];
			int iRet = sscanf( sLine, "%s %s", szScsiDevice, szMountPoint );
			if( iRet != 2 || szScsiDevice[0] == '#')
				continue;	// don't process this line

			/* Get the real kernel device name, which should match
			 * the name from /sys/block, by following symlinks in
			 * /dev.  This allows us to specify persistent names in
			 * /etc/fstab using things like /dev/device/by-path. */
			char szUnderlyingDevice[PATH_MAX];
			if( realpath(szScsiDevice, szUnderlyingDevice) == NULL )
			{
				// "No such file or directory" is understandable
				if (errno != ENOENT)
					LOG->Warn( "realpath(\"%s\"): %s", szScsiDevice, strerror(errno) );
				continue;
			}

			RString sMountPoint = szMountPoint;
			TrimLeft( sMountPoint );
			TrimRight( sMountPoint );

			// search for the mountpoint corresponding to the device
			for( unsigned i=0; i<vDevicesOut.size(); i++ )
			{
				UsbStorageDevice& usbd = vDevicesOut[i];
				if( usbd.sDevice == szUnderlyingDevice )	// found our match
				{
					// Use the device entry from fstab so the mount command works
					usbd.sDevice = szScsiDevice;
					usbd.sOsMountDir = sMountPoint;
					break;	// stop looking for a match
				}
			}
		}
	}

	for( unsigned i=0; i<vDevicesOut.size(); i++ )
	{
		UsbStorageDevice& usbd = vDevicesOut[i];
		LOG->Trace( "    sDevice: %s, iBus: %d, iLevel: %d, iPort: %d, id: %04X:%04X, Vendor: '%s', Product: '%s', sSerial: \"%s\", sOsMountDir: %s",
				usbd.sDevice.c_str(), usbd.iBus, usbd.iLevel, usbd.iPort, usbd.idVendor, usbd.idProduct, usbd.sVendor.c_str(),
				usbd.sProduct.c_str(), usbd.sSerial.c_str(), usbd.sOsMountDir.c_str() );
	}
	
	/* Remove any devices that we couldn't find a mountpoint for. */
	for( unsigned i=0; i<vDevicesOut.size(); i++ )
	{
		UsbStorageDevice& usbd = vDevicesOut[i];
		if( usbd.sOsMountDir.empty() )
		{
			LOG->Trace( "Ignoring %s (couldn't find in /etc/fstab)", usbd.sDevice.c_str() );
			
			vDevicesOut.erase( vDevicesOut.begin()+i );
			--i;
		}
	}
	
	LOG->Trace( "Done with GetUSBStorageDevices" );
}
Example #10
0
void PrintFileAsBase64(const std::string &Path) {
  std::string Cmd = "base64 -w 0 < " + Path + "; echo";
  ExecuteCommand(Cmd);
}
Example #11
0
bool GuiTextEdit::OnKeyEvent(const KeyEvent& ke)
{
  if (!IsVisible())
  {
    return false;
  }

  // Buttons can generate key events, so this GuiTextEdit object may not have the focus (the button
  //  just clicked would have it). So the last GuiTextEdit to have the focus should accept this key.
  if (!HasFocus())
  {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Key event ignored by " << m_name << " as does not have focus.\n";
#endif
    return false;
  }

  // Is this the current or most recent GuiTextEdit to have focus ?
  // TODO 

  if (!ke.keyDown)
  {
    return true;
  }

  switch (ke.keyType)
  {
  case AMJU_KEY_CHAR:
    // Prevent chars like Tab 
    if (ke.key >= ' ') // && ke.key <= (char)127)
    {
      Insert(ke.key);
    }
    else
    {
      // TODO Alert user that character is out of range
    }
    break;

  case AMJU_KEY_UP:
  case AMJU_KEY_DOWN:
    // TODO Multi line text
    break;

  case AMJU_KEY_LEFT:
#ifdef MACOSX
    if (ke.modifier & AMJU_KEY_MOD_ALT) // jump to prev word
#else
    if (ke.modifier & AMJU_KEY_MOD_CTRL)
#endif
    {
      // Prev word
      if (ke.modifier & AMJU_KEY_MOD_SHIFT)
      {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Prev word + select\n";
#endif
        m_caret = PrevWord(m_caret);
        m_triListSelection = 0;
      }
      else
      {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Prev word\n";
#endif
        m_caret = PrevWord(m_caret);
        m_selectedText = m_caret; 
        m_triListSelection = 0;
      }
    }
    else if (ke.modifier & AMJU_KEY_MOD_SHIFT)
    {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Prev char + select\n";
#endif
      // Select char to left
      if (m_caret > 0)
      {
        m_caret--;
        m_triListSelection = 0;
      }
    }
    else 
    {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Prev char\n";
#endif
      if (m_caret > 0)
      {
        // Move caret left
        m_caret--;
        m_selectedText = m_caret; 
        m_triListSelection = 0;
      }
    }
    break;

  case AMJU_KEY_RIGHT:
#ifdef MACOSX
    if (ke.modifier & AMJU_KEY_MOD_ALT) // jump to next word
#else
    if (ke.modifier & AMJU_KEY_MOD_CTRL)
#endif
    {
      // Next word
      if (ke.modifier & AMJU_KEY_MOD_SHIFT)
      {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Next word + select\n";
#endif
        m_caret = NextWord(m_caret);
        m_triListSelection = 0;
      }
      else 
      {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Next word\n";
#endif
        m_caret = NextWord(m_caret);
        m_selectedText = m_caret; 
        m_triListSelection = 0;
      }
    }
    else if (ke.modifier & AMJU_KEY_MOD_SHIFT)
    {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Next char + select\n";
#endif
      if (m_caret < (int)m_text.size())
      {
        m_caret++;
        m_triListSelection = 0;
      } 
    }
    else 
    {
#ifdef TEXT_EDIT_DEBUG
std::cout << "Next char\n";
#endif
      if (m_caret < (int)m_text.size())
      {
        m_caret++;
        m_selectedText = m_caret; 
        m_triListSelection = 0;
      }
    }

    break;

  case AMJU_KEY_ENTER:
    // TODO multi-line
    ExecuteCommand();
    break;

  case AMJU_KEY_SPACE:
    Insert(' ');
    break;

  case AMJU_KEY_ESC:
    // OnCancel();
    break;

  case AMJU_KEY_BACKSPACE:
    {
      int left = std::min(m_caret, m_selectedText);  
      int right = std::max(m_caret, m_selectedText);  
      if (left == right && m_caret > 0)
      {
        left--;
      }

      std::string leftStr = m_text.substr(0, left);
      std::string rightStr = m_text.substr(right);
      m_text = leftStr + rightStr;
      m_caret = left;
      m_selectedText = m_caret; 
      m_triListSelection = 0;
  
      if (m_onChangeFunc)
      {
        m_onChangeFunc(this);
      }
      m_triList = 0; // force rebuild
    }
    break;

  case AMJU_KEY_DELETE:
    //if ()
    {
      int left = std::min(m_caret, m_selectedText);  
      int right = std::max(m_caret, m_selectedText);  
      if (left == right && m_caret < (int)m_text.size())
      {
        right++;
      }

      std::string leftStr = m_text.substr(0, left);
      std::string rightStr = m_text.substr(right);
      m_text = leftStr + rightStr;
      m_caret = left;
      m_selectedText = m_caret; 
      m_triListSelection = 0;

      if (m_onChangeFunc)
      {
        m_onChangeFunc(this);
      }
      m_triList = 0; // force rebuild
    }
    break;

  default:
#ifdef _DEBUG
std::cout << "Unexpected key type: " << ke.keyType << " key: '" << ke.key << "' (int: " << (int)ke.key << ")\n"; 
#endif
//    Assert(0); // handle this key ?
    break;
  }

  if (m_caret >= m_last || m_caret <= m_first)
  {
    RecalcFirstLast();
  }

  return true; // handled
}
// ---------------------------------------------------------------------------
// CATDetectNetwork::StartRequestL
// other items were commented in a header
// ---------------------------------------------------------------------------
void CATDetectNetwork::StartRequest()
	{
	iCommandRunning = ETrue;
	ExecuteCommand();
	}
ECommandResult::Type FProvider::Execute(
	const TSharedRef<ISourceControlOperation, ESPMode::ThreadSafe>& InOperation,
	const TArray<FString>& InFiles, 
	EConcurrency::Type InConcurrency,
	const FSourceControlOperationComplete& InOperationCompleteDelegate
)
{
	// the "Connect" operation is the only operation that can be performed while the
	// provider is disabled, if the operation is successful the provider will be enabled
	if (!IsEnabled() && (InOperation->GetName() != OperationNames::Connect))
	{
		return ECommandResult::Failed;
	}

	// attempt to create a worker to perform the requested operation
	FWorkerPtr WorkerPtr = CreateWorker(InOperation->GetName());
	if (!WorkerPtr.IsValid())
	{
		// apparently we don't support this particular operation
		FFormatNamedArguments Arguments;
		Arguments.Add(TEXT("OperationName"), FText::FromName(InOperation->GetName()));
		Arguments.Add(TEXT("ProviderName"), FText::FromName(GetName()));
		LogError(
			FText::Format(
				LOCTEXT(
					"UnsupportedOperation", 
					"Operation '{OperationName}' not supported by source control provider '{ProviderName}'"
				),
				Arguments
			)
		);
		return ECommandResult::Failed;
	}
	
	auto* Command = new FCommand(
		GetWorkingDirectory(), AbsoluteContentDirectory, InOperation,
		WorkerPtr.ToSharedRef(), InOperationCompleteDelegate
	);

	TArray<FString> AbsoluteFiles;
	if (InOperation->GetName() == OperationNames::Connect)
	{
		AbsoluteFiles.Add(Settings.GetMercurialPath());
	}
	else if (InOperation->GetName() == OperationNames::MarkForAdd)
	{
		TArray<FString> AbsoluteLargeFiles;
		PrepareFilenamesForAddCommand(InFiles, AbsoluteFiles, AbsoluteLargeFiles);
		
		if (AbsoluteLargeFiles.Num() > 0)
		{
			Command->SetAbsoluteLargeFiles(AbsoluteLargeFiles);
		}
	}
	else
	{
		for (const auto& Filename : InFiles)
		{
			AbsoluteFiles.Add(FPaths::ConvertRelativePathToFull(Filename));
		}
	}

	if (AbsoluteFiles.Num() > 0)
	{
		Command->SetAbsoluteFiles(AbsoluteFiles);
	}

	if (InConcurrency == EConcurrency::Synchronous)
	{
		auto Result = ExecuteSynchronousCommand(Command, InOperation->GetInProgressString());
		delete Command;
		return Result;
	}
	else
	{
		return ExecuteCommand(Command, true);
	}
}
Example #14
0
//----------------------------------------------
//	execute menu item command
//----------------------------------------------
Bool TLMenu::TMenuController::ExecuteMenuItem(TRefRef MenuItemRef)
{
	TPtr<TMenuItem> pMenuItem = GetMenuItem(MenuItemRef);
	if ( !pMenuItem )
	{
		TLDebug_Break("No such menu item");
		return FALSE;
	}
	
	//	get command of menu item
	TRefRef MenuCommand = pMenuItem->GetMenuCommand();
	
	TRefRef AudioRef = pMenuItem->GetAudioRef();;
	
	//	open-menu command
	if ( MenuCommand == "Open" )
	{
		// Already has a queued command?
		if(m_QueuedCommand.GetRef().IsValid())
			return FALSE;
		
		// Queue up the command.  
		m_QueuedCommand.SetRef(MenuCommand);
		m_QueuedCommand.SetTypeRef(pMenuItem->GetNextMenu());
	}
	else if ( MenuCommand == "Close" )
	{
		// Already has a queued command?
		if(m_QueuedCommand.GetRef().IsValid())
			return FALSE;
		
		// Queue up the command.  
		m_QueuedCommand.SetRef(MenuCommand);
	}
	else
	{
		//	do non standard command
		if ( !ExecuteCommand( MenuCommand, pMenuItem->GetData() ) )
			return FALSE;
	}
	
	// Valid audio to play?
	// Create menu audio for command execution
	//	gr: this should go in menu renderer code, not menu logic code
	if(AudioRef.IsValid())
	{
		TLMessaging::TMessage Message(TLCore::InitialiseRef);
		Message.ExportData("Asset", AudioRef);
		Message.ExportData("Play", TRUE);
		Message.ExportData("RateOfDecay", 0.0f); // Make 2D
		Message.ExportData("MinRange", 100000.0f);
		Message.ExportData("MaxRange", 100000.0f);
		
		TLAudio::g_pAudiograph->StartAudio(MenuCommand, AudioRef);
	}
	
	//	publish that command has been executed
	OnMenuItemExecuted( MenuCommand, pMenuItem->GetData() );
	
	return TRUE;
}
Example #15
0
void ProcUtils::GetChildren(long pid, std::vector<long> &proclist)
{
#ifdef __WXMSW__
	OSVERSIONINFO osver ;

	// Check to see if were running under Windows95 or
	// Windows NT.
	osver.dwOSVersionInfoSize = sizeof( osver ) ;
	if ( !GetVersionEx( &osver ) ) {
		return;
	}

	if ( osver.dwPlatformId != VER_PLATFORM_WIN32_NT ) {
		return;
	}

	//get child processes of this node
	HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (!hProcessSnap) {
		return;
	}

	//Fill in the size of the structure before using it.
	PROCESSENTRY32 pe;
	memset(&pe, 0, sizeof(pe));
	pe.dwSize = sizeof(PROCESSENTRY32);

	// Walk the snapshot of the processes, and for each process,
	// kill it if its parent is pid.
	if (!Process32First(hProcessSnap, &pe)) {
		// Can't get first process.
		CloseHandle (hProcessSnap);
		return;
	}

	//loop over all processes and collect all the processes their parent
	//pid matches PID
	do {
		if ((long)pe.th32ParentProcessID == pid) {
			proclist.push_back((long)pe.th32ProcessID);
		}
	} while (Process32Next (hProcessSnap, &pe));
	CloseHandle (hProcessSnap);

#elif defined(__FreeBSD__)
	kvm_t *kvd;
	struct kinfo_proc *ki;
	int nof_procs, i;

	if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL)))
	    return;

	if (!(ki = kvm_getprocs(kvd, KERN_PROC_PROC, pid, &nof_procs))) {
	    kvm_close(kvd);
	    return;
	}

	for (i=0; i<nof_procs; i++) {
	    ProcessEntry entry;
	    if (ki[i].ki_ppid == pid)
		proclist.push_back(ki[i].ki_pid);
	}

	kvm_close(kvd);

#else
	//GTK and other
	wxArrayString output;
#ifdef __WXGTK__
	ExecuteCommand(wxT("ps -A -o pid,ppid  --no-heading"), output);
#else
	ExecuteCommand(wxT("ps -A -o pid,ppid "), output);
#endif
	//parse the output and search for our process ID
	for (size_t i=0; i< output.GetCount(); i++) {
		long lpid(0);
		long lppid(0);
		wxString line = output.Item(i);

		//remove whitespaces
		line = line.Trim().Trim(false);

		//get the process ID
		wxString spid  = line.BeforeFirst(wxT(' '));
		spid.ToLong( &lpid );

		//get the process Parent ID
		wxString sppid = line.AfterFirst(wxT(' '));
		sppid.ToLong( &lppid );
		if (lppid == pid) {
			proclist.push_back(lpid);
		}
	}
#endif
}
BOOL CPropPageRestore::RestoreProject()
{
    BOOL    bReturn = FALSE;

    // get installation path: install path + Engineering\bin
    CString strCmdLine;
    CString strInstallPath;
    CString strBackupPath(m_strBackupPath);
    size_t sizeInstDir = MAX_PATH;
    if(S_OK != UTIL_GetInstallPath(strInstallPath.GetBuffer(MAX_PATH), &sizeInstDir))
    {
        return bReturn;
    }
    strInstallPath.ReleaseBuffer();
    strInstallPath += _T("Engineering\\bin");
    
    if(m_iSource == TARGET_MODE)
    {
        m_pMainSheet->SetStatusText(_T("Upload from Target ..."));
        // get temporary backup path
        CString strTempPath;
        CString strFileName;
        VERIFY(::GetTempPath(_MAX_PATH, strTempPath.GetBuffer(_MAX_PATH)));
        strTempPath.ReleaseBuffer();
        VERIFY(::GetTempFileName(strTempPath, "bar", 1, strFileName.GetBuffer(_MAX_PATH)));
        strFileName.ReleaseBuffer();

        strBackupPath = strFileName;
        ::DeleteFile(strBackupPath);    // delete temporary backup file

        m_pMainSheet->SetStatusText(_T("Upload from Target ..."));

        // upload backup file from target
        CString strTargetType = m_pMainSheet->GetTargetType();
        CString strTargetControl = m_pMainSheet->GetControlString(m_strAddress);

        if(UploadProject(strBackupPath, strTargetControl, strTargetType))
        {
            m_pMainSheet->SetStatusText(_T("Upload Done"));
        }
        else
        {
            AfxMessageBox(_T("Could not upload project"), MB_ICONEXCLAMATION);
            return FALSE;
        }
    }
    
    // build command line
    CString strExe;
    CString strParam;
    CString strPassword;
    strExe.Format(_T("\"%s\\4cbar.exe\""), strInstallPath);

    if(!m_strPassword.IsEmpty())
    {
        strPassword.Format(_T(" -encrypt \"%s\""), m_strPassword);
    }

    strExe.Format(_T("\"%s\\4cbar.exe\""), strInstallPath);
    strParam.Format(_T(" -project \"%s\" -restore \"%s\" -file%s"), m_strProjectPath, strBackupPath, strPassword);

    strCmdLine = strExe + strParam;

    // execute command
    m_pMainSheet->SetStatusText(_T("Restore from File ..."));

    TRACE("%s", strCmdLine);
    int iRet = ExecuteCommand(strCmdLine);

    if(iRet != ST_OK)
    {
        CString strMessage = _T("Restore failed");
        CString strReason;
        
        switch(iRet)
        {
            case 502:
                strReason = _T("Project directory already exists.");
                break;
            case 503:
                strReason = _T("Invalid archive format.");
                break;
            case 507:
                strReason = _T("Wrong encryption password.");
                break;
            case 600:
                strReason = _T("Wrong format or encryption password missing.");
                break;
        }
        if(!strReason.IsEmpty())
        {
            strMessage += _T(":\n") + strReason;
        }
        else
        {
            strReason = strMessage;
        }
        AfxMessageBox(strMessage);
        m_pMainSheet->SetStatusText(strReason);
        return FALSE;
    }

    if(!LoadTargetInfoList(m_strProjectPath, TRUE))
    {
        m_pMainSheet->SetStatusText(_T("Could not read target info. OPC-Configuration not restored"));
        if(m_iSource == TARGET_MODE)
        {
            ::DeleteFile(strBackupPath);    // delete temporary backup file
        }
        return FALSE;
    }

    if(iRet == ST_OK)
    {
        if(m_bOPCServerConfig)
        {
            TTargetInfo*    pTargetInfo;
            CString         strErrMessage;
            CString         strErrTargets;
            BOOL            bError;

            POSITION    pos = m_tTargetInfoList.GetHeadPosition();
            while(pos)
            {
                bError = FALSE;
                pTargetInfo = m_tTargetInfoList.GetNext(pos);
                if(CopyOPCServerConfig(pTargetInfo, m_strProjectPath) != ST_OK)
                {
                    bError = TRUE;
                }
                if(PatchOPCServerRegistry(pTargetInfo, m_strProjectPath) != ST_OK)
                {
                    bError = TRUE;
                }
                if(bError)
                {
                    if(!strErrTargets.IsEmpty())
                    {
                        strErrTargets += _T(", ");
                    }
                    strErrTargets += pTargetInfo->strTargetName;
                }
            }
            if(strErrTargets.IsEmpty())
            {
                bReturn = TRUE;
            }
            else
            {
                strErrMessage.Format(IDS_ERR_RESTORE_OPC_CONFIG, strErrTargets);
                m_pMainSheet->SetStatusText(_T("Error: could not restore OPC configuration"));
                ::AfxMessageBox(strErrMessage, MB_ICONEXCLAMATION);
            }
        }
        else
        {
            // nothing to do -> ok
            bReturn = TRUE;
        }
    }

    if(m_iSource == TARGET_MODE)
    {
        ::DeleteFile(strBackupPath);    // delete temporary backup file
    }

    return bReturn;
}
// The front SD slot
IPCCommandResult CWII_IPC_HLE_Device_sdio_slot0::IOCtl(u32 _CommandAddress)
{
    u32 Cmd = Memory::Read_U32(_CommandAddress + 0xC);

    u32 BufferIn = Memory::Read_U32(_CommandAddress + 0x10);
    u32 BufferInSize = Memory::Read_U32(_CommandAddress + 0x14);
    u32 BufferOut = Memory::Read_U32(_CommandAddress + 0x18);
    u32 BufferOutSize = Memory::Read_U32(_CommandAddress + 0x1C);

    // As a safety precaution we fill the out buffer with zeros to avoid
    // returning nonsense values
    Memory::Memset(BufferOut, 0, BufferOutSize);

    u32 ReturnValue = 0;
    switch (Cmd)
    {
    case IOCTL_WRITEHCR:
    {
        u32 reg = Memory::Read_U32(BufferIn);
        u32 val = Memory::Read_U32(BufferIn + 16);

        DEBUG_LOG(WII_IPC_SD, "IOCTL_WRITEHCR 0x%08x - 0x%08x", reg, val);

        if (reg >= 0x200)
        {
            DEBUG_LOG(WII_IPC_SD, "IOCTL_WRITEHCR out of range");
            break;
        }

        if ((reg == HCR_CLOCKCONTROL) && (val & 1))
        {
            // Clock is set to oscillate, enable bit 1 to say it's stable
            m_Registers[reg] = val | 2;
        }
        else if ((reg == HCR_SOFTWARERESET) && val)
        {
            // When a reset is specified, the register gets cleared
            m_Registers[reg] = 0;
        }
        else
        {
            // Default to just storing the new value
            m_Registers[reg] = val;
        }
    }
    break;

    case IOCTL_READHCR:
    {
        u32 reg = Memory::Read_U32(BufferIn);

        if (reg >= 0x200)
        {
            DEBUG_LOG(WII_IPC_SD, "IOCTL_READHCR out of range");
            break;
        }

        u32 val = m_Registers[reg];
        DEBUG_LOG(WII_IPC_SD, "IOCTL_READHCR 0x%08x - 0x%08x", reg, val);

        // Just reading the register
        Memory::Write_U32(val, BufferOut);
    }
    break;

    case IOCTL_RESETCARD:
        DEBUG_LOG(WII_IPC_SD, "IOCTL_RESETCARD");
        if (m_Card)
            m_Status |= CARD_INITIALIZED;
        // Returns 16bit RCA and 16bit 0s (meaning success)
        Memory::Write_U32(0x9f620000, BufferOut);
        break;

    case IOCTL_SETCLK:
    {
        DEBUG_LOG(WII_IPC_SD, "IOCTL_SETCLK");
        // libogc only sets it to 1 and makes sure the return isn't negative...
        // one half of the sdclk divisor: a power of two or zero.
        u32 clock = Memory::Read_U32(BufferIn);
        if (clock != 1)
            INFO_LOG(WII_IPC_SD, "Setting to %i, interesting", clock);
    }
    break;

    case IOCTL_SENDCMD:
        INFO_LOG(WII_IPC_SD, "IOCTL_SENDCMD %x IPC:%08x", Memory::Read_U32(BufferIn), _CommandAddress);
        ReturnValue = ExecuteCommand(BufferIn, BufferInSize, 0, 0, BufferOut, BufferOutSize);
        break;

    case IOCTL_GETSTATUS:
        if (SConfig::GetInstance().m_WiiSDCard)
            m_Status |= CARD_INSERTED;
        else
            m_Status = CARD_NOT_EXIST;
        INFO_LOG(WII_IPC_SD, "IOCTL_GETSTATUS. Replying that SD card is %s%s",
                 (m_Status & CARD_INSERTED) ? "inserted" : "not present",
                 (m_Status & CARD_INITIALIZED) ? " and initialized" : "");
        Memory::Write_U32(m_Status, BufferOut);
        break;

    case IOCTL_GETOCR:
        DEBUG_LOG(WII_IPC_SD, "IOCTL_GETOCR");
        Memory::Write_U32(0x80ff8000, BufferOut);
        break;

    default:
        ERROR_LOG(WII_IPC_SD, "Unknown SD IOCtl command (0x%08x)", Cmd);
        break;
    }

    // INFO_LOG(WII_IPC_SD, "InBuffer");
    // DumpCommands(BufferIn, BufferInSize / 4, LogTypes::WII_IPC_SD);
    // INFO_LOG(WII_IPC_SD, "OutBuffer");
    // DumpCommands(BufferOut, BufferOutSize/4, LogTypes::WII_IPC_SD);

    if (ReturnValue == RET_EVENT_REGISTER)
    {
        // async
        m_event.addr = _CommandAddress;
        Memory::Write_U32(0, _CommandAddress + 0x4);
        // Check if the condition is already true
        EventNotify();
        return GetNoReply();
    }
    else if (ReturnValue == RET_EVENT_UNREGISTER)
    {
        // release returns 0
        // unknown sd int
        // technically we do it out of order, oh well
        EnqueueReply(m_event.addr, EVENT_INVALID);
        m_event.addr = 0;
        m_event.type = EVENT_NONE;
        Memory::Write_U32(0, _CommandAddress + 0x4);
        return GetDefaultReply();
    }
    else
    {
        Memory::Write_U32(ReturnValue, _CommandAddress + 0x4);
        return GetDefaultReply();
    }
}
Example #18
0
// Handle external test scripts.  We support three kinds, makefiles (rl.mak),
// command shell (dotest.cmd), and JScript (*.js).
//
// Standardized makefiles have the following targets:
//   clean: delete all generated files
//   build: build the test (OPT=compile options)
//   run: run the test
//   copy: copy the generated files to a subdirectory (COPYDIR=subdir)
//
int
    DoOneExternalTest(
    CDirectory* pDir,
    TestVariant *pTestVariant,
    const char *optFlags,
    const char *inCCFlags,
    const char *inLinkFlags,
    const char *testCmd,
    ExternalTestKind kind,
    BOOL fSyncVariationWhenFinished,
    BOOL fCleanBefore,
    BOOL fCleanAfter,
    BOOL fSuppressNoGPF,
    void *envFlags,
    DWORD millisecTimeout
    )
{
#define NMAKE "nmake -nologo -R -f "
    char full[MAX_PATH];
    char cmdbuf[BUFFER_SIZE];
    char buf[BUFFER_SIZE];
    char ccFlags[BUFFER_SIZE];
    char linkFlags[BUFFER_SIZE];
    char nogpfFlags[BUFFER_SIZE];
    char optReportBuf[BUFFER_SIZE];
    char nonZeroReturnBuf[BUFFER_SIZE];
    const char *reason = NULL;
    time_t start_variation;
    UINT elapsed_variation;
    time_t start_build_variation;
    UINT elapsed_build_variation;
    LARGE_INTEGER start_run, end_run, frequency;
    UINT elapsed_run;
    BOOL fFailed = FALSE;
    BOOL fDumpOutputFile = FVerbose;
    BOOL fFileToDelete = FALSE;
    int  cmdResult;
    static unsigned int testCount = 0;
    unsigned int localTestCount = InterlockedIncrement(&testCount);

    // Avoid conditionals by copying/creating ccFlags appropriately.

    if (inCCFlags)
    {
        if (pDir->HasTestInfoData(TIK_SOURCE_PATH))
        {
            sprintf_s(ccFlags, " %s -baselinePath:%s", inCCFlags, pDir->GetDirectoryPath());
        }
        else
        {
            sprintf_s(ccFlags, " %s", inCCFlags);
        }
    }
    else
    {
        ccFlags[0] = '\0';
    }

    switch (TargetMachine) {
    case TM_WVM:
    case TM_WVMX86:
    case TM_WVM64:
        strcat_s(ccFlags, " /BC ");
        break;
    }

    if (inLinkFlags)
        strcpy_s(linkFlags, inLinkFlags);
    else
        linkFlags[0] = '\0';

    sprintf_s(optReportBuf, "%s%s%s", optFlags, *linkFlags ? ";" : "", linkFlags);

    // Update the status.

    sprintf_s(buf, " (%s)", optReportBuf);
    ThreadInfo[ThreadId].SetCurrentTest(pDir->GetDirectoryName(),
        buf, pDir->IsBaseline());
    UpdateTitleStatus();

    // Make sure the file that will say pass or fail is not present.

    sprintf_s(full, "%s\\testout%d", pDir->GetDirectoryPath(), localTestCount);
    DeleteFileIfFound(full);

    start_variation = time(NULL);

    if (kind == TK_MAKEFILE) {
        Message(""); // newline
        Message("Processing %s with '%s' flags",
            testCmd, optReportBuf);
        Message(""); // newline

        if (FTest)
        {
            return 0;
        }

        if (fCleanBefore) {

            // Clean the directory.

            sprintf_s(cmdbuf, NMAKE"%s clean", testCmd);
            Message(cmdbuf);
            ExecuteCommand(pDir->GetDirectoryPath(), cmdbuf);
        }

        FillNoGPFFlags(nogpfFlags, fSuppressNoGPF);

        // Build the test.

        start_build_variation = time(NULL);

        sprintf_s(cmdbuf, NMAKE"%s build OPT=\"%s %s%s\" LINKFLAGS=\"%s %s %s\"",
            testCmd,
            optFlags, EXTRA_CC_FLAGS, ccFlags,
            LINKFLAGS, linkFlags, nogpfFlags);
        if (strlen(cmdbuf) > BUFFER_SIZE - 1)
            Fatal("Buffer overrun");

        Message(cmdbuf);
        fFailed = ExecuteCommand(pDir->GetDirectoryPath(), cmdbuf);

        elapsed_build_variation = (int)(time(NULL) - start_build_variation);

        if (Timing & TIME_VARIATION) {
            Message("RL: Variation elapsed time (build) (%s, %s, %s): %02d:%02d",
                pDir->GetDirectoryName(),
                "rl.mak",
                optReportBuf,
                elapsed_build_variation / 60, elapsed_build_variation % 60);
        }

        if (fFailed) {
            reason = "build failure";
            goto logFailure;
        }

        // Run the test.

        QueryPerformanceCounter(&start_run);

        sprintf_s(cmdbuf, NMAKE"%s run", testCmd);
        Message(cmdbuf);
        cmdResult = ExecuteCommand(pDir->GetDirectoryPath(), cmdbuf, millisecTimeout);

        QueryPerformanceCounter(&end_run);
        QueryPerformanceFrequency(&frequency);
        elapsed_run = (int) (((end_run.QuadPart - start_run.QuadPart) * 1000UI64) / frequency.QuadPart);

        if (Timing & TIME_VARIATION) {
            Message("RL: Variation elapsed time (run) (%s, %s, %s): %02d:%02d.%03d",
                pDir->GetDirectoryName(),
                "rl.mak",
                optReportBuf,
                elapsed_run / 60000, (elapsed_run % 60000)/1000, elapsed_run % 1000);
        }
    }
    else if (kind == TK_CMDSCRIPT)
    {

        // Build up the test command string

        sprintf_s(cmdbuf, "%s %s %s%s >testout%d", testCmd, optFlags, EXTRA_CC_FLAGS, ccFlags, localTestCount);

        Message("Running '%s'", cmdbuf);

        if (FTest)
        {
            return 0;
        }
        cmdResult = ExecuteCommand(pDir->GetDirectoryPath(), cmdbuf, millisecTimeout, envFlags);
    }
    else if (kind == TK_JSCRIPT || kind==TK_HTML || kind == TK_COMMAND)
    {
        char tempExtraCCFlags[MAX_PATH*2] = {0};

        // Only append when EXTRA_CC_FLAGS isn't empty.
        if (EXTRA_CC_FLAGS[0])
        {
            // Append test case unique identifier to the end of EXTRA_CC_FLAGS.
            if (FAppendTestNameToExtraCCFlags)
            {
                sprintf_s(tempExtraCCFlags, "%s.%s", EXTRA_CC_FLAGS, pTestVariant->testInfo.data[TIK_FILES]);
            }
            else
            {
                strcpy_s(tempExtraCCFlags, EXTRA_CC_FLAGS);
            }
        }

        const char* cmd = JCBinary;
        if (kind != TK_JSCRIPT && kind != TK_HTML)
        {
            cmd = pTestVariant->testInfo.data[TIK_COMMAND];
        }
        sprintf_s(cmdbuf, "%s %s %s %s %s >%s 2>&1", cmd, optFlags, tempExtraCCFlags, ccFlags, testCmd, full);

        Message("Running '%s'", cmdbuf);

        if(FTest)
        {
            DeleteFileIfFound(full);
            return 0;
        }

        cmdResult = ExecuteCommand(pDir->GetFullPathFromSourceOrDirectory(), cmdbuf, millisecTimeout, envFlags);

        if (cmdResult && cmdResult != WAIT_TIMEOUT && !pTestVariant->testInfo.data[TIK_BASELINE]) // failure code, not baseline diffing
        {
            fFailed = TRUE;
            sprintf_s(nonZeroReturnBuf, "non-zero (%08X) return value from test command", cmdResult);
            reason = nonZeroReturnBuf;
            goto logFailure;
        }
    }
    else
    {
        ASSERTNR(UNREACHED);
        cmdResult = NOERROR; // calm compiler warning about uninitialized variable usage
    }

    // Check for timeout.

    if (cmdResult == WAIT_TIMEOUT) {
        ASSERT(millisecTimeout != INFINITE);
        sprintf_s(nonZeroReturnBuf, "timed out after %u second%s", millisecTimeout / 1000, millisecTimeout == 1000 ? "" : "s");
        reason = nonZeroReturnBuf;
        fFailed = TRUE;
        goto logFailure;
    }

    // If we have a baseline test, we need to check the baseline file.
    if (pTestVariant->testInfo.data[TIK_BASELINE]) {
        char baseline_file[_MAX_PATH];

        sprintf_s(baseline_file, "%s\\%s", pDir->GetFullPathFromSourceOrDirectory(),
            pTestVariant->testInfo.data[TIK_BASELINE]);
        if (DoCompare(baseline_file, full, pTestVariant->testInfo.hasData[TIK_EOL_NORMALIZATION])) {
            reason = "diffs from baseline";
            sprintf_s(optReportBuf, "%s", baseline_file);
            fFailed = TRUE;
            CopyRebaseFile(full, baseline_file);
        }
    }
    else if ((kind == TK_JSCRIPT || kind == TK_HTML || kind == TK_COMMAND) && !pTestVariant->testInfo.hasData[TIK_BASELINE]) {
        if (!CheckForPass(full, optReportBuf, cmdbuf, fDumpOutputFile)) {
            fFailed = TRUE;
            goto SkipLogFailure;
        }
    }

logFailure:
    if (fFailed) {
        LogOut("ERROR: Test failed to run correctly: %s (%s):",
            reason, optReportBuf);
        LogOut("    %s", cmdbuf);
        if (fDumpOutputFile) {
            DumpFileToLog(full);
        }
    }

SkipLogFailure:
    if (fFileToDelete && !FNoDelete) {
        DeleteFileRetryMsg(full);
    }

    elapsed_variation = (int)(time(NULL) - start_variation);
    if (Timing & TIME_VARIATION) {
        Message("RL: Variation elapsed time (%s, %s, %s): %02d:%02d",
            pDir->GetDirectoryName(),
            kind == TK_MAKEFILE ? "rl.mak" : "dotest.cmd",
            optReportBuf,
            elapsed_variation / 60, elapsed_variation % 60);
    }

    if (kind == TK_MAKEFILE) {

        // If the test failed and we are asked to copy the failures, do so.

        if (fFailed && FCopyOnFail) {
            sprintf_s(cmdbuf, NMAKE"%s copy COPYDIR=\"fail.%s.%s\"",
                testCmd, optFlags, linkFlags);
            Message(cmdbuf);
            ExecuteCommand(pDir->GetDirectoryPath(), cmdbuf);
        }

        // Clean up after ourselves.

        if (!FNoDelete && (fFailed || fCleanAfter)) {
            sprintf_s(cmdbuf, NMAKE"%s clean", testCmd);
            Message(cmdbuf);
            ExecuteCommand(pDir->GetDirectoryPath(), cmdbuf);
        }
    }

    if (FSyncVariation) {
        if (FRLFE && fFailed) {
            RLFEAddLog(pDir, RLFES_FAILED, testCmd,
                optReportBuf, ThreadOut->GetText());
        }

        if (fSyncVariationWhenFinished)
            FlushOutput();
    }
    DeleteFileIfFound(full);

    return fFailed ? -1 : 0;
}
Example #19
0
BOOL CCLITerminal::ExecuteVirtualKey(CLISESSION *pSession, int nVKey)
{
	if (m_pCLIService->GetRunLevel() == RUNLEVEL_DEBUG)
		return TRUE;

	switch(pSession->nVKey) {
	  case VKEY_F1 :
		   if (!pSession->bLogined)
			   break;
		   strcpy(pSession->szCommand, (char *)m_pCLIService->m_szVirtualKey[0]);
		   WriteStream(pSession, pSession->szCommand);
		   pSession->nCmdLength = strlen(pSession->szCommand);
		   ExecuteCommand(pSession, FALSE, FALSE);
		   break;

	  case VKEY_F2 :
		   if (!pSession->bLogined)
			   break;
		   strcpy(pSession->szCommand, (char *)m_pCLIService->m_szVirtualKey[1]);
		   WriteStream(pSession, pSession->szCommand);
		   pSession->nCmdLength = strlen(pSession->szCommand);
		   ExecuteCommand(pSession, FALSE, FALSE);
		   break;

	  case VKEY_F3 :
		   if (!pSession->bLogined)
			   break;
		   strcpy(pSession->szCommand, (char *)m_pCLIService->m_szVirtualKey[2]);
		   WriteStream(pSession, pSession->szCommand);
		   pSession->nCmdLength = strlen(pSession->szCommand);
		   ExecuteCommand(pSession, FALSE, FALSE);
		   break;

	  case VKEY_F4 :
		   if (!pSession->bLogined)
			   break;
		   strcpy(pSession->szCommand, (char *)m_pCLIService->m_szVirtualKey[3]);
		   WriteStream(pSession, pSession->szCommand);
		   pSession->nCmdLength = strlen(pSession->szCommand);
		   ExecuteCommand(pSession, FALSE, FALSE);
		   break;

	  case VKEY_UP :
		   if (!pSession->bLogined || (pSession->nCurHistory <= 0))
			  break;
		   pSession->nCurHistory--;
		   ReplaceCommand(pSession, pSession->pszHistory[pSession->nCurHistory]);
		   break;

	  case VKEY_DOWN :
		   if (!pSession->bLogined)
			   break;
		   if (pSession->nCurHistory >= pSession->nHistoryCount)
		   {
			   if (pSession->nCmdLength != 0)
		   	   	   ReplaceCommand(pSession, "");
			   break;
		   }
		   pSession->nCurHistory++;
		   ReplaceCommand(pSession, pSession->pszHistory[pSession->nCurHistory]);
		   break;

	  case VKEY_LEFT :
		   break;

	  case VKEY_RIGHT :
		   break;

	  case VKEY_HOME :
		   break;

	  case VKEY_END :
		   break;

	  case VKEY_USERMENU :
		   if (pSession->nMode == CLIMODE_USER)
			   break;

		   if (pSession->nType == CLITYPE_TELNET)
       		   break;

		   pSession->nMode = CLIMODE_USER;
		   DisplayUserMenu(pSession);
		   break;
	}
	return TRUE;
}
Example #20
0
BOOL
    DoOneSimpleTest(
    CDirectory *pDir,
    Test * pTest,
    TestVariant * pTestVariant,
    const char *optFlags,
    const char *inCCFlags,
    const char *inLinkFlags,
    BOOL fSyncVariationWhenFinished,
    BOOL fCleanAfter,
    BOOL fLinkOnly,    // relink only
    BOOL fSuppressNoGPF,
    DWORD millisecTimeout
    )
{
    int rc;
    char *p = NULL;
    char cmdbuf[BUFFER_SIZE*2];
    char ccFlags[BUFFER_SIZE];
    char linkFlags[BUFFER_SIZE];
    char nogpfFlags[BUFFER_SIZE];
    char optReportBuf[BUFFER_SIZE];
    char full[MAX_PATH];
    char exebuf[BUFFER_SIZE];
    char fullexebuf[BUFFER_SIZE];
    char buf[BUFFER_SIZE];
    char failDir[BUFFER_SIZE];
    char copyName[BUFFER_SIZE];
    char tmp_file1[MAX_PATH];
    char tmp_file2[MAX_PATH];
    time_t start_variation;
    UINT elapsed_variation;
    BOOL fFailed;
    void *envFlags = GetEnvFlags(pTestVariant);

    // Avoid conditionals by copying/creating ccFlags appropriately.

    if (inCCFlags)
        sprintf_s(ccFlags, " %s", inCCFlags);
    else
        ccFlags[0] = '\0';

    switch (TargetMachine) {
    case TM_WVM:
    case TM_WVMX86:
    case TM_WVM64:
        strcat_s(ccFlags, " /BC ");
        break;
    }

    if (inLinkFlags)
        strcpy_s(linkFlags, inLinkFlags);
    else
        linkFlags[0] = '\0';

    sprintf_s(optReportBuf, "%s%s%s", optFlags, *linkFlags ? ";" : "", linkFlags);

    // Figure out the exe name and path

    strcpy_s(exebuf, pTest->name);
    p = strrchr(exebuf, '.');
    if (p != NULL)
    {
        strcpy_s(p + 1, REMAININGARRAYLEN(exebuf, p + 1), "exe");
    }
    else
    {
        strcat_s(exebuf, ".exe");
    }

    sprintf_s(fullexebuf, "%s\\%s", pDir->GetDirectoryPath(), exebuf);

    start_variation = time(NULL);

    // Build up the compile command string.

    sprintf_s(cmdbuf, "%s %s%s %s", REGR_CL,
        optFlags, ccFlags, EXTRA_CC_FLAGS);

    for (StringList * pFile = pTest->files; pFile != NULL; pFile = pFile->next)
    {
        strcat_s(cmdbuf, " ");
        strcat_s(cmdbuf, pFile->string);

        // If we're only relinking, hammer the extension to .obj

        if (fLinkOnly)
        {
            p = strrchr(cmdbuf, '.');
            sprintf_s(p, REMAININGARRAYLEN(cmdbuf, p), ".obj");
        }
    }

    // Build the link option string.

    if (LINKFLAGS && LINKFLAGS[0] != '\0') {
        strcat_s(linkFlags, " ");
        strcat_s(linkFlags, LINKFLAGS);
    }

    FillNoGPFFlags(nogpfFlags, fSuppressNoGPF);
    strcat_s(linkFlags, nogpfFlags);

    switch (TargetMachine) {
    case TM_X86:
    case TM_IA64:
    case TM_AMD64:
    case TM_AMD64SYS:
    case TM_AM33:
    case TM_ARM:
    case TM_ARM64:
    case TM_THUMB:
    case TM_M32R:
    case TM_MIPS:
    case TM_SH3:
    case TM_SH4:
    case TM_SH5M:
    case TM_SH5C:
    case TM_WVMX86:
        if (*linkFlags) {
            strcat_s(cmdbuf, " /link ");
            strcat_s(cmdbuf, linkFlags);
        }
        break;
    case TM_WVM:
        strcat_s(cmdbuf, " /c ");
        break;
    case TM_PPCWCE:
        if (*linkFlags) {
            strcat_s(cmdbuf, " ");
            strcat_s(cmdbuf, linkFlags);
        }
        break;
    }

    sprintf_s(buf, "%s (%s)", pTest->name, optReportBuf);
    ThreadInfo[ThreadId].SetCurrentTest(pDir->GetDirectoryName(), buf, pDir->IsBaseline());
    UpdateTitleStatus();

    // Remove exe if it's already there. We have to keep trying to delete it
    // until it's gone, or else the link will fail (if it is somehow still in
    // use).

    DeleteFileRetryMsg(fullexebuf);

    if (FTest)
    {
        Message("%s", cmdbuf);
        if (pTestVariant->testInfo.data[TIK_BASELINE]) {
            Message("   (baseline %s)", pTestVariant->testInfo.data[TIK_BASELINE]);
        }
        return 0;
    }

    // Do the compile.

    Message("Compiling:");
    Message("    %s", cmdbuf);

    rc = ExecuteCommand(pDir->GetDirectoryPath(), cmdbuf);

    // Some machines require separate linking of the
    // compiler and/or assembler output.

    if (rc == 0)
    {
        switch (TargetMachine)
        {
        case TM_WVM:
            // Build up the linker command string.

            strcpy_s(cmdbuf, LINKER);

            for (StringList * pFile = pTest->files;
                pFile != NULL;
                pFile = pFile->next)
            {
                strcat_s(cmdbuf, " ");
                strcat_s(cmdbuf, pFile->string);
                p = strrchr(cmdbuf, '.');
                strcpy_s(p + 1, REMAININGARRAYLEN(cmdbuf, p + 1), "obj");
            }

            if (linkFlags) {
                strcat_s(cmdbuf, " ");
                strcat_s(cmdbuf, linkFlags);
            }

            // Do the link.

            Message("Linking:");
            Message("    %s", cmdbuf);
            ExecuteCommand(pDir->GetDirectoryPath(), cmdbuf);
            break;

        default:
            break;
        }
    }

    // See if the compile succeeded by checking for the existence
    // of the executable.

    if ((rc != 0) || GetFileAttributes(fullexebuf) == INVALID_FILE_ATTRIBUTES) {
        LogOut("ERROR: Test failed to compile or link (%s):", optReportBuf);
        LogOut("    %s", cmdbuf);
        fFailed = TRUE;
        goto logFailure;
    }

    // Run the resulting exe.

    if (TargetVM) {
        strcpy_s(buf, TargetVM);
        strcat_s(buf, " ");
        strcat_s(buf, exebuf);

        // Copy the VM command to cmdbuf, so we get a useful error message
        // in the log file if test fails.

        strcpy_s(cmdbuf, buf);
    }
    else {
        strcpy_s(buf, exebuf);
    }

    // We need some temporary files.
    // Note: these are full pathnames, not relative pathnames. Also, note that
    // mytmpnam creates the file to be used. To avoid losing that file, and
    // risking another program using it, don't delete the file before use.
    // We currently delete the file before running the test, so we can see if
    // the test ever creates it. We should probably create the temp files in
    // the same directory as the test, since we guarantee that no other copies
    // of RL are running in the same directory.

    if (mytmpnam(pDir->GetDirectoryPath(), TMP_PREFIX, tmp_file1) == NULL ||
        mytmpnam(pDir->GetDirectoryPath(), TMP_PREFIX, tmp_file2) == NULL) {
            Fatal("Unable to create temporary files");
    }

    ThreadInfo[ThreadId].AddToTmpFileList(tmp_file1);
    ThreadInfo[ThreadId].AddToTmpFileList(tmp_file2);

    if (FVerbose)
        Message("INFO: tmp file 1 = %s, tmp file 2 = %s", tmp_file1, tmp_file2);

    Message("Running the test (%s)", buf);
    strcat_s(buf, " > ");
    strcat_s(buf, tmp_file1);

    // Make sure the output file isn't there.

    DeleteFileIfFound(tmp_file1);

    fFailed = FALSE;

    // Check for timeout.
    {
        int retval = ExecuteCommand(pDir->GetDirectoryPath(), buf, millisecTimeout, envFlags);
        if (retval == WAIT_TIMEOUT) {
            ASSERT(millisecTimeout != INFINITE);
            LogOut("ERROR: Test timed out after %ul seconds", millisecTimeout / 1000);
            fFailed = TRUE;
            goto logFailure;
        }
    }

    // Check the output.

    if (pTestVariant->testInfo.data[TIK_BASELINE]) {
        int spiff_ret;

        // Check to see if the exe ran at all.

        if (GetFileAttributes(tmp_file1) == INVALID_FILE_ATTRIBUTES) {
            LogOut("ERROR: Test failed to run. Couldn't find file '%s' (%s):", tmp_file1, optReportBuf);
            LogOut("    %s", cmdbuf);
            fFailed = TRUE;
        }
        else {
            sprintf_s(full, "%s\\%s", pDir->GetFullPathFromSourceOrDirectory(),
                pTestVariant->testInfo.data[TIK_BASELINE]);
            if (DoCompare(tmp_file1, full, pTestVariant->testInfo.hasData[TIK_EOL_NORMALIZATION])) {

                // Output differs, run spiff to see if it's just minor
                // floating point anomalies.

                DeleteFileIfFound(tmp_file2);
                sprintf_s(buf, "spiff -m -n -s \"command spiff\" %s %s > %s",
                    tmp_file1, full, tmp_file2);
                spiff_ret = ExecuteCommand(pDir->GetDirectoryPath(), buf);
                if (GetFileAttributes(tmp_file2) == INVALID_FILE_ATTRIBUTES) {
                    LogError("ERROR: spiff failed to run");
                    fFailed = TRUE;
                }
                else if (spiff_ret) {
                    LogOut("ERROR: Test failed to run correctly. spiff returned %d (%s):", spiff_ret, optReportBuf);
                    LogOut("    %s", cmdbuf);
                    fFailed = TRUE;
                }
            }
        }
    }
    else {
        if (!CheckForPass(tmp_file1, optReportBuf, cmdbuf)) {
            fFailed = TRUE;
        }
    }

logFailure:

    if (fFailed) {
        if (FCopyOnFail) {
            if (FVerbose)
                Message("INFO: Copying '%s' failure", optReportBuf);

            sprintf_s(failDir, "%s\\fail.%s",
                pDir->GetDirectoryPath(), optReportBuf);

            if ((GetFileAttributes(failDir) == INVALID_FILE_ATTRIBUTES) &&
                !CreateDirectory(failDir, NULL)) {
                    Message("ERROR: Couldn't create directory '%s'", failDir);
            }
            else
            {
                for (StringList * pFile = pTest->files;
                    pFile != NULL;
                    pFile = pFile->next)
                {
                    sprintf_s(copyName, "%s\\%s", failDir, pFile->string);
                    p = strrchr(copyName, '.') + 1;
                    strcpy_s(p, REMAININGARRAYLEN(copyName, p + 1), "obj");
                    sprintf_s(buf, "%s\\%s", pDir->GetDirectoryPath(),
                        pFile->string);
                    p = strrchr(buf, '.') + 1;
                    strcpy_s(p, REMAININGARRAYLEN(buf, p + 1), "obj");

                    if (!CopyFile(buf, copyName, FALSE)) {
                        Message("ERROR: Couldn't copy '%s' to '%s'",
                            buf, copyName);
                    }
                }

                sprintf_s(copyName, "%s\\%s", failDir, exebuf);
                if (!CopyFile(fullexebuf, copyName, FALSE)) {
                    Message("ERROR: Couldn't copy '%s' to '%s'",
                        fullexebuf, copyName);
                }
            }
        }
    }

    if (FRLFE) {
        RLFETestStatus(pDir);
    }

    if (FVerbose)
        Message("INFO: cleaning up test run");

    // Remove the exe.

    if (!FNoDelete) {
        DeleteFileRetryMsg(fullexebuf);
    }

    // Don't trash fullexebuf!

    strcpy_s(buf, fullexebuf);

    p = strrchr(buf, '.') + 1;

    // Remove the pdb(s) (if it exists).

    strcpy_s(p, REMAININGARRAYLEN(buf, p), "pdb");
    DeleteFileIfFound(buf);
    DeleteMultipleFiles(pDir, "*.pdb");

    // Remove the ilk (if it exists).

    strcpy_s(p, REMAININGARRAYLEN(buf, p), "ilk");
    DeleteFileIfFound(buf);

    // Remove the objs.

    if (!FNoDelete)
    {
        for (StringList * pFile = pTest->files;
            pFile != NULL;
            pFile = pFile->next)
        {
            sprintf_s(buf, "%s\\%s", pDir->GetDirectoryPath(), pFile->string);
            p = strrchr(buf, '.') + 1;

            if (fCleanAfter)
            {
                strcpy_s(p, REMAININGARRAYLEN(buf, p), "obj");
                DeleteFileRetryMsg(buf);
            }

            if (REGR_ASM) {
                strcpy_s(p, REMAININGARRAYLEN(buf, p), "asm");
                DeleteFileRetryMsg(buf);
            }
        }
    }

    elapsed_variation = (int)(time(NULL) - start_variation);
    if (Timing & TIME_VARIATION) {
        Message("RL: Variation elapsed time (%s, %s, %s): %02d:%02d",
            pDir->GetDirectoryName(), pTest->name, optReportBuf,
            elapsed_variation / 60, elapsed_variation % 60);
    }

    if (FSyncVariation) {
        if (FRLFE && fFailed)
            RLFEAddLog(pDir, RLFES_FAILED, pTest->name, optReportBuf, ThreadOut->GetText());

        if (fSyncVariationWhenFinished)
            FlushOutput();
    }

    ThreadInfo[ThreadId].DeleteTmpFileList();

    return fFailed ? -1 : 0;
}
Example #21
0
// Update
void Game_Interpreter::Update() {
	// 10000 based on: https://gist.github.com/4406621
	for (loop_count = 0; loop_count < 10000; ++loop_count) {
		/* If map is different than event startup time
		set event_id to 0 */
		if (Game_Map::GetMapId() != map_id) {
			event_id = 0;
		}

		/* If there's any active child interpreter, update it */
		if (child_interpreter) {

			child_interpreter->Update();

			if (!child_interpreter->IsRunning()) {
				child_interpreter.reset();
			}

			// If child interpreter still exists
			if (child_interpreter) {
				return;
			}
		}

		if (Game_Message::message_waiting || Game_Message::closing) {
			return;
		}

		// If waiting for a move to end
		if (move_route_waiting) {
			if (Main_Data::game_player->IsMoveRouteOverwritten()) {
				return;
			}

			Game_Event* g_event;
			for (size_t i = 0; i < Game_Map::GetEvents().size(); i++) {
				g_event = Game_Map::GetEvents().find(i)->second.get();

				if (g_event->IsMoveRouteOverwritten()) {
					return;
				}
			}
			move_route_waiting = false;
		}

		if (button_input_variable_id > 0) {
			InputButton();
			return;
		}

		if (wait_count > 0) {
			wait_count--;
			return;
		}

		if (Game_Temp::forcing_battler != NULL) {
			return;
		}

		if (Game_Temp::transition_processing) {
			return;
		}

		if (Game_Temp::battle_calling ||
			Game_Temp::shop_calling ||
//			Game_Temp::inn_calling ||
			Game_Temp::name_calling ||
			Game_Temp::menu_calling ||
			Game_Temp::save_calling ||
			Game_Temp::to_title ||
			Game_Temp::gameover) {

			return;
		}

		if (continuation) {
			bool result = (this->*continuation)(list[index]);
			if (result)
				continue;
			else
				return;
		}

		if (!Main_Data::game_player->IsTeleporting()) {
			if (Game_Map::GetNeedRefresh()) {
				Game_Map::Refresh();
			}
		}

		if (list.empty()) {
			return;
		}

		if (!ExecuteCommand()) {
			CloseMessageWindow();
			active = true;
			return;
		}

		active = false;

		// FIXME?
		// After calling SkipTo this index++ will skip execution of e.g. END.
		// This causes a different timing because loop_count reaches 10000
		// faster then Player does.
		// No idea if any game depends on this special case.
		index++;
	} // for

	// Executed Events Count exceeded (10000)
	active = true;
	Output::Debug("Event %d exceeded execution limit", event_id);
	CloseMessageWindow();
}
Example #22
0
int PushConsoleManager::OnCommand(const HashedString& command, const strutil::strvec& parameter_vector) {
	int result = Parent::OnCommand(command, parameter_vector);
	if (result < 0) {
		result = 0;

		CommandClient _command = (CommandClient)TranslateCommand(command);
		switch ((int)_command) {
			case kCommandSetAvatar: {
				if (parameter_vector.size() == 1) {
					((PushManager*)GetGameManager())->SelectAvatar(parameter_vector[0]);
				} else {
					log_.Warningf("usage: %s <avatar>", command.c_str());
					result = 1;
				}
			} break;
			case kCommandSetAvatarEnginePower: {
				if (parameter_vector.size() == 2) {
					log_debug("Setting avatar engine power.");
					int aspect = 0;
					strutil::StringToInt(parameter_vector[0], aspect);
					double power;
					strutil::StringToDouble(parameter_vector[1], power);
					if (!((PushManager*)GetGameManager())->SetAvatarEnginePower(aspect, (float)power)) {
						log_.Error("Could not set avatar engine power!");
						result = 1;
					}
				} else {
					log_.Warningf("usage: %s <aspect> <power>", command.c_str());
					result = 1;
				}
			} break;
#if defined(LEPRA_DEBUG) && defined(LEPRA_WINDOWS)
			case kCommandBuildData: {
				const cure::GameObjectId avatar_id = ((PushManager*)GetGameManager())->GetAvatarInstanceId();
				if (!avatar_id) {
					break;
				}
				const str avatar_type = GetGameManager()->GetContext()->GetObject(avatar_id)->GetClassId();
				((PushManager*)GetGameManager())->Logout();
				Thread::Sleep(0.5);
				GetResourceManager()->ForceFreeCache();
				const str current_dir = SystemManager::GetCurrentDirectory();
				::SetCurrentDirectoryA(astrutil::Encode(Path::GetParentDirectory(current_dir)).c_str());
				::system("c:/Program/Python31/python.exe -B Tools/build/rgo.py builddata");
				::SetCurrentDirectoryA(astrutil::Encode(current_dir).c_str());
				const str user_name = v_slowget(GetVariableScope(), kRtvarLoginUsername, EmptyString);
				const str server = v_slowget(GetVariableScope(), kRtvarNetworkServeraddress, EmptyString);
				wstr pw(L"CarPassword");
				const cure::LoginId login_id(wstrutil::Encode(user_name), cure::MangledPassword(pw));
				((PushManager*)GetGameManager())->RequestLogin(server, login_id);
				((PushManager*)GetGameManager())->ToggleConsole();
				ExecuteCommand("wait-login");
				((PushManager*)GetGameManager())->SelectAvatar(avatar_type);
			} break;
#endif // Debug & Windows
			default: {
				result = -1;
			} break;
		}
	}
	return (result);
}
Example #23
0
static bool ExecuteIcingaCommand(const std::string& arguments)
{
	return ExecuteCommand(GetIcingaInstallPath() + "\\sbin\\icinga2.exe", arguments);
}
Example #24
0
/*
** Parses and executes the given command.
**
*/
void CommandHandler::ExecuteCommand(const WCHAR* command, Skin* skin, bool multi)
{
	if (command[0] == L'!')	// Bang
	{
		++command;	// Skip "!"

		if (_wcsnicmp(L"Execute", command, 7) == 0)
		{
			command += 7;
			command = wcschr(command, L'[');
			if (!command) return;
		}
		else
		{
			if (_wcsnicmp(command, L"Rainmeter", 9) == 0)
			{
				// Skip "Rainmeter" for backwards compatibility
				command += 9;
			}

			std::wstring bang;
			std::vector<std::wstring> args;

			// Find the first space
			const WCHAR* pos = wcschr(command, L' ');
			if (pos)
			{
				bang.assign(command, 0, pos - command);
				args = ParseString(pos + 1, skin ? &skin->GetParser() : nullptr);
			}
			else
			{
				bang = command;
			}

			ExecuteBang(bang.c_str(), args, skin);
			return;
		}
	}

	if (multi && command[0] == L'[')	// Multi-bang
	{
		std::wstring bangs = command;
		std::wstring::size_type start = std::wstring::npos;
		int count = 0;
		for (size_t i = 0, isize = bangs.size(); i < isize; ++i)
		{
			if (bangs[i] == L'[')
			{
				if (count == 0)
				{
					start = i;
				}
				++count;
			}
			else if (bangs[i] == L']')
			{
				--count;

				if (count == 0 && start != std::wstring::npos)
				{
					// Change ] to nullptr
					bangs[i] = L'\0';

					// Skip whitespace
					start = bangs.find_first_not_of(L" \t\r\n", start + 1, 4);

					ExecuteCommand(bangs.c_str() + start, skin, false);
				}
			}
			else if (bangs[i] == L'"' && isize > (i + 2) && bangs[i + 1] == L'"' && bangs[i + 2] == L'"')
			{
				i += 3;

				std::wstring::size_type pos = bangs.find(L"\"\"\"", i);
				if (pos != std::wstring::npos)
				{
					i = pos + 2;	// Skip "", loop will skip last "
				}
			}
		}
	}
	else
	{
		// Check for built-ins
		if (_wcsnicmp(L"PLAY", command, 4) == 0)
		{
			if (command[4] == L' ' ||                      // PLAY
				_wcsnicmp(L"LOOP ", &command[4], 5) == 0)  // PLAYLOOP
			{
				command += 4;	// Skip PLAY

				DWORD flags = SND_FILENAME | SND_ASYNC;

				if (command[0] != L' ')
				{
					flags |= SND_LOOP | SND_NODEFAULT;
					command += 4;	// Skip LOOP
				}

				++command;	// Skip the space
				if (command[0] != L'\0')
				{
					std::wstring sound = command;

					// Strip the quotes
					std::wstring::size_type len = sound.length();
					if (len >= 2 && sound[0] == L'"' && sound[len - 1] == L'"')
					{
						len -= 2;
						sound.assign(sound, 1, len);
					}

					if (skin)
					{
						skin->GetParser().ReplaceMeasures(sound);
						skin->MakePathAbsolute(sound);
					}

					PlaySound(sound.c_str(), nullptr, flags);
				}
				return;
			}
			else if (_wcsnicmp(L"STOP", &command[4], 4) == 0)  // PLAYSTOP
			{
				PlaySound(nullptr, nullptr, SND_PURGE);
				return;
			}
		}

		// Run command
		std::wstring tmpSz = command;
		if (skin)
		{
			skin->GetParser().ReplaceMeasures(tmpSz);
		}
		RunCommand(tmpSz);
	}
}
Example #25
0
/**
 * Implements the state machine.
 */
void StateMachine(void)
{
    char *gameend;

    State = STATE_WAITING;

    CurrentPosition = InitialPosition();
    ComputerSide = Black;

    while(State != STATE_END) {

	if(AutoSave) {
	    SaveGame(CurrentPosition, AutoSaveFileName);
	}

        switch(State) {
            case STATE_WAITING:
                if(!XBoardMode) {
                    Print(0, "%s(%d): ", 
                        CurrentPosition->turn == White ? "White":"Black", 
                        (CurrentPosition->ply/2)+1);
                }

                if(!ReadLine(InputBuffer, 1023)) {
                    State = STATE_END;
                } else {
                    struct Command *command = ParseInput(InputBuffer);
                    if(command) {
                        ExecuteCommand(command);
                        if(command->move != M_NONE) {
                            if(!ForceMode) State = STATE_CALCULATING;
                        }
                    }
                }
                break;
            case STATE_CALCULATING:
                ComputerSide = CurrentPosition->turn;
                SearchRoot(CurrentPosition);
                if(EasyMode || ForceMode) {
                    State = STATE_WAITING;
                }
                else {
                    State = STATE_PONDERING;
                }
                break;
            case STATE_PONDERING:
                switch(PermanentBrain(CurrentPosition)) {
                    case PB_NO_PB_MOVE:
                        State = STATE_WAITING;
                        break;
                    case PB_NO_PB_HIT:
                        State = ForceMode ? STATE_WAITING : STATE_CALCULATING;
                        break;
                    case PB_HIT:
                        if(EasyMode) {
                            State = STATE_WAITING;
                        }
                        break;
                }
                break;
            case STATE_ANALYZING:
		AnalysisMode(CurrentPosition);
                break;
        }

        /*
         * Check for game termination
         */

        gameend = GameEnd(CurrentPosition);
        if(gameend != NULL) {
            Print(0, "%s\n", gameend);
            if(State == STATE_ANALYZING) {
                State = STATE_WAITING;
            }
        }
    }

    FreePosition(CurrentPosition);
}
Example #26
0
wxString ProcUtils::GetProcessNameByPid(long pid)
{
#ifdef __WXMSW__
	//go over the process modules and get the full path of
	//the executeable
	HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
	MODULEENTRY32 me32;

	//  Take a snapshot of all modules in the specified process.
	hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, (DWORD)pid );
	if ( hModuleSnap == INVALID_HANDLE_VALUE ) {
		return wxEmptyString;
	}

	//  Set the size of the structure before using it.
	me32.dwSize = sizeof( MODULEENTRY32 );

	//  Retrieve information about the first module,
	//  and exit if unsuccessful
	if (!Module32First( hModuleSnap, &me32 )) {
		CloseHandle( hModuleSnap );    // Must clean up the
		// snapshot object!
		return wxEmptyString;
	}

	//get the name of the process (it is located in the first entry)
	CloseHandle( hModuleSnap );
	return me32.szExePath;

#elif defined(__FreeBSD__)
	kvm_t *kvd;
	struct kinfo_proc *ki;
	int nof_procs;
	wxString cmd;

	if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL)))
	    return wxEmptyString;

	if (!(ki = kvm_getprocs(kvd, KERN_PROC_PID, pid, &nof_procs))) {
	    kvm_close(kvd);
	    return wxEmptyString;
	}

	cmd = wxString(ki->ki_ocomm, wxConvUTF8);
	kvm_close(kvd);

	return (cmd);
#else
	wxArrayString output;
	ExecuteCommand(wxT("ps -A -o pid,command --no-heading"), output);
	//parse the output and search for our process ID
	for (size_t i=0; i< output.GetCount(); i++) {
		wxString line = output.Item(i);
		//remove whitespaces
		line = line.Trim();
		line = line.Trim(false);
		//get the process ID
		wxString spid = line.BeforeFirst(wxT(' '));
		long cpid(0);
		spid.ToLong( &cpid );
		if (cpid == pid) {
			//we got a match, extract the command, it is in the second column
			wxString command = line.AfterFirst(wxT(' '));
			return command;
		}
	}
	return wxEmptyString;	//Not implemented yet
#endif
}
Example #27
0
void ConnectionPanel::OnRawCommand(wxCommandEvent &evt)
{
    ExecuteCommand(GetCommandText());
}
Example #28
0
void ProcUtils::GetProcessList(std::vector<ProcessEntry> &proclist)
{
#ifdef __WXMSW__
	OSVERSIONINFO osver ;

	// Check to see if were running under Windows95 or
	// Windows NT.
	osver.dwOSVersionInfoSize = sizeof( osver ) ;
	if ( !GetVersionEx( &osver ) ) {
		return;
	}

	if ( osver.dwPlatformId != VER_PLATFORM_WIN32_NT ) {
		return;
	}

	//get child processes of this node
	HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (!hProcessSnap) {
		return;
	}

	//Fill in the size of the structure before using it.
	PROCESSENTRY32 pe;
	memset(&pe, 0, sizeof(pe));
	pe.dwSize = sizeof(PROCESSENTRY32);

	// Walk the snapshot of the processes, and for each process,
	// kill it if its parent is pid.
	if (!Process32First(hProcessSnap, &pe)) {
		// Can't get first process.
		CloseHandle (hProcessSnap);
		return;
	}

	do {
		ProcessEntry entry;
		entry.name = pe.szExeFile;
		entry.pid = (long)pe.th32ProcessID;
		proclist.push_back(entry);
	} while (Process32Next (hProcessSnap, &pe));
	CloseHandle (hProcessSnap);

#elif defined(__FreeBSD__)
	kvm_t *kvd;
	struct kinfo_proc *ki;
	int nof_procs, i;

	if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL)))
	    return;

	if (!(ki = kvm_getprocs(kvd, KERN_PROC_PROC, 0, &nof_procs))) {
	    kvm_close(kvd);
	    return;
	}

	for (i=0; i<nof_procs; i++) {
	    ProcessEntry entry;
	    entry.pid = ki[i].ki_pid;
	    entry.name = wxString(ki[i].ki_ocomm, wxConvUTF8);
	    proclist.push_back(entry);
	}
	kvm_close(kvd);

#else
	//GTK and other
	wxArrayString output;
#if defined (__WXGTK__)
	ExecuteCommand(wxT("ps -A -o pid,command  --no-heading"), output);
#elif defined (__WXMAC__)
	// Mac does not like the --no-heading...
	ExecuteCommand(wxT("ps -A -o pid,command "), output);
#endif
	for (size_t i=0; i< output.GetCount(); i++) {
		wxString line = output.Item(i);
		//remove whitespaces
		line = line.Trim().Trim(false);

		//get the process ID
		ProcessEntry entry;
		wxString spid = line.BeforeFirst(wxT(' '));
		spid.ToLong( &entry.pid );
		entry.name = line.AfterFirst(wxT(' '));

		if (entry.pid == 0 && i > 0) {
			//probably this line belongs to the provious one
			ProcessEntry e = proclist.back();
			proclist.pop_back();
			e.name << entry.name;
			proclist.push_back(e);
		} else {
			proclist.push_back( entry );
		}
	}
#endif
}
Example #29
0
int _tmain(int argc, _TCHAR* argv[])
{
	UINT loop_times = 0;
	BOOL loop_endless = FALSE;
	DWORD ms_between_loop = 0;
	BOOL enable_logs = FALSE;
	TCHAR command[CMD_BUF_SIZE] = {0}; 

	if ( ParameterCheck(argc, argv, loop_times, ms_between_loop, enable_logs, command, CMD_BUF_SIZE) )
	{
		loop_endless = ( 0 == loop_times ); 
	}
	else
	{
		PrintUsage(argv[0]);
		return 1;
	}

	HANDLE hLogFile = INVALID_HANDLE_VALUE;

	if( TRUE == enable_logs)
	{
		SYSTEMTIME st;
		GetSystemTime(&st);

		TCHAR logFileName[MAX_PATH] = {0};

		_stprintf_s(logFileName, MAX_PATH - 1, _T("loop_trace_%04d%02d%02d-%d-%02d%02d%02d-%03d.log"),
			st.wYear,st.wMonth,st.wDay,st.wDayOfWeek,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);

		dbgtprintf(logFileName); 
		dbgtprintf(L"\n"); 


		hLogFile = CreateFile(logFileName,
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ,
			NULL,
			CREATE_ALWAYS,
			FILE_ATTRIBUTE_NORMAL,
			NULL);

		if(INVALID_HANDLE_VALUE == hLogFile)
		{
			_tprintf(_T("Failed to Create Log File, st = 0x%x\n"), GetLastError());
			return 1;
		}
		else
		{
			dbgtprintf(TEXT("OK to CreateFile.\n")); 
		}
	}

	while( loop_endless || loop_times > 0 )
	{
		if(!loop_endless)
		{
			--loop_times;
		}

		CHAR printedCommand[CMD_BUF_SIZE] = {0}; 
		
		sprintf_s(printedCommand, CMD_BUF_SIZE - 1, "\n-> %S\n\n",
			command + _tcsnlen(BASE_CMD, CMD_BUF_SIZE) + 1);

		printf(printedCommand);

		if (INVALID_HANDLE_VALUE != hLogFile)
		{
			DWORD dwToWrite = sizeof(CHAR) * strnlen(printedCommand, CMD_BUF_SIZE);
			DWORD dwWritten = 0;
			BOOL bWrite = WriteFile( hLogFile, 
						printedCommand, 
						dwToWrite, 
						&dwWritten, 
						NULL);
			
			if(!bWrite)
			{
				_tprintf(_T("Write to log file error, st=0x%x\n"), GetLastError());
				assert(false);
			}

			assert(dwToWrite == dwWritten);
		}

		ExecuteCommand(command, CMD_BUF_SIZE, enable_logs, hLogFile);

		
		Sleep(ms_between_loop);
	}

	if (INVALID_HANDLE_VALUE != hLogFile)
	{
		CloseHandle(hLogFile);
	}

	return 0;
}
Example #30
0
BOOL CMobileServer::OnReceiveSession(WORKSESSION *pSession, LPSTR pszBuffer, int nLength)
{
    char	*p, *p1, *pszHeader;
    int		i, len;

    time(&m_tmLastReceived);
//	printf("MobileServer: %d Bytes recv.\r\n", nLength);
//	DUMPSTRING(pszBuffer, nLength);

#ifdef __TEST_ONLY__
//  int     nError;
//	IF4Invoke	*pInvoke;
//  CIF4Invoke  invoke("192.168.0.23", 8000, 60);
//
//	pInvoke = invoke.GetHandle();
//	pInvoke->bAsync = TRUE;
//
//  invoke.AddParam("4.2.1", 5);
//  invoke.AddParam("4.2.2", 1);
//  invoke.AddParam("1.9", 0);
//
//  nError = invoke.Command("104.12", IF4_CMDATTR_REQUEST | IF4_CMDATTR_MCUIPC | IF4_CMDATTR_RESPONSE);
//  if (nError != IF4ERR_NOERROR)
//      printf("ERROR: %s\r\n", IF4API_GetErrorMessage(nError));
#endif

    if (m_nState != STATE_DATA)
    {
        m_Chunk.Add(pszBuffer, nLength);
        m_Chunk.Close();
        p   = m_Chunk.GetBuffer();
        len = m_Chunk.GetSize();

        pszHeader = NULL;
        for(i=0; i<len; i++)
        {
            if (strncmp(p+i, "NURI/", 5) == 0)
            {
                pszHeader = p+i;
                break;
            }
        }

        if (len >= 512)
        {
            m_Chunk.Flush();
            return TRUE;
        }

        if (pszHeader == NULL)
            return TRUE;

        p1 = strstr(pszHeader, "\n\n");
        if (p1 == NULL)
            p1 = strstr(pszHeader, "\r\r");
        if (p1 == NULL)
            p1 = strstr(pszHeader, "\r\n\r\n");
        if (p1 == NULL)
            return TRUE;

        *p1 = '\0';
        if (GetHeader(&m_theHeader, pszHeader, strlen(pszHeader)))
        {
            m_bLiveSession = TRUE;
            switch(m_theHeader.nMethod) {
            case MOBILE_METHOD_TELNET :
                SendResult(MTPERR_TELNET_ACCEPT);
                usleep(1000000);
                m_theClient.NewConnection(atoi(m_theHeader.szURL));
                m_nState = STATE_DATA;
                break;

            case MOBILE_METHOD_NACS :
                SendResult(MTPERR_NACS_ACCEPT);
                usleep(1000000);
                m_theClient.NewConnection(atoi(m_theHeader.szURL));
                m_nState = STATE_DATA;
                break;

            case MOBILE_METHOD_COMMAND :
                ExecuteCommand(m_theHeader.szURL);
                break;

            case MOBILE_METHOD_GET :
                SendResult(MTPERR_GET_ACCEPT);
                m_nState = STATE_DATA;
                break;

            case MOBILE_METHOD_PUT :
                SendResult(MTPERR_PUT_ACCEPT);
                m_theHeader.fp = fopen("/tmp/upload.tmp", "wb");
                m_nState = STATE_DATA;
                break;

            case MOBILE_METHOD_LIST :
                SendResult(MTPERR_LIST_ACCEPT);
                m_nState = STATE_DATA;
                break;
            }
        }
        else
        {
            // Return to error message
            SendResult(MTPERR_INVALID_REQUEST);
        }

        m_Chunk.Flush();
        return TRUE;
    }

    switch(m_theHeader.nMethod) {
    case MOBILE_METHOD_TELNET :
    case MOBILE_METHOD_NACS :
        m_theClient.SendToHost(pszBuffer, nLength);
        break;

    case MOBILE_METHOD_GET :
        break;

    case MOBILE_METHOD_PUT :
        OnPut(pSession, pszBuffer, nLength);
        break;

    case MOBILE_METHOD_LIST :
        break;
    }
    return TRUE;
}