Exemplo n.º 1
0
/*
 * ::openEvents
 */
BOOL openEvents(HANDLE *outEvtDebugee, HANDLE *outEvtDebugger) {
#define EVENT_NAME_LEN (32)
#define SHMEM_NAME_LEN (64)

    wchar_t eventName[EVENT_NAME_LEN];
    DWORD processId = 0;

    /* Sanity checks. */
    if ((outEvtDebugee == NULL) || (outEvtDebugger == NULL)) {
        return TRUE;
    }

    /* TODO: Possible hazard when using multiple instances simultanously. */
    processId = GetCurrentProcessId();

    _snwprintf(eventName, EVENT_NAME_LEN, L"%udbgee", processId);
    if ((*outEvtDebugee = OpenEventW(EVENT_ALL_ACCESS, FALSE, eventName)) 
            == NULL) {
        dbgPrint(DBGLVL_ERROR, "OpenEvent(\"%s\") failed: %u.\n",
		          eventName, GetLastError());
        return FALSE;
    }

    _snwprintf(eventName, EVENT_NAME_LEN, L"%udbgr", processId);
    if ((*outEvtDebugger = OpenEventW(EVENT_ALL_ACCESS, FALSE, eventName)) 
            == NULL) {
        dbgPrint(DBGLVL_ERROR, "OpenEvent(\"%s\") failed: %u.\n",
		         eventName, GetLastError());
        return FALSE;
    }

    return TRUE;
#undef EVENT_NAME_LEN
}
Exemplo n.º 2
0
DBWin::DBWin(DWORD pid = -1)
{
	initialized = false;
	processId = pid;

	hMutex = OpenMutexW(SYNCHRONIZE, FALSE, L"DBWinMutex");
	if (!hMutex)
	{
		std::cerr << "Failed opening DBWinMutex" << std::endl;
		return;
	}

	hBufferReady = OpenEventW(EVENT_ALL_ACCESS, FALSE, L"DBWIN_BUFFER_READY");
	if (!hBufferReady)
	{
		hBufferReady = CreateEventW(nullptr, FALSE, TRUE, L"DBWIN_BUFFER_READY");
		if (!hBufferReady)
		{
			std::cerr << "Failed to open or create DBWIN_BUFFER_READY" << std::endl;
			return;
		}
	}

	hDataReady = OpenEventW(EVENT_ALL_ACCESS, FALSE, L"DBWIN_DATA_READY");
	if (!hDataReady)
	{
		hDataReady = CreateEventW(nullptr, FALSE, FALSE, L"DBWIN_DATA_READY");
		if (!hDataReady)
		{
			std::cerr << "Failed to open or create DBWIN_DATA_READY" << std::endl;
			return;
		}
	}

	hBuffer = OpenFileMappingW(FILE_MAP_READ, FALSE, L"DBWIN_BUFFER");
	if (!hBuffer)
	{
		hBuffer = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0,
			sizeof(dbwin_buffer), L"DBWIN_BUFFER");
		if (!hBuffer)
		{
			std::cerr << "Failed to open or create DBWIN_BUFFER" << std::endl;
			return;
		}
	}

	dbBuffer = static_cast<dbwin_buffer*>(MapViewOfFile(hBuffer, SECTION_MAP_READ, 0, 0, 0));
	if (!dbBuffer)
	{
		std::cerr << "Failed to map memory to dbBuffer" << std::endl;
		return;
	}

	initialized = true;
}
Exemplo n.º 3
0
BOOL
WINAPI
RefreshPolicyEx(IN BOOL bMachine,
                IN DWORD dwOptions)
{
    if (dwOptions & ~RP_FORCE)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (dwOptions & RP_FORCE)
    {
        HANDLE hEvent;
        BOOL Ret = TRUE;

        hEvent = OpenEventW(EVENT_MODIFY_STATE,
                            FALSE,
                            (bMachine ? szMachineGPForceRefreshEvent : szLocalGPForceRefreshEvent));
        if (hEvent != NULL)
        {
            Ret = SetEvent(hEvent);
            CloseHandle(hEvent);
        }

        /* return TRUE even if the mutex doesn't exist! */
        return Ret;
    }
    else
    {
        return RefreshPolicy(bMachine);
    }
}
Exemplo n.º 4
0
static
VOID
WaitForLsass(VOID)
{
    HANDLE hEvent;
    DWORD dwError;

    hEvent = CreateEventW(NULL,
                          TRUE,
                          FALSE,
                          L"LSA_RPC_SERVER_ACTIVE");
    if (hEvent == NULL)
    {
        dwError = GetLastError();
        TRACE("WL: Failed to create the notification event (Error %lu)\n", dwError);

        if (dwError == ERROR_ALREADY_EXISTS)
        {
            hEvent = OpenEventW(SYNCHRONIZE,
                                FALSE,
                                L"LSA_RPC_SERVER_ACTIVE");
            if (hEvent == NULL)
            {
               ERR("WL: Could not open the notification event (Error %lu)\n", GetLastError());
               return;
            }
        }
    }

    TRACE("WL: Wait for the LSA server!\n");
    WaitForSingleObject(hEvent, INFINITE);
    TRACE("WL: LSA server running!\n");

    CloseHandle(hEvent);
}
Exemplo n.º 5
0
VOID
LsapSignalRpcIsActive(
    )
/*++

Routine Description:

    It creates the LSA_RPC_SERVER_ACTIVE event if one does not already exist
    and signals it so that the service controller can proceed with LSA calls.

Arguments:

    None.

Return Value:

    None.

--*/
{
    DWORD status;
    HANDLE EventHandle;


    EventHandle = CreateEventW(
                      NULL,    // No special security
                      TRUE,    // Must be manually reset
                      FALSE,   // The event is initially not signalled
                      LSA_RPC_SERVER_ACTIVE
                      );

    if (EventHandle == NULL) {

        status = GetLastError();

        //
        // If the event already exists, the service controller beats us
        // to creating it.  Just open it.
        //

        if (status == ERROR_ALREADY_EXISTS) {

            EventHandle = OpenEventW(
                              GENERIC_WRITE,
                              FALSE,
                              LSA_RPC_SERVER_ACTIVE
                              );
        }

        if (EventHandle == NULL) {
            //
            // Could not create or open the event.  Nothing we can do...
            //
            return;
        }
    }

    (VOID) SetEvent(EventHandle);
}
Exemplo n.º 6
0
// address: 0x4012f8
void _start(int param1, int param2, int param3, int param4, RECT param5, int param6) {
    int eax; 		// r24
    union { __size32 * x7; unsigned int x8; } eax_1; 		// r24{257}
    int ecx; 		// r25
    int edx; 		// r26
    unsigned int edx_1; 		// r26{338}
    int esp; 		// r28

    eax = GetCurrentProcessId();
    if (eax != 1019) {
    }
    CharUpperA();
    OpenEventW();
    GetDC();
    eax = GetCurrentThreadId(); /* Warning: also results in ecx */
    if (eax == 621) {
        ecx = ecx ^ param6;
    }
    if (ecx != 0) {
    }
    __set_app_type();
    GetFileAttributesA();
    CharUpperA();
    GetProcessHeap();
    CharUpperA();
    OpenMutexA();
    IsWindow();
    eax = GetCurrentThreadId(); /* Warning: also results in ecx */
    if ((eax & 0xae4) != ecx) {
    }
    eax = GetClientRect(0, &param5); /* Warning: also results in edx */
    eax = eax | param4;
    if (eax != edx) {
        eax = (esp - 552);
        edx = edx ^ param2;
        edx = edx ^ param3;
        edx = edx & param1;
    }
    eax_1 = eax;
    edx_1 = edx;
    edx = edx_1 ^ 0x21cd;
    flags = SUBFLAGS32(eax_1, edx_1 ^ 0x21cd, eax_1 - (edx_1 ^ 0x21cd));
    if (eax_1 != (edx_1 ^ 0x21cd)) {
        edx = (edx_1 ^ 0x21cd) + (edx_1 ^ 0x21cd) + (eax_1 < (unsigned int)(edx_1 ^ 0x21cd));
        eax_1 = eax_1 - 0x3421;
        flags = SUBFLAGS32(eax_1, 0x3421, eax_1 - 0x3421);
    }
    if (eax_1 + edx + CF == 816) {
    }
    eax = CreateItemMoniker(); /* Warning: also results in edx */
    if ((eax ^ 0x80070057) == 0) {
        if ((eax ^ 0x80070057) + edx == 0) {
        }
    }
    return;
}
HOOKFUNC HANDLE WINAPI MyOpenEventW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName)
{
	HANDLE rv = OpenEventW(dwDesiredAccess, bInheritHandle, lpName);
	debuglog(LCF_SYNCOBJ, __FUNCTION__ " returned 0x%X.\n", rv);
	EnterCriticalSection(&s_handleCS);
	std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
	handles.insert(rv);
	LeaveCriticalSection(&s_handleCS);
	return rv;
}
Exemplo n.º 8
0
 HOOKFUNC HANDLE WINAPI MyOpenEventW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpName)
 {
     ENTER();
     HANDLE rv = OpenEventW(dwDesiredAccess, bInheritHandle, lpName);
     LEAVE(rv);
     EnterCriticalSection(&s_handleCS);
     std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
     handles.insert(rv);
     LeaveCriticalSection(&s_handleCS);
     return rv;
 }
Exemplo n.º 9
0
int __cdecl main( int argc, char **argv )
{
    /* local variables */
    HANDLE                  hEvent = NULL;
    WCHAR                   wcName[] = {'P','A','L','R','o','c','k','s','\0'};
    LPWSTR                  lpName = wcName;
    
    int result = PASS;

    /* initialize the PAL */
    if( PAL_Initialize(argc, argv) != 0 )
    {
	    return( FAIL );
    }


    /* open a handle to the event created in the child process */
    hEvent = OpenEventW( EVENT_ALL_ACCESS,  /* we want all rights */
                         FALSE,             /* no inherit         */
                         lpName );

    if( hEvent == NULL )
    {
        /* ERROR */
        Trace( "ERROR:%lu:OpenEventW() call failed\n", GetLastError() );
        result = FAIL;
        goto parentwait;
    }

    /* set the event -- should take effect in the child process */
    if( ! SetEvent( hEvent ) )
    {
        /* ERROR */
        Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() );
        result = FAIL;
    }

parentwait:
    /* close the event handle */
    if( ! CloseHandle( hEvent ) )
    {
        /* ERROR */
        Fail(   "ERROR:%lu:CloseHandle() call failed in child\n",
                GetLastError());
    }

    /* terminate the PAL */
    PAL_TerminateEx(result);

    /* return success or failure */
    return result;
}
Exemplo n.º 10
0
static BOOL
SetShellReadyEvent(IN LPCWSTR lpEventName)
{
    HANDLE hEvent;

    hEvent = OpenEventW(EVENT_MODIFY_STATE, FALSE, lpEventName);
    if (hEvent != NULL)
    {
        SetEvent(hEvent);

        CloseHandle(hEvent);
        return TRUE;
    }

    return FALSE;
}
Exemplo n.º 11
0
HANDLE
APIENTRY
OpenEventA(
    DWORD dwDesiredAccess,
    BOOL bInheritHandle,
    LPCSTR lpName
)

/*++

Routine Description:

    ANSI thunk to OpenNamedEventW

--*/

{
    PUNICODE_STRING Unicode;
    ANSI_STRING AnsiString;
    NTSTATUS Status;

    if ( ARGUMENT_PRESENT(lpName) ) {
        Unicode = &NtCurrentTeb()->StaticUnicodeString;
        RtlInitAnsiString(&AnsiString,lpName);
        Status = RtlAnsiStringToUnicodeString(Unicode,&AnsiString,FALSE);
        if ( !NT_SUCCESS(Status) ) {
            if ( Status == STATUS_BUFFER_OVERFLOW ) {
                SetLastError(ERROR_FILENAME_EXCED_RANGE);
            }
            else {
                BaseSetLastNTError(Status);
            }
            return NULL;
        }
    }
    else {
        BaseSetLastNTError(STATUS_INVALID_PARAMETER);
        return NULL;
    }

    return OpenEventW(
               dwDesiredAccess,
               bInheritHandle,
               (LPCWSTR)Unicode->Buffer
           );
}
Exemplo n.º 12
0
BOOL
WINAPI
WaitForMachinePolicyForegroundProcessing(VOID)
{
    HANDLE hEvent;
    BOOL Ret = FALSE;

    hEvent = OpenEventW(SYNCHRONIZE,
                        FALSE,
                        szMachineGPDoneEvent);
    if (hEvent != NULL)
    {
        Ret = WaitForSingleObject(hEvent,
                                  INFINITE) != WAIT_FAILED;
        CloseHandle(hEvent);
    }

    return Ret;
}
Exemplo n.º 13
0
BOOL
WINAPI
RefreshPolicy(IN BOOL bMachine)
{
    HANDLE hEvent;
    BOOL Ret = TRUE;

    hEvent = OpenEventW(EVENT_MODIFY_STATE,
                        FALSE,
                        (bMachine ? szMachineGPRefreshEvent : szLocalGPRefreshEvent));
    if (hEvent != NULL)
    {
        Ret = SetEvent(hEvent);
        CloseHandle(hEvent);
    }

    /* return TRUE even if the mutex doesn't exist! */
    return Ret;
}
Exemplo n.º 14
0
int __stdcall NotifyService()
{
	int nRet = 0;
	log.Print(LL_DEBUG_INFO,"Enter NotifyService\r\n");
	HANDLE hevent = OpenEventW(EVENT_ALL_ACCESS,false,EventName);
	
	if ((hevent == NULL) || (hevent == INVALID_HANDLE_VALUE) )
	{
		log.Print(LL_DEBUG_INFO,"OpenEventW Global\\FS_Index_Notify !GetLastError=%d\r\n",GetLastError());

		hevent = CreateEventW(NULL,true,false,EventName);
	}
	
	if (!SetEvent(hevent))
	{	
		log.Print(LL_DEBUG_INFO,"SetEvent Failed!GetLastError=%d \r\n",GetLastError());
		nRet = -1;
	}

	CloseHandle(hevent);
	log.Print(LL_DEBUG_INFO,"Leave NotifyService\r\n");
	return nRet;
}
Exemplo n.º 15
0
int main() {

	int argc;
	wchar_t ** argv = CommandLineToArgvW(GetCommandLine(), &argc);

	// Make sure that we've been passed the right number of arguments
	if (argc < 8) {
		_tprintf(_T("Usage: %s (four inheritable event handles) (CommandLineToSpawn)\n"),
				argv[0]);
		return(0);
	}

	// Construct the full command line
	int nCmdLineLength= MAX_CMD_LINE_LENGTH;
	wchar_t * szCmdLine= (wchar_t *)malloc(nCmdLineLength * sizeof(wchar_t));
	szCmdLine[0]= 0;
	int nPos = 0;

	for(int i = 8; i < argc; ++i)
	{
		int nCpyLen;
		int len= wcslen(argv[i]);
		int requiredSize= nPos+len+2;
		if (requiredSize > 32*1024) {
#ifdef DEBUG_MONITOR
			OutputDebugStringW(_T("Command line too long!\n"));
#endif
			return 0;
		}
		ensureSize(&szCmdLine, &nCmdLineLength, requiredSize);
		if (NULL == szCmdLine) {
#ifdef DEBUG_MONITOR
			OutputDebugStringW(_T("Not enough memory to build cmd line!\n"));
#endif
			return 0;
		}
		if(0 > (nCpyLen = copyTo(szCmdLine + nPos, argv[i], len, nCmdLineLength - nPos)))
		{
#ifdef DEBUG_MONITOR
			OutputDebugStringW(_T("Not enough space to build command line\n"));
#endif
			return 0;
		}
		nPos += nCpyLen;
		szCmdLine[nPos] = _T(' ');
		++nPos;
	}
	szCmdLine[nPos] = _T('\0');

	STARTUPINFOW si = {sizeof(si)};
	PROCESS_INFORMATION pi = {0};
	DWORD dwExitCode = 0;
#ifdef DEBUG_MONITOR
	int currentPID = GetCurrentProcessId();
	wchar_t buffer[MAX_CMD_LINE_LENGTH];
#endif

	BOOL exitProc = FALSE;
	HANDLE waitEvent = OpenEventW(EVENT_ALL_ACCESS, TRUE, argv[4]);
	HANDLE h[5];
	h[0] = OpenEventW(EVENT_ALL_ACCESS, TRUE, argv[3]);	// simulated SIGINT (CTRL-C or Cygwin 'kill -SIGINT')
//  h[1] we reserve for the process handle
	h[2] = OpenEventW(EVENT_ALL_ACCESS, TRUE, argv[5]); // simulated SIGTERM
	h[3] = OpenEventW(EVENT_ALL_ACCESS, TRUE, argv[6]); // simulated SIGKILL
	h[4] = OpenEventW(EVENT_ALL_ACCESS, TRUE, argv[7]); // CTRL-C, in all cases
	
	SetConsoleCtrlHandler(HandlerRoutine, TRUE);

	int parentPid = wcstol(argv[1], NULL, 10);
	int nCounter = wcstol(argv[2], NULL, 10);
	wchar_t inPipeName[PIPE_NAME_LENGTH];
	wchar_t outPipeName[PIPE_NAME_LENGTH];
	wchar_t errPipeName[PIPE_NAME_LENGTH];

	swprintf(inPipeName, L"\\\\.\\pipe\\stdin%08i%010i", parentPid, nCounter);
	swprintf(outPipeName, L"\\\\.\\pipe\\stdout%08i%010i", parentPid, nCounter);
	swprintf(errPipeName, L"\\\\.\\pipe\\stderr%08i%010i", parentPid, nCounter);
#ifdef DEBUG_MONITOR
	swprintf(buffer, _T("Pipes: %s, %s, %s\n"), inPipeName, outPipeName, errPipeName);
	OutputDebugStringW(buffer);
#endif

	HANDLE stdHandles[3];

	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.bInheritHandle = TRUE;
	sa.lpSecurityDescriptor = NULL;

	if((INVALID_HANDLE_VALUE == (stdHandles[0] = CreateFileW(inPipeName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, &sa))) ||
			(INVALID_HANDLE_VALUE == (stdHandles[1] = CreateFileW(outPipeName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, &sa))) ||
			(INVALID_HANDLE_VALUE == (stdHandles[2] = CreateFileW(errPipeName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, &sa))))
	{
#ifdef DEBUG_MONITOR
		swprintf(buffer, _T("Failed to open pipe %i, %i, %i: %i\n"), stdHandles[0], stdHandles[1], stdHandles[2], GetLastError());
		OutputDebugStringW(buffer);
#endif
		CloseHandle(stdHandles[0]);
		CloseHandle(stdHandles[1]);
		CloseHandle(stdHandles[2]);
		return -1;;
	}
	SetHandleInformation(stdHandles[0], HANDLE_FLAG_INHERIT, TRUE);
	SetHandleInformation(stdHandles[1], HANDLE_FLAG_INHERIT, TRUE);
	SetHandleInformation(stdHandles[2], HANDLE_FLAG_INHERIT, TRUE);

	if(!SetStdHandle(STD_INPUT_HANDLE, stdHandles[0]) ||
			!SetStdHandle(STD_OUTPUT_HANDLE, stdHandles[1]) ||
			!SetStdHandle(STD_ERROR_HANDLE, stdHandles[2])) {
#ifdef DEBUG_MONITOR
		swprintf(buffer, _T("Failed to reassign standard streams: %i\n"), GetLastError());
		OutputDebugStringW(buffer);
#endif
		CloseHandle(stdHandles[0]);
		CloseHandle(stdHandles[1]);
		CloseHandle(stdHandles[2]);
		return -1;;
	}

#ifdef DEBUG_MONITOR
	wchar_t * lpvEnv = GetEnvironmentStringsW();

	// If the returned pointer is NULL, exit.
	if (lpvEnv == NULL)
	OutputDebugStringW(_T("Cannot Read Environment\n"));
	else {
		// Variable strings are separated by NULL byte, and the block is 
		// terminated by a NULL byte. 

		OutputDebugStringW(_T("Starter: Environment\n"));
		for (wchar_t * lpszVariable = (wchar_t *) lpvEnv; *lpszVariable; lpszVariable+=wcslen(lpszVariable) + 1) {
			swprintf(buffer, _T("%s\n"), lpszVariable);
			OutputDebugStringW(buffer);
		}

		FreeEnvironmentStringsW(lpvEnv);
	}
#endif
#ifdef DEBUG_MONITOR
	swprintf(buffer, _T("Starting: %s\n"), szCmdLine);
	OutputDebugStringW(buffer);
#endif
	// Create job object
	HANDLE hJob = CreateJobObject(NULL, NULL);
	
	// Spawn the other processes as part of this Process Group
	BOOL f = CreateProcessW(NULL, szCmdLine, NULL, NULL, TRUE,
			0, NULL, NULL, &si, &pi);

	// We don't need them any more
	CloseHandle(stdHandles[0]);
	CloseHandle(stdHandles[1]);
	CloseHandle(stdHandles[2]);
	
	if (f) {
#ifdef DEBUG_MONITOR
		swprintf(buffer, _T("Process %i started\n"), pi.dwProcessId);
		OutputDebugStringW(buffer);
#endif
		SetEvent(waitEvent); // Means thar process has been spawned
		CloseHandle(pi.hThread);
		h[1] = pi.hProcess;

		if(NULL != hJob) {
			if(!AssignProcessToJobObject(hJob, pi.hProcess)) {
#ifdef DEBUG_MONITOR
				swprintf(buffer, _T("Cannot assign process %i to a job\n"), pi.dwProcessId);
				OutputDebugStringW(buffer);
				DisplayErrorMessage();
#endif
			}
		}

		while(!exitProc)
		{
			// Wait for the spawned-process to die or for the event
			// indicating that the processes should be forcibly killed.
			DWORD event = WaitForMultipleObjects(5, h, FALSE, INFINITE);
			switch (event)
			{
			case WAIT_OBJECT_0 + 0: // SIGINT
			case WAIT_OBJECT_0 + 4: // CTRL-C
#ifdef DEBUG_MONITOR
				swprintf(buffer, _T("starter (PID %i) received CTRL-C event\n"), currentPID);
				OutputDebugStringW(buffer);
#endif
				if ((event == (WAIT_OBJECT_0 + 0)) && isCygwin(h[1])) {
					// Need to issue a kill command
					wchar_t kill[1024];
					swprintf(kill, L"kill -SIGINT %d", pi.dwProcessId);
					if (!runCygwinCommand(kill)) {
						// fall back to console event
						GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
					}
				} else {
					GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
				}

				SetEvent(waitEvent);
				break;

			case WAIT_OBJECT_0 + 1: // App terminated normally
				// Make it's exit code our exit code
#ifdef DEBUG_MONITOR
				swprintf(buffer, _T("starter: launched process has been terminated(PID %i)\n"),
						pi.dwProcessId);
				OutputDebugStringW(buffer);
#endif
				GetExitCodeProcess(pi.hProcess, &dwExitCode);
				exitProc = TRUE;
				break;

			// Terminate and Kill behavior differ only for cygwin processes, where
			// we use the cygwin 'kill' command. We send a SIGKILL in one case,
			// SIGTERM in the other. For non-cygwin processes, both requests
			// are treated exactly the same
			case WAIT_OBJECT_0 + 2:	// TERM
			case WAIT_OBJECT_0 + 3:	// KILL
			{
				const wchar_t* signal = (event == WAIT_OBJECT_0 + 2) ? L"TERM" : L"KILL";
#ifdef DEBUG_MONITOR
				swprintf(buffer, _T("starter received %s event (PID %i)\n"), signal, currentPID);
				OutputDebugStringW(buffer);
#endif
				if (isCygwin(h[1])) {
					// Need to issue a kill command
					wchar_t kill[1024];
					swprintf(kill, L"kill -%s %d", signal, pi.dwProcessId);
					if (!runCygwinCommand(kill)) {
						// fall back to console event
						GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
					}
				} else {				
					GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
				}
				
				SetEvent(waitEvent);
				
				if(NULL != hJob) {
					if(!TerminateJobObject(hJob, (DWORD)-1)) {
#ifdef DEBUG_MONITOR
						OutputDebugStringW(_T("Cannot terminate job\n"));
						DisplayErrorMessage();
#endif
					}
				}

				// Note that we keep trucking until the child process terminates (case WAIT_OBJECT_0 + 1)
				break;
			}

			default:
				// Unexpected code
#ifdef DEBUG_MONITOR
				DisplayErrorMessage();
#endif
				exitProc = TRUE;
				break;
			}

		}
	} else {
#ifdef DEBUG_MONITOR
		swprintf(buffer, _T("Cannot start: %s\n"), szCmdLine);
		OutputDebugStringW(buffer);

		DisplayErrorMessage();
#endif
	}

	if (NULL != szCmdLine)
	{
		free(szCmdLine);
	}

	CloseHandle(waitEvent);
	CloseHandle(h[0]);
	CloseHandle(h[1]);
	CloseHandle(h[2]);
	CloseHandle(h[3]);
	CloseHandle(h[4]);

	return(dwExitCode);
}
Exemplo n.º 16
0
int __cdecl main( int argc, char **argv )

{
    /* local variables */
    BOOL                    ret = FAIL;
    DWORD                   dwRet = 0;
    HANDLE                  hEvent = NULL;
    HANDLE                  hTestEvent = NULL;
    LPSECURITY_ATTRIBUTES   lpEventAttributes = NULL;
    BOOL                    bManualReset = TRUE;
    BOOL                    bInitialState = FALSE;
    LPSTR                   lpNameA = "ShakeIt";
    WCHAR                   wcName[] = {'S','h','a','k','e','I','t','\0'};
    LPWSTR                  lpNameW = wcName;


    /* PAL initialization */
    if( (PAL_Initialize(argc, argv)) != 0 )
    {
        return( FAIL );
    }


    /* create an event which we can use with SetEvent */
    hEvent = CreateEventA(  lpEventAttributes,
                            bManualReset,
                            bInitialState,
                            lpNameA );

    if( hEvent == NULL )
    {
        /* ERROR */
        Fail( "ERROR:%lu:CreateEvent() call failed\n", GetLastError() );
    }

    /* open a new handle to our event */
    hTestEvent = OpenEventW(EVENT_ALL_ACCESS,  /* we want all rights */
                            FALSE,             /* no inherit         */
                            lpNameW );

    if( hTestEvent == NULL )
    {
        /* ERROR */
        Trace( "ERROR:%lu:OpenEventW() call failed\n", GetLastError() );
        goto cleanup;
    }

    /* verify that the event isn't signalled yet by waiting on both */
    /* handles to the event object                                  */
    dwRet = WaitForSingleObject( hEvent, 0 );
    if( dwRet != WAIT_TIMEOUT )
    {
        /* ERROR */
        Trace( "ERROR:WaitForSingleObject() call returned %lu, "
                "expected WAIT_TIMEOUT\n",
                dwRet );
        goto cleanup;
    }

    dwRet = WaitForSingleObject( hTestEvent, 0 );
    if( dwRet != WAIT_TIMEOUT )
    {
        /* ERROR */
        Trace( "ERROR:WaitForSingleObject() call returned %lu, "
                "expected WAIT_TIMEOUT\n",
                dwRet );
        goto cleanup;
    }


    /* set the event using the original handle */
    if( ! SetEvent( hEvent ) )
    {
        /* ERROR */
        Trace( "ERROR:%lu:SetEvent() call failed\n", GetLastError() );
        goto cleanup;
    }

    /* verify that the event is signalled by waiting on both handles */
    dwRet = WaitForSingleObject( hEvent, 0 );
    if( dwRet != WAIT_OBJECT_0 )
    {
        /* ERROR */
        Trace( "ERROR:WaitForSingleObject() call returned %lu, "
                "expected WAIT_OBJECT_0\n",
                dwRet );
        goto cleanup;
    }

    dwRet = WaitForSingleObject( hTestEvent, 0 );
    if( dwRet != WAIT_OBJECT_0 )
    {
        /* ERROR */
        Trace( "ERROR:WaitForSingleObject() call returned %lu, "
                "expected WAIT_OBJECT_0\n",
                dwRet );
        goto cleanup;
    }

    /* reset the event using the new handle */
    if( ! ResetEvent( hTestEvent ) )
    {
        /* ERROR */
        Trace( "ERROR:%lu:ResetEvent() call failed\n", GetLastError() );
        goto cleanup;
    }

    /* verify that the event isn't signalled by waiting on both  handles */
    dwRet = WaitForSingleObject( hEvent, 0 );
    if( dwRet != WAIT_TIMEOUT )
    {
        /* ERROR */
        Trace( "ERROR:WaitForSingleObject() call returned %lu, "
                "expected WAIT_TIMEOUT\n",
                dwRet );
        goto cleanup;
    }

    dwRet = WaitForSingleObject( hTestEvent, 0 );
    if( dwRet != WAIT_TIMEOUT )
    {
        /* ERROR */
        Trace( "ERROR:WaitForSingleObject() call returned %lu, "
                "expected WAIT_TIMEOUT\n",
                dwRet );
        goto cleanup;
    }


    /* test was successful */
    ret = PASS;


cleanup:
    /* close the new event handle */
    if( hTestEvent != NULL )
    {
        if( ! CloseHandle( hTestEvent ) )
        {
            ret = FAIL;
            Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() );
        }
    }

    /* close the original event handle */
    if( ! CloseHandle( hEvent ) )
    {
        ret = FAIL;
        Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() );
    }

    /* failure message */
    if( ret != PASS )
    {
        Fail( "Test failed\n" );
    }


    /* PAL termination */
    PAL_Terminate();

    /* return success or failure */
    return ret;
}
Exemplo n.º 17
0
int __cdecl main(int argc, char **argv)
{
    HANDLE  hCreateEvent;
    HANDLE  hOpenEvent;
    HANDLE  hDupEvent;
    WCHAR   lpEventName[]={'E','v','e','n','t','\0'};

    /*Initialize the PAL.*/
    if ((PAL_Initialize(argc,argv)) != 0)
    {
        return (FAIL);
    }
    
    /*Create an Event, and set it in the signaled state.*/
    hCreateEvent = CreateEventW(0,
                                TRUE, 
                                TRUE, 
                                lpEventName);
    if (hCreateEvent == NULL)
    {
        Fail("ERROR: %u :unable to create event %s\n", 
              GetLastError(),
              lpEventName);
    }

    /*Open another handle to hCreateHandle with OpenEvent*/
    hOpenEvent = OpenEventW(EVENT_ALL_ACCESS,
                            TRUE,
                            lpEventName);
    if (hOpenEvent == NULL)
    {
        Trace("ERROR: %u :unable to create handle with OpenEvent to %s\n",
             GetLastError(),
             lpEventName);
        CloseHandle(hCreateEvent);
        Fail("");
    }

    /*Create a duplicate Event handle*/
    if (!(DuplicateHandle(GetCurrentProcess(), 
                          hOpenEvent,
                          GetCurrentProcess(),
                          &hDupEvent,
                          GENERIC_READ|GENERIC_WRITE,
                          FALSE, 
                          DUPLICATE_SAME_ACCESS)))
    {
        Trace("ERROR: %u :Fail to create the duplicate handle"
                " to hCreateEvent=0x%lx\n",
                GetLastError(),
                hCreateEvent);
        CloseHandle(hCreateEvent);
        CloseHandle(hOpenEvent);
        Fail("");
    }

    /*Perform wait on Event that is in signaled state*/
    if ((WaitForSingleObject(hOpenEvent, 1000)) != WAIT_OBJECT_0)
    {
        Trace("ERROR: %u :WaitForSignalObject on hOpenEvent=0x%lx set to "
                " signaled state failed\n",
                GetLastError(),
                hOpenEvent);
        CloseHandle(hCreateEvent);
        CloseHandle(hOpenEvent);
        CloseHandle(hDupEvent);
        Fail("");
    }

    /*Set the Duplicate Event handle to nonsignaled state*/
    if ((ResetEvent(hDupEvent)) == 0)
    {
        Trace("ERROR: %u: unable to reset hDupEvent=0x%lx\n", 
             GetLastError(),
             hDupEvent);
        CloseHandle(hCreateEvent);
        CloseHandle(hOpenEvent);
        CloseHandle(hDupEvent);
        Fail("");
    }

    /*Perform wait on Event that is in signaled state*/
    if ((WaitForSingleObject(hOpenEvent, 1000)) == WAIT_OBJECT_0)
    {
        Trace("ERROR: %u :WaitForSignalObject succeeded on hOpenEvent=0x%lx "
                " when Duplicate hDupEvent=0x%lx set to nonsignaled state"
                " succeeded\n",
                GetLastError(),
                hOpenEvent,
                hDupEvent);
        CloseHandle(hCreateEvent);
        CloseHandle(hOpenEvent);
        CloseHandle(hDupEvent);
        Fail("");
    }

    /*Close handles the events*/
    CloseHandle(hCreateEvent);
    CloseHandle(hOpenEvent);
    CloseHandle(hDupEvent);

    PAL_Terminate();
    return (PASS);
}
Exemplo n.º 18
0
int __cdecl main(int argc, char **argv)
{
    int i, iRet;
    BOOL bRet;
    BOOL bNamedEvent = 0;
    BOOL bMutex = 0;
    BOOL bMutexAndNamedEvent = 0;
    BOOL bSemaphore = 0;
    DWORD dwRet;
    HANDLE hNamedEvent;
    HANDLE hMutex;
    char szTestName[256];
    WCHAR wszTestName[256] = { 0 };
    char szEventName[128] = { 0 };
    char szMutexName[128] = { 0 };
    char szSemName[128] = { 0 };
    WCHAR wszEventName[128];
    WCHAR wszMutexName[128];
    WCHAR wszSemName[128];
    DWORD iExitCode = 0;
    HANDLE hSemaphore;
    
    if(0 != (PAL_Initialize(argc, argv)))
    {
        return ( FAIL );
    }

    Trace("[child] Starting\n");

    for (i=1; i<argc; i++)
    {
        if (0 == strcmp(argv[i],"-event"))
        {
            bNamedEvent = 1;
        }
        else if (0 == strcmp(argv[i],"-mutex"))
        {
            bMutex = 1;
        }
        else if (0 == strcmp(argv[i],"-mutex_and_named_event"))
        {
            bMutexAndNamedEvent = 1;
        }
        else if (0 == strcmp(argv[i],"-semaphore"))
        {
            bSemaphore = 1;
        }
        else if (0 == strcmp(argv[i],"-exitcode") && i < argc-1 )
        {
            i++;
            iExitCode = atoi(argv[i]);
            Trace("[child] My exit code is %d\n", iExitCode);
        }

        else if ('-' != *argv[i])
        {
            strncpy(szTestName, argv[i], 256);
            szTestName[255] = 0;
            iRet = MultiByteToWideChar(CP_ACP, 0, szTestName, strlen(szTestName)+1, wszTestName, 256);            
            if (0 == iRet)
            {
                Fail("Failed to convert test string\n");
            }
        }
    }

    sprintf_s(szEventName, 128, "%s_Event", szTestName);
    szEventName[127] = 0;
    sprintf_s(szMutexName, 128, "%s_Mutex", szTestName);
    szMutexName[127] = 0;
    sprintf_s(szSemName, 128, "%s_Semaphore", szTestName);
    szSemName[127] = 0;

    iRet = MultiByteToWideChar(CP_ACP, 0, szEventName, strlen(szEventName)+1, wszEventName, 128);
    iRet &= MultiByteToWideChar(CP_ACP, 0, szMutexName, strlen(szMutexName)+1, wszMutexName, 128);
    iRet &= MultiByteToWideChar(CP_ACP, 0, szSemName, strlen(szSemName)+1, wszSemName, 128);
    if (0 == iRet)
    {
        Fail("[child] Failed to convert strings\n");
    }

    Trace("[child] TestName=%s Event: %S, Mutex: %S, Semaphore = %S\n",
          szTestName, wszEventName, wszMutexName, wszSemName);

    hNamedEvent = OpenEventW(0, FALSE, wszEventName);
    if (NULL == hNamedEvent)
    {
        Fail("[child] OpenEventW failed [szEventName=%s GetLastError()=%u]\n",
             szEventName, GetLastError());
    }
    hMutex = OpenMutexW(0, FALSE, wszMutexName);
    if (NULL == hMutex)
    {
        Fail("[child] OpenMutexW failed [GetLastError()=%u]\n", 
             GetLastError());
    }
    hSemaphore = CreateSemaphoreW(NULL, 0, 256, wszSemName);
    if (NULL == hSemaphore)
    {
        Fail("[child] CreateSemaphore failed [GetLastError()=%u]\n",
             GetLastError());
    }

    
    if (bMutex)
    {    
        Trace("[child] Going to wait on mutex %s\n", szMutexName);
        dwRet = WaitForSingleObject(hMutex, INFINITE);
        if (WAIT_FAILED == dwRet)
        {
            Fail("[child] WaitForMultipleObjects failed [GetLastError()=%u]\n",
                 GetLastError());
        }

        Trace("[child] Setting event %s\n", szEventName);
        bRet = SetEvent(hNamedEvent);
        if (FALSE == bRet)
        {
            Fail("[child] SetEvent failed [GetLastError()=%u]\n",
                 GetLastError());
        }

        // mutex will be abandoned        
    }
    else if (bMutexAndNamedEvent)
    {    
        dwRet = WaitForSingleObject(hMutex, INFINITE);
        if (WAIT_FAILED == dwRet)
        {
            Fail("[child] WaitForMultipleObjects failed [GetLastError()=%u]\n",
                 GetLastError());
        }

        Sleep(2000);

        bRet = ReleaseMutex(hMutex);
        if (FALSE == bRet)
        {
            Fail("[child] ReleaseMutex failed [GetLastError()=%u]\n",
                 GetLastError());
        }

        Sleep(1000);

        bRet = SetEvent(hNamedEvent);
        if (FALSE == bRet)
        {
            Fail("[child] SetEvent failed [GetLastError()=%u]\n",
                 GetLastError());
        }
    }
    else if (bSemaphore)
    {
        LONG lPrevCount = 42;        


        Trace("[child] Going to wait on event %s\n", szEventName);
        dwRet = WaitForSingleObject(hNamedEvent, INFINITE);
        if (WAIT_FAILED == dwRet)
        {
            Fail("[child] WaitForMultipleObjects failed [GetLastError()=%u]\n",
                 GetLastError());
        }

        Trace("[child] Releasing semaphore %s\n", szSemName);
        bRet = ReleaseSemaphore(hSemaphore, 10, &lPrevCount);
        if (FALSE == bRet)
        {
            Fail("ReleaseMutex failed [GetLastError()=%u]\n",
                 GetLastError());
        }
        if (0 != lPrevCount)
        {
            Fail("Previous count from semaphore=%d, expected 0\n", lPrevCount);
        }        
    }
    else if (bNamedEvent)
    {   
        Sleep(1000);
    
        bRet = SetEvent(hNamedEvent);
        if (FALSE == bRet)
        {
            Fail("[child] SetEvent failed [GetLastError()=%u]\n",
                 GetLastError());
        }
    }

    Sleep(1000);

    Trace("[child] Done\n");
   
    PAL_TerminateEx(iExitCode);
    return iExitCode;
}
Exemplo n.º 19
0
 int __cdecl main(INT argc, CHAR **argv)
{
    unsigned int i = 0;
    HANDLE hThread[MAXIMUM_WAIT_OBJECTS];
    DWORD  threadId[MAXIMUM_WAIT_OBJECTS];

    WCHAR *wcObjName = NULL;

    char ObjName[MAX_PATH] = "SHARED_EVENT";
    DWORD dwParam = 0;

    int returnCode = 0;
    
    /* Variables to capture the file name and the file pointer at thread level*/
    char fileName[MAX_PATH];
    FILE *pFile = NULL;
    struct statistics* buffer = NULL;
    int statisticsSize = 0;

    /* Variables to capture the file name and the file pointer at process level*/
    char processFileName[MAX_PATH];
    FILE *pProcessFile = NULL;   
    struct ProcessStats processStats;
    DWORD dwStartTime;

    testStatus = PASS;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return ( FAIL );
    }

    ZeroMemory( objectSuffix, MAX_PATH );

    if(GetParameters(argc, argv))
    {
        Fail("Error in obtaining the parameters\n");
    }
//    Trace("Process created, value of process count is [%d]\n", USE_PROCESS_COUNT);

    if(argc == 5)
    {
        strncat(ObjName, objectSuffix, MAX_PATH - (sizeof(ObjName) + 1) );
    }

     /* Register the start time */  
    dwStartTime = GetTickCount();
    processStats.relationId = RELATION_ID;
    processStats.processId  = USE_PROCESS_COUNT;

    _snprintf(processFileName, MAX_PATH, "%d_process_event_%d_.txt", USE_PROCESS_COUNT, RELATION_ID);
    pProcessFile = fopen(processFileName, "w+");
    if(pProcessFile == NULL)
    { 
        Fail("Error:%d: in opening Process File for write for process [%d]\n", GetLastError(), USE_PROCESS_COUNT);
    }

    statisticsSize = sizeof(struct statistics);

    _snprintf(fileName, MAX_PATH, "%d_thread_event_%d_.txt", USE_PROCESS_COUNT, RELATION_ID);
    pFile = fopen(fileName, "w+");
    
    if(pFile == NULL)
    { 
        Fail("Error:%d: in opening thread file for write for process [%d]\n", GetLastError(), USE_PROCESS_COUNT);
    }
    // For each thread we will log operations failed (int), passed (int), total (int)
    // and number of ticks (DWORD) for the operations
    resultBuffer = new ResultBuffer( THREAD_COUNT, statisticsSize);

    wcObjName = convert(ObjName);

    StartTestsEvHandle  = CreateEvent( NULL, /* lpEventAttributes*/
                                        TRUE,  /* bManualReset */
                                        FALSE,   /* bInitialState */
                                        NULL);  /* name of Event */

    if( StartTestsEvHandle  == NULL )
    {
        Fail("Error:%d: Unexpected failure "
            "to create %s Event for process count %d\n", GetLastError(), sTmpEventName, USE_PROCESS_COUNT );
  
    }

    /* Create StartTest Event */

    hEventHandle = OpenEventW(
                                EVENT_ALL_ACCESS, /* lpEventAttributes, inheritable to child processes*/
                                FALSE,  /* bAutomaticReset */
                                wcObjName  
                               );
            
    if( hEventHandle == NULL)
    {
        Fail("Unable to create Event handle for process id [%d], returned error [%d]\n", i, GetLastError());
    }
    /* We already assume that the Event was created previously*/

    for( i = 0; i < THREAD_COUNT; i++ )
    {
        dwParam = (int) i;
        //Create thread
        hThread[i] = CreateThread(
                                    NULL,                   /* no security attributes */
                                    0,                      /* use default stack size */
                                    (LPTHREAD_START_ROUTINE)Run_Thread,/* thread function */
                                    (LPVOID)dwParam,  /* argument to thread function */
                                    0,                      /* use default creation flags  */
                                    &threadId[i]     /* returns the thread identifier*/                                  
                                  );
  
        if(hThread[i] == NULL)
        {
            Fail("Create Thread failed for %d process, and GetLastError value is %d\n", USE_PROCESS_COUNT, GetLastError());
        }
    
    }

    if (!SetEvent(StartTestsEvHandle))
    {
        Fail("Set Event for Start Tests failed for %d process, and GetLastError value is %d\n", USE_PROCESS_COUNT, GetLastError());           
    }

    /* Test running */
    returnCode = WaitForMultipleObjects( THREAD_COUNT, hThread, TRUE, INFINITE);  

    if( WAIT_OBJECT_0 != returnCode )
    {
        Trace("Wait for Object(s) for %d process returned %d, and GetLastError value is %d\n", USE_PROCESS_COUNT, returnCode, GetLastError());
        testStatus = FAIL;
    }
    
    processStats.operationTime = GetTimeDiff(dwStartTime);  

    /* Write to a file*/
    if(pFile!= NULL)
    { 
        for( i = 0; i < THREAD_COUNT; i++ )
        {  
            buffer = (struct statistics *)resultBuffer->getResultBuffer(i);
            returnCode = fprintf(pFile, "%d,%d,%d,%d,%lu,%d\n", buffer->processId, buffer->operationsFailed, buffer->operationsPassed, buffer->operationsTotal, buffer->operationTime, buffer->relationId );
//            Trace("Iteration %d over\n", i);
            
        }
    }

    if(fclose(pFile))
    {
        Trace("Error: fclose failed for pFile at Process %d\n", USE_PROCESS_COUNT);
        testStatus = FAIL;
    }

    fprintf(pProcessFile, "%d,%d,%d\n", USE_PROCESS_COUNT, processStats.operationTime, processStats.relationId );
    if(fclose(pProcessFile))
    {
        Trace("Error: fclose failed for pProcessFile at Process %d\n", USE_PROCESS_COUNT);
        testStatus = FAIL;
    }
    /* Logging for the test case over, clean up the handles */

//    Trace("Test Thread %d done\n", USE_PROCESS_COUNT);
    
    for( i = 0; i < THREAD_COUNT; i++ )
    {
        if(!CloseHandle(hThread[i]) )
        {
            Trace("Error:%d: CloseHandle failed for Process [%d] hThread[%d]\n", GetLastError(), USE_PROCESS_COUNT, i);
            testStatus = FAIL;
        }
    }

    if(!CloseHandle(StartTestsEvHandle))
    {
        Trace("Error:%d: CloseHandle failed for Process [%d] StartTestsEvHandle\n", GetLastError(), USE_PROCESS_COUNT);
        testStatus = FAIL;
    }

    if(!CloseHandle(hEventHandle))
    {
        Trace("Error:%d: CloseHandle failed for Process [%d] hEventHandle\n", GetLastError(), USE_PROCESS_COUNT);
        testStatus = FAIL;
    } 

    free(wcObjName);
    PAL_Terminate();
    return testStatus;
}
Exemplo n.º 20
0
int __cdecl main( int argc, char **argv )

{
    /* local variables */
    BOOL                    bRet = PASS;
    DWORD                   dwLastError = 0;
    HANDLE                  hMutex = NULL;
    HANDLE                  hTestEvent = NULL;
    LPSECURITY_ATTRIBUTES   lpSecurityAttributes = NULL;
    BOOL                    bInitialState = TRUE;
    WCHAR                   wcName[] = {'I','m','A','M','u','t','e','x','\0'};
    LPWSTR                  lpName = wcName;


    /* PAL initialization */
    if( (PAL_Initialize(argc, argv)) != 0 )
    {
        return( FAIL );
    }

    /* create a mutex object */
    hMutex = CreateMutexW(  lpSecurityAttributes,
                             bInitialState,
                             lpName );

    if( hMutex == NULL )
    {
        /* ERROR */
        Fail( "ERROR:%lu:CreateMutexW() call failed\n", GetLastError() );
    }

    /* open a new handle to our event */
    hTestEvent = OpenEventW(EVENT_ALL_ACCESS,  /* we want all rights */
                            FALSE,             /* no inherit         */
                            lpName );

    if( hTestEvent != NULL )
    {
        /* ERROR */
        Trace( "ERROR:OpenEventW() call succeeded against a named "
                "mutex, should have returned NULL\n" );
        if( ! CloseHandle( hTestEvent ) )
        {
            Trace( "ERROR:%lu:CloseHandle() call failed \n", GetLastError() );
        }
        bRet = FAIL;
    }
    else
    {
        dwLastError = GetLastError();
        if( dwLastError != ERROR_INVALID_HANDLE )
        {
            /* ERROR */
            Trace( "ERROR:OpenEventW() call failed against a named "
                    "mutex, but returned an unexpected result: %lu\n",
                    dwLastError );
            bRet = FAIL;
        }
    }


    /* close the mutex handle */
    if( ! CloseHandle( hMutex ) )
    {
        Trace( "ERROR:%lu:CloseHandle() call failed \n", GetLastError() );
        bRet = FAIL;
    }


    /* fail here if we weren't successful */
    if( bRet == FAIL )
    {
        Fail( "" );
    }


    /* PAL termination */
    PAL_Terminate();

    /* return success or failure */
    return PASS;
}
Exemplo n.º 21
0
void D3D9Capture(IDirect3DDevice9* device) {
	h3d::EventProcess();

	if (!has_textured && capture_run) {

		//fix for some [backbuffers aren't actually being properly used]
		//get size/format at actual current rt at time of present
		IDirect3DSurface9* back_buffer = NULL;
		if (SUCCEEDED(device->GetRenderTarget(0, &back_buffer))) {
			D3DSURFACE_DESC sd;
			ZeroMemory(&sd, sizeof(sd));

			if (SUCCEEDED(back_buffer->GetDesc(&sd))) {
				//todo something
			}

			back_buffer->Release();
		}


		if (gpu_support)
			CreateD3D9GPUCapture(device);
		else
			CreateCPUCapture(device);
	}

	//KeeapAliveProcess(Flush()) Crash In Xp(WMware Workstation)
	//I Think Cry
	if (capture_run) {
			LONGLONG capture_tp = h3d::GetOSMillSeconds(); 
			if (capture_tp - prev_point > KEEP_TIME_DURATION) {
					HANDLE keepAlive = OpenEventW(EVENT_ALL_ACCESS, FALSE, sKeepAlive.c_str()); 
					if (keepAlive)
						CloseHandle(keepAlive); 
					else {
							Flush();
							logstream << "Don't Exist Event[" << sKeepAlive << "] (OBS Process Unexpected Exit,Wait Next Begin Event)" << std::endl;
							capture_run = false; 
					}
						prev_point = capture_tp; 
			}
	}
	//todo some keep alive state check

	if (has_textured && capture_run) {
		if (gpu_support)
			D3D9CaptureGPU(device);
		else {
			//copy texture data only when GetRenderTargetData completes
			for (UINT i = 0; i != NUM_BACKBUFF; ++i) {
				if (issued_querys[i]) {
					if (d3d9_querys[i]->GetData(0, 0, 0) == S_OK) {
						issued_querys[i] = false;

						IDirect3DSurface9* texture = d3d9_textures[i];
						D3DLOCKED_RECT locked_rect;

						if (SUCCEEDED(texture->LockRect(&locked_rect, NULL, D3DLOCK_READONLY))) {
							copy_data = locked_rect.pBits;
							copy_index = i;
							locked_textures[i] = true;

							SetEvent(copy_event);
						}
					}
				}
			}

			//todo fps maintain
			DWORD next_capture = (curr_capture == NUM_BACKBUFF - 1) ? 0 : (curr_capture + 1);
			IDirect3DSurface9* src_texture = d3d9_copytextures[curr_capture];
			IDirect3DSurface9* back_buffer = NULL;

			if (SUCCEEDED(device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &back_buffer))) {
				device->StretchRect(back_buffer, NULL, src_texture, NULL, D3DTEXF_NONE);
				back_buffer->Release();

				if (copy_wait < NUM_BACKBUFF - 1)
					++copy_wait;//直到填满三个
				else {
					IDirect3DSurface9* prev_texture = d3d9_copytextures[next_capture];
					IDirect3DSurface9* target_texture = d3d9_textures[next_capture];

					if (locked_textures[next_capture]) {
						EnterCriticalSection(&data_mutexs[next_capture]);

						target_texture->UnlockRect();
						locked_textures[next_capture] = false;

						LeaveCriticalSection(&data_mutexs[next_capture]);
					}

					if (FAILED(device->GetRenderTargetData(prev_texture, target_texture)))
						logstream << "Failed captureing frame via cpu" << std::endl;

					d3d9_querys[next_capture]->Issue(D3DISSUE_END);
					issued_querys[next_capture] = true;

					//logstream << "Successfully captureing frame via cpu" << std::endl;
				}
			}

			curr_capture = next_capture;
		}
	}
	else if (has_textured)
		Flush();
}
Exemplo n.º 22
0
//  Returns -1 if we could not make the socket pair successfully
int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_)
{
#if defined ZMQ_HAVE_EVENTFD
    fd_t fd = eventfd (0, 0);
    if (fd == -1) {
        errno_assert (errno == ENFILE || errno == EMFILE);
        *w_ = *r_ = -1;
        return -1;
    }
    else {
        *w_ = *r_ = fd;
        return 0;
    }

#elif defined ZMQ_HAVE_WINDOWS
#   if !defined _WIN32_WCE
    // Windows CE does not manage security attributes
    SECURITY_DESCRIPTOR sd;
    SECURITY_ATTRIBUTES sa;
    memset (&sd, 0, sizeof sd);
    memset (&sa, 0, sizeof sa);

    InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl (&sd, TRUE, 0, FALSE);

    sa.nLength = sizeof (SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = &sd;
#   endif

    //  This function has to be in a system-wide critical section so that
    //  two instances of the library don't accidentally create signaler
    //  crossing the process boundary.
    //  We'll use named event object to implement the critical section.
    //  Note that if the event object already exists, the CreateEvent requests
    //  EVENT_ALL_ACCESS access right. If this fails, we try to open
    //  the event object asking for SYNCHRONIZE access only.
    HANDLE sync = NULL;

    //  Create critical section only if using fixed signaler port
    //  Use problematic Event implementation for compatibility if using old port 5905.
    //  Otherwise use Mutex implementation.
    int event_signaler_port = 5905;

    if (signaler_port == event_signaler_port) {
#       if !defined _WIN32_WCE
        sync = CreateEventW (&sa, FALSE, TRUE, L"Global\\zmq-signaler-port-sync");
#       else
        sync = CreateEventW (NULL, FALSE, TRUE, L"Global\\zmq-signaler-port-sync");
#       endif
        if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED)
            sync = OpenEventW (SYNCHRONIZE | EVENT_MODIFY_STATE,
                              FALSE, L"Global\\zmq-signaler-port-sync");

        win_assert (sync != NULL);
    }
    else
    if (signaler_port != 0) {
        wchar_t mutex_name [MAX_PATH];
#       ifdef __MINGW32__
        _snwprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d", signaler_port);
#       else
        swprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d", signaler_port);
#       endif

#       if !defined _WIN32_WCE
        sync = CreateMutexW (&sa, FALSE, mutex_name);
#       else
        sync = CreateMutexW (NULL, FALSE, mutex_name);
#       endif
        if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED)
            sync = OpenMutexW (SYNCHRONIZE, FALSE, mutex_name);

        win_assert (sync != NULL);
    }

    //  Windows has no 'socketpair' function. CreatePipe is no good as pipe
    //  handles cannot be polled on. Here we create the socketpair by hand.
    *w_ = INVALID_SOCKET;
    *r_ = INVALID_SOCKET;

    //  Create listening socket.
    SOCKET listener;
    listener = open_socket (AF_INET, SOCK_STREAM, 0);
    wsa_assert (listener != INVALID_SOCKET);

    //  Set SO_REUSEADDR and TCP_NODELAY on listening socket.
    BOOL so_reuseaddr = 1;
    int rc = setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
        (char *) &so_reuseaddr, sizeof so_reuseaddr);
    wsa_assert (rc != SOCKET_ERROR);
    BOOL tcp_nodelay = 1;
    rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY,
        (char *) &tcp_nodelay, sizeof tcp_nodelay);
    wsa_assert (rc != SOCKET_ERROR);

    //  Init sockaddr to signaler port.
    struct sockaddr_in addr;
    memset (&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
    addr.sin_port = htons (signaler_port);

    //  Create the writer socket.
    *w_ = open_socket (AF_INET, SOCK_STREAM, 0);
    wsa_assert (*w_ != INVALID_SOCKET);

    //  Set TCP_NODELAY on writer socket.
    rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY,
        (char *) &tcp_nodelay, sizeof tcp_nodelay);
    wsa_assert (rc != SOCKET_ERROR);

    if (sync != NULL) {
        //  Enter the critical section.
        DWORD dwrc = WaitForSingleObject (sync, INFINITE);
        zmq_assert (dwrc == WAIT_OBJECT_0 || dwrc == WAIT_ABANDONED);
    }

    //  Bind listening socket to signaler port.
    rc = bind (listener, (const struct sockaddr *) &addr, sizeof addr);

    if (rc != SOCKET_ERROR && signaler_port == 0) {
        //  Retrieve ephemeral port number
        int addrlen = sizeof addr;
        rc = getsockname (listener, (struct sockaddr *) &addr, &addrlen);
    }

    //  Listen for incoming connections.
    if (rc != SOCKET_ERROR)
        rc = listen (listener, 1);

    //  Connect writer to the listener.
    if (rc != SOCKET_ERROR)
        rc = connect (*w_, (struct sockaddr *) &addr, sizeof addr);

    //  Accept connection from writer.
    if (rc != SOCKET_ERROR)
        *r_ = accept (listener, NULL, NULL);

    //  Send/receive large chunk to work around TCP slow start
    //  This code is a workaround for #1608
    if (*r_ != INVALID_SOCKET) {
        size_t dummy_size = 1024 * 1024;        //  1M to overload default receive buffer
        unsigned char *dummy = (unsigned char *) malloc (dummy_size);
        int still_to_send = (int) dummy_size;
        int still_to_recv = (int) dummy_size;
        while (still_to_send || still_to_recv) {
            int nbytes;
            if (still_to_send > 0) {
                nbytes = ::send (*w_, (char *) (dummy + dummy_size - still_to_send), still_to_send, 0);
                wsa_assert (nbytes != SOCKET_ERROR);
                still_to_send -= nbytes;
            }
            nbytes = ::recv (*r_, (char *) (dummy + dummy_size - still_to_recv), still_to_recv, 0);
            wsa_assert (nbytes != SOCKET_ERROR);
            still_to_recv -= nbytes;
        }
        free (dummy);
    }

    //  Save errno if error occurred in bind/listen/connect/accept.
    int saved_errno = 0;
    if (*r_ == INVALID_SOCKET)
        saved_errno = WSAGetLastError ();

    //  We don't need the listening socket anymore. Close it.
    closesocket (listener);

    if (sync != NULL) {
        //  Exit the critical section.
        BOOL brc;
        if (signaler_port == event_signaler_port)
            brc = SetEvent (sync);
        else
            brc = ReleaseMutex (sync);
        win_assert (brc != 0);

        //  Release the kernel object
        brc = CloseHandle (sync);
        win_assert (brc != 0);
    }

    if (*r_ != INVALID_SOCKET) {
#   if !defined _WIN32_WCE
        //  On Windows, preventing sockets to be inherited by child processes.
        BOOL brc = SetHandleInformation ((HANDLE) *r_, HANDLE_FLAG_INHERIT, 0);
        win_assert (brc);
#   endif
        return 0;
    }
    else {
        //  Cleanup writer if connection failed
        if (*w_ != INVALID_SOCKET) {
            rc = closesocket (*w_);
            wsa_assert (rc != SOCKET_ERROR);
            *w_ = INVALID_SOCKET;
        }
        //  Set errno from saved value
        errno = wsa_error_to_errno (saved_errno);
        return -1;
    }

#elif defined ZMQ_HAVE_OPENVMS

    //  Whilst OpenVMS supports socketpair - it maps to AF_INET only.  Further,
    //  it does not set the socket options TCP_NODELAY and TCP_NODELACK which
    //  can lead to performance problems.
    //
    //  The bug will be fixed in V5.6 ECO4 and beyond.  In the meantime, we'll
    //  create the socket pair manually.
    struct sockaddr_in lcladdr;
    memset (&lcladdr, 0, sizeof lcladdr);
    lcladdr.sin_family = AF_INET;
    lcladdr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
    lcladdr.sin_port = 0;

    int listener = open_socket (AF_INET, SOCK_STREAM, 0);
    errno_assert (listener != -1);

    int on = 1;
    int rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
    errno_assert (rc != -1);

    rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELACK, &on, sizeof on);
    errno_assert (rc != -1);

    rc = bind (listener, (struct sockaddr *) &lcladdr, sizeof lcladdr);
    errno_assert (rc != -1);

    socklen_t lcladdr_len = sizeof lcladdr;

    rc = getsockname (listener, (struct sockaddr *) &lcladdr, &lcladdr_len);
    errno_assert (rc != -1);

    rc = listen (listener, 1);
    errno_assert (rc != -1);

    *w_ = open_socket (AF_INET, SOCK_STREAM, 0);
    errno_assert (*w_ != -1);

    rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
    errno_assert (rc != -1);

    rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELACK, &on, sizeof on);
    errno_assert (rc != -1);

    rc = connect (*w_, (struct sockaddr *) &lcladdr, sizeof lcladdr);
    errno_assert (rc != -1);

    *r_ = accept (listener, NULL, NULL);
    errno_assert (*r_ != -1);

    close (listener);

    return 0;

#else
    // All other implementations support socketpair()
    int sv [2];
    int rc = socketpair (AF_UNIX, SOCK_STREAM, 0, sv);
    if (rc == -1) {
        errno_assert (errno == ENFILE || errno == EMFILE);
        *w_ = *r_ = -1;
        return -1;
    }
    else {
        *w_ = sv [0];
        *r_ = sv [1];
        return 0;
    }
#endif
}
Exemplo n.º 23
0
int WINAPI wWinMain(HINSTANCE hinstance, HINSTANCE /* hprevinstance */, PWSTR cmdline, int /* cmdshow */)
{
	//AllocConsole();
	//freopen("CONOUT$", "w", stdout);

	auto args = getArgs(cmdline);

	auto standby = args.size() > 2 && args[2] == "standby";

	const auto instanceString = L"XKXjdwnFYYL2eVdB";
	auto singleInstanceEvent = HandlePtr(OpenEventW(EVENT_ALL_ACCESS, false, instanceString));

	if (singleInstanceEvent != nullptr)
	{
		if (!standby)
		{
			auto decision = MessageBox(nullptr, L"There is already an instance "
				"of passchain running. Start anyway?", L"Warning", MB_OKCANCEL);

			if (decision != IDOK)
			{
				return 0;
			}
		}
	}
	else
	{
		singleInstanceEvent = HandlePtr(CreateEventW(nullptr, false, false, instanceString));
	}

	std::unique_ptr<LoginDatabase> database;
	std::string password;
	std::string filename = getFullyQualifiedPathName(args.size() > 1 ? args[1] : "passchain.dat");

	while (database == nullptr)
	{
		try
		{
			PasswordDialogCreateParams params;
			params.password = &password;
			params.filename = &filename;
			params.standby = standby;

			auto result = DialogBoxParamW(hinstance, MAKEINTRESOURCEW(DIALOG_PASSWORD), nullptr,
				dialogProcPassword, reinterpret_cast<LPARAM>(&params));

			if (result == 0)
			{ // Pressed cancel or close button
				return 0;
			}

			database = std::make_unique<LoginDatabase>(std::move(password));

			auto attributes = GetFileAttributesW(toWideString(filename).c_str());

			if (attributes != INVALID_FILE_ATTRIBUTES)
			{
				database->mergeFromEncryptedFile(filename);
			}
		}
		catch (std::exception& e)
		{
			database = nullptr;
			standby = false;
			showMessageBox("Error", e.what());
		}
	}

	bool timeoutQuit = false;

	MainDialogCreateParams mainParams;
	mainParams.database = database.get();
	mainParams.filename = &filename;
	mainParams.timeoutQuit = &timeoutQuit;

	CreateDialogParamW(hinstance, MAKEINTRESOURCE(DIALOG_MAIN), nullptr, 
		dialogProcMain, reinterpret_cast<LPARAM>(&mainParams));

	MSG message;

	while (GetMessageW(&message, nullptr, 0, 0) > 0)
	{
		database->reseedRng(&message, sizeof message);

		if (!IsDialogMessageW(GetParent(message.hwnd), &message))
		{
			TranslateMessage(&message);
			DispatchMessageW(&message);
		}
	}

	if (timeoutQuit)
	{
		auto callString = formatString("%s %s standby", args[0].c_str(), filename.c_str());

		STARTUPINFOA startupInfo = { sizeof startupInfo };
		PROCESS_INFORMATION processInformation;

		if (0 == CreateProcessA(nullptr, &callString[0], nullptr, nullptr,
			false, 0, nullptr, nullptr, &startupInfo, &processInformation))
		{
			showMessageBox("Warning", "Failed to create standby process.");
		}
	}

	return static_cast<int>(message.wParam);
}
Exemplo n.º 24
0
/***********************************************************************
 *           OutputDebugStringA   (KERNEL32.@)
 *
 *  Output by an application of an ascii string to a debugger (if attached)
 *  and program log.
 *
 * PARAMS
 *  str [I] The message to be logged and given to the debugger.
 *
 * RETURNS
 *
 *  Nothing.
 */
void WINAPI OutputDebugStringA( LPCSTR str )
{
    static HANDLE DBWinMutex = NULL;
    static BOOL mutex_inited = FALSE;
    BOOL caught_by_dbg = TRUE;

    if (!str) str = "";
    WARN("%s\n", debugstr_a(str));

    /* raise exception, WaitForDebugEvent() will generate a corresponding debug event */
    __TRY
    {
        ULONG_PTR args[2];
        args[0] = strlen(str) + 1;
        args[1] = (ULONG_PTR)str;
        RaiseException( DBG_PRINTEXCEPTION_C, 0, 2, args );
    }
    __EXCEPT(debug_exception_handler)
    {
        caught_by_dbg = FALSE;
    }
    __ENDTRY
    if (caught_by_dbg) return;

    /* send string to a system-wide monitor */
    if (!mutex_inited)
    {
        /* first call to OutputDebugString, initialize mutex handle */
        static const WCHAR mutexname[] = {'D','B','W','i','n','M','u','t','e','x',0};
        HANDLE mutex = CreateMutexExW( NULL, mutexname, 0, SYNCHRONIZE );
        if (mutex)
        {
            if (InterlockedCompareExchangePointer( &DBWinMutex, mutex, 0 ) != 0)
            {
                /* someone beat us here... */
                CloseHandle( mutex );
            }
        }
        mutex_inited = TRUE;
    }

    if (DBWinMutex)
    {
        static const WCHAR shmname[] = {'D','B','W','I','N','_','B','U','F','F','E','R',0};
        static const WCHAR eventbuffername[] = {'D','B','W','I','N','_','B','U','F','F','E','R','_','R','E','A','D','Y',0};
        static const WCHAR eventdataname[] = {'D','B','W','I','N','_','D','A','T','A','_','R','E','A','D','Y',0};
        HANDLE mapping;

        mapping = OpenFileMappingW( FILE_MAP_WRITE, FALSE, shmname );
        if (mapping)
        {
            LPVOID buffer;
            HANDLE eventbuffer, eventdata;

            buffer = MapViewOfFile( mapping, FILE_MAP_WRITE, 0, 0, 0 );
            eventbuffer = OpenEventW( SYNCHRONIZE, FALSE, eventbuffername );
            eventdata = OpenEventW( EVENT_MODIFY_STATE, FALSE, eventdataname );

            if (buffer && eventbuffer && eventdata)
            {
                /* monitor is present, synchronize with other OutputDebugString invocations */
                WaitForSingleObject( DBWinMutex, INFINITE );

                /* acquire control over the buffer */
                if (WaitForSingleObject( eventbuffer, 10000 ) == WAIT_OBJECT_0)
                {
                    int str_len;
                    struct _mon_buffer_t {
                        DWORD pid;
                        char buffer[1];
                    } *mon_buffer = (struct _mon_buffer_t*) buffer;

                    str_len = strlen( str );
                    if (str_len > (4096 - sizeof(DWORD) - 1))
                        str_len = 4096 - sizeof(DWORD) - 1;

                    mon_buffer->pid = GetCurrentProcessId();
                    memcpy( mon_buffer->buffer, str, str_len );
                    mon_buffer->buffer[str_len] = 0;

                    /* signal data ready */
                    SetEvent( eventdata );
                }
                ReleaseMutex( DBWinMutex );
            }

            if (buffer)
                UnmapViewOfFile( buffer );
            if (eventbuffer)
                CloseHandle( eventbuffer );
            if (eventdata)
                CloseHandle( eventdata );
            CloseHandle( mapping );
        }
    }
}
Exemplo n.º 25
0
/*++
Function:
  CreateEventW

Note:
  Events could be used for cross-process synchroniztion.
  Security Attributes could be ignored.
  lpName could be non NULL.

See MSDN doc.
--*/
HANDLE
PALAPI
CreateEventW(
    IN LPSECURITY_ATTRIBUTES lpEventAttributes,
    IN BOOL bManualReset,
    IN BOOL bInitialState,
    IN LPCWSTR lpName)
{
    HANDLE hEvent = NULL;
    Event *pEvent;
    GLOBAL_EVENT_SYSTEM_OBJECT *pEventInfo;
    SHMPTR newEvent;
    DWORD OldLastError;
    BOOL need_unlock = FALSE;
    LPCWSTR lpObjectName = NULL;
    WCHAR MangledObjectName[MAX_PATH];

    PERF_ENTRY(CreateEventW);
    ENTRY("CreateEventW(lpEventAttr=%p, bManualReset=%d, "
          "bInitialState=%d, lpName=%p (%S)\n", lpEventAttributes, bManualReset,
          bInitialState, lpName?lpName:W16_NULLSTRING, lpName?lpName:W16_NULLSTRING);

    /* Validate parameters */

    if (lpEventAttributes != NULL)
    {
        ASSERT("lpEventAttributes must be NULL\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto CreateEventExit;
    }

    if (lpName)
    {
        lpObjectName=lpName;
        if (!MangleObjectNameW(&lpObjectName, MangledObjectName))
        {
            goto CreateEventExit;
        }

        /* take the shared memory lock to prevent other threads/processes from
           creating/deleting the object behind our back*/
        SHMLock();
        need_unlock = TRUE;

        /* Verify if there's an Event already created with that name */
        OldLastError = GetLastError();

        /* Try to open the event, using its unmangled name, as OpenEventW
               will mangle it */
        hEvent = OpenEventW(EVENT_ALL_ACCESS, FALSE, lpName);

        if (hEvent != NULL)
        {
            TRACE("Event (%S) already exist.\n", lpName);
            SetLastError(ERROR_ALREADY_EXISTS);
            goto CreateEventExit;
        }

        if (GetLastError() == ERROR_INVALID_HANDLE)
        {
            ERROR("Another kernel object is using that name\n");
            SetLastError(ERROR_INVALID_HANDLE);
            goto CreateEventExit;
        }

        SetLastError(OldLastError);
    }

    /* Allocate the event object */
    pEvent = (Event *) malloc(sizeof(Event));

    if (pEvent == NULL)
    {
        ERROR("Unable to allocate memory\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto CreateEventExit;
    }

    /* Allocate the EventInfo in shared memory, so it can be accessible by
       other processes */

    newEvent = SHMalloc(sizeof(GLOBAL_EVENT_SYSTEM_OBJECT));

    if (newEvent == (SHMPTR) NULL)
    {
        ERROR("Unable to allocate shared memory\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        free( pEvent );
        goto CreateEventExit;
    }

    pEvent->objHeader.type = HOBJ_EVENT;
    pEvent->objHeader.close_handle = CloseEventHandle;
    pEvent->objHeader.dup_handle = DupEventHandle;

    pEvent->refCount = 1;
    pEvent->info = newEvent;

    pEventInfo = (GLOBAL_EVENT_SYSTEM_OBJECT*) SHMPTR_TO_PTR(newEvent);
    pEventInfo->refCount = 1;
    pEventInfo->state = bInitialState;
    pEventInfo->manualReset = bManualReset;
    pEventInfo->waitingThreads = (SHMPTR) NULL;
    pEventInfo->next = (SHMPTR) NULL;

    pEventInfo->ShmHeader.ObjectType = SHM_NAMED_EVENTS;
    pEventInfo->ShmHeader.ShmSelf = newEvent;
    if (lpName)
    {
        if ((pEventInfo->ShmHeader.ShmObjectName = SHMWStrDup( lpObjectName )) == 0)
        {
            ERROR( "Unable to allocate shared memory!\n " );
            SetLastError(ERROR_INTERNAL_ERROR);
            SHMfree(newEvent);
            free(pEvent);
            goto CreateEventExit;
        }
    }
    else
    {
        pEventInfo->ShmHeader.ShmObjectName = 0;
    }

    hEvent = HMGRGetHandle((HOBJSTRUCT *) pEvent);

    if (hEvent == INVALID_HANDLE_VALUE)
    {
        if (lpName != NULL)
        {
            SHMfree(pEventInfo->ShmHeader.ShmObjectName);
        }
        SHMfree(newEvent);
        free(pEvent);
        ERROR("Unable to get a free handle\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto CreateEventExit;
    }

    /* Save the EventInfo into the global link list in shared memory.
       (Only if it has a name) */
    if (lpName)
    {
        SHMAddNamedObject(newEvent);
    }

    TRACE("Event created (HANDLE=%p)\n", hEvent);

CreateEventExit:
    if(need_unlock)
    {
        /* release the lock taken before OpenEventW */
        SHMRelease();
    }
    LOGEXIT("CreateEventW returns HANDLE %p\n", hEvent);
    PERF_EXIT(CreateEventW);
    return hEvent;
}
Exemplo n.º 26
0
NTSTATUS WINAPI
LsapInitLsa(VOID)
{
    HANDLE hEvent;
    DWORD dwError;
    NTSTATUS Status;

    TRACE("LsapInitLsa() called\n");

    /* Initialize the well known SIDs */
    LsapInitSids();

    /* Initialize the SRM server */
    Status = LsapRmInitializeServer();
    if (!NT_SUCCESS(Status))
    {
        ERR("LsapRmInitializeServer() failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    /* Initialize the LSA database */
    LsapInitDatabase();

    /* Initialize logon sessions */
    LsapInitLogonSessions();

    /* Initialize registered authentication packages */
    Status = LsapInitAuthPackages();
    if (!NT_SUCCESS(Status))
    {
        ERR("LsapInitAuthPackages() failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    /* Start the authentication port thread */
    Status = StartAuthenticationPort();
    if (!NT_SUCCESS(Status))
    {
        ERR("StartAuthenticationPort() failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    /* Start the RPC server */
    LsarStartRpcServer();

    TRACE("Creating notification event!\n");
    /* Notify the service manager */
    hEvent = CreateEventW(NULL,
                          TRUE,
                          FALSE,
                          L"LSA_RPC_SERVER_ACTIVE");
    if (hEvent == NULL)
    {
        dwError = GetLastError();
        TRACE("Failed to create the notication event (Error %lu)\n", dwError);

        if (dwError == ERROR_ALREADY_EXISTS)
        {
            hEvent = OpenEventW(GENERIC_WRITE,
                                FALSE,
                                L"LSA_RPC_SERVER_ACTIVE");
            if (hEvent == NULL)
            {
               ERR("Could not open the notification event (Error %lu)\n", GetLastError());
               return STATUS_UNSUCCESSFUL;
            }
        }
    }

    TRACE("Set notification event!\n");
    SetEvent(hEvent);

    /* NOTE: Do not close the event handle!!!! */

    return STATUS_SUCCESS;
}
Exemplo n.º 27
0
/***********************************************************************
 *           OutputDebugStringA   (KERNEL32.@)
 *
 *  Output by an application of an ascii string to a debugger (if attached)
 *  and program log.
 *
 * PARAMS
 *  str [I] The message to be logged and given to the debugger.
 *
 * RETURNS
 *
 *  Nothing.
 */
void WINAPI OutputDebugStringA( LPCSTR str )
{
    static HANDLE DBWinMutex = NULL;
    static BOOL mutex_inited = FALSE;

    if (!str) str = "";

    /* send string to attached debugger */
    SERVER_START_REQ( output_debug_string )
    {
        req->string  = wine_server_client_ptr( str );
        req->length  = strlen(str) + 1;
        wine_server_call( req );
    }
    SERVER_END_REQ;

    WARN("%s\n", debugstr_a(str));

    /* send string to a system-wide monitor */
    /* FIXME should only send to monitor if no debuggers are attached */

    if (!mutex_inited)
    {
        /* first call to OutputDebugString, initialize mutex handle */
        static const WCHAR mutexname[] = {'D','B','W','i','n','M','u','t','e','x',0};
        HANDLE mutex = CreateMutexExW( NULL, mutexname, 0, SYNCHRONIZE );
        if (mutex)
        {
            if (InterlockedCompareExchangePointer( &DBWinMutex, mutex, 0 ) != 0)
            {
                /* someone beat us here... */
                CloseHandle( mutex );
            }
        }
        mutex_inited = TRUE;
    }

    if (DBWinMutex)
    {
        static const WCHAR shmname[] = {'D','B','W','I','N','_','B','U','F','F','E','R',0};
        static const WCHAR eventbuffername[] = {'D','B','W','I','N','_','B','U','F','F','E','R','_','R','E','A','D','Y',0};
        static const WCHAR eventdataname[] = {'D','B','W','I','N','_','D','A','T','A','_','R','E','A','D','Y',0};
        HANDLE mapping;

        mapping = OpenFileMappingW( FILE_MAP_WRITE, FALSE, shmname );
        if (mapping)
        {
            LPVOID buffer;
            HANDLE eventbuffer, eventdata;

            buffer = MapViewOfFile( mapping, FILE_MAP_WRITE, 0, 0, 0 );
            eventbuffer = OpenEventW( SYNCHRONIZE, FALSE, eventbuffername );
            eventdata = OpenEventW( EVENT_MODIFY_STATE, FALSE, eventdataname );

            if (buffer && eventbuffer && eventdata)
            {
                /* monitor is present, synchronize with other OutputDebugString invocations */
                WaitForSingleObject( DBWinMutex, INFINITE );

                /* acquire control over the buffer */
                if (WaitForSingleObject( eventbuffer, 10000 ) == WAIT_OBJECT_0)
                {
                    int str_len;
                    struct _mon_buffer_t {
                        DWORD pid;
                        char buffer[1];
                    } *mon_buffer = (struct _mon_buffer_t*) buffer;

                    str_len = strlen( str );
                    if (str_len > (4096 - sizeof(DWORD) - 1))
                        str_len = 4096 - sizeof(DWORD) - 1;

                    mon_buffer->pid = GetCurrentProcessId();
                    memcpy( mon_buffer->buffer, str, str_len );
                    mon_buffer->buffer[str_len] = 0;

                    /* signal data ready */
                    SetEvent( eventdata );
                }
                ReleaseMutex( DBWinMutex );
            }

            if (buffer)
                UnmapViewOfFile( buffer );
            if (eventbuffer)
                CloseHandle( eventbuffer );
            if (eventdata)
                CloseHandle( eventdata );
            CloseHandle( mapping );
        }
    }
}
Exemplo n.º 28
0
int __cdecl main(int argc, char *argv[])
{
     
    BOOL  success = TRUE;  /* assume success */
    struct allhandles_t Comms = {0,0,0} ;

    /* variables to track storage to alter */
    char *pTarget = NULL;
    unsigned int sizeTarget;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    /* hook up with the events created by the parent */
    Comms.hEvToHelper = OpenEventW(EVENT_ALL_ACCESS, 0, szcToHelperEvName);
    if (!Comms.hEvToHelper) 
    {
        Fail("WriteProcessMemory: OpenEvent of '%S' failed (%u). "
             "(the event should already exist!)\n", 
             szcToHelperEvName, GetLastError());
    }
    Comms.hEvFromHelper = OpenEventW(EVENT_ALL_ACCESS, 0, szcFromHelperEvName);
    if (!Comms.hEvToHelper) 
    {
        Trace("WriteProcessMemory: OpenEvent of '%S' failed (%u). "
              "(the event should already exist!)\n",  
              szcFromHelperEvName, GetLastError());
        success = FALSE;
        goto EXIT;
    }
    Comms.valuesFileName = argv[1];

    {
        char autoAllocatedOnStack[51];

        /* Get the parent process to write to the local stack */
        success &= wpmDoIt(Comms, autoAllocatedOnStack, 
                          sizeof(autoAllocatedOnStack),
                          autoAllocatedOnStack + sizeof(int), 
                          sizeof(autoAllocatedOnStack) - 2 * sizeof(int),
                          "const size array on stack with int sized guards");
    }

    /* Get the parent process to write to stuff on the heap */
    sizeTarget =  2 * sizeof(int) + 23 ;  /* 23 is just a random prime > 16 */
    if (!(pTarget = (char*)malloc(sizeTarget))) 
    {
        Trace("WriteProcessMemory helper: unable to allocate '%s'->%d bytes of memory"
              "(%u).\n",
              argv[3], sizeTarget, GetLastError());
        success = FALSE;
        goto EXIT;
        
    }
    success &= wpmDoIt(Comms, pTarget, sizeTarget,
                      pTarget + sizeof(int), 
                      sizeTarget - 2 * sizeof(int),
                      "array on heap with int sized guards");

    /* just to be nice try something 16 - 2 * sizeof(int) bytes long */
    {
        char autoAllocatedOnStack[16];

        /* Get the parent process to write to the local stack */
        success &= wpmDoIt(Comms, autoAllocatedOnStack, 
                          sizeof(autoAllocatedOnStack),
                          autoAllocatedOnStack + sizeof(int), 
                          sizeof(autoAllocatedOnStack) - 2 * sizeof(int),
                          "another 16 byte array on stack with int sized guards inside");
    }

    /* NOTE: Don't try 0 bytes long.  Win32 WriteProcessMemory claims
     * it writes 8 bytes in that case! */

    /* and 1 byte long... */
    {
        char autoAllocatedOnStack[1+ 2 * sizeof(int)];

        /* Get the parent process to write to the local stack */
        success &= wpmDoIt(Comms, autoAllocatedOnStack, 
                           sizeof(autoAllocatedOnStack),
                           autoAllocatedOnStack + sizeof(int), 
                           1,
                           "no bytes with int sized guards outside on stack");
    }


EXIT:
    /* Tell the parent that we are done */
    if (!DeleteFile(Comms.valuesFileName))
    {
        Trace("helper: DeleteFile failed so parent (test1) is unlikely "
             "to exit cleanly\n");
    }
    PEDANTIC(ResetEvent, (Comms.hEvToHelper)); 
    if (!SetEvent(Comms.hEvFromHelper))
    {
        Trace("helper: SetEvent failed so parent (test1) is unlikely "
              "to exit cleanly\n");
    }

    free(pTarget);
    PEDANTIC(CloseHandle, (Comms.hEvToHelper));
    PEDANTIC(CloseHandle, (Comms.hEvFromHelper));

    if (!success) 
    {
        Fail("");
    }

    PAL_Terminate();

    return success ? PASS : FAIL;
}
Exemplo n.º 29
0
void CNTService::Running(DWORD dwArgc,LPTSTR *lpszArgv)
{
	int index = 0;

	m_hStopEvent = CreateEventW(NULL,    // default security attributes
		TRUE,    // manual reset event
		FALSE,   // not signaled
		NULL);   // no name
	if (NULL == m_hStopEvent)
	{
		ReportSvcStatus(SERVICE_STOPPED,NO_ERROR,0);
		return;
	}

	m_hOnlyMutex = CreateMutex(NULL,FALSE,m_wszMutexName);
	if (NULL != m_hOnlyMutex)
	{
		if (ERROR_ALREADY_EXISTS == GetLastError())
		{
			ReportSvcStatus(SERVICE_STOPPED,NO_ERROR,0);
			return;
		}
	}
	else
	{
		ReportSvcStatus(SERVICE_STOPPED,NO_ERROR,0);
		return;
	}

	//Report running status when initialization is complete.
	ReportSvcStatus(SERVICE_RUNNING,NO_ERROR,0);

	//Perform work until service stops.
	for (index = 0; index < m_nWorkDispCount; index++)
	{
		m_lpWorkDispHandles[index] = CreateThread(NULL,0,m_lpWorkDisp[index].pDisHandler,
			m_lpWorkDisp[index].lpParam,0,NULL);
		if (NULL != m_lpWorkDispHandles[index])
		{
			OutputDebugStringW(L"SVR: CreateThread() OK!");
		}
	}

	OutputDebugStringW(L"SVR: call WaitForSingleObject()!");

	//Check whether to stop the service.
	WaitForSingleObject(m_hStopEvent,INFINITE);

	OutputDebugStringW(L"SVR: WaitForSingleObject() OK!");
	for (index = 0; index < m_nWorkDispCount; index++)
	{
		//stop thread by event_name.
		if (NULL != m_lpWorkDispHandles[index])
		{
			HANDLE hThreadStopEvent = OpenEventW(EVENT_MODIFY_STATE,FALSE,m_lpWorkDisp[index].wszStopEventName);
			if (NULL != hThreadStopEvent)
			{
				SetEvent(hThreadStopEvent);

				WaitForSingleObject(m_lpWorkDispHandles[index],INFINITE);

				CloseHandle(hThreadStopEvent);
				hThreadStopEvent = NULL;
			}

			CloseHandle(m_lpWorkDispHandles[index]);
			m_lpWorkDispHandles[index] = NULL;
		}			
	}

	OutputDebugStringW(L"SVR: Service over!");

	ReportSvcStatus(SERVICE_STOPPED,NO_ERROR,0);
}
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
	CRecordProgram::GetInstance()->RecordCommonInfo(MY_PRO_NAME, MY_THREAD_ID_INIT, L"启动");

	DWORD pid = ::GetCurrentThreadId();
	HRESULT hRes = ::CoInitialize(NULL);
	g_strSkinDir = ::GetModulePath();
	g_strSkinDir += _T("\\Skin\\");
// If you are running on NT 4.0 or higher you can use the following call instead to 
// make the EXE free threaded. This means that calls come in on a random RPC thread.
//	HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);

	if (_tcsncmp(lpstrCmdLine, _T("-reblack"), 8) == 0)
	{
		HANDLE hEvent = OpenEventW(EVENT_ALL_ACCESS, FALSE, L"MONEYHUBEVENT_BLACKUPDATE");
		CRecordProgram::GetInstance()->RecordCommonInfo(MY_PRO_NAME, MY_THREAD_ID_INIT, L"重新创建黑名单");
		CGlobalData::GetInstance()->Init();
		int iReturn = (int)_SecuCheckPop.CheckBlackListCache();
		if( hEvent )
		{
			SetEvent(hEvent);
			CloseHandle(hEvent);
		}
		return iReturn;
	}

	if (_tcsncmp(lpstrCmdLine, _T("-rebuild"), 8) == 0)
	{
		HANDLE hEvent = OpenEventW(EVENT_ALL_ACCESS, FALSE, L"MONEYHUBEVENT_WHITEUPDATE");
		CRecordProgram::GetInstance()->RecordCommonInfo(MY_PRO_NAME, MY_THREAD_ID_INIT, L"重新创建白名单");
		CGlobalData::GetInstance()->Init();
		int iReturn = (int)_SecuCheckPop.ReBuildSercurityCache();
		if( hEvent )
		{
			SetEvent(hEvent);
			CloseHandle(hEvent);
		}
		return iReturn;
	}

	ThreadCacheDC::InitializeThreadCacheDC();
	ThreadCacheDC::CreateThreadCacheDC();

	DWORD dw;
	CloseHandle(CreateThread(NULL, 0, _threadTestDownloadMode, NULL, 0, &dw));

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

	if(CGlobalData::GetInstance()->IsPopAlreadyRunning() == TRUE)
	{
		mhMessageBox(NULL, _T("泡泡程序已经在运行中..."), L"财金汇", MB_OK | MB_SETFOREGROUND);
		return 0;
	}

	ATLASSERT(SUCCEEDED(hRes));

	CUserBehavior::GetInstance()->BeginFeedBack();

	_SecuCheckPop.Start();// 开启安全检测及驱动进程
	CRecordProgram::GetInstance()->RecordCommonInfo(MY_PRO_NAME, MY_THREAD_ID_INIT, L"启动安全检测及驱动进程");

	//CUSBControl::GetInstance()->BeginUSBControl();
	// this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
	::DefWindowProc(NULL, 0, 0, 0L);

	AtlInitCommonControls(ICC_WIN95_CLASSES | ICC_PROGRESS_CLASS | ICC_BAR_CLASSES);	// add flags to support other controls

	hRes = _Module.Init(NULL, hInstance);
	ATLASSERT(SUCCEEDED(hRes));


	CRecordProgram::GetInstance()->RecordCommonInfo(MY_PRO_NAME, MY_THREAD_ID_INIT, L"运行");

	int nRet = Run(lpstrCmdLine, nCmdShow);

	_Module.Term();

	//::CoUninitialize();

	CUserBehavior::GetInstance()->CloseFeedBack();

	return nRet;
}