コード例 #1
0
ファイル: IPCContext.cpp プロジェクト: Archomeda/Lightpack
bool IPCContext::init() {
    if (NULL == (m_hMutex = OpenMutexW(SYNCHRONIZE, false, HOOKSGRABBER_MUTEX_MEM_NAME))) {
        m_logger->reportLogError(L"error occured while opening mutex 0x%x", GetLastError());
        this->free();
        return false;
    }

    if (NULL == (m_hSharedMem = OpenFileMappingW(GENERIC_WRITE | GENERIC_READ, false, HOOKSGRABBER_SHARED_MEM_NAME))) {
        m_logger->reportLogError(L"error occured while opening memory-mapped file 0x%x", GetLastError());
        this->free();
        return false;
    }

    if (NULL == (m_hFrameGrabbedEvent = CreateEventW(NULL, true, false, HOOKSGRABBER_FRAMEGRABBED_EVENT_NAME))) {
        m_logger->reportLogError(L"error occured while opening event 0x%x", GetLastError());
        this->free();
        return false;
    }

    m_pMemMap = MapViewOfFile(m_hSharedMem, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, HOOKSGRABBER_SHARED_MEM_SIZE);
    if (m_pMemMap == NULL) {
        m_logger->reportLogError(L"error occured while creating mapview 0x%x", GetLastError());
        this->free();
        return false;
    }

    m_pMemDesc = (HOOKSGRABBER_SHARED_MEM_DESC*)m_pMemMap;

    return true;
}
コード例 #2
0
HRESULT __stdcall initialize_patch(
    IAudioClient* this_, AUDCLNT_SHAREMODE ShareMode, DWORD StreamFlags, 
    REFERENCE_TIME hnsBufferDuration, REFERENCE_TIME hnsPeriodicity, 
    const WAVEFORMATEX* pFormat, LPCGUID AudioSessionGuid)
{
    // synchronize initializing so it doesn't happen while streams are being flushed
    HANDLE audio_router_mutex = OpenMutexW(SYNCHRONIZE, FALSE, L"Local\\audio-router-mutex");
    assert(audio_router_mutex != NULL);
    if(audio_router_mutex)
    {
        DWORD res = WaitForSingleObject(audio_router_mutex, INFINITE);
        assert(res == WAIT_OBJECT_0);
    }

    IAudioClient* proxy = get_duplicate(this_)->proxy;
    LPCGUID guid = ((GUID***)this_)[0][17];
    DWORD_PTR* old_vftptr = swap_vtable(this_);
    HRESULT hr = proxy->Initialize(
        ShareMode, 
        StreamFlags | 
        AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED | 
        AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED,
        hnsBufferDuration, 
        hnsPeriodicity, 
        pFormat, 
        guid);
    ((DWORD_PTR**)this_)[0] = old_vftptr;
    if(hr != S_OK)
        tell_error(hr);
    else
        *((WORD***)this_)[0][18] = pFormat->nBlockAlign;
    if(hr == S_OK)
    {
        for(iaudioclient_duplicate* next = get_duplicate(this_)->next;
            next != NULL; next = next->next)
        {
            HRESULT hr2 = next->proxy->Initialize(
                ShareMode,
                StreamFlags |
                AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM |
                AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY |
                AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
                AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED,
                hnsBufferDuration,
                hnsPeriodicity,
                pFormat,
                guid);
            if(hr2 != S_OK)
                tell_error(hr2);
        }
    }

    ReleaseMutex(audio_router_mutex);
    CloseHandle(audio_router_mutex);
    return hr;
}
コード例 #3
0
HOOKFUNC HANDLE WINAPI MyOpenMutexW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName)
{
	HANDLE rv = OpenMutexW(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;
}
コード例 #4
0
ファイル: DBWin.cpp プロジェクト: nhurman/LoL_API_Sandbox
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;
}
コード例 #5
0
void CTextService::_StartConfigure()
{
	HANDLE hMutex = OpenMutexW(SYNCHRONIZE, FALSE, cnfmutexname);
	if(hMutex != NULL)
	{
		CloseHandle(hMutex);
		return;
	}

	_StartProcess(VIMCNFEXE);
}
コード例 #6
0
 HOOKFUNC HANDLE WINAPI MyOpenMutexW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName)
 {
     ENTER();
     HANDLE rv = OpenMutexW(dwDesiredAccess, bInheritHandle, lpName);
     LEAVE(rv);
     EnterCriticalSection(&s_handleCS);
     std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
     handles.insert(rv);
     LeaveCriticalSection(&s_handleCS);
     return rv;
 }
コード例 #7
0
void CTextService::_StartManager()
{
	HANDLE hMutex = OpenMutexW(SYNCHRONIZE, FALSE, mgrmutexname);
	if(hMutex != nullptr)
	{
		CloseHandle(hMutex);
		return;
	}

	StartProcess(g_hInst, IMCRVMGREXE);
}
コード例 #8
0
ファイル: proc_mutex.c プロジェクト: KunZheng/mosbench
APR_DECLARE(apr_status_t) apr_proc_mutex_child_init(apr_proc_mutex_t **mutex,
                                                    const char *fname,
                                                    apr_pool_t *pool)
{
    HANDLE hMutex;
    void *mutexkey;

    if (!fname) {
        /* Reinitializing unnamed mutexes is a noop in the Unix code. */
        return APR_SUCCESS;
    }

    /* res_name_from_filename turns file into a pseudo-name
     * without slashes or backslashes, and prepends the \global
     * prefix on Win2K and later
     */
    mutexkey = res_name_from_filename(fname, 1, pool);

#if defined(_WIN32_WCE)
    hMutex = CreateMutex(NULL, FALSE, mutexkey);
    if (hMutex && ERROR_ALREADY_EXISTS != GetLastError()) {
        CloseHandle(hMutex);
        hMutex = NULL;
        SetLastError(ERROR_FILE_NOT_FOUND);
    }
#else
#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        hMutex = OpenMutexW(MUTEX_ALL_ACCESS, FALSE, mutexkey);
    }
#endif
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
    {
        hMutex = OpenMutexA(MUTEX_ALL_ACCESS, FALSE, mutexkey);
    }
#endif
#endif

    if (!hMutex) {
        return apr_get_os_error();
    }

    *mutex = (apr_proc_mutex_t *)apr_palloc(pool, sizeof(apr_proc_mutex_t));
    (*mutex)->pool = pool;
    (*mutex)->handle = hMutex;
    (*mutex)->fname = fname;
    apr_pool_cleanup_register((*mutex)->pool, *mutex, 
                              proc_mutex_cleanup, apr_pool_cleanup_null);
    return APR_SUCCESS;
}
コード例 #9
0
void CTextService::_StartConfigure()
{
	HANDLE hMutex = OpenMutexW(SYNCHRONIZE, FALSE, cnfmutexname);
	if(hMutex != nullptr)
	{
		CloseHandle(hMutex);
		return;
	}

	AllowSetForegroundWindow(ASFW_ANY);

	_CommandDic(REQ_EXEC_CNF);
}
コード例 #10
0
void CTextService::_StartConfigure()
{
	HANDLE hMutex = OpenMutexW(SYNCHRONIZE, FALSE, cnfmutexname);
	if(hMutex != nullptr)
	{
		CloseHandle(hMutex);
		return;
	}

	hMutex = OpenMutexW(SYNCHRONIZE, FALSE, mgrmutexname);
	if(hMutex != nullptr)
	{
		CloseHandle(hMutex);

		AllowSetForegroundWindow(ASFW_ANY);

		_CommandDic(REQ_EXEC_CNF);
	}
	else
	{
		StartProcess(g_hInst, IMCRVCNFEXE);
	}
}
コード例 #11
0
ファイル: exclusive_hack.c プロジェクト: ThreeGe/mpv
static void internal_api_load(void)
{
    HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
    if (!ntdll)
        return;
    pNtQueryMutant = (void*)GetProcAddress(ntdll, "NtQueryMutant");
    if (!pNtQueryMutant)
        return;
    excl_mode_mutex = OpenMutexW(MUTANT_QUERY_STATE, FALSE,
                                 L"Local\\__DDrawExclMode__");
    if (!excl_mode_mutex)
        return;

    internal_api_loaded = true;
}
コード例 #12
0
ファイル: synch.c プロジェクト: shuowen/OpenNT
HANDLE
APIENTRY
OpenMutexA(
    DWORD dwDesiredAccess,
    BOOL bInheritHandle,
    LPCSTR lpName
)

/*++

Routine Description:

    ANSI thunk to OpenMutexW

--*/

{
    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 OpenMutexW(
               dwDesiredAccess,
               bInheritHandle,
               (LPCWSTR)Unicode->Buffer
           );
}
コード例 #13
0
DWORD WINAPI _threadCheckState(LPVOID lpParameter)
{

	CRecordProgram::GetInstance()->RecordCommonInfo(MY_PRO_NAME, MY_THREAD_ID_INIT, L"进入监控线程");

	HWND hMainFrame = (*(HWND*)(lpParameter));

	DWORD dwMainProcessId = 0;
	::GetWindowThreadProcessId(hMainFrame, &dwMainProcessId);

	HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwMainProcessId);
	if (hProcess == NULL)
	{
		CleanHistory();
		::TerminateProcess(::GetCurrentProcess(), 1);
	}

	HANDLE _hMainProcessMutex = NULL;
	DWORD dwExitCode = 0;
	while(1)
	{
		LPCTSTR lpszProcessMutex = _T("_Moneyhub_{878B413D-D8FF-49e7-808D-9A9E6DDCF2B6}");
		_hMainProcessMutex  = OpenMutexW(NULL, TRUE, lpszProcessMutex);

		DWORD err = GetLastError();
		if(_hMainProcessMutex != NULL)
			::CloseHandle(_hMainProcessMutex);

		// 当内核对象已经存在或者禁止进入时,说明主框架进程还在
		if (err == ERROR_ALREADY_EXISTS || err == ERROR_ACCESS_DENIED)
		{
			Sleep(1300);
		}
		else // 如果主框架进程被杀了
		{
			CRecordProgram::GetInstance()->RecordCommonInfo(MY_PRO_NAME, MY_THREAD_ID_INIT, L"监控线程关闭内核进程");
			CleanHistory();
			::TerminateProcess(::GetCurrentProcess(), 1);
		}
	}


	return 0;
}
コード例 #14
0
ファイル: child6.cpp プロジェクト: A-And/coreclr
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;
}
コード例 #15
0
ファイル: signaler.cpp プロジェクト: craxycat/flylinkdc-r5xx
//  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
}
コード例 #16
0
CPluginMutex::CPluginMutex(const std::wstring& name, int errorSubidBase) 
  : m_isLocked(false), m_errorSubidBase(errorSubidBase), system_name(L"Global\\AdblockPlus" + name)
{
  if (m_errorSubidBase != PLUGIN_ERROR_MUTEX_DEBUG_FILE)
  {
    DEBUG_MUTEX(L"Mutex::Create name:" + name)
  }
  m_hMutex = CreateMutexW(NULL, FALSE, system_name.c_str());

  if (m_hMutex == NULL)
  {
    DWORD error = GetLastError();
    m_hMutex = OpenMutexW(MUTEX_ALL_ACCESS, FALSE, system_name.c_str());
    if (m_hMutex == NULL)
    {
      system_name = L"Local\\AdblockPlus" + name;
      m_hMutex = CreateMutexW(NULL, FALSE, system_name.c_str());
      if (m_hMutex == NULL)
      {
        m_hMutex = OpenMutexW(NULL, FALSE, system_name.c_str());
        if (m_hMutex == NULL)
        {
          DWORD error = GetLastError();
          DEBUG_ERROR_LOG(::GetLastError(), PLUGIN_ERROR_MUTEX, PLUGIN_ERROR_MUTEX_CREATE + m_errorSubidBase, "Mutex::CreateMutex");
        }
      }
      else
      // TODO: Combine this block with identical one below.
      {
        switch (::WaitForSingleObject(m_hMutex, 3000))
        {
          // The thread got ownership of the mutex
        case WAIT_OBJECT_0: 
          m_isLocked = true;
          break;

        case WAIT_TIMEOUT:
          DEBUG_ERROR_LOG(::GetLastError(), PLUGIN_ERROR_MUTEX, PLUGIN_ERROR_MUTEX_WAIT_TIMEOUT + m_errorSubidBase, "Mutex::CreateMutex - Timeout");
          m_hMutex = NULL;
          break;

        case WAIT_FAILED:
          DEBUG_ERROR_LOG(::GetLastError(), PLUGIN_ERROR_MUTEX, PLUGIN_ERROR_MUTEX_WAIT + m_errorSubidBase, "Mutex::CreateMutex - Wait error");
          break;
        }
      }

    }
  }
  else
  // TODO: Combine this block with identical one above.
  {
    switch (::WaitForSingleObject(m_hMutex, 3000))
    {
      // The thread got ownership of the mutex
    case WAIT_OBJECT_0: 
      m_isLocked = true;
      break;

    case WAIT_TIMEOUT:
      DEBUG_ERROR_LOG(::GetLastError(), PLUGIN_ERROR_MUTEX, PLUGIN_ERROR_MUTEX_WAIT_TIMEOUT + m_errorSubidBase, "Mutex::CreateMutex - Timeout");
      m_hMutex = NULL;
      break;

    case WAIT_FAILED:
      DEBUG_ERROR_LOG(::GetLastError(), PLUGIN_ERROR_MUTEX, PLUGIN_ERROR_MUTEX_WAIT + m_errorSubidBase, "Mutex::CreateMutex - Wait error");
      break;
    }
  }
}
コード例 #17
0
//----------------------------------------------------------------------------------------
amf_handle AMF_CDECL_CALL amf_open_mutex(const wchar_t* pName)
{
    return OpenMutexW(MUTEX_ALL_ACCESS, FALSE, pName);
}
コード例 #18
0
ファイル: main.c プロジェクト: vgalnt/reactos
/***********************************************************************
 *
 *       WinMain
 */
int WINAPI wWinMain(HINSTANCE hInstance,
                    HINSTANCE prev,
                    LPWSTR cmdline,
                    int show)
{
    HANDLE hMutex;
    INT LayoutResource;

    UNREFERENCED_PARAMETER(prev);
    UNREFERENCED_PARAMETER(cmdline);
    UNREFERENCED_PARAMETER(show);

    ZeroMemory(&Globals, sizeof(Globals));
    Globals.hInstance = hInstance;

    /* Load the settings from the registry hive */
    LoadDataFromRegistry();

    /* If the member of the struct (bShowWarning) is set then display the dialog box */
    if (Globals.bShowWarning)
    {
        DialogBoxW(Globals.hInstance, MAKEINTRESOURCEW(IDD_WARNINGDIALOG_OSK), Globals.hMainWnd, OSK_WarningProc);
    }

    /* Before initializing the dialog execution, check if the chosen keyboard type is standard or enhanced */
    if (Globals.bIsEnhancedKeyboard)
    {
        LayoutResource = MAIN_DIALOG_ENHANCED_KB;
    }
    else
    {
        LayoutResource = MAIN_DIALOG_STANDARD_KB;
    }

    /* Rry to open a mutex for a single instance */
    hMutex = OpenMutexW(MUTEX_ALL_ACCESS, FALSE, L"osk");

    if (!hMutex)
    {
        /* Mutex doesn’t exist. This is the first instance so create the mutex. */
        hMutex = CreateMutexW(NULL, FALSE, L"osk");

        /* Create the modal box based on the configuration registry */
        DialogBoxW(hInstance,
                   MAKEINTRESOURCEW(LayoutResource),
                   GetDesktopWindow(),
                   OSK_DlgProc);

        /* Delete the mutex */
        if (hMutex) CloseHandle(hMutex);
    }
    else
    {
        /* Programme already launched */

        /* Delete the mutex */
        CloseHandle(hMutex);

        ExitProcess(0);
    }

    return 0;
}
コード例 #19
0
ファイル: debugger.c プロジェクト: HBelusca/NasuTek-Odyssey
static
HANDLE
K32CreateDBMonMutex(void)
{
    static SID_IDENTIFIER_AUTHORITY siaNTAuth = {SECURITY_NT_AUTHORITY};
    static SID_IDENTIFIER_AUTHORITY siaWorldAuth = {SECURITY_WORLD_SID_AUTHORITY};
    HANDLE hMutex;

    /* SIDs to be used in the DACL */
    PSID psidSystem = NULL;
    PSID psidAdministrators = NULL;
    PSID psidEveryone = NULL;

    /* buffer for the DACL */
    PVOID pDaclBuf = NULL;

    /* minimum size of the DACL: an ACL descriptor and three ACCESS_ALLOWED_ACE
       headers. We'll add the size of SIDs when we'll know it
    */
    SIZE_T nDaclBufSize =
         sizeof(ACL) + (sizeof(ACCESS_ALLOWED_ACE) -
                        sizeof(((ACCESS_ALLOWED_ACE*)0)->SidStart)) * 3;

    /* security descriptor of the mutex */
    SECURITY_DESCRIPTOR sdMutexSecurity;

    /* attributes of the mutex object we'll create */
    SECURITY_ATTRIBUTES saMutexAttribs = {sizeof(saMutexAttribs),
                                          &sdMutexSecurity,
                                          TRUE};

    NTSTATUS nErrCode;

    /* first, try to open the mutex */
    hMutex = OpenMutexW (SYNCHRONIZE | READ_CONTROL | MUTANT_QUERY_STATE,
                         TRUE,
                         L"DBWinMutex");

    if(hMutex != NULL)
    {
        /* success */
        return hMutex;
    }
    /* error other than the mutex not being found */
    else if(GetLastError() != ERROR_FILE_NOT_FOUND)
    {
        /* failure */
        return NULL;
    }

	/* if the mutex doesn't exist, create it */

    /* first, set up the mutex security */
    /* allocate the NT AUTHORITY\SYSTEM SID */
    nErrCode = RtlAllocateAndInitializeSid(&siaNTAuth,
                                           1,
                                           SECURITY_LOCAL_SYSTEM_RID,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           &psidSystem);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* allocate the BUILTIN\Administrators SID */
    nErrCode = RtlAllocateAndInitializeSid(&siaNTAuth,
                                           2,
                                           SECURITY_BUILTIN_DOMAIN_RID,
                                           DOMAIN_ALIAS_RID_ADMINS,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           &psidAdministrators);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* allocate the Everyone SID */
    nErrCode = RtlAllocateAndInitializeSid(&siaWorldAuth,
                                           1,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           0,
                                           &psidEveryone);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* allocate space for the SIDs too */
    nDaclBufSize += RtlLengthSid(psidSystem);
    nDaclBufSize += RtlLengthSid(psidAdministrators);
    nDaclBufSize += RtlLengthSid(psidEveryone);

    /* allocate the buffer for the DACL */
    pDaclBuf = GlobalAlloc(GMEM_FIXED, nDaclBufSize);

    /* failure */
    if(pDaclBuf == NULL) goto l_Cleanup;

    /* create the DACL */
    nErrCode = RtlCreateAcl(pDaclBuf, nDaclBufSize, ACL_REVISION);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* grant the minimum required access to Everyone */
    nErrCode = RtlAddAccessAllowedAce(pDaclBuf,
                                      ACL_REVISION,
                                      SYNCHRONIZE |
                                      READ_CONTROL |
                                      MUTANT_QUERY_STATE,
                                      psidEveryone);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* grant full access to BUILTIN\Administrators */
    nErrCode = RtlAddAccessAllowedAce(pDaclBuf,
                                      ACL_REVISION,
                                      MUTANT_ALL_ACCESS,
                                      psidAdministrators);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* grant full access to NT AUTHORITY\SYSTEM */
    nErrCode = RtlAddAccessAllowedAce(pDaclBuf,
                                      ACL_REVISION,
                                      MUTANT_ALL_ACCESS,
                                      psidSystem);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* create the security descriptor */
    nErrCode = RtlCreateSecurityDescriptor(&sdMutexSecurity,
                                           SECURITY_DESCRIPTOR_REVISION);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* set the descriptor's DACL to the ACL we created */
    nErrCode = RtlSetDaclSecurityDescriptor(&sdMutexSecurity,
                                            TRUE,
                                            pDaclBuf,
                                            FALSE);

    /* failure */
    if(!NT_SUCCESS(nErrCode)) goto l_Cleanup;

    /* create the mutex */
    hMutex = CreateMutexW(&saMutexAttribs, FALSE, L"DBWinMutex");

l_Cleanup:
    /* free the buffers */
    if(pDaclBuf) GlobalFree(pDaclBuf);
    if(psidEveryone) RtlFreeSid(psidEveryone);
    if(psidAdministrators) RtlFreeSid(psidAdministrators);
    if(psidSystem) RtlFreeSid(psidSystem);

	return hMutex;
}