void CWE253_Incorrect_Check_of_Function_Return_Value__char_w32CreateMutex_12_bad()
{
    if(globalReturnsTrueOrFalse())
    {
        {
            HANDLE hMutex = NULL;
            hMutex = CreateMutexA(NULL, FALSE, NULL);
            /* FLAW: If CreateMutexA() 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);
        }
    }
    else
    {
        {
            HANDLE hMutex = NULL;
            hMutex = CreateMutexA(NULL, FALSE, NULL);
            /* FIX: check for the correct return value */
            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);
        }
    }
}
/* good1() uses the GoodSink on both sides of the "if" statement */
static void good1()
{
    if(globalReturnsTrueOrFalse())
    {
        {
            HANDLE hMutex = NULL;
            hMutex = CreateMutexA(NULL, FALSE, NULL);
            /* FIX: check for the correct return value */
            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);
        }
    }
    else
    {
        {
            HANDLE hMutex = NULL;
            hMutex = CreateMutexA(NULL, FALSE, NULL);
            /* FIX: check for the correct return value */
            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);
        }
    }
}
Example #3
0
// =================================================================
// Texture access mutex locks
//
// A general mutex lock for DirectX 9 and for DirectX11 textures
//
// =================================================================
bool spoutDirectX::CreateAccessMutex(const char *name, HANDLE &hAccessMutex)
{
	DWORD errnum;
	char szMutexName[300]; // name of the mutex

	// Create the mutex name to control access to the shared texture
	sprintf_s((char*)szMutexName, 300, "%s_SpoutAccessMutex", name);

	// Create or open mutex depending, on whether it already exists or not
    hAccessMutex = CreateMutexA ( NULL,   // default security
						  FALSE,  // No initial owner
						  (LPCSTR)szMutexName);

	if (hAccessMutex == NULL) {
        return false;
	}
	else {
		errnum = GetLastError();
		if(errnum == ERROR_INVALID_HANDLE) {
			printf("access mutex [%s] invalid handle\n", szMutexName);
		}
	}

	return true;

}
Example #4
0
static gboolean
publish_session_bus (const char *address)
{
  HANDLE init_mutex;

  init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);

  published_daemon_mutex = CreateMutexA (NULL, FALSE, DBUS_DAEMON_MUTEX);
  if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
    {
      release_mutex (init_mutex);
      CloseHandle (published_daemon_mutex);
      published_daemon_mutex = NULL;
      return FALSE;
    }

  published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
  if (!published_shared_mem)
    {
      release_mutex (init_mutex);
      CloseHandle (published_daemon_mutex);
      published_daemon_mutex = NULL;
      return FALSE;
    }

  release_mutex (init_mutex);
  return TRUE;
}
Example #5
0
void ofxOscReceiver::setup( int listen_port )
{
	// if we're already running, shutdown before running again
	if ( listen_socket )
		shutdown();
	
	// create the mutex
	#ifdef TARGET_WIN32
	mutex = CreateMutexA( NULL, FALSE, NULL );
	#else
	pthread_mutex_init( &mutex, NULL );
	#endif
	
	// create socket
	socketHasShutdown = false;
	listen_socket = new UdpListeningReceiveSocket( IpEndpointName( IpEndpointName::ANY_ADDRESS, listen_port ), this );

	// start thread
	#ifdef TARGET_WIN32
	thread	= CreateThread(
							   NULL,              // default security attributes
							   0,                 // use default stack size
							&ofxOscReceiver::startThread,        // thread function
							   (void*)this,             // argument to thread function
							   0,                 // use default creation flags
							   NULL);             // we don't the the thread id

	#else
	pthread_create( &thread, NULL, &ofxOscReceiver::startThread, (void*)this );
	#endif
}
bool CourseTrainerApp::OnInit()
{
    #ifdef WINDOWS
        CreateMutexA(0, FALSE, "Local\\$myprogram$"); // try to create a named mutex
        if(GetLastError() == ERROR_ALREADY_EXISTS) // did the mutex already exist?
        {
            wxMessageDialog(NULL, "Another process already running.","Error").ShowModal();
            return false;
        }
    #else
        pid_t pid = getpid();
        std::stringstream command;
        command << "ps -eo pid,comm | grep CourseTrainer | grep -v " << pid;
        int isRuning = system(command.str().c_str());

        if (isRuning==0)
        {
            wxMessageDialog(NULL, "Another process already running.","Error").ShowModal();
            return false;
        }
    #endif // WINDOWS
    frame = new CourseTrainerFrame(0L, _("Course Calculatings"));
    WelcomeScreen* dialog=new WelcomeScreen(nullptr,wxID_ANY,"Identification",frame);
    dialog->Show();
    return true;
}
Example #7
0
NamedMutexImpl::NamedMutexImpl(const std::string& name):
	_name(name)
{
	_mutex = CreateMutexA(NULL, FALSE, _name.c_str());
	if (!_mutex) 
		throw SystemException("cannot create named mutex", _name);
}
Example #8
0
/**
 * Mutex
 */
LPDM_MUTEX mutexNew(const char *name)
{
    LPDM_MUTEX m = NULL;
#ifdef WIN32
    m = CreateMutexA(NULL, FALSE, name);
    if(m == NULL){
        DWORD dwError = GetLastError();
        if(dwError == ERROR_ACCESS_DENIED)
            m = OpenMutexA(SYNCHRONIZE, FALSE, name);
    }
#else
	pthread_mutexattr_t mutexattr;

	pthread_mutexattr_init(&mutexattr);
    m = (LPDM_MUTEX)malloc(sizeof(DM_MUTEX));
    m->context = NULL;
    if(name){
        int mutexexist = 0;
        mutexexist = shm_exist(name);
        m->context = mmapOpen(name, sizeof(pthread_mutex_t));
        m->mutex = (pthread_mutex_t*)m->context->data;
        if(mutexexist)
            return m;
        pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED);
        pthread_mutexattr_setrobust(&mutexattr, PTHREAD_MUTEX_ROBUST);
    }
    else
        m->mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));

	pthread_mutex_init(m->mutex, &mutexattr);
	pthread_mutexattr_destroy(&mutexattr);
#endif
    return m;
}
Example #9
0
//
// Create a memory-mapping to the Freetrack data.
// It contains the tracking data, a handle to the main-window and the program-name of the Game!
//
//
FT_EXPORT(bool) FTCreateMapping(void)
{
	//
	// Memory-mapping already exists!
	//
	if ( pMemData != NULL ) {
		return true;
	}

    dbg_report("FTCreateMapping request (pMemData == NULL).\n");

	//
	// A FileMapping is used to create 'shared memory' between the FTClient and the FTServer.
	//
	// Try to create a FileMapping to the Shared Memory. This is done to check if it's already there (what
	// may mean the face-tracker program is already running).
	//
	// If one already exists: close it and open the file-mapping to the existing one.
	//
	hFTMemMap = CreateFileMappingA( INVALID_HANDLE_VALUE , 00 , PAGE_READWRITE , 0 , 
		                           sizeof( FTMemMap ), 
								   (LPCSTR) FT_MM_DATA );

    if (hFTMemMap == NULL)
    {
        pMemData = NULL;
        return false;
    }

    pMemData = (FTMemMap *) MapViewOfFile(hFTMemMap, FILE_MAP_WRITE, 0, 0, sizeof( FTMemMap ) );
    hFTMutex = CreateMutexA(NULL, false, FREETRACK_MUTEX);

	return true;
}
Example #10
0
static void cbOpenMutexA()
{
    char mutex_name[20]="";
    long mutex_addr=0;
    long esp_addr=0;
    unsigned int return_addr=0;
    DeleteAPIBreakPoint((char*)"kernel32.dll", (char*)"OpenMutexA", UE_APISTART);
    esp_addr=(long)GetContextData(UE_ESP);
    if(!ReadProcessMemory(g_fdProcessInfo->hProcess, (const void*)esp_addr, &return_addr, 4, 0))
    {
        VF_FatalError(rpmerror(), g_ErrorMessageCallback);
        return;
    }
    if(!ReadProcessMemory(g_fdProcessInfo->hProcess, (const void*)(esp_addr+12), &mutex_addr, 4, 0))
    {
        VF_FatalError(rpmerror(), g_ErrorMessageCallback);
        return;
    }
    if(!ReadProcessMemory(g_fdProcessInfo->hProcess, (const void*)mutex_addr, &mutex_name, 20, 0))
    {
        VF_FatalError(rpmerror(), g_ErrorMessageCallback);
        return;
    }
    CreateMutexA(0, FALSE, mutex_name);
    if(GetLastError()==ERROR_SUCCESS)
        SetAPIBreakPoint((char*)"kernel32.dll", (char*)"VirtualProtect", UE_BREAKPOINT, UE_APISTART, (void*)cbVirtualProtect);
    else
    {
        char log_message[256]="";
        sprintf(log_message, "[Fail] Failed to create mutex %s", mutex_name);
        VF_FatalError(log_message, g_ErrorMessageCallback);
    }
}
Example #11
0
int main(int argc, char const *argv[])
{
	CreateMutexA(0,0,"Dr.COM_AUTH_SERVICE_MUTEX");
	if (GetLastError()==ERROR_ALREADY_EXISTS){
		printf("%s\n", "Drcom auth service is running!");
	}
	return 0;
}
Example #12
0
ofxOscReceiver::ofxOscReceiver()
{
#ifdef TARGET_WIN32
	mutex = CreateMutexA( NULL, FALSE, NULL );
#else
	pthread_mutex_init( &mutex, NULL );
#endif
}
Example #13
0
 bool acquire() {
     mMutex = CreateMutexA(nullptr, FALSE, "TempleofElementalEvilMutex");
     if (GetLastError() == ERROR_ALREADY_EXISTS) {
         MessageBoxA(nullptr, "Temple of Elemental Evil is already running.", "Temple of Elemental Evil", MB_OK | MB_ICONERROR);
         return false;
     }
     return true;
 }
Example #14
0
bool SpoutSharedMemory::Open(const char* name)
{
	// Don't call open twice on the same object without a Close()
	assert(name);

	if (m_hMap)
	{
		assert(strcmp(name, m_pName) == 0);
		assert(m_pBuffer && m_hMutex);
		return true;
	}

	m_hMap = OpenFileMappingA ( FILE_MAP_ALL_ACCESS,
									FALSE,
									(LPCSTR)name);

	if (m_hMap == NULL)
	{
		return false;
	}


	DWORD err = GetLastError();

	if (err == ERROR_ALREADY_EXISTS)
	{
		// We should ensure the already existing mapping is at least
		// the size we expect
	}

	m_pBuffer = (char*)MapViewOfFile(m_hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);


	if (!m_pBuffer)
	{
		Close();
		return false;
	}

	std::string	mutexName;
	mutexName = name;
	mutexName += "_mutex";

	m_hMutex = CreateMutexA(NULL, FALSE, mutexName.c_str());

	if (!m_hMutex)
	{
		Close();
		return false;
	}

	// m_pName = strdup(name);
	m_pName = _strdup(name);
	m_size = 0;

	return true;

}
Example #15
0
//***********************************************************************
static BOOL WeAreAlone(LPSTR szName)
{
   HANDLE hMutex = CreateMutexA(NULL, true, szName);
   if (GetLastError() == ERROR_ALREADY_EXISTS) {
      CloseHandle(hMutex);
      return false;
   }
   return true;
}
Example #16
0
int main(int argc, char *argv[])
{
    KLUPD::CoreError result = KLUPD::CORE_ADMKIT_FAILURE;

    IniConfiguration iniConfiguration;
    if(iniConfiguration.parse(argc, argv))
    {
        if(iniConfiguration.writeDump())
        {
            MiniDumper::enable();
            if(iniConfiguration.suppressErrorDialog())
                MiniDumper::suppressErrorDialog();
        }

        // protection against multiple instances
        #if defined(UNICODE) || defined(_UNICODE)
            #ifdef WSTRING_SUPPORTED
                HANDLE h = CreateMutex(0, FALSE, KLUPD::asciiToWideChar(iniConfiguration.applicaitonInstanceMutexName()).c_str());
            #else
                HANDLE h = CreateMutexA(0, FALSE, iniConfiguration.applicaitonInstanceMutexName().c_str());
            #endif
        #else
                HANDLE h = CreateMutex(0, FALSE, iniConfiguration.applicaitonInstanceMutexName().c_str());
        #endif

        // there is already an instance of this application running, or failed to create mutex
        if(!h || (GetLastError() == ERROR_ALREADY_EXISTS))
        {
            // TODO: change to code: failed to run several updater instances
        }
        else
            result = mainLoop(iniConfiguration);

        if(h)
            CloseHandle(h);
    }

    // writing single line result report to file
    KLUPD::AutoStream resultFile(0);
    const KLUPD::CoreError openResultFileResult = resultFile.open(iniConfiguration.updateReadableResultFileName(), L"w");
    if(isSuccess(openResultFileResult))
    {
        #ifdef WSTRING_SUPPORTED
            fwprintf(resultFile.stream(), L"%d\n%s", result, KLUPD::toString(result).toWideChar());
        #else
            fprintf(resultFile.stream(), "%d\n%s", result, KLUPD::toString(result).toAscii());
        #endif
    }
    else
    {
        std::cerr << "Failed to open trace file '" << iniConfiguration.updateReadableResultFileName().toAscii()
            << "', result " << KLUPD::toString(openResultFileResult).toAscii();
    }

    return result;
}
Example #17
0
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
	HANDLE hMutex = CreateMutexA(NULL, FALSE, "Escape_");
	if (hMutex != NULL && ERROR_ALREADY_EXISTS == GetLastError())
	{
		return 0;
	}
	nDialogRet = DialogBox( hInstance, MAKEINTRESOURCE(IDD_DIALOG_MAIN), NULL, DialogProc);
	return 0;
}
HOOKFUNC HANDLE WINAPI MyCreateMutexA(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCSTR lpName)
{
	HANDLE rv = CreateMutexA(lpMutexAttributes, 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;
}
/*!
    \internal
*/
void QInterProcessChannel::init() {
  // while(isRunning())
  //  quit();

  // create global mutex to check single instance
  CreateMutexA(NULL, FALSE, qPrintable(globalMutexStr));
  serverMode = !(GetLastError() == ERROR_ALREADY_EXISTS);

  // start listening thread in single instance mode
  if (serverMode) start();
}
 HOOKFUNC HANDLE WINAPI MyCreateMutexA(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCSTR lpName)
 {
     ENTER();
     HANDLE rv = CreateMutexA(lpMutexAttributes, bInitialOwner, lpName);
     LEAVE(rv);
     EnterCriticalSection(&s_handleCS);
     std::set<HANDLE>& handles = s_threadIdHandles[GetCurrentThreadId()];
     handles.insert(rv);
     LeaveCriticalSection(&s_handleCS);
     return rv;
 }
Example #21
0
void *try_open_single_program(const char *name) {
    char full_name[255];
    HANDLE program_instance;

    strcpy(full_name, "Global\\{");
    strcat(full_name, name);
    strcat(full_name, "}");
    program_instance = CreateMutexA(NULL, FALSE, full_name);
    if (GetLastError() == ERROR_ALREADY_EXISTS || program_instance == NULL) {
        return NULL;
    }
    return program_instance;
}
Example #22
0
	void Check(const char *url, const char *post)
	{
		// ·ÀÖ¹¶à´Îµ÷ÓÃ
		HANDLE mutex = CreateMutexA(NULL, TRUE, url);
		if (GetLastError() == ERROR_ALREADY_EXISTS)
		{
			CloseHandle(mutex);
			return;
		}

		std::thread check_thread = std::thread(CheckThread, url, post);
		check_thread.join();
	}
Example #23
0
int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE hMutex = CreateMutexA( NULL, TRUE, "MutexName111a" ); // 뮤텍스 생성
	printf( "hMutex = %d\n", hMutex );
	printf( "WaitForSingleObject\n" );
	WaitForSingleObject( hMutex, INFINITE );

	printf( "Process\n" );

	Sleep( 5000 );
	CloseHandle(hMutex);
	return 0;
}
/*!
    \brief Send a message to server instance
*/
void QInterProcessChannel::sendMessage(const QByteArray& msg) {
  if (msg.count()) {
    // a lot of simultaneous clients cause that pipe sometimes omits
    // some of these clients despite results of writing functions are ok ;/
    // workaround: reserve mutex, wait 100ms before every write operation

    HANDLE mutex = CreateMutexA(NULL, FALSE, qPrintable(blockerMutexStr));
    WaitForSingleObject(mutex, INFINITE);
    Sleep(100);

    HANDLE hPipe;

    // loop to get pipe's handle
    for (;;) {
      hPipe = CreateFileA(qPrintable(pipeName), GENERIC_WRITE, 0, NULL,
                          OPEN_EXISTING, 0, NULL);

      if (hPipe != INVALID_HANDLE_VALUE) break;

      if (GetLastError() != ERROR_PIPE_BUSY) {
        ReleaseMutex(mutex);
        return;
      }

      // wait max 1s and retry
      WaitNamedPipeA(qPrintable(pipeName), 1000);
    }

    // ok, now we have pipe's handle, we can prepare buffers and write to the
    // pipe

    char buffer[bufferSize];
    strncpy(buffer, msg.constData(), bufferSize);
    buffer[bufferSize - 1] = 0;

    DWORD bytesWritten;
    bool writeSuccess =
        WriteFile(hPipe, buffer, strlen(buffer) + 1, &bytesWritten, NULL);

    if (!writeSuccess) {
      ReleaseMutex(mutex);
      return;
    }

    CloseHandle(hPipe);
    ReleaseMutex(mutex);
  } else {
    // qWarning("::sendMessage(%d): Empty messages are not carried out...",
    // GetCurrentProcessId());
  }
}
bool ValidateDumperMutex()
{	VU("ValidateDumperMutex");

	char mtx[256];
	sprintf(mtx, V("TeknoPDump%08X"), GetCurrentProcessId() ^ 0x80);
	CreateMutexA(0, true, mtx);
	if(GetLastError() != 0xB7)
	{
		return false;
	}

	return true;	
	VE();
}
Example #26
0
    BOOL Client::WatchOverServer(VOID)
    {
        BOOL watch_over_server_result = false;

        HANDLE watch_over_server_mutex_handle = CreateMutexA(NULL, FALSE,  SERVER_IS_WORKING_MUTEX_GUID);  
        if (( watch_over_server_mutex_handle != NULL ) && (GetLastError() != ERROR_ALREADY_EXISTS))
        { 
            watch_over_server_result = true;
        }

        CLOSE_HANDLE(watch_over_server_mutex_handle);

        return watch_over_server_result;
    }
Example #27
0
File: Scene.cpp Project: sdp0et/gtp
Scene::Scene()
{
  mediaEta = 1 ;
  bgColor = 0; //Vector(1,1,1,1) ; // If you use a WHITE bg color and monte trace with 1 bounce,
  // you get an AO render
  
  useFarLights = false ;

  mutexShapeList = CreateMutexA( 0, 0, "Shape list lock" ) ;
  mutexVizList = CreateMutexA( 0, 0, "Viz list lock" ) ;
  mutexScenery = CreateMutexA( 0, 0, "scenery lock" ) ;
  mutexDebugLines = CreateMutexA( 0, 0, "mutex-mutexDebugLines" ) ;
  mutexFCR = CreateMutexA( 0, 0, "mutex-mutexFCR" ) ;

  spExact=0,spMesh=0,spAll=0;
  lastVertexCount = 0 ;
  spacePartitioningOn = 1 ; // assume it's on.
  perlinSkyOn = 1 ;
  spRotated = 0 ;
  shCombinedViz = 0 ;
  activeCubemap = 0 ;
  //activeLightIndex = 0 ;
}
Example #28
0
void Entry(void)
{
	HANDLE hMutex;
	int result=1;
	Options options;

	g_controlMsg=RegisterWindowMessageA(CONTROL_MESSAGE_NAME);

	ZeroFill(&options,sizeof options);
	ProcessCommandLine(&options);

#ifdef _DEBUG
	options.showWindow=TRUE;
#endif

	hMutex=OpenMutexA(MUTEX_ALL_ACCESS,FALSE,MUTEX_NAME);
	if(hMutex)
	{
		// Already running.
		ApplyOptions(&options);
	}
	else
	{
		if(options.nextLayout||options.prevLayout)
		{
			// Don't do anything.
		}
		else
		{
			hMutex=CreateMutexA(0,FALSE,MUTEX_NAME);

			if(!RunHelpers())
				result=1;
			else
			{
				result=Main(&options);

				ReleaseMutex(hMutex);
				hMutex=NULL;
			}

			PostMessage(HWND_BROADCAST,g_controlMsg,CONTROL_QUIT,0);
		}
	}

	LocalFree(options.pLayoutToSet);
	options.pLayoutToSet=NULL;

	ExitProcess(result);
}
Example #29
0
HRESULT CPipeline::Create() 
{ 
	PreviewEngine = NULL;
	//fTime= 0;
	
    CreateRoot();

	ReadWriteMutex = CreateMutexA(NULL, FALSE, "DXCCPipeline_SceneReadWriteLock");
	InitializeCriticalSection(&ZeroSceneReadersSection);
	SceneReadersCount = 0;
	ZeroSceneReadersEvent = CreateEventA(NULL, TRUE, TRUE, "DXCCPipeline_ZeroReaders");

	return S_OK; 
}
Example #30
0
// for a sender to set a mutex for a receiver to test
void spoutMemoryShare::CreateSenderMutex()
{
    HANDLE hMutex = OpenMutexA(MUTEX_ALL_ACCESS, 0, "SpoutMemorySender");

	// If no sender is running yet, create a mutex that a receiver can check
	if (!hMutex) {
		#ifdef CONSOLE_DEBUG 
		printf("Creating sender mutex\n"); 
		#endif
		hSenderMutex = CreateMutexA(0, 0, "SpoutMemorySender");
	}

	CloseHandle(hMutex);
}