void JobGroup_Z::Shut()
{
	SCHEDULER_MESSAGE_Z("[JobGroup_Z] SHUT JobGroup_Z %x",this);

	// Don't Remove ! Have to test and reset Wait Sate.
	WaitForCompletion();
}
void JobGroup_Z::Run( U32 count, JobProc_Z task, void* userData, Bool bWaitForCompletion )
{
	SCHEDULER_MESSAGE_Z("[JobGroup_Z] Run(%d,0x%x,0x%x)", count, task, userData);
	PROFILER_SCOPED_CPU_MARKER_L1(COLOR_GREEN,"Run");

	if(bWaitForCompletion)
		WaitForCompletion();

	// Add Jobs.
	m_CompletionEvent->Reset();
	Thread_Z::SafeAdd(&m_PendingJobCount,count);
	TaskScheduler_Z::TheUnicJobScheduler.Submit(count,*this,task,userData);

	if(m_bAsynchronous)
		WaitForCompletion();
}
Esempio n. 3
0
std::wstring ChildProcess::GetOutput()
{
	if (!hProcess_)
		return L"";
	WaitForCompletion(false);
	return RemoveOutputText();
}
Esempio n. 4
0
////////////////////////////////////////////////////////////////////////////
// Function: Load an XML document from a given stream object
////////////////////////////////////////////////////////////////////////////
HRESULT CXMLDocument::LoadStream(CString strFileName)
{
	HRESULT hr = S_OK;

	// Create an IStream object for reading the specified URL.
	char szURL[MAX_PATH];
	if (!strncmp(strFileName, "http:", 5))
		strcpy(szURL, strFileName);
	else
		::GetFullPathNameA(strFileName, MAX_PATH, szURL, NULL);

	IStreamPtr pStream = NULL;
	hr = ::URLOpenBlockingStreamA(0, szURL, &pStream, 0, 0);
	hr = CheckHR(hr, "in load stream: URLOpenBlockingStreamA");

	IPersistStreamInitPtr pPSI = m_pDoc;
	if (pPSI == NULL)
		return E_FAIL;

	hr = pPSI->Load(pStream);
	hr = CheckHR(hr, "in load stream");

	// Since we don't know whether this was a URLStream or not.
	WaitForCompletion();

	hr = CheckLoad();

	return hr;
}
void CErrorReportExporter::ExportReport(LPCTSTR szOutFileName)
{
	SetExportFlag(TRUE, szOutFileName);

	// Wait for completion of crash info collector.
	WaitForCompletion();
	DoWorkAssync(COMPRESS_REPORT|RESTART_APP);    
}
Esempio n. 6
0
DWORD ChildProcess::GetExitCode()
{
	if (!hProcess_)
		return 0;
	// Don't allow getting the exit code unless the process has exited.
	WaitForCompletion(true);
	DWORD result;
	(void)GetExitCodeProcess(hProcess_, &result);
	return result;
}
// This method cleans up temporary files
BOOL CErrorReportExporter::Finalize()
{  
	// Wait until worker thread exits.
	WaitForCompletion();

	// If needed, restart the application
	DoWork(RESTART_APP); 

	// Done OK
	return TRUE;
}
// Test If Task is finished.
Bool JobGroup_Z::PollForCompletion(Bool ReleaseIfCompleted)
{
	SCHEDULER_MESSAGE_Z("[JobGroup_Z] PollForCompletion()");

	if( m_PendingJobCount != 0 )
		return FALSE;

	if (ReleaseIfCompleted)
		WaitForCompletion();

	return TRUE;
}
Esempio n. 9
0
////////////////////////////////////////////////////////////////////////////
// Function: Load an XML Document from the specified file or URL synchronously.
////////////////////////////////////////////////////////////////////////////
HRESULT CXMLDocument::Load(CString strURLFileName, bool bAsync)
{
	// set asynchronous loading flag
	HRESULT hr = m_pDoc->put_async(bAsync ? VARIANT_TRUE : VARIANT_FALSE);
	hr = CheckHR(hr, "in load: put_async");

	// Load xml document from the given URL or file path
	VARIANT_BOOL vbIsSuccessful = false;
	hr = m_pDoc->load(CComVariant(strURLFileName), &vbIsSuccessful);
	hr = CheckHR(hr, "in load");

	// Now wait for download to complete!
	if (bAsync)
		WaitForCompletion();

	hr = CheckLoad();
					
	return hr;
}
/* void Abort (); */
NS_IMETHODIMP CDatabaseQuery::Abort(PRBool *_retval)
{
  NS_ENSURE_ARG_POINTER(_retval);
  *_retval = PR_FALSE;

  if(m_IsExecuting)
  {
    PRInt32 nWaitResult = 0;

    {
      sbSimpleAutoLock lock(m_pLock);
      m_IsAborting = PR_TRUE;
    }

    WaitForCompletion(&nWaitResult);

    *_retval = PR_TRUE;
  }

  return NS_OK;
}
Esempio n. 11
0
bool LibUSB::Transfer::isComplete()
{

	if (m_AsynchronousTransferPending)
	{
		
		// Check the status of the thread.
		if (*m_TransferThreadRunning)
		{
			// Nothing to see here, move along.
			return false;
		}
		else
		{
			return WaitForCompletion();
		}

	}

	

	return m_pTransferImpl->isComplete();
	
}
Esempio n. 12
0
static HRESULT DoRevertVMToSnapshot()
{
	BazisLib::String rawMachineID = VBoxCmdLineToMachineID(GetCommandLineW());
	if (rawMachineID.empty())
		return E_FAIL;

	CComBSTR machineID = rawMachineID.c_str();

	CComPtr<IVirtualBox> pVirtualBox;
	HRESULT hR = pVirtualBox.CoCreateInstance(CLSID_VirtualBox, NULL, CLSCTX_LOCAL_SERVER);
	if (!SUCCEEDED(hR))
		return hR;

	CComPtr<IMachine> pMachine;
	hR = pVirtualBox->FindMachine(machineID, &pMachine);
	if (!SUCCEEDED(hR))
		return hR;

	CComPtr<ISession> pSession;
	hR = pSession.CoCreateInstance(CLSID_Session, NULL, CLSCTX_INPROC_SERVER);
	if (!SUCCEEDED(hR))
		return hR;

	hR = pMachine->LockMachine(pSession, LockType_Shared);
	if (!SUCCEEDED(hR))
	{
		if (hR == E_FAIL)
			MessageBox(HWND_DESKTOP, L"Cannot connect to VirtualBox. Ensure that both VirtualBox and Visual Studio are running from the same user account, either both elevated (UAC), or both not.", L"Error", MB_ICONERROR);
		return hR;
	}

	CComPtr<IConsole> pConsole;
	hR = pSession->get_Console(&pConsole);
	if (!SUCCEEDED(hR))
		return hR;

	CComPtr<ISnapshot> pSnapshot;
	hR = pMachine->get_CurrentSnapshot(&pSnapshot);
	if (!SUCCEEDED(hR))
	{
		pSession->UnlockMachine();
		return hR;
	}

	CComBSTR snapshotID;
	hR = pSnapshot->get_Id(&snapshotID);
	if (!SUCCEEDED(hR))
		return hR;

	CComPtr<IProgress> pProgress;
	hR = pConsole->PowerDown(&pProgress);
	if (!SUCCEEDED(hR))
		return hR;

	hR = WaitForCompletion(pProgress);
	if (!SUCCEEDED(hR))
		return hR;

	pProgress = NULL;
	pSession->UnlockMachine();

	BazisLib::DateTime dtStart = BazisLib::DateTime::Now();
	
	for (;;)
	{
		hR = pMachine->LockMachine(pSession, LockType_Shared);
		if (!SUCCEEDED(hR) && (dtStart.MillisecondsElapsed() >= 10000))
			return hR;
		if (SUCCEEDED(hR))
			break;
		Sleep(100);
	}

	pConsole = NULL;
	hR = pSession->get_Console(&pConsole);
	if (!SUCCEEDED(hR))
		return hR;

	hR = pConsole->RestoreSnapshot(pSnapshot, &pProgress);
	if (!SUCCEEDED(hR))
		return hR;

	hR = WaitForCompletion(pProgress);
	if (!SUCCEEDED(hR))
		return hR;
	
	pSession->UnlockMachine();

	CComBSTR sessionType = L"gui";
	pProgress = NULL;

	hR = pMachine->LaunchVMProcess(pSession, sessionType, NULL, &pProgress);
	if (!SUCCEEDED(hR))
		return hR;

	hR = WaitForCompletion(pProgress);
	if (!SUCCEEDED(hR))
		return hR;

	pSession->UnlockMachine();


	pProgress = NULL;

	return S_OK;
}
int main(int argc, char** argv)
{
    PRUintn index;
    PRBool boolean;
    CSClient_t *client;
    PRStatus rv, joinStatus;
    CSServer_t *server = NULL;

    PRUintn backlog = DEFAULT_BACKLOG;
    PRUintn clients = DEFAULT_CLIENTS;
    const char *serverName = DEFAULT_SERVER;
    PRBool serverIsLocal = PR_TRUE;
    PRUintn accepting = ALLOWED_IN_ACCEPT;
    PRUintn workersMin = DEFAULT_WORKERS_MIN;
    PRUintn workersMax = DEFAULT_WORKERS_MAX;
    PRIntn execution = DEFAULT_EXECUTION_TIME;
    PRIntn low = DEFAULT_LOW, high = DEFAULT_HIGH;

    /*
     * -G           use global threads
     * -a <n>       threads allowed in accept
     * -b <n>       backlock for listen
     * -c <threads> number of clients to create
     * -f <low>     low water mark for caching FDs
     * -F <high>    high water mark for caching FDs
     * -w <threads> minimal number of server threads
     * -W <threads> maximum number of server threads
     * -e <seconds> duration of the test in seconds
     * -s <string>  dsn name of server (implies no server here)
     * -v           verbosity
     */

    PLOptStatus os;
    PLOptState *opt = PL_CreateOptState(argc, argv, "GX6b:a:c:f:F:w:W:e:s:vdhp");

    debug_out = PR_GetSpecialFD(PR_StandardError);

    while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
        if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'G':  /* use global threads */
            thread_scope = PR_GLOBAL_THREAD;
            break;
        case 'X':  /* use XTP as transport */
            protocol = 36;
            break;
        case '6':  /* Use IPv6 */
            domain = PR_AF_INET6;
            break;
        case 'a':  /* the value for accepting */
            accepting = atoi(opt->value);
            break;
        case 'b':  /* the value for backlock */
            backlog = atoi(opt->value);
            break;
        case 'c':  /* number of client threads */
            clients = atoi(opt->value);
            break;
        case 'f':  /* low water fd cache */
            low = atoi(opt->value);
            break;
        case 'F':  /* low water fd cache */
            high = atoi(opt->value);
            break;
        case 'w':  /* minimum server worker threads */
            workersMin = atoi(opt->value);
            break;
        case 'W':  /* maximum server worker threads */
            workersMax = atoi(opt->value);
            break;
        case 'e':  /* program execution time in seconds */
            execution = atoi(opt->value);
            break;
        case 's':  /* server's address */
            serverName = opt->value;
            break;
        case 'v':  /* verbosity */
            verbosity = IncrementVerbosity();
            break;
        case 'd':  /* debug mode */
            debug_mode = PR_TRUE;
            break;
        case 'p':  /* pthread mode */
            pthread_stats = PR_TRUE;
            break;
        case 'h':
        default:
            Help();
            return 2;
        }
    }
    PL_DestroyOptState(opt);

    if (0 != PL_strcmp(serverName, DEFAULT_SERVER)) serverIsLocal = PR_FALSE;
    if (0 == execution) execution = DEFAULT_EXECUTION_TIME;
    if (0 == workersMax) workersMax = DEFAULT_WORKERS_MAX;
    if (0 == workersMin) workersMin = DEFAULT_WORKERS_MIN;
    if (0 == accepting) accepting = ALLOWED_IN_ACCEPT;
    if (0 == backlog) backlog = DEFAULT_BACKLOG;

    if (workersMin > accepting) accepting = workersMin;

    PR_STDIO_INIT();
    TimeOfDayMessage("Client/Server started at", PR_GetCurrentThread());

    cltsrv_log_file = PR_NewLogModule("cltsrv_log");
    MY_ASSERT(NULL != cltsrv_log_file);
    boolean = PR_SetLogFile("cltsrv.log");
    MY_ASSERT(boolean);

    rv = PR_SetFDCacheSize(low, high);
    PR_ASSERT(PR_SUCCESS == rv);

    if (serverIsLocal)
    {
        /* Establish the server */
        TEST_LOG(
            cltsrv_log_file, TEST_LOG_INFO,
            ("main(0x%p): starting server\n", PR_GetCurrentThread()));

        server = PR_NEWZAP(CSServer_t);
        PR_INIT_CLIST(&server->list);
        server->state = cs_init;
        server->ml = PR_NewLock();
        server->backlog = backlog;
        server->port = DEFAULT_PORT;
        server->workers.minimum = workersMin;
        server->workers.maximum = workersMax;
        server->workers.accepting = accepting;
        server->stateChange = PR_NewCondVar(server->ml);
        server->pool.exiting = PR_NewCondVar(server->ml);
        server->pool.acceptComplete = PR_NewCondVar(server->ml);

        TEST_LOG(
            cltsrv_log_file, TEST_LOG_NOTICE,
            ("main(0x%p): creating server thread\n", PR_GetCurrentThread()));

        server->thread = PR_CreateThread(
            PR_USER_THREAD, Server, server, PR_PRIORITY_HIGH,
            thread_scope, PR_JOINABLE_THREAD, 0);
        TEST_ASSERT(NULL != server->thread);

        TEST_LOG(
            cltsrv_log_file, TEST_LOG_VERBOSE,
            ("main(0x%p): waiting for server init\n", PR_GetCurrentThread()));

        PR_Lock(server->ml);
        while (server->state == cs_init)
            PR_WaitCondVar(server->stateChange, PR_INTERVAL_NO_TIMEOUT);
        PR_Unlock(server->ml);

        TEST_LOG(
            cltsrv_log_file, TEST_LOG_VERBOSE,
            ("main(0x%p): server init complete (port #%d)\n",
            PR_GetCurrentThread(), server->port));
    }

    if (clients != 0)
    {
        /* Create all of the clients */
        PRHostEnt host;
        char buffer[BUFFER_SIZE];
        client = (CSClient_t*)PR_CALLOC(clients * sizeof(CSClient_t));

        TEST_LOG(
            cltsrv_log_file, TEST_LOG_VERBOSE,
            ("main(0x%p): creating %d client threads\n",
            PR_GetCurrentThread(), clients));
        
        if (!serverIsLocal)
        {
            rv = PR_GetHostByName(serverName, buffer, BUFFER_SIZE, &host);
            if (PR_SUCCESS != rv)
            {
                PL_FPrintError(PR_STDERR, "PR_GetHostByName");
                return 2;
            }
        }

        for (index = 0; index < clients; ++index)
        {
            client[index].state = cs_init;
            client[index].ml = PR_NewLock();
            if (serverIsLocal)
            {
				if (PR_AF_INET6 != domain)
                	(void)PR_InitializeNetAddr(
                    	PR_IpAddrLoopback, DEFAULT_PORT,
                    	&client[index].serverAddress);
				else
					rv = PR_SetNetAddr(PR_IpAddrLoopback, PR_AF_INET6,
							DEFAULT_PORT, &client[index].serverAddress);
            }
            else
            {
                (void)PR_EnumerateHostEnt(
                    0, &host, DEFAULT_PORT, &client[index].serverAddress);
            }
            client[index].stateChange = PR_NewCondVar(client[index].ml);
            TEST_LOG(
                cltsrv_log_file, TEST_LOG_INFO,
                ("main(0x%p): creating client threads\n", PR_GetCurrentThread()));
            client[index].thread = PR_CreateThread(
                PR_USER_THREAD, Client, &client[index], PR_PRIORITY_NORMAL,
                thread_scope, PR_JOINABLE_THREAD, 0);
            TEST_ASSERT(NULL != client[index].thread);
            PR_Lock(client[index].ml);
            while (cs_init == client[index].state)
                PR_WaitCondVar(client[index].stateChange, PR_INTERVAL_NO_TIMEOUT);
            PR_Unlock(client[index].ml);
        }
    }

    /* Then just let them go at it for a bit */
    TEST_LOG(
        cltsrv_log_file, TEST_LOG_ALWAYS,
        ("main(0x%p): waiting for execution interval (%d seconds)\n",
        PR_GetCurrentThread(), execution));

    WaitForCompletion(execution);

    TimeOfDayMessage("Shutting down", PR_GetCurrentThread());

    if (clients != 0)
    {
        for (index = 0; index < clients; ++index)
        {
            TEST_LOG(cltsrv_log_file, TEST_LOG_STATUS, 
                ("main(0x%p): notifying client(0x%p) to stop\n",
                PR_GetCurrentThread(), client[index].thread));

            PR_Lock(client[index].ml);
            if (cs_run == client[index].state)
            {
                client[index].state = cs_stop;
                PR_Interrupt(client[index].thread);
                while (cs_stop == client[index].state)
                    PR_WaitCondVar(
                        client[index].stateChange, PR_INTERVAL_NO_TIMEOUT);
            }
            PR_Unlock(client[index].ml);

            TEST_LOG(cltsrv_log_file, TEST_LOG_VERBOSE, 
                ("main(0x%p): joining client(0x%p)\n",
                PR_GetCurrentThread(), client[index].thread));

		    joinStatus = PR_JoinThread(client[index].thread);
		    TEST_ASSERT(PR_SUCCESS == joinStatus);
            PR_DestroyCondVar(client[index].stateChange);
            PR_DestroyLock(client[index].ml);
        }
        PR_DELETE(client);
    }

    if (NULL != server)
    {
        /* All clients joined - retrieve the server */
        TEST_LOG(
            cltsrv_log_file, TEST_LOG_NOTICE, 
            ("main(0x%p): notifying server(0x%p) to stop\n",
            PR_GetCurrentThread(), server->thread));

        PR_Lock(server->ml);
        server->state = cs_stop;
        PR_Interrupt(server->thread);
        while (cs_exit != server->state)
            PR_WaitCondVar(server->stateChange, PR_INTERVAL_NO_TIMEOUT);
        PR_Unlock(server->ml);

        TEST_LOG(
            cltsrv_log_file, TEST_LOG_NOTICE, 
            ("main(0x%p): joining server(0x%p)\n",
            PR_GetCurrentThread(), server->thread));
        joinStatus = PR_JoinThread(server->thread);
        TEST_ASSERT(PR_SUCCESS == joinStatus);

        PR_DestroyCondVar(server->stateChange);
        PR_DestroyCondVar(server->pool.exiting);
        PR_DestroyCondVar(server->pool.acceptComplete);
        PR_DestroyLock(server->ml);
        PR_DELETE(server);
    }

    TEST_LOG(
        cltsrv_log_file, TEST_LOG_ALWAYS, 
        ("main(0x%p): test complete\n", PR_GetCurrentThread()));

    PT_FPrintStats(debug_out, "\nPThread Statistics\n");

    TimeOfDayMessage("Test exiting at", PR_GetCurrentThread());
    PR_Cleanup();
    return 0;
}  /* main */
Esempio n. 14
0
// thread main routine
void CUsbIoReader::ThreadRoutine()
{
  CUsbIoBuf *Buf;
  DWORD ErrorCounter=0;
  DWORD Status;

  if ( BufPool.CurrentCount() == 0 ) {
    // no BufPool is allocated !
    return;
  }

  // initializiation
  FirstPending=NULL;
  LastPending=NULL;
  
  // thread main loop
  for (;;) {
    
    if ( TerminateFlag ) {
      // thread should be terminated
      break;
    }

    if ( ErrorCounter > MaxErrorCount ) {
      // max number of io errors reached
      break;
    } 
    
    // submit all available buffers to the driver
    while ( (Buf=BufPool.Get()) != NULL ) {
      // get transfer count
      ProcessBuffer(Buf);
      if ( !Buf->OperationFinished && Buf->NumberOfBytesToTransfer>0 ) {
        // issue read request
        Read(Buf);
        // chain buffer to pending list
        if ( FirstPending == NULL ) {
          FirstPending = Buf;
        } else {
          LastPending->Next = Buf;
        }
        LastPending = Buf;
        Buf->Next = NULL;
      } else {
        // put the buffer back to pool
        BufPool.Put(Buf);
        break;
      }
    }
    
    if ( FirstPending==NULL ) {
      // no pending request, break loop
      break;
    }

    // wait for completion on the first pending buffer
    Buf = FirstPending;
    Status = WaitForCompletion(Buf); // INFINITE
    if ( Status != USBIO_ERR_SUCCESS ) {
      if (Status != USBIO_ERR_POWER_DOWN) {
        ErrorCounter++;
      }
      BufErrorHandler(Buf);
    } else {
      ErrorCounter=0;
    }
    
    // remove buffer from pending list
    FirstPending = Buf->Next;
    // process data
    ProcessData(Buf);
    // put the buffer back to pool
    BufPool.Put(Buf);

  } //for

  // wait for all pending buffers to complete
  while ( (Buf=FirstPending) != NULL ) {
    WaitForCompletion(Buf); // INFINITE
    FirstPending = Buf->Next;
    BufPool.Put(Buf);
  }
}
Esempio n. 15
0
i32 RunApplicationMainLoop() {
	SDL_Event event;
	bool active = true;
	while (active) {
		while (SDL_PollEvent(&event)) {

			switch (event.type) {

			case SDL_QUIT:
				active = false;
				break;
			case SDL_KEYDOWN:
				if (event.key.keysym.sym == SDLK_ESCAPE) {
					active = false;
					break;
				}
				else {
					GApplicationKeyDownFunction(event.key.keysym.sym);
				}
				break;
			case SDL_TEXTINPUT:
				{
					GApplicationTextInputFunction((wchar_t*)event.text.text);
				}
				break;
			case SDL_MOUSEWHEEL:
				{
					GApplicationMouseWheelFunction(event.wheel.y);
				}
				break;
			case SDL_DROPFILE:
				{
					const char* path = event.drop.file;
					GApplicationFileDropFunction(path);
					SDL_free((void*)path);
				}
				break;
			case SDL_WINDOWEVENT:
				{
					switch (event.window.event) {
					case SDL_WINDOWEVENT_RESIZED:
						{
							GDisplaySettings.resolution.x = event.window.data1;
							GDisplaySettings.resolution.y = event.window.data2;
							WaitForCompletion();
							ResizeSwapChain(GDisplaySettings.resolution.x, GDisplaySettings.resolution.y);
							GApplicationWindowResizeFunction();
						}
						break;
					}
				}
				break;
			}
		}

		static INT64 PreviousTime = 0;
		static INT64 TicksPerSecond = 0;

		INT64 currentTime;
		Verify(QueryPerformanceCounter((LARGE_INTEGER *)&currentTime));

		double DeltaTime = (double)(currentTime - PreviousTime) / (double)TicksPerSecond;

		if (TicksPerSecond == 0) {
			Verify(QueryPerformanceFrequency((LARGE_INTEGER *)&TicksPerSecond));

			DeltaTime = 1. / 60.;
		}
		PreviousTime = currentTime;

		float fDeltaTime = (float)DeltaTime;

		ImGuiIO& io = ImGui::GetIO();
		RECT rect;
		GetClientRect(GDisplaySettings.hwnd, &rect);

		io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
		io.DeltaTime = (float)DeltaTime;
		io.MouseDrawCursor = true;
		SDL_ShowCursor(SDL_DISABLE);

		io.KeyShift = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_LSHIFT];
		io.KeyCtrl = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_LCTRL];
		io.KeyAlt = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_LALT];

		io.KeysDown[SDL_SCANCODE_TAB] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_TAB];
		io.KeysDown[SDL_SCANCODE_LEFT] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_LEFT];
		io.KeysDown[SDL_SCANCODE_RIGHT] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_RIGHT];
		io.KeysDown[SDL_SCANCODE_UP] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_UP];
		io.KeysDown[SDL_SCANCODE_DOWN] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_DOWN];
		io.KeysDown[SDL_SCANCODE_HOME] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_HOME];
		io.KeysDown[SDL_SCANCODE_END] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_END];
		io.KeysDown[SDL_SCANCODE_DELETE] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_DELETE];
		io.KeysDown[SDL_SCANCODE_RETURN] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_RETURN];
		io.KeysDown[SDL_SCANCODE_ESCAPE] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_ESCAPE];
		io.KeysDown[SDL_SCANCODE_BACKSPACE] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_BACKSPACE];
		io.KeysDown[SDL_SCANCODE_A] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_A];
		io.KeysDown[SDL_SCANCODE_C] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_C];
		io.KeysDown[SDL_SCANCODE_V] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_V];
		io.KeysDown[SDL_SCANCODE_X] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_X];
		io.KeysDown[SDL_SCANCODE_Y] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_Y];
		io.KeysDown[SDL_SCANCODE_Z] = !!SDL_GetKeyboardState(NULL)[SDL_SCANCODE_Z];

		int x, y;
		auto buttonState = SDL_GetMouseState(&x, &y);
		io.MousePos = ImVec2((float)x, (float)y);
		io.MouseDown[0] = !!(buttonState & SDL_BUTTON(SDL_BUTTON_LEFT));
		io.MouseDown[1] = !!(buttonState & SDL_BUTTON(SDL_BUTTON_RIGHT));
		io.MouseDown[2] = !!(buttonState & SDL_BUTTON(SDL_BUTTON_MIDDLE));

		ImGui::NewFrame();

		GApplicationTickFunction(fDeltaTime);

		EndCommandsFrame(GGPUMainQueue);
	}

	GApplicationShutdownFunction();

	WaitForCompletion();
	FreeModelsMemory();
	ImGui::Shutdown();
	ShutdownRenderingEngines();
	ShutdownResources();
	ShutdownDevice();
	FreeShadersMemory();

	ShutdownSDL(SDLWindow);

	ShutdownScheduler();
	ShutdownProfiler();
	ShutdownMainThread();
	return 0;
}
Esempio n. 16
0
/*
 * ubsec_CipherCommand: Process a list of Cipher commands.
 *
 * Immediate Status is returned. Completion status is returned
 * on a per command callback
 */
ubsec_Status_t 
ubsec_CipherCommand(ubsec_DeviceContext_t Context,
	      ubsec_CipherCommandInfo_pt pCommand,
	      int *NumCommands)
{
  DeviceInfo_pt pDevice=(DeviceInfo_pt)Context;
  VOLATILE MasterCommand_t  *pMCR;
  VOLATILE Packet_t         *pPacket;
  VOLATILE PacketContext_t  *pContext;
  VOLATILE CipherContext_t  *pCipherContext;
  VOLATILE int             PacketIndex;
  VOLATILE int  NumFrags;   /* Number of fragments */
  ubsec_FragmentInfo_t ExtraFragment, *pExtraFragment;
  int CommandIndex=0;
  int CommandCount=*NumCommands;
  ubsec_Status_t Status;
  UBS_UINT32 SaveConfig = 0;

  Dbg_Print(DBG_CMD,( "ubsec:  ubsec command %d",*NumCommands ));

  /*
   * Check some parameters
   */    
  if(pDevice==NULL_DEVICE_INFO) {
    Dbg_Print(DBG_FATAL,( "NO DEV\n " ));
    return(UBSEC_STATUS_NO_DEVICE );
  }
  Dbg_Print(DBG_CMD,( "\n"));

  if (OS_EnterCriticalSection(pDevice,SaveConfig)) {
    return(UBSEC_STATUS_DEVICE_BUSY);
  }

  /* Get the next MCR to load */
 Get_New_MCR:
  *NumCommands=CommandIndex; /* Update number completed */
  if ((pMCR=GetFreeMCR(pDevice,UBSEC_CIPHER_LIST,&Status))== NULL_MASTER_COMMAND) {
    Dbg_Print(DBG_CMD_FAIL,("ubsec: device busy MCR %x\n", Status));
    goto Error_Return;
  }

  /* Add packets to this MCR. */

  Dbg_Print(DBG_CMD,( "ubsec: mcr_index %d MCR %0x\n",pMCR->Index,pMCR));
  /* Initialize the packet information */

  PacketIndex = pMCR->NumberOfPackets; 
  pPacket = &(pMCR->PacketArray[PacketIndex]); /* Set up the current packet. */
  pContext = &pMCR->ContextList[PacketIndex]; 
  Status=UBSEC_STATUS_SUCCESS; /* Wishful thinking? */

  /* Process all the commands in the command list. */
  for (; CommandIndex < CommandCount ; CommandIndex++) { /* Add all the packets to the MCR */
    if( PacketIndex >= MCR_MAXIMUM_PACKETS ) {
      Dbg_Print(DBG_CMD,( "ubsec:  overran mcr buffer. %d %d\n",PacketIndex,CommandIndex ));
      /* 
       * We have filled this MCR with the max # of packets,
       * but still have more packets (commands) to do.
       * Advance next free. Wrap around if necessary
       */
      pDevice->NextFreeMCR[UBSEC_CIPHER_LIST]=
	(MasterCommand_pt) pMCR->pNextMCR;

      /* For crypto MCRs, the contexts are accessed using a single handle   */
      /* for an array of contexts. This means that all contexts for an MCR  */
      /* are contiguous in memory, and that we can sync all contexts at     */
      /* once (now that we know that we're finished loading this MCR).      */
      /* Make DMA memory actually hold CPU-initialized context data         */
      Dbg_Print(DBG_CNTXT_SYNC,( "ubsec: ubsec_CipherCommand Sync %d Contexts to Device (0x%08X,%d,%d)\n", 
			 pMCR->NumberOfPackets,
			 pMCR->ContextListHandle[0],
			 0,
			 pMCR->NumberOfPackets * sizeof(PacketContext_t)));
      OS_SyncToDevice(pMCR->ContextListHandle[0],0,
		      pMCR->NumberOfPackets * sizeof(PacketContext_t));

      PushMCR(pDevice); /* Get it going (pipeline) */
      goto Get_New_MCR; /* Try to add to the next MCR */
    }
    
    /* Save the callback information. */
    pMCR->CompletionArray[PacketIndex].CompletionCallback = pCommand->CompletionCallback;
    pMCR->CompletionArray[PacketIndex].CommandContext = pCommand->CommandContext;

    /* Now set up the packet processing parameters */
    Dbg_Print(DBG_PACKET,( "ubsec: packet_Index %d, Context Buf %0x\n",PacketIndex,pContext ));
    pPacket->PacketContextBuffer=pContext->PhysicalAddress;
    pCipherContext=&pContext->Context.Cipher;
    RTL_MemZero(pCipherContext,sizeof(*pCipherContext));
#ifdef UBSEC_582x_CLASS_DEVICE
    /* Some extra fields to be filled in . */
    pContext->cmd_structure_length= CPU_TO_CTRL_SHORT(sizeof(*pCipherContext)+4); /* For header. */
    pContext->operation_type=OPERATION_IPSEC; /* send mode for DH */
#endif    
    /*
     * Now add the packet input fragment information
     * First fragment will need to skip the MAC Header
     * We need at least one fragment.
     */
    /* Sanity checks.*/
    if (!(NumFrags=pCommand->NumSource)) {
      Dbg_Print(DBG_PACKET,( "ubsec:  No Input fragments\n" ));
      Status=UBSEC_STATUS_INVALID_PARAMETER;
      goto MCR_Done;
    }
    if (NumFrags>(UBSEC_MAX_FRAGMENTS+1)) {
      Dbg_Print(DBG_PACKET,( "ubsec:  Too Many Input fragments\n" ));
      Status=UBSEC_STATUS_INVALID_PARAMETER;
      goto MCR_Done;
    }

    Dbg_Print(DBG_PACKET,( "ubsec: Num Input Frags %d \n",NumFrags));

    /* SetupInputFragmentList will always be successful here because of */
    /* the sanity checks performed above.                               */
    SetupInputFragmentList((MasterCommand_t *)pMCR, (Packet_t *)pPacket,NumFrags,pCommand->SourceFragments);

    /*
     * Now add the packet output fragment information
     * We need at least one fragment.
     */
    /* Sanity checks */
    if (!(NumFrags=pCommand->NumDestination)) {
      Dbg_Print(DBG_PACKET,( "ubsec:  No Output fragments\n" ));
      Status=UBSEC_STATUS_INVALID_PARAMETER;
      goto MCR_Done;
    }
    if (NumFrags > (UBSEC_MAX_FRAGMENTS+1)) {
      Dbg_Print(DBG_PACKET,( "ubsec:  Too Many Output fragments\n" ));
      Status=UBSEC_STATUS_INVALID_PARAMETER;
      goto MCR_Done;
    }

    Dbg_Print(DBG_PACKET,( "ubsec: Num Output Frags %d \n",NumFrags));

    if (UBSEC_USING_MAC(pCommand->Command)) { 
      /* We need an 'extra' fragment info struct for the auth data */
      ExtraFragment.FragmentAddress = 
	pCommand->AuthenticationInfo.FragmentAddress;
      /* Easy to do check here for invalid 'extra' fragment address */
      if ( (long) ExtraFragment.FragmentAddress & 0x03 ) {
	Dbg_Print(DBG_PACKET,("ubsec:  ################INVALID HMAC ADDRESS %08x\n",ExtraFragment.FragmentAddress));
	Status=UBSEC_STATUS_INVALID_PARAMETER;
	goto Error_Return;
      }
      /* The CryptoNet chip knows how big the auth fragment is, but */
      /* SetupOutputFragmentList() needs to see a length of zero.   */
      ExtraFragment.FragmentLength = 0;
      pExtraFragment = &ExtraFragment;
    }
    else { /* not doing authentication; pass NULL extra fragment info */
      pExtraFragment = (ubsec_FragmentInfo_pt) 0;
    }
    /* SetupOutputFragmentList() checks frag list for allowable fragment */
    /* addresses (4-byte aligned) and lengths (4-byte multiples).        */
    if (SetupOutputFragmentList((MasterCommand_t *)pMCR,(Packet_t *)pPacket,NumFrags,
			    pCommand->DestinationFragments,pExtraFragment)) {
      Status=UBSEC_STATUS_INVALID_PARAMETER;
      goto Error_Return;
    }

    /* Set up the context flags */
    if (pCommand->Command & UBSEC_ENCODE)
      pCipherContext->CryptoFlag = CF_ENCODE;
    else
      pCipherContext->CryptoFlag = CF_DECODE;

    if (UBSEC_USING_CRYPT( pCommand->Command )) {
      pCipherContext->CryptoFlag |= CF_3DES;
      pCipherContext->CryptoOffset = CPU_TO_CTRL_SHORT( pCommand->CryptHeaderSkip );
      if (pCommand->Command &UBSEC_3DES) {
#if (UBS_CRYPTONET_ATTRIBUTE == UBS_BIG_ENDIAN)
	RTL_Memcpy( &pCipherContext->CryptoKey1[0], pCommand->CryptKey, 24);
#else
	copywords((UBS_UINT32 *)&pCipherContext->CryptoKey1[0], (UBS_UINT32 *)pCommand->CryptKey, 6);
#endif
      } 
      else {  
	/* Des is implemented by using 3 copies of the same DES key */
#if (UBS_CRYPTONET_ATTRIBUTE == UBS_BIG_ENDIAN)
	RTL_Memcpy( &pCipherContext->CryptoKey1[0], pCommand->CryptKey, 8); 
#else
	copywords((UBS_UINT32 *) &pCipherContext->CryptoKey1[0], (UBS_UINT32 *) pCommand->CryptKey, 2); 
#endif
	RTL_Memcpy( &pCipherContext->CryptoKey2[0],&pCipherContext->CryptoKey1[0],sizeof(pCipherContext->CryptoKey1));
	RTL_Memcpy( &pCipherContext->CryptoKey3[0],&pCipherContext->CryptoKey1[0],sizeof(pCipherContext->CryptoKey1));
      }
#if (UBS_CRYPTONET_ATTRIBUTE == UBS_BIG_ENDIAN)
      RTL_Memcpy(&pCipherContext->ComputedIV[0],&pCommand->InitialVector[0],8);
#else
      copywords((UBS_UINT32 *) &pCipherContext->ComputedIV[0], (UBS_UINT32 *) &pCommand->InitialVector[0],2);
#endif
    }
    /* If using HMAC then copy the authentication state to the context. */
    if( UBSEC_USING_MAC( pCommand->Command ) ) {
      RTL_Memcpy( &pCipherContext->HMACInnerState[0],
		  pCommand->HMACState,
		  sizeof(ubsec_HMAC_State_t));
      if( UBSEC_MAC_MD5 & pCommand->Command )
	    pCipherContext->CryptoFlag |= CF_MD5;
      else if( UBSEC_MAC_SHA1 & pCommand->Command )
	    pCipherContext->CryptoFlag |= CF_SHA1;
    }
    
    Dbg_Print( DBG_PACKET, ("ubsec:  CryptoOffset and Flag [%04x][%04x]\n",
        CTRL_TO_CPU_SHORT( pCipherContext->CryptoOffset ), 
        CTRL_TO_CPU_SHORT( pCipherContext->CryptoFlag )) );

#ifdef UBSEC_STATS
    if (pCipherContext->CryptoFlag & CF_DECODE) {
      pDevice->Statistics.BlocksDecryptedCount++;
      pDevice->Statistics.BytesDecryptedCount+=CTRL_TO_CPU_SHORT(pPacket->PacketLength);
    }
    else {
      pDevice->Statistics.BlocksEncryptedCount++;
      pDevice->Statistics.BytesEncryptedCount+=CTRL_TO_CPU_SHORT(pPacket->PacketLength);
    }
#endif

   /* Now inc the number of packets and prepare for the next command. */
    pMCR->NumberOfPackets++;
    pCommand++;
    PacketIndex++;
    pPacket++;
    pContext++;

  } /* For NumCommands-- */

  /*
   * If we are here then the last packet(s) (commands) have been added to
   * the current MCR.
   * Push the MCR to the device. 
   */
 MCR_Done:
  *NumCommands=CommandIndex; /* Update number completed */

  /* For crypto MCRs, the contexts are accessed using a single handle   */
  /* for an array of contexts. This means that all contexts for an MCR  */
  /* are contiguous in memory, and that we can sync all contexts at     */
  /* once (now that we know that we're finished loading this MCR).      */
  /* Make DMA memory actually hold CPU-initialized context data         */
  Dbg_Print(DBG_CNTXT_SYNC,( "ubsec: ubsec_CipherCommand Sync %d Contexts to Device (0x%08X,%d,%d)\n", 
			 pMCR->NumberOfPackets,
			 pMCR->ContextListHandle[0],
			 0,
			 pMCR->NumberOfPackets * sizeof(PacketContext_t)));
  OS_SyncToDevice(pMCR->ContextListHandle[0],0,
		  pMCR->NumberOfPackets * sizeof(PacketContext_t));

  PushMCR(pDevice);

#ifdef BLOCK 
  /* Wait for all outstanding  to complete */
    while ((Status=WaitForCompletion(pDevice,(UBS_UINT32)100000,UBSEC_CIPHER_LIST))
	   == UBSEC_STATUS_SUCCESS);
    if (Status!=UBSEC_STATUS_TIMEOUT) /* We are nested, return success */
      Status=UBSEC_STATUS_SUCCESS;
 Error_Return:
#else

 Error_Return:  /* Label to make sure that IRQs are enabled. */
#ifdef COMPLETE_ON_COMMAND_THREAD
    ubsec_PollDevice(pDevice);  /* Try to complete some & cut down on ints */
#endif
#endif
    OS_LeaveCriticalSection(pDevice,SaveConfig);

#ifdef UBSEC_STATS
		if (Status != UBSEC_STATUS_SUCCESS)
			pDevice->Statistics.CryptoFailedCount++;
#endif
   return(Status);
}
Esempio n. 17
0
/*
 * ubsec_SSLCommand: Process a list of Cipher commands.
 *
 * Immediate Status is returned. Completion status is returned
 * on a per command callback
 */
ubsec_Status_t 
ubsec_SSLCommand(ubsec_DeviceContext_t Context,
	      ubsec_SSLCommandInfo_pt pCommand,
	      int *NumCommands)
{
#ifdef UBSEC_SSL_SUPPORT
  DeviceInfo_pt pDevice=(DeviceInfo_pt)Context;
  VOLATILE MasterCommand_t   *pMCR;
  VOLATILE Packet_t          *pPacket;
  VOLATILE PacketContext_t   *pContext;
  VOLATILE SSL_MACContext_t  *pSSLMACContext;
  VOLATILE TLS_HMACContext_t *pTLSHMACContext;
  VOLATILE SSL_CryptoContext_t *pSSLCryptoContext;
  VOLATILE ARC4_CryptoContext_t *pARC4Context;
  VOLATILE Hash_Context_t *pHashContext;
  int i;
  long *plong;
  VOLATILE int             PacketIndex;

  int CommandIndex=0;
  int CommandCount=*NumCommands;
  ubsec_Status_t Status;
  unsigned long SaveConfig;
  ubsec_FragmentInfo_pt pExtraFragment=(ubsec_FragmentInfo_pt) 0;

  Dbg_Print(DBG_CMD,( "ubsec:  SSL command %d",*NumCommands ));
  /*
   * Check some parameters
   */    
  if(pDevice==NULL_DEVICE_INFO) {
    Dbg_Print(DBG_FATAL,( "NO DEV\n " ));
    return(UBSEC_STATUS_NO_DEVICE );
  }
  Dbg_Print(DBG_CMD,( "\n"));

  if (!(UBSEC_IS_SSL_DEVICE(pDevice))) {
    Dbg_Print(DBG_FATAL,( "ubsec: SSL Command for a non SSL device %x \n ",pDevice->DeviceID ));
    return(UBSEC_STATUS_NO_DEVICE );
  }

  /*  SaveConfig=OS_EnterCriticalSection(pDevice); */
  OS_EnterCriticalSection(pDevice, SaveConfig);

  /* Get the next MCR to load */
 Get_New_MCR:
  *NumCommands=CommandIndex; /* Update number completed */
  if ((pMCR=GetFreeMCR(pDevice,UBSEC_CIPHER_LIST,&Status))== NULL_MASTER_COMMAND) {
    Dbg_Print(DBG_CMD_FAIL,("ubsec: device busy MCR %x\n",Status));
    goto Error_Return;
  }

  /* Add packets to this MCR. */

  Dbg_Print(DBG_CMD,( "ubsec: mcr_index %d MCR %0x\n",pMCR->Index,pMCR));
  /* Initialize the packet information */

  PacketIndex = pMCR->NumberOfPackets; 
  pPacket = &(pMCR->PacketArray[PacketIndex]); /* Set up the current packet. */
  pContext = &pMCR->ContextList[PacketIndex]; 
  Status=UBSEC_STATUS_SUCCESS; /* Wishful thinking? */

  /* Process all the commands in the command list. */
  for (; CommandIndex < CommandCount ; CommandIndex++) { /* Add all the packets to the MCR */
    if( PacketIndex >= MCR_MAXIMUM_PACKETS ) {
      Dbg_Print(DBG_CMD,( "ubsec:  overran mcr buffer. %d\n",PacketIndex,CommandIndex ));
      /* 
       * We have filled this MCR. 
       * Advance next free. Wrap around if necessary
       */
      pDevice->NextFreeMCR[0]=(MasterCommand_pt) pMCR->pNextMCR;
      PushMCR(pDevice); /* Get it going (pipeline) */
      goto Get_New_MCR; /* Try to add to the next MCR */
    }
    
    pPacket->PacketContextBuffer=pContext->PhysicalAddress; 
    
    /* Save the callback information. */
    pMCR->CompletionArray[PacketIndex].CompletionCallback = pCommand->CompletionCallback;
    pMCR->CompletionArray[PacketIndex].CommandContext = pCommand->CommandContext;

    /* Now set up the packet processing parameters */
    Dbg_Print(DBG_PACKET,( "ubsec: packet_Index %d, Context Buf %0x\n",PacketIndex,pContext ));

        /* Now setup the particular context */

    pExtraFragment=(ubsec_FragmentInfo_pt) 0;
    switch (UBSEC_SSL_COMMAND(pCommand->Command)) {


    case UBSEC_SSL_MAC:
      pContext->cmd_structure_length= CPU_TO_CTRL_SHORT(SSLMAC_CONTEXT_SIZE);
      pContext->operation_type=OPERATION_SSL_MAC;
      pCommand->NumDestination=0; /* Make sure */

      pSSLMACContext=&pContext->Context.SSL_Mac;
      RTL_MemZero(pSSLMACContext,sizeof(*pSSLMACContext));

#if (UBS_CRYPTONET_ATTRIBUTE == UBS_BIG_ENDIAN)
      pSSLMACContext->SequenceHigh=pCommand->Parameters.SSLMACParams.SequenceNumber.HighWord;
      pSSLMACContext->SequenceLow=pCommand->Parameters.SSLMACParams.SequenceNumber.LowWord;
      RTL_Memcpy(&pSSLMACContext->HMACKey[0],&pCommand->Parameters.SSLMACParams.key[0],20);
#else
      pSSLMACContext->SequenceHigh=BYTESWAPLONG(pCommand->Parameters.SSLMACParams.SequenceNumber.HighWord);
      pSSLMACContext->SequenceLow=BYTESWAPLONG(pCommand->Parameters.SSLMACParams.SequenceNumber.LowWord);
      copywords((UBS_UINT32 *)&pSSLMACContext->HMACKey[0],
		(UBS_UINT32 *)&pCommand->Parameters.SSLMACParams.key[0],5);
#endif

      pSSLMACContext->DataLength=CPU_TO_CTRL_SHORT(pCommand->Parameters.SSLMACParams.DataLength);
      pSSLMACContext->ContentType=pCommand->Parameters.SSLMACParams.ContentType;

      /*
      for (i=0,plong=(long *)&pSSLMACContext->HMACPad; i <SSL_MAC_PAD_LENGTH_LONG; i++)
	*plong++=SSL_MAC_PAD_VALUE_LONG;
      */
      RTL_Memset((unsigned char*)pSSLMACContext->HMACPad, 0x36, 48);

      pExtraFragment=&pCommand->Parameters.HashParams.OutputHMAC;
      if( UBSEC_MAC_MD5 & pCommand->Command )
	pSSLMACContext->CryptoFlag = CF_MD5;
      else if( UBSEC_MAC_SHA1 & pCommand->Command )
	pSSLMACContext->CryptoFlag = CF_SHA1;
      
      break;

    case UBSEC_TLS: 
      pContext->cmd_structure_length= CPU_TO_CTRL_SHORT(TLSHMAC_CONTEXT_SIZE);
      pContext->operation_type=OPERATION_TLS_HMAC;
      pCommand->NumDestination=0; /* Make sure */
           
      pTLSHMACContext=&pContext->Context.TLS_HMac;
      RTL_MemZero(pTLSHMACContext,sizeof(*pTLSHMACContext));

#if (UBS_CRYPTONET_ATTRIBUTE == UBS_BIG_ENDIAN)
      /* Assume sequence numbers are in proper format. */
      pTLSHMACContext->SequenceHigh=pCommand->Parameters.TLSHMACParams.SequenceNumber.HighWord;
      pTLSHMACContext->SequenceLow=pCommand->Parameters.TLSHMACParams.SequenceNumber.LowWord;
#else
      /* Assume sequence numbers are in proper format. */
      pTLSHMACContext->SequenceHigh=BYTESWAPLONG(pCommand->Parameters.TLSHMACParams.SequenceNumber.HighWord);
      pTLSHMACContext->SequenceLow=BYTESWAPLONG(pCommand->Parameters.TLSHMACParams.SequenceNumber.LowWord);
#endif      
      RTL_Memcpy( &pTLSHMACContext->HMACInnerState[0],
		  pCommand->Parameters.TLSHMACParams.HMACState,sizeof(ubsec_HMAC_State_t)); 
      /* printk("md5 = x%x sha = x%x command = x%x\n", UBSEC_MAC_MD5, UBSEC_MAC_SHA1, pCommand->Command); */
      pTLSHMACContext->CryptoFlag = 0;
      if( UBSEC_MAC_MD5 & pCommand->Command )
	pTLSHMACContext->CryptoFlag |= CF_MD5;
      else if( UBSEC_MAC_SHA1 & pCommand->Command )
	pTLSHMACContext->CryptoFlag |= CF_SHA1;

      pTLSHMACContext->ContentType=pCommand->Parameters.TLSHMACParams.ContentType;
      pTLSHMACContext->Version = CPU_TO_CTRL_SHORT(pCommand->Parameters.TLSHMACParams.Version);
      pTLSHMACContext->DataLengthHi=HIGH_BYTE(pCommand->Parameters.TLSHMACParams.DataLength);
	pTLSHMACContext->DataLengthLo=LOW_BYTE(pCommand->Parameters.TLSHMACParams.DataLength);
      pExtraFragment=&pCommand->Parameters.TLSHMACParams.OutputHMAC;
      break;
    case UBSEC_SSL_CRYPTO:
      pContext->cmd_structure_length= CPU_TO_CTRL_SHORT(SSLCRYPTO_CONTEXT_SIZE);
      pContext->operation_type=OPERATION_SSL_CRYPTO;
      pSSLCryptoContext=&pContext->Context.SSL_Crypto;
      RTL_MemZero(pSSLCryptoContext,sizeof(*pSSLCryptoContext));

      if (UBSEC_USING_CRYPT( pCommand->Command )) {
	pSSLCryptoContext->CryptoFlag |= CF_3DES;
	  
#if (UBS_CRYPTONET_ATTRIBUTE == UBS_BIG_ENDIAN)
	RTL_Memcpy(&pSSLCryptoContext->CryptoKey1[0], pCommand->Parameters.SSLCipherParams.CryptKey, 24);
	RTL_Memcpy(&pSSLCryptoContext->ComputedIV[0], &pCommand->Parameters.SSLCipherParams.InitialVector[0],8);
#else
	copywords((UBS_UINT32 *)&pSSLCryptoContext->CryptoKey1[0], pCommand->Parameters.SSLCipherParams.CryptKey, 6);
	copywords((UBS_UINT32 *)&pSSLCryptoContext->ComputedIV[0], (UBS_UINT32 *)&pCommand->Parameters.SSLCipherParams.InitialVector[0],2);
#endif
	}
        /* Set up the context flags for direction */
      if (pCommand->Command & UBSEC_ENCODE)
	pSSLCryptoContext->CryptoFlag = CF_ENCODE;
      else
	pSSLCryptoContext->CryptoFlag = CF_DECODE;

      break;

    case UBSEC_HASH:
      pContext->cmd_structure_length= CPU_TO_CTRL_SHORT(HASH_CONTEXT_SIZE);
      pContext->operation_type=OPERATION_HASH; 
      pHashContext=&pContext->Context.Hash;
      RTL_MemZero(pHashContext,sizeof(*pHashContext));

      if( UBSEC_MAC_MD5 & pCommand->Command )
	pHashContext->CryptoFlag |= CF_MD5;
      else if( UBSEC_MAC_SHA1 & pCommand->Command )
	pHashContext->CryptoFlag |= CF_SHA1;
      pExtraFragment=&pCommand->Parameters.HashParams.OutputHMAC;
      pExtraFragment->FragmentLength=0; /* Only pointer is used .*/
      pCommand->NumDestination=0; /* Should already be but... */
      break;

    case UBSEC_ARC4:

    #if defined(UBSEC_582x) 
      /* ARC4_NULL_DATA mode supported in "582x mode" driver for BCM5821 and later chips only */
      if ((pCommand->Parameters.ARC4Params.KeyStateFlag & UBSEC_ARC4_STATE_NULL_DATA) && \
	   (pDevice->DeviceID < BROADCOM_DEVICE_ID_5821)) {
	Status=UBSEC_STATUS_INVALID_PARAMETER;
	goto MCR_Done;
      }
    #else
      /* ARC4_NULL_DATA mode not supported in "5820 mode" driver */
      if (pCommand->Parameters.ARC4Params.KeyStateFlag & UBSEC_ARC4_STATE_NULL_DATA) {
	Status=UBSEC_STATUS_INVALID_PARAMETER;
	goto MCR_Done;
      }       
#endif /* UBSEC_582x */

      pContext->cmd_structure_length= CPU_TO_CTRL_SHORT(ARC4_CONTEXT_SIZE);
      pContext->operation_type=OPERATION_ARC4; 
      pARC4Context=&pContext->Context.ARC4_Crypto;
      RTL_MemZero(pARC4Context,sizeof(*pARC4Context));

      if (pCommand->Parameters.ARC4Params.KeyStateFlag & UBSEC_ARC4_STATE_WRITEBACK) {
	/*  printk("\nSRL: keystateflag = %d\n", pCommand->Parameters.ARC4Params.KeyStateFlag); */
	pARC4Context->StateInfo|=ARC4_STATE_WRITEBACK;
      }
      if (pCommand->Parameters.ARC4Params.KeyStateFlag & UBSEC_ARC4_STATE_STATEKEY) {
	/*  printk("\nSRL: keystateflag = %d\n", pCommand->Parameters.ARC4Params.KeyStateFlag); */
	pARC4Context->StateInfo|=ARC4_STATE_STATEKEY;
      }
    #if defined(UBSEC_582x) 
      if (pCommand->Parameters.ARC4Params.KeyStateFlag & UBSEC_ARC4_STATE_NULL_DATA) {
	/* printk("\nSRL: keystateflag = %d\n", pCommand->Parameters.ARC4Params.KeyStateFlag); */
	pARC4Context->StateInfo|=ARC4_STATE_NULL_DATA;
      } 
    #endif /* UBSEC_582x */


#if (UBS_CRYPTONET_ATTRIBUTE == UBS_BIG_ENDIAN)
      /* The initial "packed key" must be byteswapped for big endian CryptoNet builds */
      if (pCommand->Parameters.ARC4Params.KeyStateFlag & UBSEC_ARC4_STATE_STATEKEY) 
	copywords( (UBS_UINT32 *)pARC4Context->KeyState,
		   (UBS_UINT32 *)pCommand->Parameters.ARC4Params.KeyStateIn,
		   sizeof(ubsec_ARC4_State_t)/4);
      else
#endif
      RTL_Memcpy( pARC4Context->KeyState,pCommand->Parameters.ARC4Params.KeyStateIn,sizeof(ubsec_ARC4_State_t));


      pExtraFragment=&pCommand->Parameters.ARC4Params.state_out;
      break;
    default:
      Dbg_Print(DBG_CMD,( "ubsec:  SSL Invalid Command %x\n",pCommand->Command ));
      Status=UBSEC_STATUS_INVALID_PARAMETER;
      goto MCR_Done;
    };


    /*
     * Now add the packet input fragment information
     * First fragment will need to skip the MAC Header
     * Must have at least one fragment (pCommand->NumSource > 0).
     *
     * For ARC4_NULL_DATA mode, we still need to know how big the message is.
     * You can actually build a DMA-able input fragment list just like if you were
     * not using ARC4_NULL_DATA mode, but that method incurs unnecessary CPU cycles.
     * The fastest way is to create a single "dummy" input fragment, with
     * a FragmentLength equal to the length of the "virtual" message. 
     * The "dummy" fragment's DataAddress will be ignored. Either way,
     * at least one input fragment must be present.
     */
    if ((Status=SetupInputFragmentList((MasterCommand_pt)pMCR, (Packet_t *)pPacket,pCommand->NumSource,pCommand->SourceFragments))) {
      goto MCR_Done;
    }

    /*
     * Now add the packet output fragment information
     */
    if ((Status=SetupOutputFragmentList((MasterCommand_pt)pMCR, (Packet_t *)pPacket,pCommand->NumDestination,pCommand->DestinationFragments,pExtraFragment))) {
      goto MCR_Done;
    }

    /* Sync the current context memory region for CryptoNet DMA use */
    Dbg_Print(DBG_CNTXT_SYNC,( "ubsec: ubsec_SSLCommand() Sync Context to Device (0x%08X,%d,%d)\n", pMCR->ContextListHandle[PacketIndex],
		       0,
		       CTRL_TO_CPU_SHORT(pContext->cmd_structure_length)));
    OS_SyncToDevice(pMCR->ContextListHandle[PacketIndex],
		    0,
		    CTRL_TO_CPU_SHORT(pContext->cmd_structure_length));


#ifdef UBSEC_STATS
    if (UBSEC_SSL_COMMAND(pCommand->Command)== UBSEC_SSL_CRYPTO){
      	if (pCommand->Command & UBSEC_ENCODE){
      		pDevice->Statistics.BlocksEncryptedCount++;
      		pDevice->Statistics.BytesEncryptedCount+=CTRL_TO_CPU_SHORT(pPacket->PacketLength);
    		}
    		else {
      		pDevice->Statistics.BlocksDecryptedCount++;
      		pDevice->Statistics.BytesDecryptedCount+=CTRL_TO_CPU_SHORT(pPacket->PacketLength);
    		}
	}
#endif

   /* Now inc the number of packets and prepare for the next command. */
    pMCR->NumberOfPackets++;
    pCommand++;
    PacketIndex++;
    pPacket++;
    pContext++;
  } /* For (;CommandIndex < CommandCount ; CommandIndex++) */

#ifdef UBSDBG
  /* Print out the context information if required */
  DumpCipherMCR(pMCR);
#endif


  /*
   * If we are here then the MCR is built.
   * Either everything went great or we came straight here at the first
   * error condition we encountered. The MCR is filled only with those
   * packets that were built successfully (before any encountered error). 
   * Push the MCR to the device. 
   */
 MCR_Done:
  *NumCommands=CommandIndex; /* Update number completed */

  PushMCR(pDevice);

#ifdef BLOCK 
  /* Wait for all outstanding  to complete */
    while ((Status=WaitForCompletion(pDevice,(unsigned long)100000,UBSEC_CIPHER_LIST))
	   == UBSEC_STATUS_SUCCESS);
    if (Status!=UBSEC_STATUS_TIMEOUT) /* We are nested, return success */
      Status=UBSEC_STATUS_SUCCESS;
 Error_Return:
#else /* not BLOCKing */

 Error_Return:  /* Label to make sure that IRQs are enabled. */
#ifdef COMPLETE_ON_COMMAND_THREAD
    ubsec_PollDevice(pDevice);  /* Try to complete some & cut down on ints */
#endif

#endif /* BLOCK */
    OS_LeaveCriticalSection(pDevice,SaveConfig);

#ifdef UBSEC_STATS
		if (Status != UBSEC_STATUS_SUCCESS)
			pDevice->Statistics.CryptoFailedCount++;
#endif
   return(Status);

#else /* UBSEC_SSL_SUPPORT not defined */
    return(UBSEC_STATUS_NO_DEVICE);
#endif /* UBSEC_SSL_SUPPORT */

}
Esempio n. 18
0
void VirtCoreThread::run() {
	// Implementation for command line:
	// VBoxManage startvm "Windows XP"
	// timeout 10
	// VBoxManage guestcontrol "Windows XP" --username "vbox" --password "12345" run fsutil.exe --wait-stdout -- fsinfo drives
	// VBoxManage guestcontrol "Windows XP" --username "vbox" --password "12345" run fsutil.exe --wait-stdout -- volume diskfree c:\
	// ...
	enum { waitLaunchPeriod = 120000 };
	enum { waitLoginPeriod = 2000 };
	enum { delayLaunchVM = 5000 };
	enum { delayLogin = 500 };
	enum { reloginCount = 3 };

	const CoInit coInit;
	
	// Get machine and create session
	const auto machine = machineByName(virtualBox(), machine_.machine);
	const auto session = ::session();

	// Launch and lock machine
	if (isRuning(machine)) {
		if (!lock(machine, session)) {
			emit processMessage(
				tr("Lock machine '%1' fail").arg(machine_.machine)
			);
			return;
		}
	}
	else {
		const auto progress = launchVM(machine, session);

		emit processMessage(tr("Launch machine '%1'").arg(machine_.machine));

		if (!progress || !waitFor(
			[&progress, &machine]() {
				progress->WaitForCompletion(ticPeriod);
				return isCompleted(progress) && isRuning(machine);
			},
			waitLaunchPeriod
		)) {
			if (progress) {
				progress->Cancel();
			}

			if (!stop_) {
				emit processMessage(
					tr("Launch error for machine '%1'").arg(machine_.machine)
				);
			}

			return;
		}
		else {
			msleep(delayLaunchVM);
			if (stop_) { return; }
		}
	}

	// Login
	CComPtr<IGuestSession> guestSession;
	struct closer {
		CComPtr<IGuestSession> session;
		~closer() { if(session) session->Close(); }
	} closeSession = { nullptr };

	emit processMessage(
		tr("Login user '%1' on machine '%2")
		.arg(machine_.userName)
		.arg(machine_.machine)
	);
	
	bool sucessLogin = false;
	for (int relogin = 0; relogin < reloginCount; ++relogin)
	{
		guestSession = createGuestSession(
			session,
			machine_.userName,
			machine_.password
		);
		
		if (guestSession && waitFor([&guestSession, this]() {
				return waitForLogin(guestSession, ticPeriod);
			}, waitLoginPeriod)) {
			sucessLogin = true;
			break;
		}
	}
	
	if (!sucessLogin) {
		emit processMessage(
			tr("Login failed for user '%1' on machine '%2'")
			.arg(machine_.userName)
			.arg(machine_.machine)
		);

		return;
	}

	closeSession.session = guestSession;

	emit processMessage(
		tr("Success login user '%1' on machine '%2")
		.arg(machine_.userName)
		.arg(machine_.machine)
	);

	msleep(delayLogin);
	if (stop_) { return; }

	// Get volume information
	emit processMessage(tr("Get the volume list"));

	const auto volumeList = ::volumeList(guestSession);
	if (volumeList.isEmpty()) {
		emit processMessage(tr("Failed to get the volume list"));
		return;
	}
	if (stop_) { return; }

	VolumeInformationList volumeInformationList;
	volumeInformationList.reserve(volumeList.size());
	for (auto& volume : volumeList) {
		emit processMessage(tr("Get information for volume '%1'").arg(volume));
		const auto volumeSize = ::volumeSize(guestSession, volume);
		volumeInformationList.push_back({
			volume,
			volumeSize.size,
			volumeSize.freeSize
		});
		if (stop_) { return; }
	}
	
	emit volumeInformation(machine_.machine, volumeInformationList);
}