예제 #1
0
    Pimpl (String name, const int timeOutMillisecs)
        : handle (0), refCount (1)
    {
        name = name.replaceCharacter ('\\', '/');
        handle = CreateMutexW (0, TRUE, ("Global\\" + name).toWideCharPointer());

        // Not 100% sure why a global mutex sometimes can't be allocated, but if it fails, fall back to
        // a local one. (A local one also sometimes fails on other machines so neither type appears to be
        // universally reliable)
        if (handle == 0)
            handle = CreateMutexW (0, TRUE, ("Local\\" + name).toWideCharPointer());

        if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
        {
            if (timeOutMillisecs == 0)
            {
                close();
                return;
            }

            switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
            {
            case WAIT_OBJECT_0:
            case WAIT_ABANDONED:
                break;

            case WAIT_TIMEOUT:
            default:
                close();
                break;
            }
        }
    }
예제 #2
0
static BOOL winpidgin_set_running(BOOL fail_if_running) {
	HANDLE h;

	if ((h = CreateMutexW(NULL, FALSE, L"pidgin_is_running"))) {
		DWORD err = GetLastError();
		if (err == ERROR_ALREADY_EXISTS) {
			if (fail_if_running) {
				HWND msg_win;

				printf("An instance of Pidgin is already running.\n");

				if((msg_win = FindWindowExW(NULL, NULL, L"WinpidginMsgWinCls", NULL)))
					if(SendMessage(msg_win, PIDGIN_WM_FOCUS_REQUEST, (WPARAM) NULL, (LPARAM) NULL))
						return FALSE;

				/* If we get here, the focus request wasn't successful */

				MessageBoxW(NULL,
					L"An instance of Pidgin is already running",
					NULL, MB_OK | MB_TOPMOST);

				return FALSE;
			}
		} else if (err != ERROR_SUCCESS)
			printf("Error (%u) accessing \"pidgin_is_running\" mutex.\n", (UINT) err);
	}
	return TRUE;
}
void CWE253_Incorrect_Check_of_Function_Return_Value__wchar_t_w32CreateMutex_15_bad()
{
    switch(6)
    {
    case 6:
    {
        HANDLE hMutex = NULL;
        hMutex = CreateMutexW(NULL, FALSE, NULL);
        /* FLAW: If CreateMutexW() failed, the return value will be NULL,
           but we are checking to see if the return value is INVALID_HANDLE_VALUE */
        if (hMutex == INVALID_HANDLE_VALUE)
        {
            exit(1);
        }
        /* We'll leave out most of the implementation since it has nothing to do with the CWE
         * and since the checkers are looking for certain function calls anyway */
        CloseHandle(hMutex);
    }
    break;
    default:
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
        break;
    }
}
예제 #4
0
파일: asmcache.c 프로젝트: GYGit/reactos
/******************************************************************
 *  CreateAssemblyCache   (FUSION.@)
 */
HRESULT WINAPI CreateAssemblyCache(IAssemblyCache **ppAsmCache, DWORD dwReserved)
{
    IAssemblyCacheImpl *cache;

    TRACE("(%p, %d)\n", ppAsmCache, dwReserved);

    if (!ppAsmCache)
        return E_INVALIDARG;

    *ppAsmCache = NULL;

    cache = HeapAlloc(GetProcessHeap(), 0, sizeof(IAssemblyCacheImpl));
    if (!cache)
        return E_OUTOFMEMORY;

    cache->IAssemblyCache_iface.lpVtbl = &AssemblyCacheVtbl;
    cache->ref = 1;
    cache->lock = CreateMutexW( NULL, FALSE, cache_mutex_nameW );
    if (!cache->lock)
    {
        HeapFree( GetProcessHeap(), 0, cache );
        return HRESULT_FROM_WIN32( GetLastError() );
    }
    *ppAsmCache = &cache->IAssemblyCache_iface;
    return S_OK;
}
예제 #5
0
void apply_emet(HMODULE pHandle, int a2)
{
    // has this point
    if ( setting_heapspray )
        heapspray_apply();
    if ( setting_bottomuprand )
        bottomuprand_apply();
    if ( setting_nullpage )
        nullpage_apply();
    if ( setting_dep )
        enableDEP();
    if ( setting_sehop ){
        getModuleHandleEx(pHandle);
        set_sehop_ceh_handler();
        enable_sehop = 1;
    }
    if ( setting_eaf ){
        hook_eat(L"kernel32.dll");
        hook_eat(L"ntdll.dll");
        HMODULE handle;
        getModuleHandleEx(handle);
        set_ceh_handler();
        HANDLE thread_lock = CreateMutexW(0, 1, 0);
        thread_count = 0;
        ReleaseMutex(thread_lock);
        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)StartAddress, 0, 0, 0);
        has_new_thread = true;
        save_current_threadid();
    }
}
예제 #6
0
파일: main.cpp 프로젝트: TieJu/swtorla
int APIENTRY WinMain(HINSTANCE hInstance
                    ,HINSTANCE /*hPrevInstance*/
                    ,LPSTR /*lpCmdLine*/
                    ,int /*nCmdShow*/) {

    auto exh = std::make_unique<google_breakpad::ExceptionHandler>( L".", nullptr, nullptr, nullptr, google_breakpad::ExceptionHandler::HANDLER_ALL, MiniDumpWithFullMemory, (const wchar_t*)nullptr, nullptr );
    //int arg_c;
    //auto arg_v = CommandLineToArgvW(GetCommandLine(), &arg_c);
    auto hMutex = CreateMutexW(nullptr, TRUE, L"swtor_log_analizer_unique");
    //WaitForSingleObject(hMutex, INFINITE);
    /*
    auto wnd = CreateDialogParamW(hInstance, MAKEINTRESOURCEW(IDD_MAIN_WINDOW), nullptr, DialogProc, 5);
    ShowWindow(wnd,SW_NORMAL);
    MSG msg
    {};
    while ( GetMessageW(&msg, wnd, 0, 0) ) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    DestroyWindow(wnd);*/

    try {
        app { APP_CATION, CONFIG_PATH }();
    } catch ( const std::exception& e ) {
        MessageBoxA(nullptr, e.what(), "Crash!", 0);
    } catch ( ... ) {
        MessageBoxA(nullptr, "Very bad crash", "Crash!", 0);
    }
    CloseHandle(hMutex);
}
예제 #7
0
파일: mutex.c 프로젝트: hoangduit/reactos
int main(int argc, char* argv[])
{
  DWORD dwError;
  DWORD id1,id2;

  AllocConsole();
  InputHandle = GetStdHandle(STD_INPUT_HANDLE);
  OutputHandle =  GetStdHandle(STD_OUTPUT_HANDLE);

  dprintf("Calling CreateMutex()\n");
  hMutex = CreateMutexW(NULL, FALSE, L"TestMutex");
  if (hMutex == INVALID_HANDLE_VALUE)
    {
      dprintf("CreateMutex() failed! Error: %lu\n", GetLastError());
      return 0;
    }
  dprintf("CreateMutex() succeeded!\n");

  hThread[0] = CreateThread(0, 0, thread1, 0, 0, &id1);
  hThread[1] = CreateThread(0, 0, thread2, 0, 0, &id2);

  dprintf("Calling WaitForMultipleObject()\n");
  dwError = WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
  dprintf("WaitForMultipleObject() Error: %lu\n", dwError);

  CloseHandle(hThread[0]);
  CloseHandle(hThread[1]);

  CloseHandle(hMutex);

  dprintf("Main thread done!\n");

  return 0;
}
예제 #8
0
파일: exechelp.c 프로젝트: gpg/gpgol
/* Lock a spawning process.  The caller needs to provide the address
   of a variable to store the lock information and the name or the
   process.  */
gpg_error_t
gpgol_lock_spawning (lock_spawn_t *lock)
{
  int waitrc;
  int timeout = 5;

  *lock = CreateMutexW (NULL, FALSE, L"spawn_gnupg_uiserver_sentinel");
  if (!*lock)
    {
      log_error ("failed to create the spawn mutex: rc=%ld", GetLastError ());
      return gpg_error (GPG_ERR_GENERAL);
    }

 retry:
  waitrc = WaitForSingleObject (*lock, 1000);
  if (waitrc == WAIT_OBJECT_0)
    return 0;

  if (waitrc == WAIT_TIMEOUT && timeout)
    {
      timeout--;
      goto retry;
    }
  if (waitrc == WAIT_TIMEOUT)
    log_error ("error waiting for the spawn mutex: timeout");
  else
    log_error ("error waiting for the spawn mutex: (code=%d) rc=%ld",
                waitrc, GetLastError ());
  return gpg_error (GPG_ERR_GENERAL);
}
SystemWideMutex::MutexData::MutexData(const wchar_t *mutex_name)
    : m_acquired(0)
{
    static const wchar_t prefix[] = L"csr_mutex_";
    //  this call previously used _alloca.  It is probably better to do so,
    //  but I'm a coward when it comes to new things...  this string gets
    //  deleted at the end of the function.

#ifdef MUTEX_LOG
    enable_logging_ = (wcscmp(mutex_name, L"spi_app_mutex" ) == 0);
#endif

    wchar_t * string = new wchar_t [ wcslen(mutex_name) + wcslen(prefix) + 1 ];
    wcscpy(string, prefix);
    wcscat(string, mutex_name);

    wchar_t *sp = string;
    while (*sp)
    {
        if (wcschr(L".\\/\"*", *sp))
            *sp = L'-';
        sp++;
    }
    handle = CreateMutexW(NULL, 0, string);
    OUTPUT_HANDLE_CREATE(handle);

    // OutputDebugString("Mutex created:");
    // OutputDebugString(string);
    // OutputDebugString("\n");
    // int lasterr = GetLastError();
    // assert(handle);
    delete string;
}
예제 #10
0
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
	HANDLE hMutex;
	INITCOMMONCONTROLSEX icex;

	_wsetlocale(LC_ALL, L"JPN");

	hInst = hInstance;

	CreateConfigPath();

	hMutex = CreateMutexW(NULL, FALSE, cnfmutexname);
	if(hMutex == NULL || GetLastError() == ERROR_ALREADY_EXISTS)
	{
		return 0;
	}

	icex.dwSize = sizeof(icex);
	icex.dwICC = ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES | ICC_PROGRESS_CLASS;
	InitCommonControlsEx(&icex);

	CreateProperty();

	return 0;
}
예제 #11
0
MutexImpl::MutexImpl(MutexTypeImpl type)
	: _lockCount(0)
	, _recursive(type == MUTEX_RECURSIVE_IMPL)
{
	_mutex = CreateMutexW(NULL, FALSE, NULL);
	if (!_mutex) throw SystemException("cannot create mutex");
}
예제 #12
0
파일: startup.cpp 프로젝트: Moteesh/reactos
BOOL DoStartStartupItems(ITrayWindow *Tray)
{
    DWORD dwWait;

    if (!bExplorerIsShell)
        return FALSE;

    if (!s_hStartupMutex)
    {
        // Accidentally, there is possibility that the system starts multiple Explorers
        // before startup of shell. We use a mutex to match the timing of shell initialization.
        s_hStartupMutex = CreateMutexW(NULL, FALSE, L"ExplorerIsShellMutex");
        if (s_hStartupMutex == NULL)
            return FALSE;
    }

    dwWait = WaitForSingleObject(s_hStartupMutex, INFINITE);
    TRACE("dwWait: 0x%08lX\n", dwWait);
    if (dwWait != WAIT_OBJECT_0)
    {
        TRACE("LastError: %ld\n", GetLastError());

        DoFinishStartupItems();
        return FALSE;
    }

    const DWORD dwWaitTotal = 3000;     // in milliseconds
    DWORD dwTick = GetTickCount();
    while (GetShellWindow() == NULL && GetTickCount() - dwTick < dwWaitTotal)
    {
        TrayProcessMessages(Tray);
    }

    if (GetShellWindow() == NULL)
    {
        DoFinishStartupItems();
        return FALSE;
    }

    // Check the volatile "StartupHasBeenRun" key
    HKEY hSessionKey, hKey;
    HRESULT hr = SHCreateSessionKey(KEY_WRITE, &hSessionKey);
    if (SUCCEEDED(hr))
    {
        ASSERT(hSessionKey);

        DWORD dwDisp;
        LONG Error = RegCreateKeyExW(hSessionKey, L"StartupHasBeenRun", 0, NULL,
                                     REG_OPTION_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp);
        RegCloseKey(hSessionKey);
        RegCloseKey(hKey);
        if (Error == ERROR_SUCCESS && dwDisp == REG_OPENED_EXISTING_KEY)
        {
            return FALSE;   // Startup programs has already been run
        }
    }

    return TRUE;
}
예제 #13
0
NamedMutexImpl::NamedMutexImpl(const std::string& name):
	_name(name)
{
	UnicodeConverter::toUTF16(_name, _uname);
	_mutex = CreateMutexW(NULL, FALSE, _uname.c_str());
	if (!_mutex) 
		throw SystemException("cannot create named mutex", _name);
}
예제 #14
0
파일: socket.c 프로젝트: Logan-lu/flinux
static int socket_open(int domain, int type, int protocol)
{
	/* Translation constants to their Windows counterparts */
	int win32_af = translate_address_family(domain);
	if (win32_af < 0)
		return win32_af;
	int win32_type;
	switch (type & LINUX_SOCK_TYPE_MASK)
	{
	case LINUX_SOCK_DGRAM: win32_type = SOCK_DGRAM; break;
	case LINUX_SOCK_STREAM: win32_type = SOCK_STREAM; break;
	case LINUX_SOCK_RAW: win32_type = SOCK_RAW; break;
	case LINUX_SOCK_RDM: win32_type = SOCK_RDM; break;
	case LINUX_SOCK_SEQPACKET: win32_type = SOCK_SEQPACKET; break;
	default:
		log_error("Unknown type: %d", type & LINUX_SOCK_TYPE_MASK);
		return -L_EPROTONOSUPPORT;
	}

	socket_ensure_initialized();
	SOCKET sock = socket(win32_af, win32_type, protocol);
	if (sock == INVALID_SOCKET)
	{
		log_warning("socket() failed, error code: %d", WSAGetLastError());
		return translate_socket_error(WSAGetLastError());
	}
	HANDLE event_handle = init_socket_event(sock);
	if (!event_handle)
	{
		closesocket(sock);
		log_error("init_socket_event() failed.");
		return -L_ENFILE;
	}
	HANDLE mutex;
	SECURITY_ATTRIBUTES attr;
	attr.nLength = sizeof(SECURITY_ATTRIBUTES);
	attr.lpSecurityDescriptor = NULL;
	attr.bInheritHandle = TRUE;
	mutex = CreateMutexW(&attr, FALSE, NULL);

	struct socket_file *f = (struct socket_file *) kmalloc(sizeof(struct socket_file));
	file_init(&f->base_file, &socket_ops, O_RDWR);
	f->socket = sock;
	f->event_handle = event_handle;
	f->mutex = mutex;
	f->shared = (struct socket_file_shared *)kmalloc_shared(sizeof(struct socket_file_shared));
	f->shared->af = domain;
	f->shared->type = (type & LINUX_SOCK_TYPE_MASK);
	f->shared->events = 0;
	f->shared->connect_error = 0;
	if ((type & O_NONBLOCK))
		f->base_file.flags |= O_NONBLOCK;

	int fd = vfs_store_file((struct file *)f, (type & O_CLOEXEC) > 0);
	if (fd < 0)
		vfs_release((struct file *)f);
	return fd;
}
예제 #15
0
파일: cemisc.c 프로젝트: mmcx/cegcc
HANDLE
XCECreateMutexW(LPSECURITY_ATTRIBUTES sa, BOOL io, LPTSTR name)
{
  HANDLE hnd;

  hnd = CreateMutexW(sa, io, name);
  WCETRACE(WCE_SYNCH, "cmw: %p", hnd);
  return(hnd);
}
예제 #16
0
파일: winfs.c 프로젝트: xwlan/flinux
static int winfs_open(struct file_system *fs, const char *pathname, int flags, int mode, struct file **fp, char *target, int buflen)
{
	/* TODO: mode */
	DWORD desired_access, create_disposition;
	HANDLE handle;

	if (flags & O_PATH)
		desired_access = 0;
	else if (flags & O_RDWR)
		desired_access = GENERIC_READ | GENERIC_WRITE;
	else if (flags & O_WRONLY)
		desired_access = GENERIC_WRITE;
	else
		desired_access = GENERIC_READ;
	if (flags & __O_DELETE)
		desired_access |= DELETE;
	if (flags & O_EXCL)
		create_disposition = FILE_CREATE;
	else if (flags & O_CREAT)
		create_disposition = FILE_OPEN_IF;
	else
		create_disposition = FILE_OPEN;
	int r = open_file(&handle, pathname, desired_access, create_disposition, flags, fp != NULL, target, buflen);
	if (r < 0 || r == 1)
		return r;
	if ((flags & O_TRUNC) && ((flags & O_WRONLY) || (flags & O_RDWR)))
	{
		/* Truncate the file */
		FILE_END_OF_FILE_INFORMATION info;
		info.EndOfFile.QuadPart = 0;
		IO_STATUS_BLOCK status_block;
		NTSTATUS status = NtSetInformationFile(handle, &status_block, &info, sizeof(info), FileEndOfFileInformation);
		if (!NT_SUCCESS(status))
			log_error("NtSetInformationFile() failed, status: %x", status);
	}

	if (fp)
	{
		int pathlen = strlen(pathname);
		struct winfs_file *file = (struct winfs_file *)kmalloc(sizeof(struct winfs_file) + pathlen);
		file_init(&file->base_file, &winfs_ops, flags);
		file->handle = handle;
		SECURITY_ATTRIBUTES attr;
		attr.nLength = sizeof(SECURITY_ATTRIBUTES);
		attr.bInheritHandle = TRUE;
		attr.lpSecurityDescriptor = NULL;
		/* TODO: Don't need this mutex for directory or symlink */
		file->fp_mutex = CreateMutexW(&attr, FALSE, NULL);
		file->restart_scan = 1;
		file->pathlen = pathlen;
		memcpy(file->pathname, pathname, pathlen);
		*fp = (struct file *)file;
	}
	else
		CloseHandle(handle);
	return 0;
}
예제 #17
0
DWORD service_start(struct service_entry *service, DWORD service_argc, LPCWSTR *service_argv)
{
    DWORD err;
    LPWSTR name;
    HANDLE process_handle = NULL;

    err = scmdatabase_lock_startup(service->db);
    if (err != ERROR_SUCCESS)
        return err;

    if (WaitForSingleObject(service->process, 0) == WAIT_TIMEOUT)
    {
        scmdatabase_unlock_startup(service->db);
        return ERROR_SERVICE_ALREADY_RUNNING;
    }

    CloseHandle(service->control_pipe);
    service->control_mutex = CreateMutexW(NULL, TRUE, NULL);

    if (!service->status_changed_event)
        service->status_changed_event = CreateEventW(NULL, FALSE, FALSE, NULL);
    if (!service->overlapped_event)
        service->overlapped_event = CreateEventW(NULL, TRUE, FALSE, NULL);

    name = service_get_pipe_name();
    service->control_pipe = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                  PIPE_TYPE_BYTE|PIPE_WAIT, 1, 256, 256, 10000, NULL );
    HeapFree(GetProcessHeap(), 0, name);
    if (service->control_pipe==INVALID_HANDLE_VALUE)
    {
        WINE_ERR("failed to create pipe for %s, error = %d\n",
            wine_dbgstr_w(service->name), GetLastError());
        err = GetLastError();
    }
    else
    {
        err = service_start_process(service, &process_handle);
        if (err == ERROR_SUCCESS)
        {
            if (!service_send_start_message(service, process_handle, service_argv, service_argc))
                err = ERROR_SERVICE_REQUEST_TIMEOUT;
        }

        if (err == ERROR_SUCCESS)
            err = service_wait_for_startup(service, process_handle);
    }

    if (err == ERROR_SUCCESS)
        ReleaseMutex(service->control_mutex);
    else
        service_terminate(service);
    scmdatabase_unlock_startup(service->db);

    WINE_TRACE("returning %d\n", err);

    return err;
}
예제 #18
0
HOOKFUNC HANDLE WINAPI MyCreateMutexW(LPSECURITY_ATTRIBUTES lpMutexWttributes, BOOL bInitialOwner, LPCSTR lpName)
{
	HANDLE rv = CreateMutexW(lpMutexWttributes, bInitialOwner, 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;
}
예제 #19
0
파일: test3.c 프로젝트: l1183479157/coreclr
int __cdecl main( int argc, char **argv)
{
    HANDLE Mutex;
    HANDLE hThread = 0;
    DWORD dwThreadId = 0;
    int ret;

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

    Mutex = CreateMutexW(NULL, FALSE, NULL);
    if (Mutex == NULL)
    {
        Fail("Unable to create the mutex.  GetLastError returned %d\n",
             GetLastError());
    }

    hThread = CreateThread( NULL,
                            0,
                            (LPTHREAD_START_ROUTINE)AcquiringProc,
                            (LPVOID) Mutex,
                            0,
                            &dwThreadId);

    if (hThread == NULL)
    {
        Fail("ERROR: Was not able to create the thread to test!\n"
             "GetLastError returned %d\n", GetLastError());
    }

    Sleep(ParentDelayTime);

    ret = WaitForMultipleObjectsEx(1, &Mutex, FALSE, INFINITE, FALSE);
    if (ret != WAIT_OBJECT_0)
    {
        Fail("Expected WaitForMultipleObjectsEx to return WAIT_OBJECT_0\n"
             "Got %d\n", ret);
    }

    if (!CloseHandle(Mutex))
    {
        Fail("CloseHandle on the mutex failed!\n");
    }

    if (!CloseHandle(hThread))
    {
        Fail("CloseHandle on the thread failed!\n");
    }

    PAL_Terminate();
    return PASS;
}
예제 #20
0
//----------------------------------------------------------------------------------------
amf_handle AMF_CDECL_CALL amf_create_mutex(amf_bool bInitiallyOwned, const wchar_t* pName)
{
#if defined(METRO_APP)
    DWORD flags = (bInitiallyOwned) ? CREATE_MUTEX_INITIAL_OWNER : 0;
    return CreateMutexEx(NULL, pName, flags, STANDARD_RIGHTS_ALL);

#else
    return CreateMutexW(NULL, bInitiallyOwned == true, pName);

#endif
}
예제 #21
0
 HOOKFUNC HANDLE WINAPI MyCreateMutexW(LPSECURITY_ATTRIBUTES lpMutexWttributes, BOOL bInitialOwner, LPCSTR lpName)
 {
     ENTER();
     HANDLE rv = CreateMutexW(lpMutexWttributes, bInitialOwner, lpName);
     LEAVE(rv);
     EnterCriticalSection(&s_handleCS);
     std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
     handles.insert(rv);
     LeaveCriticalSection(&s_handleCS);
     return rv;
 }
void CWE252_Unchecked_Return_Value__wchar_t_w32CreateMutex_18_bad()
{
    goto sink;
sink:
    {
        HANDLE hMutex = NULL;
        hMutex = CreateMutexW(NULL, FALSE, NULL);
        /* FLAW: Do not check the return value */
        /* We'll leave out most of the implementation since it has nothing to do with the CWE
         * and since the checkers are looking for certain function calls anyway */
        CloseHandle(hMutex);
    }
}
예제 #23
0
int __cdecl main( int argc, char **argv )
{
    HANDLE hMutex;
    WCHAR wszMutexName[] = { 'T','E','S','T','1','1','\0' };
    DWORD dwRet;
    int i;

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

    /* open a mutex to synchronize with the parent process */
    hMutex = CreateMutexW( NULL, FALSE, wszMutexName );
    if( hMutex == NULL )
    {
        Fail( "ERROR:%lu:CreateMutex() call failed\r\n", GetLastError() );
    }

    /* acquire the mutex lock */
    dwRet = WaitForSingleObject( hMutex, 10000 );
    if( dwRet != WAIT_OBJECT_0 )
    {
        Trace( "ERROR:WaitForSingleObject() returned %lu, "
                "expected WAIT_OBJECT_0",
                dwRet );
        if( ! CloseHandle( hMutex ) )
        {
            Trace( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() );
        }
        Fail( "test failed\n" );
    }


    /* simulate some activity  */
    for( i=0; i<50000; i++ )
        ;

    /* close our mutex handle */
    if( ! CloseHandle( hMutex ) )
    {
        Fail( "ERROR:%lu:CloseHandle() call failed\n", GetLastError() );
    }

    /* terminate the PAL */
    PAL_Terminate();

    /* return the predefined exit code */
    return TEST_EXIT_CODE;
}
예제 #24
0
파일: RWLock_WIN32.cpp 프로젝트: 119/vdc
RWLockImpl::RWLockImpl(): _readers(0), _writersWaiting(0), _writers(0)
{
	_mutex = CreateMutexW(NULL, FALSE, NULL);
	if (_mutex == NULL)
		throw SystemException("cannot create reader/writer lock");

	_readEvent = CreateEventW(NULL, TRUE, TRUE, NULL);
	if (_readEvent == NULL)
		throw SystemException("cannot create reader/writer lock");

	_writeEvent = CreateEventW(NULL, TRUE, TRUE, NULL);
	if (_writeEvent == NULL)
		throw SystemException("cannot create reader/writer lock");
}
예제 #25
0
Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate)
{
    if (mutexname.isEmpty()) {
        QFileInfo fi(*this);
        mutexname = QString::fromLatin1(MUTEX_PREFIX)
                    + fi.absoluteFilePath().toLower();
    }
    QString mname(mutexname);
    if (idx >= 0)
        mname += QString::number(idx);

    Qt::HANDLE mutex;
    if (doCreate) {
        QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); },
               { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } );
예제 #26
0
/*********************************************************
设定运行标志
*********************************************************/
LIBUTILS_API int UTILS_API set_runningW(const wchar_t * szProgramName)
{
    HANDLE hMutex;
    hMutex=CreateMutexW(0,TRUE,szProgramName);
    if(!hMutex)
    {
        return -1;
    }
    if(ERROR_ALREADY_EXISTS == GetLastError())
    {
        CloseHandle(hMutex);
        return 1;
    }
    return 0;
}
예제 #27
0
파일: proc_mutex.c 프로젝트: MiKTeX/miktex
APR_DECLARE(apr_status_t) apr_proc_mutex_create(apr_proc_mutex_t **mutex,
                                                const char *fname,
                                                apr_lockmech_e mech,
                                                apr_pool_t *pool)
{
    HANDLE hMutex;
    void *mutexkey;

    if (mech != APR_LOCK_DEFAULT) {
        return APR_ENOTIMPL;
    }

    /* res_name_from_filename turns fname into a pseduo-name
     * without slashes or backslashes, and prepends the \global
     * prefix on Win2K and later
     */
    if (fname) {
        mutexkey = res_name_from_filename(fname, 1, pool);
    }
    else {
        mutexkey = NULL;
    }

#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        hMutex = CreateMutexW(NULL, FALSE, mutexkey);
    }
#endif
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
    {
        hMutex = CreateMutexA(NULL, FALSE, mutexkey);
    }
#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;
}
예제 #28
0
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
  AutoHandle mutex(CreateMutexW(0, false, L"AdblockPlusEngine"));
  if (!mutex)
  {
    DebugLastError("CreateMutex failed");
    return 1;
  }

  if (GetLastError() == ERROR_ALREADY_EXISTS)
  {
    DebugLastError("Named pipe exists, another engine instance appears to be running");
    return 1;
  }

  int argc;
  LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
  std::wstring locale(argc >= 2 ? argv[1] : L"");
  Communication::browserSID = argc >= 3 ? argv[2] : L"";
  LocalFree(argv);
  Dictionary::Create(locale);
  filterEngine = CreateFilterEngine(locale);
  updater.reset(new Updater(filterEngine->GetJsEngine()));

  for (;;)
  {
    try
    {
      Communication::Pipe* pipe = new Communication::Pipe(Communication::pipeName,
            Communication::Pipe::MODE_CREATE);

      AutoHandle thread(CreateThread(0, 0, ClientThread, static_cast<LPVOID>(pipe), 0, 0));
      if (!thread)
      {
        delete pipe;
        DebugLastError("CreateThread failed");
        return 1;
      }
    }
    catch (std::runtime_error e)
    {
      DebugException(e);
      return 1;
    }
  }

  return 0;
}
/* good1() reverses the blocks on the goto statement */
static void good1()
{
    goto sink;
sink:
    {
        HANDLE hMutex = NULL;
        hMutex = CreateMutexW(NULL, FALSE, NULL);
        /* FIX: Check the return value of CreateMutex() for NULL */
        if (hMutex == NULL)
        {
            exit(1);
        }
        /* We'll leave out most of the implementation since it has nothing to do with the CWE
         * and since the checkers are looking for certain function calls anyway */
        CloseHandle(hMutex);
    }
}
예제 #30
0
파일: synch.c 프로젝트: shuowen/OpenNT
HANDLE
APIENTRY
CreateMutexA(
    LPSECURITY_ATTRIBUTES lpMutexAttributes,
    BOOL bInitialOwner,
    LPCSTR lpName
)

/*++

Routine Description:

    ANSI thunk to CreateMutexW

--*/

{
    PUNICODE_STRING Unicode;
    ANSI_STRING AnsiString;
    NTSTATUS Status;
    LPCWSTR NameBuffer;

    NameBuffer = NULL;
    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;
        }

        NameBuffer = (LPCWSTR)Unicode->Buffer;
    }

    return CreateMutexW(
               lpMutexAttributes,
               bInitialOwner,
               NameBuffer
           );
}