Exemple #1
0
void __cdecl SilAssert (
		const char * expr,
		const char * filename,
		unsigned lineno
		)
{
	/*
	 * Build the assertion message, then display it.
	 */
	int nCode = IDIGNORE;
	char * pch;
	char assertbuf[ASSERTBUFSZ];
	char progname[MAX_PATH + 1];

	/*
		* Line 1: box intro line
		*/
	strcpy_s( assertbuf, ASSERTBUFSZ, BOXINTRO );
	strcat_s( assertbuf, ASSERTBUFSZ, dblnewline );

#if WIN32
	// TODO-Linux: Find filename of managed executable
	/*
		* Line 2: program line
		*/
	strcat_s( assertbuf, ASSERTBUFSZ, PROGINTRO );

	progname[MAX_PATH] = '\0';
	if ( !GetModuleFileName( NULL, progname, MAX_PATH ))
		strcpy_s( progname, ASSERTBUFSZ, "<program name unknown>");

	pch = (char *)progname;

	/* sizeof(PROGINTRO) includes the NULL terminator */
	if ( sizeof(PROGINTRO) + strlen(progname) + NEWLINESZ > MAXLINELEN )
	{
		int cch = (sizeof(PROGINTRO) + strlen(progname) + NEWLINESZ) - MAXLINELEN;
		pch += cch;
		strncpy_s( pch, sizeof(progname) - cch, dotdotdot, DOTDOTDOTSZ );
	}

	strcat_s( assertbuf, ASSERTBUFSZ, pch );
	strcat_s( assertbuf, ASSERTBUFSZ, newline );
#endif

	/*
		* Line 3: file line
		*/
	strcat_s( assertbuf, ASSERTBUFSZ, FILEINTRO );

	/* sizeof(FILEINTRO) includes the NULL terminator */
	if ( sizeof(FILEINTRO) + strlen(filename) + NEWLINESZ > MAXLINELEN )
	{
		size_t p, len, ffn;

		pch = (char *) filename;
		ffn = MAXLINELEN - sizeof(FILEINTRO) - NEWLINESZ;

		for ( len = strlen(filename), p = 1;
				pch[len - p] != '\\' && pch[len - p] != '/' && p < len;
				p++ );

		/* keeping pathname almost 2/3rd of full filename and rest
			* is filename
			*/
		if ( (ffn - ffn/3) < (len - p) && ffn/3 > p )
		{
			/* too long. using first part of path and the
				filename string */
			strncat_s( assertbuf, ASSERTBUFSZ, pch, ffn - DOTDOTDOTSZ - p );
			strcat_s( assertbuf, ASSERTBUFSZ, dotdotdot );
			strcat_s( assertbuf, ASSERTBUFSZ, pch + len - p );
		}
		else if ( ffn - ffn/3 > len - p )
		{
			/* pathname is smaller. keeping full pathname and putting
				* dotdotdot in the middle of filename
				*/
			p = p/2;
			strncat_s( assertbuf, ASSERTBUFSZ, pch, ffn - DOTDOTDOTSZ - p );
			strcat_s( assertbuf, ASSERTBUFSZ, dotdotdot );
			strcat_s( assertbuf, ASSERTBUFSZ, pch + len - p );
		}
		else
		{
			/* both are long. using first part of path. using first and
				* last part of filename.
				*/
			strncat_s( assertbuf, ASSERTBUFSZ, pch, ffn - ffn/3 - DOTDOTDOTSZ );
			strcat_s( assertbuf, ASSERTBUFSZ, dotdotdot );
			strncat_s( assertbuf, ASSERTBUFSZ, pch + len - p, ffn/6 - 1 );
			strcat_s( assertbuf, ASSERTBUFSZ, dotdotdot );
			strcat_s( assertbuf, ASSERTBUFSZ, pch + len - (ffn/3 - ffn/6 - 2) );
		}

	}
	else
		/* plenty of room on the line, just append the filename */
		strcat_s( assertbuf, ASSERTBUFSZ, filename );

	strcat_s( assertbuf, ASSERTBUFSZ, newline );

	/*
		* Line 4: line line
		*/
	strcat_s( assertbuf, ASSERTBUFSZ, LINEINTRO );
	_itoa_s( lineno, assertbuf + strlen(assertbuf), sizeof(assertbuf) - strlen(assertbuf), 10 );
	strcat_s( assertbuf, ASSERTBUFSZ, dblnewline );

	/*
		* Line 5: message line
		*/
	strcat_s( assertbuf, ASSERTBUFSZ, EXPRINTRO );

	/* sizeof(HELPINTRO) includes the NULL terminator */

	if (    strlen(assertbuf) +
			strlen(expr) +
			2*DBLNEWLINESZ +
			sizeof(INFOINTRO)-1 +
			sizeof(HELPINTRO) > ASSERTBUFSZ )
	{
		strncat_s( assertbuf, ASSERTBUFSZ,
			expr,
			ASSERTBUFSZ -
			(strlen(assertbuf) +
			DOTDOTDOTSZ +
			2*DBLNEWLINESZ +
			sizeof(INFOINTRO)-1 +
			sizeof(HELPINTRO)) );
		strcat_s( assertbuf, ASSERTBUFSZ, dotdotdot );
	}
	else
		strcat_s( assertbuf, ASSERTBUFSZ, expr );

	strcat_s( assertbuf, ASSERTBUFSZ, dblnewline );

	/*
		* Line 6, 7: info line
		*/

	strcat_s(assertbuf, ASSERTBUFSZ, INFOINTRO);
	strcat_s( assertbuf, ASSERTBUFSZ, dblnewline );

	/*
		* Line 8: help line
		*/
	strcat_s(assertbuf, ASSERTBUFSZ, HELPINTRO);

	// SIL addition: log the message using OutputDebugString

	if (g_ReportHook)
		g_ReportHook(_CRT_ASSERT, assertbuf);
	else
		OutputDebugString(assertbuf);

	// NOTE: this method is intented to be used by unmanaged apps only;
	// managed apps should use DebugProcs.AssertProc in DebugProcs.cs

	/*
	 * Write out via MessageBox
	 */
	if (g_fShowMessageBox)
	{
		nCode = MessageBoxA(NULL, assertbuf,
			"SIL Program Failure warning (Assert failed)",
			MB_ABORTRETRYIGNORE|MB_ICONHAND|MB_SETFOREGROUND|MB_TASKMODAL);

		/* Abort: abort the program */
		if (nCode == IDABORT)
		{
			/* raise abort signal */
			raise(SIGABRT);

			/* We usually won't get here, but it's possible that
				SIGABRT was ignored.  So exit the program anyway. */

			_exit(3);
		}

		/* Retry: call the debugger */
		if (nCode == IDRETRY)
		{
#if WIN32
			_DbgBreak();
#else
			raise(SIGTRAP);
#endif
			/* return to user code */
			return;
		}

		if (nCode != IDIGNORE)
			abort();
	}
	else // !g_fShowMessageBox
	{
		// if we don't show a message box we should at least abort (and output the assertion
		// text if we haven't done that already). Note that we don't call _exit(3) as above
		// so that we can trap the signal and ignore it in unit tests
		if (g_ReportHook)
			OutputDebugString(assertbuf);
		raise(SIGABRT);
	}

	/* Ignore: continue execution */
	return;
}
Exemple #2
0
int main(int argc, char *argv[]) {
	char *bslash;
	VerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	GetVersionEx(&VerInfo);
	if (argc < 2) {
		show_usage();
		return -1;
	}
	hAdvapi = LoadLibrary("advapi32.dll");
	uChangeServiceConfig2 = (UCHANGESERVICECONFIG2)GetProcAddress(hAdvapi, "ChangeServiceConfig2A");
	if (!stricmp(argv[1], "install")) {
		SC_HANDLE hService, hSCManager;
		char path[MAX_PATH+1];
		char binpath[MAX_PATH+1];
		hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);

		if (!hSCManager) {
			exit(0);
		}
		GetModuleFileName(NULL,path,MAX_PATH);
		if ((bslash = strrchr(path, '\\')))
			*bslash = 0;
		
		strcpy(binpath,path);
		strcat(binpath, "\\UnrealIRCd.exe");
		hService = CreateService(hSCManager, "UnrealIRCd", "UnrealIRCd",
				 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
				 SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, binpath,
				 NULL, NULL, NULL, NULL, NULL); 
		if (hService) 
		{
			printf("UnrealIRCd NT Service successfully installed");
			if (VerInfo.dwMajorVersion >= 5) {
				SERVICE_DESCRIPTION info;
				info.lpDescription = "Internet Relay Chat Server. Allows users to chat with eachother via an IRC client.";
				uChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &info);
			}
			CloseServiceHandle(hService);
		} else
			printf("Failed to install UnrealIRCd NT Service - %s", show_error(GetLastError()));
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "uninstall")) {
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", DELETE); 
		if (DeleteService(hService)) 
			printf("UnrealIRCd NT Service successfully uninstalled");
		else
			printf("Failed to uninstall UnrealIRCd NT Service - %s", show_error(GetLastError()));
		CloseServiceHandle(hService);
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "start")) {
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_START); 
		if (StartService(hService, 0, NULL)) 
			printf("UnrealIRCd NT Service successfully started");
		else
			printf("Failed to start UnrealIRCd NT Service - %s", show_error(GetLastError()));
		CloseServiceHandle(hService);
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "stop")) {
		SERVICE_STATUS status;
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_STOP); 
		ControlService(hService, SERVICE_CONTROL_STOP, &status);
		printf("UnrealIRCd NT Service successfully stopped");
		CloseServiceHandle(hService);
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "restart")) {
		SERVICE_STATUS status;
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_STOP|SERVICE_START); 
		ControlService(hService, SERVICE_CONTROL_STOP, &status);
		if (StartService(hService, 0, NULL)) 
			printf("UnrealIRCd NT Service successfully restarted");
		CloseServiceHandle(hService);
		CloseServiceHandle(hSCManager);
		return 0;
	}
	else if (!stricmp(argv[1], "rehash")) {
		SERVICE_STATUS status;
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd", SERVICE_USER_DEFINED_CONTROL); 
		ControlService(hService, IRCD_SERVICE_CONTROL_REHASH, &status);
		printf("UnrealIRCd NT Service successfully rehashed");
	}
	else if (!stricmp(argv[1], "config")) {
		SERVICE_STATUS status;
		SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		SC_HANDLE hService = OpenService(hSCManager, "UnrealIRCd",
						 SERVICE_CHANGE_CONFIG|SERVICE_START); 
		if (argc < 3) {
			show_usage();
			return -1;
		}
		if (!stricmp(argv[2], "startup")) {
			if (ChangeServiceConfig(hService, SERVICE_NO_CHANGE,
					    !stricmp(argv[3], "auto") ? SERVICE_AUTO_START
						: SERVICE_DEMAND_START, SERVICE_NO_CHANGE,
					    NULL, NULL, NULL, NULL, NULL, NULL, NULL)) 
				printf("UnrealIRCd NT Service configuration changed");
			else
				printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError()));	
		}
		else if (!stricmp(argv[2], "crashrestart") && VerInfo.dwMajorVersion == 5) {
			SERVICE_FAILURE_ACTIONS hFailActions;
			SC_ACTION hAction;
			memset(&hFailActions, 0, sizeof(hFailActions));
			if (argc >= 4) {
				hFailActions.dwResetPeriod = 30;
				hFailActions.cActions = 1;
				hAction.Type = SC_ACTION_RESTART;
				hAction.Delay = atoi(argv[3])*60000;
				hFailActions.lpsaActions = &hAction;
				if (uChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS, 	
						     &hFailActions))
					printf("UnrealIRCd NT Service configuration changed");
				else
					printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError()));	
			}
			else {
				hFailActions.dwResetPeriod = 0;
				hFailActions.cActions = 0;
				hAction.Type = SC_ACTION_NONE;
				hFailActions.lpsaActions = &hAction;
				if (uChangeServiceConfig2(hService, SERVICE_CONFIG_FAILURE_ACTIONS,
						     &hFailActions)) 
					printf("UnrealIRCd NT Service configuration changed");
				else
					printf("UnrealIRCd NT Service configuration change failed - %s", show_error(GetLastError()));	

				
			}
		}
		else {
			show_usage();
			return -1;
		}	
	}
	else {
		show_usage();
		return -1;
	}

		
			
}
Exemple #3
0
NS_IMETHODIMP
nsDebugImpl::Assertion(const char *aStr, const char *aExpr, const char *aFile, PRInt32 aLine)
{
   InitLog();

   char buf[1000];
   PR_snprintf(buf, sizeof(buf),
              "###!!! ASSERTION: %s: '%s', file %s, line %d",
              aStr, aExpr, aFile, aLine);

   // Write out the assertion message to the debug log
   PR_LOG(gDebugLog, PR_LOG_ERROR, ("%s", buf));
   PR_LogFlush();

   // And write it out to the stderr
   fprintf(stderr, "%s\n", buf);
   fflush(stderr);

#if defined(_WIN32)
   char* assertBehavior = getenv("XPCOM_DEBUG_BREAK");
   if (assertBehavior && strcmp(assertBehavior, "warn") == 0)
     return NS_OK;

   if(!InDebugger())
      {
      DWORD code = IDRETRY;

      /* Create the debug dialog out of process to avoid the crashes caused by 
       * Windows events leaking into our event loop from an in process dialog.
       * We do this by launching windbgdlg.exe (built in xpcom/windbgdlg).
       * See http://bugzilla.mozilla.org/show_bug.cgi?id=54792
       */
      PROCESS_INFORMATION pi;
      STARTUPINFO si;
      char executable[MAX_PATH];
      char* pName;

      memset(&pi, 0, sizeof(pi));

      memset(&si, 0, sizeof(si));
      si.cb          = sizeof(si);
      si.wShowWindow = SW_SHOW;

      if(GetModuleFileName(GetModuleHandle(XPCOM_DLL), executable, MAX_PATH) &&
         NULL != (pName = strrchr(executable, '\\')) &&
         NULL != strcpy(pName+1, "windbgdlg.exe") &&
#ifdef DEBUG_jband
         (printf("Launching %s\n", executable), PR_TRUE) &&
#endif         
         CreateProcess(executable, buf, NULL, NULL, PR_FALSE,
                       DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
                       NULL, NULL, &si, &pi) &&
         WAIT_OBJECT_0 == WaitForSingleObject(pi.hProcess, INFINITE) &&
         GetExitCodeProcess(pi.hProcess, &code))
      {
        CloseHandle(pi.hProcess);
      }                         

      switch(code)
         {
         case IDABORT:
            //This should exit us
            raise(SIGABRT);
            //If we are ignored exit this way..
            _exit(3);
            break;
         
         case IDIGNORE:
            return NS_OK;
            // Fall Through
         }
      }
#endif

#if defined(XP_OS2)
   char* assertBehavior = getenv("XPCOM_DEBUG_BREAK");
   if (assertBehavior && strcmp(assertBehavior, "warn") == 0)
     return NS_OK;

      char msg[1200];
      PR_snprintf(msg, sizeof(msg),
                "%s\n\nClick Cancel to Debug Application.\n"
                "Click Enter to continue running the Application.", buf);
      ULONG code = MBID_ERROR;
      code = WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, msg, 
                           "nsDebug::Assertion", 0,
                           MB_ERROR | MB_ENTERCANCEL);

      /* It is possible that we are executing on a thread that doesn't have a
       * message queue.  In that case, the message won't appear, and code will
       * be 0xFFFF.  We'll give the user a chance to debug it by calling
       * Break()
       * Actually, that's a really bad idea since this happens a lot with threadsafe
       * assertions and since it means that you can't actually run the debug build
       * outside a debugger without it crashing constantly.
       */
      if(( code == MBID_ENTER ) || (code == MBID_ERROR))
      {
         return NS_OK;
         // If Retry, Fall Through
      }
#endif

      Break(aFile, aLine);
      return NS_OK;
}
Exemple #4
0
// nTimeout - таймаут подключения
HANDLE ExecuteOpenPipe(const wchar_t* szPipeName, wchar_t (&szErr)[MAX_PATH*2], const wchar_t* szModule, DWORD nServerPID, DWORD nTimeout, BOOL Overlapped /*= FALSE*/, HANDLE hStop /*= NULL*/, BOOL bIgnoreAbsence /*= FALSE*/)
{
	HANDLE hPipe = NULL;
	DWORD dwErr = 0, dwMode = 0;
	BOOL fSuccess = FALSE;
	DWORD dwStartTick = GetTickCount();
	DWORD nSleepError = 10;
	// допустимое количество обломов, отличных от ERROR_PIPE_BUSY. после каждого - Sleep(nSleepError);
	// Увеличим допустимое количество попыток, иначе облом наступает раньше секунды ожидания
	const int nDefaultTries = 100;
	int nTries = nDefaultTries;
	// nTimeout должен ограничивать ВЕРХНЮЮ границу времени ожидания
	_ASSERTE(EXECUTE_CMD_OPENPIPE_TIMEOUT >= nTimeout);
	DWORD nOpenPipeTimeout = nTimeout ? min(nTimeout,EXECUTE_CMD_OPENPIPE_TIMEOUT) : EXECUTE_CMD_OPENPIPE_TIMEOUT;
	_ASSERTE(nOpenPipeTimeout > 0);
	DWORD nWaitPipeTimeout = min(250,nOpenPipeTimeout);

	BOOL bWaitPipeRc = FALSE, bWaitCalled = FALSE;
	DWORD nWaitPipeErr = 0;
	DWORD nDuration = 0;
	DWORD nStopWaitRc = (DWORD)-1;

	#ifdef _DEBUG
	wchar_t szDbgMsg[512], szTitle[128];
	#endif

	// WinXP SP1 и выше
	DEBUGTEST(BOOL lbServerIsDebugged = nServerPID ? IsProcessDebugged(nServerPID) : FALSE);

	
	_ASSERTE(LocalSecurity()!=NULL);


	// Try to open a named pipe; wait for it, if necessary.
	while (1)
	{
		hPipe = CreateFile(
		            szPipeName,     // pipe name
		            GENERIC_READ|GENERIC_WRITE,
		            0,              // no sharing
		            LocalSecurity(), // default security attributes
		            OPEN_EXISTING,  // opens existing pipe
		            (Overlapped ? FILE_FLAG_OVERLAPPED : 0), // default attributes
		            NULL);          // no template file
		dwErr = GetLastError();

		// Break if the pipe handle is valid.
		if (hPipe && (hPipe != INVALID_HANDLE_VALUE))
		{
			break; // OK, открыли
		}
		_ASSERTE(hPipe);

		#ifdef _DEBUG
		if (gbPipeDebugBoxes)
		{
			szDbgMsg[0] = 0;
			GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg));
			msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId());
			msprintf(szDbgMsg, countof(szDbgMsg), L"Can't open pipe, ErrCode=%u\n%s\nWait: %u,%u,%u", dwErr, szPipeName, bWaitCalled, bWaitPipeRc, nWaitPipeErr);
			int nBtn = ::MessageBox(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL|MB_RETRYCANCEL);
			if (nBtn == IDCANCEL)
				return NULL;
		}
		#endif

		nDuration = GetTickCount() - dwStartTick;

		if (hStop)
		{
			// Затребовано завершение приложения или еще что-то
			nStopWaitRc = WaitForSingleObject(hStop, 0);
			if (nStopWaitRc == WAIT_OBJECT_0)
			{
				return NULL;
			}
		}

		if (dwErr == ERROR_PIPE_BUSY)
		{
			if ((nTries > 0) && (nDuration < nOpenPipeTimeout))
			{
				bWaitCalled = TRUE;

				// All pipe instances are busy, so wait for a while (not more 500 ms).
				bWaitPipeRc = WaitNamedPipe(szPipeName, nWaitPipeTimeout);
				nWaitPipeErr = GetLastError();
				UNREFERENCED_PARAMETER(bWaitPipeRc); UNREFERENCED_PARAMETER(nWaitPipeErr);
				// -- 120602 раз они заняты (но живы), то будем ждать, пока не освободятся
				//nTries--;
				continue;
			}
			else
			{
				_ASSERTEX(dwErr != ERROR_PIPE_BUSY);
			}
		}

		// Сделаем так, чтобы хотя бы пару раз он попробовал повторить
		if ((nTries <= 0) || (nDuration > nOpenPipeTimeout))
		{
			#ifdef _DEBUG
			msprintf(szErr, countof(szErr), L"%s.%u\nCreateFile(%s) failed\ncode=%u%s%s",
			          ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr,
			          (nTries <= 0) ? L", Tries" : L"", (nDuration > nOpenPipeTimeout) ? L", Duration" : L"");
			//_ASSERTEX(FALSE && "Pipe open failed with timeout!");
			int iBtn = bIgnoreAbsence ? IDCANCEL
				: MessageBox(NULL, szErr, L"Pipe open failed with timeout!", MB_ICONSTOP|MB_SYSTEMMODAL|MB_RETRYCANCEL);
			if (iBtn == IDRETRY)
			{
				nTries = nDefaultTries;
				continue;
			}
			#endif
			SetLastError(dwErr);
			return NULL;
		}
		else
		{
			nTries--;
		}

		// Может быть пайп еще не создан (в процессе срабатывания семафора)
		if (dwErr == ERROR_FILE_NOT_FOUND)
		{
			// Wait for a while (10 ms)
			Sleep(nSleepError);
			continue;
		}

		// Exit if an error other than ERROR_PIPE_BUSY occurs.
		// -- if (dwErr != ERROR_PIPE_BUSY) // уже проверено выше
		msprintf(szErr, countof(szErr), L"%s.%u: CreateFile(%s) failed, code=%u",
		          ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr);
		SetLastError(dwErr);

		// Failed!
		return NULL;

		// Уже сделано выше
		//// All pipe instances are busy, so wait for 500 ms.
		//WaitNamedPipe(szPipeName, 500);
		//if (!WaitNamedPipe(szPipeName, 1000) )
		//{
		//	dwErr = GetLastError();
		//	if (pszErr)
		//	{
		//		StringCchPrintf(pszErr, countof(pszErr), L"%s: WaitNamedPipe(%s) failed, code=0x%08X, WaitNamedPipe",
		//			szModule ? szModule : L"Unknown", szPipeName, dwErr);
		//		// Видимо это возникает в момент запуска (обычно для ShiftEnter - новая консоль)
		//		// не сразу срабатывает GUI и RCon еще не создал Pipe для HWND консоли
		//		_ASSERTE(dwErr == 0);
		//	}
		//    return NULL;
		//}
	}

#ifdef _DEBUG
	DWORD nCurState = 0, nCurInstances = 0;
	BOOL bCurState = GetNamedPipeHandleState(hPipe, &nCurState, &nCurInstances, NULL, NULL, NULL, 0);
#endif

	// The pipe connected; change to message-read mode.
	dwMode = CE_PIPE_READMODE;
	fSuccess = SetNamedPipeHandleState(
	               hPipe,    // pipe handle
	               &dwMode,  // new pipe mode
	               NULL,     // don't set maximum bytes
	               NULL);    // don't set maximum time

#if 0
	if (!fSuccess)
	{
		dwErr = GetLastError();
		_ASSERTE(fSuccess);
		//if (pszErr)
		{
			msprintf(szErr, countof(szErr), L"%s.%u: SetNamedPipeHandleState(%s) failed, code=0x%08X",
			          ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr);
			#ifdef _DEBUG
			int nCurLen = lstrlen(szErr);
			msprintf(szErr+nCurLen, countof(szErr)-nCurLen, L"\nCurState: %u,x%08X,%u", bCurState, nCurState, nCurInstances);
			#endif
		}
		CloseHandle(hPipe);

#ifdef _DEBUG
		if (gbPipeDebugBoxes)
		{
			szDbgMsg[0] = 0;
			GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg));
			msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId());
			::MessageBox(NULL, szErr, szTitle, MB_SYSTEMMODAL);
		}
#endif

		return NULL;
	}
#endif

	UNREFERENCED_PARAMETER(bWaitCalled);
	UNREFERENCED_PARAMETER(fSuccess);

	return hPipe;
}
LONG CALLBACK OBSExceptionHandler (PEXCEPTION_POINTERS exceptionInfo)
{
    HANDLE  hProcess;

    HMODULE hDbgHelp;

    MINIDUMP_EXCEPTION_INFORMATION miniInfo;

    STACKFRAME64        frame = {0};
    CONTEXT             context = *exceptionInfo->ContextRecord;
    SYMBOL_INFO         *symInfo;
    DWORD64             fnOffset;
    TCHAR               logPath[MAX_PATH];

    OSVERSIONINFOEX     osInfo;
    SYSTEMTIME          timeInfo;

    ENUMERATELOADEDMODULES64    fnEnumerateLoadedModules64;
    SYMSETOPTIONS               fnSymSetOptions;
    SYMINITIALIZE               fnSymInitialize;
    STACKWALK64                 fnStackWalk64;
    SYMFUNCTIONTABLEACCESS64    fnSymFunctionTableAccess64;
    SYMGETMODULEBASE64          fnSymGetModuleBase64;
    SYMFROMADDR                 fnSymFromAddr;
    SYMCLEANUP                  fnSymCleanup;
    MINIDUMPWRITEDUMP           fnMiniDumpWriteDump;
    SYMGETMODULEINFO64          fnSymGetModuleInfo64;

    DWORD                       i;
    DWORD64                     InstructionPtr;
    DWORD                       imageType;

    TCHAR                       searchPath[MAX_PATH], *p;

    static BOOL                 inExceptionHandler = FALSE;

    moduleinfo_t                moduleInfo;

    //always break into a debugger if one is present
    if (IsDebuggerPresent ())
        return EXCEPTION_CONTINUE_SEARCH;

    //exception codes < 0x80000000 are typically informative only and not crash worthy
    //0xe06d7363 indicates a c++ exception was thrown, let's just hope it was caught.
    //this is no longer needed since we're an unhandled handler vs a vectored handler
    
    /*if (exceptionInfo->ExceptionRecord->ExceptionCode < 0x80000000 || exceptionInfo->ExceptionRecord->ExceptionCode == 0xe06d7363 ||
        exceptionInfo->ExceptionRecord->ExceptionCode == 0x800706b5)
        return EXCEPTION_CONTINUE_SEARCH;*/

    //uh oh, we're crashing inside ourselves... this is really bad!
    if (inExceptionHandler)
        return EXCEPTION_CONTINUE_SEARCH;

    inExceptionHandler = TRUE;

    //load dbghelp dynamically
    hDbgHelp = LoadLibrary (TEXT("DBGHELP"));

    if (!hDbgHelp)
        return EXCEPTION_CONTINUE_SEARCH;

    fnEnumerateLoadedModules64 = (ENUMERATELOADEDMODULES64)GetProcAddress (hDbgHelp, "EnumerateLoadedModulesW64");
    fnSymSetOptions = (SYMSETOPTIONS)GetProcAddress (hDbgHelp, "SymSetOptions");
    fnSymInitialize = (SYMINITIALIZE)GetProcAddress (hDbgHelp, "SymInitialize");
    fnSymFunctionTableAccess64 = (SYMFUNCTIONTABLEACCESS64)GetProcAddress (hDbgHelp, "SymFunctionTableAccess64");
    fnSymGetModuleBase64 = (SYMGETMODULEBASE64)GetProcAddress (hDbgHelp, "SymGetModuleBase64");
    fnStackWalk64 = (STACKWALK64)GetProcAddress (hDbgHelp, "StackWalk64");
    fnSymFromAddr = (SYMFROMADDR)GetProcAddress (hDbgHelp, "SymFromAddrW");
    fnSymCleanup = (SYMCLEANUP)GetProcAddress (hDbgHelp, "SymCleanup");
    fnSymGetModuleInfo64 = (SYMGETMODULEINFO64)GetProcAddress (hDbgHelp, "SymGetModuleInfo64");
    fnMiniDumpWriteDump = (MINIDUMPWRITEDUMP)GetProcAddress (hDbgHelp, "MiniDumpWriteDump");

    if (!fnEnumerateLoadedModules64 || !fnSymSetOptions || !fnSymInitialize || !fnSymFunctionTableAccess64 ||
        !fnSymGetModuleBase64 || !fnStackWalk64 || !fnSymFromAddr || !fnSymCleanup || !fnSymGetModuleInfo64)
    {
        FreeLibrary (hDbgHelp);
        return EXCEPTION_CONTINUE_SEARCH;
    }

    hProcess = GetCurrentProcess();

    fnSymSetOptions (SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_LOAD_ANYTHING);

    GetModuleFileName (NULL, searchPath, _countof(searchPath)-1);
    p = srchr (searchPath, '\\');
    if (p)
        *p = 0;

    //create a log file
    GetSystemTime (&timeInfo);
    for (i = 1;;)
    {
        tsprintf_s (logPath, _countof(logPath)-1, TEXT("%s\\crashDumps\\OBSCrashLog%.4d-%.2d-%.2d_%d.txt"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i);
        if (GetFileAttributes(logPath) == INVALID_FILE_ATTRIBUTES)
            break;
        i++;
    }

    XFile   crashDumpLog;

    if (!crashDumpLog.Open(logPath, XFILE_WRITE, XFILE_CREATENEW))
    {
        FreeLibrary (hDbgHelp);
        return EXCEPTION_CONTINUE_SEARCH;
    }

    //initialize debug symbols
    fnSymInitialize (hProcess, NULL, TRUE);

#ifdef _WIN64
    InstructionPtr = context.Rip;
    frame.AddrPC.Offset = InstructionPtr;
    frame.AddrFrame.Offset = context.Rbp;
    frame.AddrStack.Offset = context.Rsp;
    imageType = IMAGE_FILE_MACHINE_AMD64;
#else
    InstructionPtr = context.Eip;
    frame.AddrPC.Offset = InstructionPtr;
    frame.AddrFrame.Offset = context.Ebp;
    frame.AddrStack.Offset = context.Esp;
    imageType = IMAGE_FILE_MACHINE_I386;
#endif

    frame.AddrFrame.Mode = AddrModeFlat;
    frame.AddrPC.Mode = AddrModeFlat;
    frame.AddrStack.Mode = AddrModeFlat;

    symInfo = (SYMBOL_INFO *)LocalAlloc (LPTR, sizeof(*symInfo) + 256);
    symInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
    symInfo->MaxNameLen = 256;
    fnOffset = 0;

    //get os info
    memset (&osInfo, 0, sizeof(osInfo));
    osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

    if (!GetVersionEx ((OSVERSIONINFO *)&osInfo))
    {
        osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        GetVersionEx ((OSVERSIONINFO *)&osInfo);
    }

    String cpuInfo;
    HKEY key;

    // get cpu info
    if(RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), &key) == ERROR_SUCCESS)
    {
        DWORD dwSize = 1024;
        cpuInfo.SetLength(dwSize);
        if (RegQueryValueEx(key, TEXT("ProcessorNameString"), NULL, NULL, (LPBYTE)cpuInfo.Array(), &dwSize) != ERROR_SUCCESS)
            cpuInfo = TEXT("<unable to query>");
        RegCloseKey(key);
    }
    else
        cpuInfo = TEXT("<unable to query>");

    //determine which module the crash occured in
    scpy (moduleInfo.moduleName, TEXT("<unknown>"));
    moduleInfo.faultAddress = InstructionPtr;
    fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo);
    slwr (moduleInfo.moduleName);

    BOOL isPlugin = FALSE;

    if (sstr (moduleInfo.moduleName, TEXT("plugins\\")))
        isPlugin = TRUE;

    String strModuleInfo;
    String crashMessage;

    fnEnumerateLoadedModules64(hProcess, (PENUMLOADED_MODULES_CALLBACK64)RecordAllLoadedModules, (VOID *)&strModuleInfo);

    crashMessage << 
        TEXT("OBS has encountered an unhandled exception and has terminated. If you are able to\r\n")
        TEXT("reproduce this crash, please submit this crash report on the forums at\r\n")
        TEXT("https://obsproject.com/ - include the contents of this crash log and the\r\n")
        TEXT("minidump .dmp file (if available) as well as your regular OBS log files and\r\n")
        TEXT("a description of what you were doing at the time of the crash.\r\n")
        TEXT("\r\n")
        TEXT("This crash appears to have occured in the '") << moduleInfo.moduleName << TEXT("' module.\r\n\r\n");

    crashDumpLog.WriteStr(crashMessage.Array());

    crashDumpLog.WriteStr(FormattedString(TEXT("**** UNHANDLED EXCEPTION: %x\r\nFault address: %I64p (%s)\r\n"), exceptionInfo->ExceptionRecord->ExceptionCode, InstructionPtr, moduleInfo.moduleName));

    crashDumpLog.WriteStr(TEXT("OBS version: ") OBS_VERSION_STRING TEXT("\r\n"));
    crashDumpLog.WriteStr(FormattedString(TEXT("Windows version: %d.%d (Build %d) %s\r\nCPU: %s\r\n\r\n"), osInfo.dwMajorVersion, osInfo.dwMinorVersion, osInfo.dwBuildNumber, osInfo.szCSDVersion, cpuInfo.Array()));

    crashDumpLog.WriteStr(TEXT("Crashing thread stack trace:\r\n"));
#ifdef _WIN64
    crashDumpLog.WriteStr(TEXT("Stack            EIP              Arg0             Arg1             Arg2             Arg3             Address\r\n"));
#else
    crashDumpLog.WriteStr(TEXT("Stack    EIP      Arg0     Arg1     Arg2     Arg3     Address\r\n"));
#endif
    crashDumpLog.FlushFileBuffers();

    while (fnStackWalk64 (imageType, hProcess, GetCurrentThread(), &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL))
    {
        scpy (moduleInfo.moduleName, TEXT("<unknown>"));
        moduleInfo.faultAddress = frame.AddrPC.Offset;
        fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo);
        slwr (moduleInfo.moduleName);

        p = srchr (moduleInfo.moduleName, '\\');
        if (p)
            p++;
        else
            p = moduleInfo.moduleName;

#ifdef _WIN64
        if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                frame.Params[0],
                frame.Params[1],
                frame.Params[2],
                frame.Params[3],
                p,
                symInfo->Name,
                fnOffset));
        }
        else
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                frame.Params[0],
                frame.Params[1],
                frame.Params[2],
                frame.Params[3],
                p,
                frame.AddrPC.Offset));
        }
#else
        if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                (DWORD)frame.Params[0],
                (DWORD)frame.Params[1],
                (DWORD)frame.Params[2],
                (DWORD)frame.Params[3],
                p,
                symInfo->Name,
                fnOffset));
        }
        else
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                (DWORD)frame.Params[0],
                (DWORD)frame.Params[1],
                (DWORD)frame.Params[2],
                (DWORD)frame.Params[3],
                p,
                frame.AddrPC.Offset
                ));
        }
#endif

        crashDumpLog.FlushFileBuffers();
    }

    //if we manually crashed due to a deadlocked thread, record some extra info
    if (exceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
    {
        HANDLE hVideoThread = NULL, hEncodeThread = NULL;
        if (App)
            App->GetThreadHandles (&hVideoThread, &hEncodeThread);

        if (hVideoThread)
        {
            crashDumpLog.WriteStr(TEXT("\r\nVideo thread stack trace:\r\n"));
#ifdef _WIN64
            crashDumpLog.WriteStr(TEXT("Stack            EIP              Arg0             Arg1             Arg2             Arg3             Address\r\n"));
#else
            crashDumpLog.WriteStr(TEXT("Stack    EIP      Arg0     Arg1     Arg2     Arg3     Address\r\n"));
#endif
            crashDumpLog.FlushFileBuffers();

            context.ContextFlags = CONTEXT_ALL;
            GetThreadContext (hVideoThread, &context);
            ZeroMemory (&frame, sizeof(frame));
#ifdef _WIN64
            InstructionPtr = context.Rip;
            frame.AddrPC.Offset = InstructionPtr;
            frame.AddrFrame.Offset = context.Rbp;
            frame.AddrStack.Offset = context.Rsp;
            imageType = IMAGE_FILE_MACHINE_AMD64;
#else
            InstructionPtr = context.Eip;
            frame.AddrPC.Offset = InstructionPtr;
            frame.AddrFrame.Offset = context.Ebp;
            frame.AddrStack.Offset = context.Esp;
            imageType = IMAGE_FILE_MACHINE_I386;
#endif

            frame.AddrFrame.Mode = AddrModeFlat;
            frame.AddrPC.Mode = AddrModeFlat;
            frame.AddrStack.Mode = AddrModeFlat;
            while (fnStackWalk64 (imageType, hProcess, hVideoThread, &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL))
            {
                scpy (moduleInfo.moduleName, TEXT("<unknown>"));
                moduleInfo.faultAddress = frame.AddrPC.Offset;
                fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo);
                slwr (moduleInfo.moduleName);

                p = srchr (moduleInfo.moduleName, '\\');
                if (p)
                    p++;
                else
                    p = moduleInfo.moduleName;

#ifdef _WIN64
                if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
                {
                    crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"),
                        frame.AddrStack.Offset,
                        frame.AddrPC.Offset,
                        frame.Params[0],
                        frame.Params[1],
                        frame.Params[2],
                        frame.Params[3],
                        p,
                        symInfo->Name,
                        fnOffset));
                }
                else
                {
                    crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"),
                        frame.AddrStack.Offset,
                        frame.AddrPC.Offset,
                        frame.Params[0],
                        frame.Params[1],
                        frame.Params[2],
                        frame.Params[3],
                        p,
                        frame.AddrPC.Offset));
                }
#else
                if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
                {
                    crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"),
                        frame.AddrStack.Offset,
                        frame.AddrPC.Offset,
                        (DWORD)frame.Params[0],
                        (DWORD)frame.Params[1],
                        (DWORD)frame.Params[2],
                        (DWORD)frame.Params[3],
                        p,
                        symInfo->Name,
                        fnOffset));
                }
                else
                {
                    crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"),
                        frame.AddrStack.Offset,
                        frame.AddrPC.Offset,
                        (DWORD)frame.Params[0],
                        (DWORD)frame.Params[1],
                        (DWORD)frame.Params[2],
                        (DWORD)frame.Params[3],
                        p,
                        frame.AddrPC.Offset
                        ));
                }
#endif

                crashDumpLog.FlushFileBuffers();
            }
        }

        if (hEncodeThread)
        {
            crashDumpLog.WriteStr(TEXT("\r\nEncode thread stack trace:\r\n"));
#ifdef _WIN64
            crashDumpLog.WriteStr(TEXT("Stack            EIP              Arg0             Arg1             Arg2             Arg3             Address\r\n"));
#else
            crashDumpLog.WriteStr(TEXT("Stack    EIP      Arg0     Arg1     Arg2     Arg3     Address\r\n"));
#endif
            crashDumpLog.FlushFileBuffers();

            context.ContextFlags = CONTEXT_ALL;
            GetThreadContext (hEncodeThread, &context);
            ZeroMemory (&frame, sizeof(frame));
#ifdef _WIN64
            InstructionPtr = context.Rip;
            frame.AddrPC.Offset = InstructionPtr;
            frame.AddrFrame.Offset = context.Rbp;
            frame.AddrStack.Offset = context.Rsp;
            imageType = IMAGE_FILE_MACHINE_AMD64;
#else
            InstructionPtr = context.Eip;
            frame.AddrPC.Offset = InstructionPtr;
            frame.AddrFrame.Offset = context.Ebp;
            frame.AddrStack.Offset = context.Esp;
            imageType = IMAGE_FILE_MACHINE_I386;
#endif

            frame.AddrFrame.Mode = AddrModeFlat;
            frame.AddrPC.Mode = AddrModeFlat;
            frame.AddrStack.Mode = AddrModeFlat;
            while (fnStackWalk64 (imageType, hProcess, hEncodeThread, &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL))
            {
                scpy (moduleInfo.moduleName, TEXT("<unknown>"));
                moduleInfo.faultAddress = frame.AddrPC.Offset;
                fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo);
                slwr (moduleInfo.moduleName);

                p = srchr (moduleInfo.moduleName, '\\');
                if (p)
                    p++;
                else
                    p = moduleInfo.moduleName;

#ifdef _WIN64
                if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
                {
                    crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"),
                        frame.AddrStack.Offset,
                        frame.AddrPC.Offset,
                        frame.Params[0],
                        frame.Params[1],
                        frame.Params[2],
                        frame.Params[3],
                        p,
                        symInfo->Name,
                        fnOffset));
                }
                else
                {
                    crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"),
                        frame.AddrStack.Offset,
                        frame.AddrPC.Offset,
                        frame.Params[0],
                        frame.Params[1],
                        frame.Params[2],
                        frame.Params[3],
                        p,
                        frame.AddrPC.Offset));
                }
#else
                if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
                {
                    crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"),
                        frame.AddrStack.Offset,
                        frame.AddrPC.Offset,
                        (DWORD)frame.Params[0],
                        (DWORD)frame.Params[1],
                        (DWORD)frame.Params[2],
                        (DWORD)frame.Params[3],
                        p,
                        symInfo->Name,
                        fnOffset));
                }
                else
                {
                    crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"),
                        frame.AddrStack.Offset,
                        frame.AddrPC.Offset,
                        (DWORD)frame.Params[0],
                        (DWORD)frame.Params[1],
                        (DWORD)frame.Params[2],
                        (DWORD)frame.Params[3],
                        p,
                        frame.AddrPC.Offset
                        ));
                }
#endif

                crashDumpLog.FlushFileBuffers();
            }
        }

    }

    //generate a minidump if possible
    if (fnMiniDumpWriteDump)
    {
        TCHAR     dumpPath[MAX_PATH];
        HANDLE    hFile;

        tsprintf_s (dumpPath, _countof(dumpPath)-1, TEXT("%s\\crashDumps\\OBSCrashDump%.4d-%.2d-%.2d_%d.dmp"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i);

        hFile = CreateFile (dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hFile != INVALID_HANDLE_VALUE)
        {
            MINIDUMP_TYPE dumpFlags = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData);

            miniInfo.ClientPointers = TRUE;
            miniInfo.ExceptionPointers = exceptionInfo;
            miniInfo.ThreadId = GetCurrentThreadId ();

            if (fnMiniDumpWriteDump (hProcess, GetCurrentProcessId(), hFile, dumpFlags, &miniInfo, NULL, NULL))
            {
                crashDumpLog.WriteStr(FormattedString(TEXT("\r\nA minidump was saved to %s.\r\nPlease include this file when posting a crash report.\r\n"), dumpPath));
            }
            else
            {
                CloseHandle (hFile);
                DeleteFile (dumpPath);
            }
        }
    }
    else
    {
        crashDumpLog.WriteStr(TEXT("\r\nA minidump could not be created. Please check dbghelp.dll is present.\r\n"));
    }

    crashDumpLog.WriteStr("\r\nList of loaded modules:\r\n");
#ifdef _WIN64
    crashDumpLog.WriteStr("Base Address                      Module\r\n");
#else
    crashDumpLog.WriteStr("Base Address      Module\r\n");
#endif
    crashDumpLog.WriteStr(strModuleInfo);

    crashDumpLog.Close();

    LocalFree (symInfo);

    fnSymCleanup (hProcess);

    if (OBSMessageBox(hwndMain, TEXT("Woops! OBS has crashed. Would you like to view a crash report?"), NULL, MB_ICONERROR | MB_YESNO) == IDYES)
        ShellExecute(NULL, NULL, logPath, NULL, searchPath, SW_SHOWDEFAULT);

    FreeLibrary (hDbgHelp);

    //we really shouldn't be returning here, if we're at the bottom of the VEH chain this is a pretty legitimate crash
    //and if we return we could end up invoking a second crash handler or other weird / annoying things
    //ExitProcess(exceptionInfo->ExceptionRecord->ExceptionCode);
    return EXCEPTION_CONTINUE_SEARCH;
}
Exemple #6
0
int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance,
                     LPSTR lpszCmdLine, int nCmdShow )
{  

  SpaceballControlStruct scs;
  SpaceballAppDataStruct app;
  PointStr World[2];
  char fname[256];
  float CTM[4][4];             /* Current transformation matrix */ 
  SiSpwHandlers DspHandlers;
  LONG addr = (long)&scs;
  HWND wndScreen;
  RECT screenRect;
  int size;
  DWORD dSizeNeeded;
  char appDir[256];
  //int ssize;
  //char DirName[256];
  ncmdshow = nCmdShow;
  //FILE *fp;
  /*
   *   Figure out how big the screen is so that we can make our
   *   window an appropriate size.
   */
  wndScreen = GetDesktopWindow();
  GetWindowRect ( wndScreen, &screenRect );
  size = (int)(.8 * SPW_MIN( (screenRect.bottom - screenRect.top),
                   (screenRect.right - screenRect.left) ));
  Spw_WindowWidth = size;   
  Spw_WindowHeight = size;
   
  /* Add code to parse command line for alternate file --here-- */

  /* Code that finds the default data file in its usual spot */
  
 // if (0 != (dSizeNeeded = GetCurrentDirectory(256, appDir)))
  if (0 != (dSizeNeeded = GetModuleFileName(NULL, appDir, 256 )))
     {
     char widgetUStr[] = "WIDGET\0";
     char widgetLStr[] = "widget\0";
     char DirName[256];
     char *pdest;
     int  result;
     FILE *fp;
     

     /* find "widget" in directory string */
     pdest = strstr( appDir, widgetUStr );
	 if (pdest == NULL)
	    {
        pdest = strstr( appDir, widgetLStr );
        }
	 if (pdest != NULL)
	    {
        /* get the index of the end of "widget" */
        result = pdest - appDir + strlen(widgetUStr);
        /* snip everything after "widget" */
        appDir[result] = '\0'; 
        /* build the file name */
        strcpy(DirName, appDir);
        strcat(DirName, "\\dat\\widget.dat");
        }
     /* see if we can open the file */
     if (NULL != (fp=fopen(DirName, "r")))
        {
        fclose(fp);              /* close it back up */
        strcpy(fname, DirName);  /* save the file name */
        }
     else /* file is in a non standard location; let user find it */
        {
        strcpy(fname, "*.dat");
        GetNTFileName( NULL, fname );
        }
     }

  /*
   *  Initialize the Spaceball data structures
   */

  /* Spaceball tuning values */

  scs.sbScaleFactor[0] = (float)0.05;
  scs.sbScaleFactor[1] = (float)0.05;
  scs.sbScaleFactor[2] = (float)0.005;
  scs.sbScaleFactor[3] = (float)0.0005;
  scs.sbScaleFactor[4] = (float)0.0005;
  scs.sbScaleFactor[5] = (float)0.0005;

  /* Initialize platform-independent data */

  MainInitialize (fname, &scs, &app, (float *)CTM, World);
  MoveWindow(hWndMain, 300, 0, Spw_WindowWidth, Spw_WindowHeight, TRUE);

  SetClassLong(hWndMain, 0, (LONG)(&scs));
 
  /*
   *  Initialize the Spaceball, render initial scene
   */

  InitializeSpaceball(0, hWndMain, &DspHandlers, &scs);
  ResetWidgetView( (float(*)[4])app.CTM, app.center );
  app.redraw = TRUE;
  InvalidateRect(hWndMain, NULL, FALSE);

  return(DispatchLoopNT(&DspHandlers));

} /* end of WinMain */
Exemple #7
0
MIR_APP_DLL(HICON) Skin_LoadProtoIcon(const char *szProto, int status, bool big)
{
	char iconName[MAX_PATH];
	INT_PTR caps2;
	if (szProto == NULL)
		caps2 = -1;
	else if ((caps2 = CallProtoServiceInt(NULL,szProto, PS_GETCAPS, PFLAGNUM_2, 0)) == CALLSERVICE_NOTFOUND)
		caps2 = 0;

	if (IsStatusConnecting(status)) {
		mir_snprintf(iconName, _countof(iconName), "%s%d", mainIconsFmt, 7);
		return IcoLib_GetIcon(iconName, big);
	}

	int statusIndx = -1;
	for (int i = 0; i < _countof(statusIcons); i++)
		if (statusIcons[i].id == status) {
			statusIndx = i;
			break;
		}

	if (statusIndx == -1)
		return NULL;

	if (!szProto) {
		// Only return a protocol specific icon if there is only one protocol
		// Otherwise return the global icon. This affects the global status menu mainly.
		if (accounts.getCount() == 1) {
			// format: core_status_%proto%statusindex
			mir_snprintf(iconName, _countof(iconName), "%s%s%d", statusIconsFmt, szProto, statusIndx);

			HICON hIcon = IcoLib_GetIcon(iconName, big);
			if (hIcon)
				return hIcon;
		}

		// format: core_status_%s%d
		mir_snprintf(iconName, _countof(iconName), "%s%s%d", statusIconsFmt, GLOBAL_PROTO_NAME, statusIndx);
		return IcoLib_GetIcon(iconName, big);
	}

	// format: core_status_%s%d
	mir_snprintf(iconName, _countof(iconName), "%s%s%d", statusIconsFmt, szProto, statusIndx);
	HICON hIcon = IcoLib_GetIcon(iconName, big);
	if (hIcon == NULL && (caps2 == 0 || (caps2 & statusIcons[statusIndx].pf2))) {
		PROTOACCOUNT *pa = Proto_GetAccount(szProto);
		if (pa) {
			TCHAR szPath[MAX_PATH], szFullPath[MAX_PATH], *str;
			GetModuleFileName(NULL, szPath, _countof(szPath));

			// Queried protocol isn't in list, adding
			TCHAR tszSection[MAX_PATH];
			mir_sntprintf(tszSection, _countof(tszSection), _T(PROTOCOLS_PREFIX)_T("/%s"), pa->tszAccountName);

			SKINICONDESC sid = { 0 };
			sid.section.t = tszSection;
			sid.flags = SIDF_ALL_TCHAR;

			str = _tcsrchr(szPath, '\\');
			if (str != NULL)
				*str = 0;
			mir_sntprintf(szFullPath, _countof(szFullPath), _T("%s\\Icons\\proto_%S.dll"), szPath, pa->szProtoName);
			if (GetFileAttributes(szFullPath) != INVALID_FILE_ATTRIBUTES)
				sid.defaultFile.t = szFullPath;
			else {
				mir_sntprintf(szFullPath, _countof(szFullPath), _T("%s\\Plugins\\%S.dll"), szPath, szProto);
				if (int(ExtractIconEx(szFullPath, statusIcons[statusIndx].resource_id, NULL, &hIcon, 1)) > 0) {
					DestroyIcon(hIcon);
					sid.defaultFile.t = szFullPath;
					hIcon = NULL;
				}

				if (sid.defaultFile.a == NULL) {
					if (str != NULL)
						*str = '\\';
					sid.defaultFile.t = szPath;
				}
			}

			// Add global icons to list
			int lowidx, highidx;
			if (caps2 == 0)
				lowidx = statusIndx, highidx = statusIndx + 1;
			else
				lowidx = 0, highidx = _countof(statusIcons);

			for (int i = lowidx; i < highidx; i++)
				if (caps2 == 0 || (caps2 & statusIcons[i].pf2)) {
					// format: core_%s%d
					mir_snprintf(iconName, _countof(iconName), "%s%s%d", statusIconsFmt, szProto, i);
					sid.pszName = iconName;
					sid.description.t = cli.pfnGetStatusModeDescription(statusIcons[i].id, 0);
					sid.iDefaultIndex = statusIcons[i].resource_id;
					IcoLib_AddIcon(&sid, 0);
				}
		}

		// format: core_status_%s%d
		mir_snprintf(iconName, _countof(iconName), "%s%s%d", statusIconsFmt, szProto, statusIndx);
		hIcon = IcoLib_GetIcon(iconName, big);
		if (hIcon)
			return hIcon;
	}

	if (hIcon == NULL) {
		mir_snprintf(iconName, _countof(iconName), "%s%s%d", statusIconsFmt, GLOBAL_PROTO_NAME, statusIndx);
		hIcon = IcoLib_GetIcon(iconName, big);
	}

	return hIcon;
}
BOOL WINAPI 
DllMain(
    HINSTANCE InstanceHandle, 
    DWORD     Reason, 
    LPVOID    Reserved)
/*++
  
  DllMain()
  
  Function Description:
  
      Please see Windows documentation for DllEntryPoint.
  
  Arguments:
  
      Please see windows documentation.
  
  Return Value:
  
      Please see windows documentation.
  
--*/
{
    
    Cstack_c   *ThreadCstack;   // points to Cstack objects in tls 
    PINITDATA   InitDataPtr;    // to pass to the window creation thread
    HKEY        hkeyAppData;
    char        szSubKeyStr[sizeof(szDtRegKey)+256],
               *ptr=NULL;
    int         ModuleLen=0;


    // OutputDebugString ("DllMain called.\n");
    switch(Reason) {

        // Determine the reason for the call and act accordingly.
        case DLL_PROCESS_ATTACH:

            if ((ModuleLen = GetModuleFileName (NULL, ModuleFileName, sizeof (ModuleFileName)))==0)
                return FALSE;


            // Allocate a TLS index.
            TlsIndex = TlsAlloc();
            if (TlsIndex==0xFFFFFFFF)
                return FALSE;

            DllInstHandle = InstanceHandle;
            try {
                InitializeCriticalSection(&CrSec);
	        }
            catch(...) {
                OutputStyle = NO_OUTPUT;
                return FALSE;
            }
            
            TextOutEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
            if (TextOutEvent==NULL)
                return FALSE;

            // Fill in the handler function table.
            DTHandlerInit(HdlFuncTable, MAX_DTCODE);

            // Build the log file name
            StringCchCopy( LogFileName, MAX_PATH+1, ModuleFileName );
            StringCchCat( LogFileName, MAX_PATH+1, ".log");

            // See if the reg key exists for this EXE
            ptr = &ModuleFileName[ModuleLen-1];
            while ( (ptr != ModuleFileName) &&  (*ptr != '\\') )
                ptr--;
            if (*ptr == '\\')
                ptr++;

            // Build the key

            StringCchPrintf(szSubKeyStr, sizeof(szDtRegKey)+255, "%s\\%s", szDtRegKey, ptr);

            OutputDebugString("Looking for key: ");
            OutputDebugString(szSubKeyStr);
            OutputDebugString("\r\n");

            if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                        szSubKeyStr,
                        0,
                        KEY_QUERY_VALUE,
                        &hkeyAppData) == NO_ERROR)
            {
                OutputDebugString("Found the registry key\r\n");
                OutputStyle = FILE_ONLY;
  
                RegCloseKey(hkeyAppData);
            }
            else
            {
                OutputStyle = NO_OUTPUT;
            }

            if (OutputStyle == FILE_ONLY)
            {
                LogFileHandle = CreateFile(LogFileName, 
                        GENERIC_WRITE, 
                        FILE_SHARE_READ | FILE_SHARE_WRITE,
                        NULL, 
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL, 
                        NULL);
                if (LogFileHandle == INVALID_HANDLE_VALUE) {
                    OutputDebugString("Unable to create log file!\r\n");
                    OutputStyle = NO_OUTPUT;
                }
            }

            // Get some information for later output to the debug window
            // or file -- get the time, PID, and TID of the calling
            // process and put into a INITDATA struct.  This memory will
            // be freed by the thread it is passed to.
            InitDataPtr = (PINITDATA) LocalAlloc(0, sizeof(INITDATA));
            GetLocalTime(&(InitDataPtr->LocalTime));
            InitDataPtr->TID = GetCurrentThreadId();
            InitDataPtr->PID = GetCurrentProcessId();

            // Normally the window thread does a DTTextOut of the time
            // and process info that we saved just above.  But in this
            // case,  there is no window thread so spit it out to the
            // file or debugger. 

            StringCchPrintf(Buffer, TEXT_LEN-1, "Log initiated: %d-%d-%d, %d:%d:%d\r\n", 
                    InitDataPtr->LocalTime.wMonth, 
                    InitDataPtr->LocalTime.wDay, 
                    InitDataPtr->LocalTime.wYear, 
                    InitDataPtr->LocalTime.wHour, 
                    InitDataPtr->LocalTime.wMinute, 
                    InitDataPtr->LocalTime.wSecond);
            DTTextOut(LogFileHandle, Buffer, OutputStyle);
            StringCchPrintf(Buffer, TEXT_LEN-1, "Process ID: 0x%X   Thread ID: 0x%X\r\n",
                    InitDataPtr->PID,
                    InitDataPtr->TID);
            DTTextOut(LogFileHandle, Buffer, OutputStyle);

            // Setting this event allows {Pre|Post}ApiNotify to
            // proceed.  This event isn't really needed in this case
            // (because there is only one thread, and we know the code
            // above has been executed before WSAPre|PostApiNotify).
            SetEvent(TextOutEvent);

            // flow through...

        case DLL_THREAD_ATTACH:

            // Store a pointer to a new Cstack_c in the slot for this
            // thread. 
            ThreadCstack = new Cstack_c();
            TlsSetValue(TlsIndex, (LPVOID)ThreadCstack);

            break;

        case DLL_PROCESS_DETACH:

            // Free up some resources.  This is like cleaning up your room
            // before the tornado strikes, but hey, it's good practice.
            TlsFree(TlsIndex);
            DeleteCriticalSection(&CrSec);

            CloseHandle(LogFileHandle);

            break;

        case DLL_THREAD_DETACH:

            // Get the pointer to this thread's Cstack, and delete the
            // object.
            ThreadCstack = (Cstack_c *)TlsGetValue(TlsIndex);
            delete ThreadCstack;

            break;

        default:

            break;
    } // switch (Reason)

    return TRUE;
} // DllMain()
Exemple #9
0
int main(int argc, const char * argv[])
{
    int return_value = EXIT_SUCCESS;
    
    bool allow_compressed_moov_atoms = false;
    
    // Process arguments
    int next_arg = 1;
    if (next_arg < argc)
    {
    	if (strcmp(argv[next_arg], "-c") == 0)
    	{
    		allow_compressed_moov_atoms = true;
    		next_arg++;
    	}
    }
    
    // Get input and output paths
    const char *input_file = NULL;
    const char *output_file = NULL;
    
    if (next_arg < argc)
    {
        input_file = argv[next_arg];
    }
    
    next_arg++;
    
    if (next_arg < argc)
    {
        output_file = argv[next_arg];
    }
    
    if (!input_file)
    {
        return_value = EXIT_FAILURE;
    }
    
    // If we had bad arguments, print our usage
    if (return_value != EXIT_SUCCESS)
    {
    	const char *prog_name;
#if defined(__APPLE__)
    	prog_name = getprogname();
#elif defined(__linux__)
    	extern const char *program_invocation_short_name;
    	prog_name = program_invocation_short_name;
#elif defined(_WIN32)
		TCHAR full_path[MAX_PATH];

		if(GetModuleFileName(NULL, full_path, MAX_PATH))
		{
			prog_name = strrchr(full_path, '\\') + 1;
		}
		else
		{
			prog_name = "COMMAND";
		}
#else
#error add a way to discover the program name on your platform here
#endif
        fprintf(stderr, "usage: %s [-c] INPUT [OUTPUT] \n", prog_name);
    }
    else
    {
        // If output_file is the same as input_file we treat it as if it isn't present
        if (output_file && strcmp(output_file, input_file) == 0)
        {
            output_file = NULL;
        }
        
        // If we are to replace the input, first try doing the flatten in-place
        if (output_file == NULL)
        {
            qtf_result result = qtf_flatten_movie_in_place(input_file, allow_compressed_moov_atoms);
            if (result == qtf_result_ok) return EXIT_SUCCESS;
            // Ignore any other error here, we'll take a stab with syc_flatten_movie()
        }
        
        // We can't flatten the file in-place, continue to flatten to a new file
        if (output_file == NULL)
        {
            output_file = input_file;
        }
        else
        {
            // We attempt to create a new file to check no such file already exists
            // (because rename() will brutally overwrite any existing file (except on Windows))
#if defined(_WIN32)
			int out_fd = _open(output_file, _O_WRONLY | _O_CREAT | _O_EXCL, _S_IREAD | _S_IWRITE);
			if (out_fd != -1)
			{
				_close(out_fd);
			}
#else
			int out_fd = open(output_file, O_WRONLY | O_CREAT | O_EXCL,
                              S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); // RW owner, R group, R others
            if (out_fd != -1)
            {
                // We created the file, we can close it now
                close(out_fd);
            }
#endif
            else
            {
                fprintf(stderr, "Error: ");
                switch (errno) {
                    case EEXIST:
                        fprintf(stderr, "The output file already exists");
                        break;
                    default:
                        fprintf(stderr, "The output file could not be created");
                        break;
                }
                fprintf(stderr, ".\n");
                return_value = EXIT_FAILURE;
            }
        }
        
        if (return_value == EXIT_SUCCESS)
        {
            // We flatten to a temporary file which we then move - this accomodates replacing the original file
            unsigned long temp_file_path_buffer_length = strlen(output_file) + strlen(temp_file_suffix) + 1;
            
            char *temp_file_path = (char *)malloc(temp_file_path_buffer_length);
            
			if (temp_file_path == NULL)
			{
				fprintf(stderr, "Error: Not enough memory was available.\n");
				return_value = EXIT_FAILURE;
			}
			else
			{
				qtf_result result = qtf_result_ok;
				snprintf(temp_file_path, temp_file_path_buffer_length, "%s%s", output_file, temp_file_suffix);

				result = qtf_flatten_movie(input_file, temp_file_path, allow_compressed_moov_atoms);

				if (result != qtf_result_ok)
				{
					fprintf(stderr, "Error: ");
					switch (result) {
					case qtf_result_file_not_movie:
						fprintf(stderr, "The file was not recognised as a valid movie");
						break;
					case qtf_result_file_read_error:
						fprintf(stderr, "The file could not be read");
						break;
					case qtf_result_file_too_complex:
						fprintf(stderr, "This type of movie file is not supported");
						break;
					case qtf_result_file_write_error:
						fprintf(stderr, "The file could not be written");
						break;
					case qtf_result_memory_error:
						fprintf(stderr, "Not enough memory was available");
						break;
					default:
						fprintf(stderr, "An unexpected error occurred");
						break;
					}
					fprintf(stderr, ".\n");
					return_value = EXIT_FAILURE;
				}

				if (return_value == EXIT_SUCCESS)
				{
#if defined(_WIN32)
					// On Windows, rename() fails if the file already exists
					remove(output_file);
#endif
					rename(temp_file_path, output_file);
				}
                else
                {
                    remove(temp_file_path);
                    if (output_file != input_file) remove(output_file);
                }

				free(temp_file_path);
			}
        }
    }

    return return_value;
}
Exemple #10
0
void ConfigDlg::LoadSymbols()
{
    g_StackDepth = GetDlgItemInt( IDC_EDIT1, NULL, FALSE );
    if( m_bChanged )
    {
        CString csExeName;
        GetModuleFileName( 0, csExeName.GetBuffer( MAX_PATH), MAX_PATH );
        csExeName.ReleaseBuffer();
        csExeName = csExeName.MakeLower();
        csExeName.Replace( _T(".exe"), _T("Mem.ini"));
        CStdioFile File;
        if( !File.Open( csExeName, CFile::modeCreate|CFile::modeWrite ))
        {
            goto LoadDll;
        }        
        int nCount = m_List.GetItemCount();
        m_csPath.Empty();
        for( int nId = 0;nId < nCount; nId++ )
        {
            CString csItem = m_List.GetItemText( nId ,0 );
            m_csPath += csItem + _T(";");            
            csItem += _T("\r\n");
            File.WriteString( csItem );
        }
        File.Close();
    }
    
LoadDll:

    HMODULE hModule = GetModuleHandle( _T("dbghelp.dll"));
    SymRefreshModuleListDef pSymRefreshModuleList;
    
    if( hModule )
    {
        pSymRefreshModuleList = (SymRefreshModuleListDef)GetProcAddress( hModule, _T("SymRefreshModuleList"));
        CString csLoadedDll;
        GetModuleFileName( hModule, csLoadedDll.GetBuffer(MAX_PATH), MAX_PATH );
        csLoadedDll.ReleaseBuffer();
        if( !pSymRefreshModuleList )
        {
            // old version of dbghelp :(
            MessageBox( "Your application has already loaded dbghelp.dll from " + csLoadedDll +
                "\n\nFor acqurate results, replace this dll with the latest version of dbghelp.dll"
                "coming with \"Debugging tools for windows\" or with the dll the application folder of this utility", 
                    "Error", MB_OK );
        }
        else
        {
            MessageBox( "Your application has already loaded dbghelp.dll from " + csLoadedDll +
                " Please confirm that the symsrv.dll exists in th same folder.\n"
                "Otherwise symbol server will not work", 
                "Warning", MB_OK );
        }
        
    }
    else 
    {
// 			static int nTempvariable;
// 			MEMORY_BASIC_INFORMATION MemInfo;
// 			CString csDllPath;
// 			if( !VirtualQuery( &nTempvariable, &MemInfo, sizeof(MemInfo)))
// 			{
// 				goto LoadDll;
// 			}
        CString csDllPath;
        HMODULE hHookDll = GetModuleHandle( _T("HookDll.dll"));
        if( !GetModuleFileName( hHookDll, csDllPath.GetBuffer( MAX_PATH), MAX_PATH ))
        {
            goto LoadDll;
        }
        csDllPath.ReleaseBuffer();
        int nPos = csDllPath.ReverseFind( _T('\\'));
        if( 0 >= nPos )
        {
            goto LoadDll;
        }
        csDllPath = csDllPath.Left( nPos + 1 );
        //csDllPath = "C:\\Program Files\\Debugging Tools for Windows (x86)\\";
        csDllPath += _T("dbghelp.dll");
        
        hModule = LoadLibrary( csDllPath );
        if( !hModule)
        {
            hModule = LoadLibrary(  _T("dbghelp.dll"));
            pSymRefreshModuleList = (SymRefreshModuleListDef)GetProcAddress( hModule, _T("SymRefreshModuleList"));
            if( !pSymRefreshModuleList )
            {
                MessageBox( "Failed to load the dbghelp.dll from the local directory\n\n"
                            "The application will continue with the default dbghelp.dll. But some feature may"
                            "be unavailable", "Error", MB_OK );
            }
            
        }
        else
        {
             pSymRefreshModuleList = (SymRefreshModuleListDef)GetProcAddress( hModule, _T("SymRefreshModuleList"));
        }
        
    }

    SymCleanup(GetCurrentProcess());
    CString csWholePath = m_csPath;
    csWholePath.TrimRight( ';' );
    DWORD dwOption = 0;//SymGetOptions();
    dwOption |= SYMOPT_CASE_INSENSITIVE|SYMOPT_LOAD_LINES|SYMOPT_FAIL_CRITICAL_ERRORS|
                SYMOPT_LOAD_ANYTHING|SYMOPT_UNDNAME;    
    SymSetOptions( dwOption );
    CWinThread* pThread = AfxBeginThread( ThreadEntry, this );
    HANDLE hThread = pThread->m_hThread;
    
    
    BOOL fInvadeProcess = (0 == pSymRefreshModuleList)?TRUE:FALSE;

    
    BOOL bRet = SymInitialize(GetCurrentProcess(), (LPTSTR)csWholePath.operator LPCTSTR() , fInvadeProcess );
    SymRegisterCallback64( GetCurrentProcess(),SymRegisterCallbackProc64,(ULONG64 )this );
    while( !m_ProgressDlg.m_hWnd )// wait untill the dialog is created
    {
        Sleep( 50 );
    }

    if( pSymRefreshModuleList )
    {
        pSymRefreshModuleList( GetCurrentProcess());
    }
    //SymRefreshModuleList( GetCurrentProcess());
    m_ProgressDlg.SendMessage( WM_CLOSE );
    WaitForSingleObject( hThread, 10000 );
}
Exemple #11
0
BOOL ConfigDlg::OnInitDialog() 
{
    
    CDialog::OnInitDialog();
    ListView_SetExtendedListViewStyleEx( m_List, LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT,LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT);

    m_List.InsertColumn( 0, "PDB Path", LVCFMT_LEFT, 500 );
    m_bChanged = false;
    //////////////////////////////////////////////////////////////////////////
    CString csExeName;
    GetModuleFileName( 0, csExeName.GetBuffer( MAX_PATH), MAX_PATH );
    csExeName.ReleaseBuffer();
    csExeName = csExeName.MakeLower();
    csExeName.Replace( _T(".exe"), _T("Mem.ini"));
    if( PathFileExists( csExeName ))
    {
        CStdioFile File;
        File.Open( csExeName,CFile::modeRead );
        CString csLine;
        while( File.ReadString( csLine ))
        {
            csLine.Replace( _T("\r"), _T(""));
            m_List.InsertItem( 0, csLine );
            m_csPath += csLine + _T(";");            
        }
        File.Close();
    }
    else
    {
        CString csSystemPath;
        if (GetEnvironmentVariable("SYSTEMROOT", csSystemPath.GetBuffer( MAX_PATH), MAX_PATH) > 0)
        {
            csSystemPath.ReleaseBuffer();
            csSystemPath += _T("\\system32");
        }
        else
        {
            csSystemPath.ReleaseBuffer();
        }        
        m_List.InsertItem( 0, csSystemPath );
        csSystemPath += _T("\r\n");     
        
        CString SymbolPath;
        if (GetEnvironmentVariable("_NT_SYMBOL_PATH", SymbolPath.GetBuffer( MAX_PATH), MAX_PATH) > 0)
        {
            SymbolPath.ReleaseBuffer();
            csSystemPath += SymbolPath + _T("\r\n");
            m_List.InsertItem( 0, SymbolPath );                

        }
        else
        {
            csSystemPath.ReleaseBuffer();
        }
        //add the hook dll path so that it can load the pdb of hookdll
        CString csDllPath;
        HMODULE hHookDll = GetModuleHandle( _T("HookDll.dll"));
        if( GetModuleFileName( hHookDll, csDllPath.GetBuffer( MAX_PATH), MAX_PATH ))
        {
            csDllPath.ReleaseBuffer();
            int nPos = csDllPath.ReverseFind( _T('\\'));
            if( 0 < nPos )
            {
                csDllPath = csDllPath.Left( nPos + 1 );
                m_List.InsertItem( 0, csDllPath );
            }
            
        }
    }
    m_EditCtrl.Create( WS_CHILD|WS_BORDER, CRect(0,0,0,0), &m_List, 1 );
    g_HookType = HT_MEMORY;
    ((CButton*)GetDlgItem( IDC_RADIO_MEM ))->SetCheck( BST_CHECKED );
    SetDlgItemText( IDC_EDIT1, _T("20"));


#if _DEBUG
    SetAppMode();
    if(g_IS_TEST_APP)
    {
        LoadSymbols();        
        PostMessage( WM_CLOSE,0,0);
    }
#endif
    return TRUE;
}
Exemple #12
0
BOOL
WINAPI MyWriteConsoleA( HANDLE hCon, LPCVOID lpBuffer,
			DWORD nNumberOfCharsToWrite,
			LPDWORD lpNumberOfCharsWritten, LPVOID lpReserved )
{
  DWORD  Mode;
  LPWSTR buf;
  DWORD  len;
  BOOL	 rc = TRUE;

  // if we write in a console buffer with processed output
  if (GetConsoleMode( hCon, &Mode ) && (Mode & ENABLE_PROCESSED_OUTPUT))
  {
    UINT cp = GetConsoleOutputCP();
    DEBUGSTR( L"\33WriteConsoleA: %lu \"%.*S\"",
	      nNumberOfCharsToWrite, nNumberOfCharsToWrite, lpBuffer );
    len = MultiByteToWideChar( cp, 0, lpBuffer, nNumberOfCharsToWrite, NULL, 0 );
    buf = malloc( len * sizeof(WCHAR) );
    if (buf == NULL)
    {
      if (lpNumberOfCharsWritten != NULL)
	*lpNumberOfCharsWritten = 0;
      return (nNumberOfCharsToWrite == 0);
    }
    MultiByteToWideChar( cp, 0, lpBuffer, nNumberOfCharsToWrite, buf, len );
    rc = ParseAndPrintString( hCon, buf, len, lpNumberOfCharsWritten );
    free( buf );
    if (rc && lpNumberOfCharsWritten != NULL &&
	      *lpNumberOfCharsWritten != nNumberOfCharsToWrite)
    {
      // Converting a multibyte character to Unicode results in a different
      // "character" count.  This causes some programs to think not everything
      // was written, so the difference is sent again.	Fudge the (presumably)
      // correct count.
      TCHAR env[2048];
      if (GetEnvironmentVariable( L"ANSICON_API", env, lenof(env) ))
      {
	BOOL not;

	not = (*env == '!');
	if (not && env[1] == '\0')
	{
	  *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
	}
	else
	{
	  TCHAR  path[MAX_PATH];
	  LPTSTR name, exe;

	  GetModuleFileName( NULL, path, lenof(path) );
	  name = wcsrchr( path, '\\' );
	  if (name == NULL)
	    name = path;
	  else
	    ++name;
	  exe = wcsrchr( name, '.' );
	  if (exe != NULL && exe != name)
	    *exe = '\0';
	  for (exe = wcstok( env + not, L";" ); exe; exe = wcstok( NULL, L";" ))
	  {
	    if (_wcsicmp( name, exe ) == 0)
	      break;
	  }
	  if ((exe && !not) || (!exe && not))
	    *lpNumberOfCharsWritten = nNumberOfCharsToWrite;
	}
      }
    }
    return rc;
  }
  else
  {
    return WriteConsoleA( hCon, lpBuffer,
			  nNumberOfCharsToWrite,
			  lpNumberOfCharsWritten,
			  lpReserved );
  }
}
Exemple #13
0
DWORD WINAPI Cadthread(LPVOID lpParam)
{
	OSVERSIONINFO OSversion;	
	OSversion.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
	GetVersionEx(&OSversion);


	HDESK desktop=NULL;
	desktop = OpenInputDesktop(0, FALSE,
								DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
								DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
								DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
								DESKTOP_SWITCHDESKTOP | GENERIC_WRITE
								);


	
	if (desktop == NULL)
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop Error \n"));
	else 
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop OK\n"));

	HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;

	char new_name[256];
	if (desktop)
	{
	if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
	{
		vnclog.Print(LL_INTERR, VNCLOG("!GetUserObjectInformation \n"));
	}

	vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK to %s (%x) from %x\n"), new_name, desktop, old_desktop);

	if (!SetThreadDesktop(desktop))
	{
		vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK:!SetThreadDesktop \n"));
	}
	}

	//////
	if(OSversion.dwMajorVersion>=6 && vncService::RunningAsService())
			{				
					if( vncService::RunningAsService() &&!IsSoftwareCadEnabled())
					{
						DWORD result=MessageBoxSecure(NULL,"UAC is Disable, make registry changes to allow cad","Warning",MB_YESNO);
						if (result==IDYES)
							{
								HANDLE hProcess=NULL,hPToken=NULL;
								DWORD id=GetExplorerLogonPid();
								if (id!=0) 
									{						
									hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id);
									if (!hProcess) goto error;
									if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
													|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
													| TOKEN_READ | TOKEN_WRITE, &hPToken))
									{
										CloseHandle(hProcess);
										goto error;
									}
									char dir[MAX_PATH];
									char exe_file_name[MAX_PATH];
									GetModuleFileName(0, exe_file_name, MAX_PATH);
									strcpy(dir, exe_file_name);
									strcat(dir, " -softwarecadhelper");
		
							
									STARTUPINFO          StartUPInfo;
									PROCESS_INFORMATION  ProcessInfo;
									HANDLE Token=NULL;
									HANDLE process=NULL;
									ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
									ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
									StartUPInfo.wShowWindow = SW_SHOW;
									StartUPInfo.lpDesktop = "Winsta0\\Default";
									StartUPInfo.cb = sizeof(STARTUPINFO);
			
									CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo);
									DWORD errorcode=GetLastError();
									if (process) CloseHandle(process);
									if (Token) CloseHandle(Token);
									if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess);
									if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread);
									if (errorcode == 1314) goto error;
									goto gotome;
									error:
											Enable_softwareCAD_elevated();							
									}
							}
					
					}
			}
	gotome:
       /////////////////////
	if(OSversion.dwMajorVersion==6)//&& OSversion.dwMinorVersion>=1) //win7  // test win7 +Vista
	{

		if (hShutdownEventcad==NULL ) hShutdownEventcad = OpenEvent(EVENT_MODIFY_STATE, FALSE, "Global\\SessionEventUltraCad");
		if (hShutdownEventcad!=NULL ) SetEvent(hShutdownEventcad);
		if (old_desktop) SetThreadDesktop(old_desktop);
		if (desktop) CloseDesktop(desktop);
		return 0;
	}

	 HKEY hKey; 
	 DWORD isLUAon = 0; 
     if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"), 0, KEY_READ, &hKey) == ERROR_SUCCESS) 
              { 
              DWORD LUAbufSize = 4; 
              RegQueryValueEx(hKey, TEXT("EnableLUA"), NULL, NULL, (LPBYTE)&isLUAon, &LUAbufSize); 
              RegCloseKey(hKey); 
			  }
     if (isLUAon != 1 && OSversion.dwMajorVersion==6) 
	 {
		 if (hShutdownEventcad==NULL ) hShutdownEventcad = OpenEvent(EVENT_MODIFY_STATE, FALSE, "Global\\SessionEventUltraCad");
		 if (hShutdownEventcad!=NULL ) SetEvent(hShutdownEventcad);
		 if (old_desktop) SetThreadDesktop(old_desktop);
		 if (desktop) CloseDesktop(desktop);
		 return 0;
	 }

//Full path needed, sometimes it just default to system32
	char WORKDIR[MAX_PATH];
	char mycommand[MAX_PATH];
	if (GetModuleFileName(NULL, WORKDIR, MAX_PATH))
		{
		char* p = strrchr(WORKDIR, '\\');
		if (p == NULL) return 0;
		*p = '\0';
		}
	strcpy(mycommand,"");
	strcat(mycommand,WORKDIR);//set the directory
	strcat(mycommand,"\\");
	strcat(mycommand,"cad.exe");

	int nr=(LONG_PTR)ShellExecute(GetDesktopWindow(), "open", mycommand, "", 0, SW_SHOWNORMAL);
	if (nr<=32)
	{
		//error
		//
		if ( nr==SE_ERR_ACCESSDENIED )
			vncTimedMsgBox::Do(
									sz_ID_CADPERMISSION,
									sz_ID_ULTRAVNC_WARNING,
									MB_ICONINFORMATION | MB_OK
									);

		if ( nr==ERROR_PATH_NOT_FOUND || nr==ERROR_FILE_NOT_FOUND)
			vncTimedMsgBox::Do(
									sz_ID_CADERRORFILE,
									sz_ID_ULTRAVNC_WARNING,
									MB_ICONINFORMATION | MB_OK
									);

	}

	if (old_desktop) SetThreadDesktop(old_desktop);
	if (desktop) CloseDesktop(desktop);
	return 0;
}
Exemple #14
0
void GetExecutablePath( char* path, int nMaxPath )
{
    GetModuleFileName( GetModuleHandle( NULL ), path, nMaxPath );
}
Exemple #15
0
void genProcess(const WmiResultItem& result, QueryData& results_data) {
  Row r;
  Status s;
  long pid;
  long lPlaceHolder;
  std::string sPlaceHolder;

  /// Store current process pid for more efficient API use.
  auto currentPid = GetCurrentProcessId();

  s = result.GetLong("ProcessId", pid);
  r["pid"] = s.ok() ? BIGINT(pid) : BIGINT(-1);

  long uid = -1;
  long gid = -1;
  HANDLE hProcess = nullptr;
  if (pid == currentPid) {
    hProcess = GetCurrentProcess();
  } else {
    hProcess =
        OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
  }

  if (GetLastError() == ERROR_ACCESS_DENIED) {
    uid = 0;
    gid = 0;
  }

  result.GetString("Name", r["name"]);
  result.GetString("ExecutablePath", r["path"]);
  result.GetString("CommandLine", r["cmdline"]);
  result.GetString("ExecutionState", r["state"]);
  result.GetLong("ParentProcessId", lPlaceHolder);
  r["parent"] = BIGINT(lPlaceHolder);
  result.GetLong("Priority", lPlaceHolder);
  r["nice"] = INTEGER(lPlaceHolder);
  r["on_disk"] = osquery::pathExists(r["path"]).toString();
  result.GetLong("ThreadCount", lPlaceHolder);
  r["threads"] = INTEGER(lPlaceHolder);

  std::vector<char> fileName(MAX_PATH);
  fileName.assign(MAX_PATH + 1, '\0');
  if (pid == currentPid) {
    GetModuleFileName(nullptr, fileName.data(), MAX_PATH);
  } else {
    GetModuleFileNameEx(hProcess, nullptr, fileName.data(), MAX_PATH);
  }
  r["cwd"] = SQL_TEXT(fileName.data());
  r["root"] = r["cwd"];

  r["pgroup"] = "-1";
  r["euid"] = "-1";
  r["suid"] = "-1";
  r["egid"] = "-1";
  r["sgid"] = "-1";

  FILETIME createTime;
  FILETIME exitTime;
  FILETIME kernelTime;
  FILETIME userTime;
  auto procRet =
      GetProcessTimes(hProcess, &createTime, &exitTime, &kernelTime, &userTime);
  if (procRet == FALSE) {
    r["user_time"] = BIGINT(-1);
    r["system_time"] = BIGINT(-1);
    r["start_time"] = BIGINT(-1);
  } else {
    // Windows stores proc times in 100 nanosecond ticks
    ULARGE_INTEGER utime;
    utime.HighPart = userTime.dwHighDateTime;
    utime.LowPart = userTime.dwLowDateTime;
    r["user_time"] = BIGINT(utime.QuadPart / 10000000);
    utime.HighPart = kernelTime.dwHighDateTime;
    utime.LowPart = kernelTime.dwLowDateTime;
    r["system_time"] = BIGINT(utime.QuadPart / 10000000);
    r["start_time"] = BIGINT(osquery::filetimeToUnixtime(createTime));
  }

  result.GetString("PrivatePageCount", sPlaceHolder);
  r["wired_size"] = BIGINT(sPlaceHolder);
  result.GetString("WorkingSetSize", sPlaceHolder);
  r["resident_size"] = sPlaceHolder;
  result.GetString("VirtualSize", sPlaceHolder);
  r["total_size"] = BIGINT(sPlaceHolder);

  /// Get the process UID and GID from its SID
  HANDLE tok = nullptr;
  std::vector<char> tokOwner(sizeof(TOKEN_OWNER), 0x0);
  auto ret = OpenProcessToken(hProcess, TOKEN_READ, &tok);
  if (ret != 0 && tok != nullptr) {
    unsigned long tokOwnerBuffLen;
    ret = GetTokenInformation(tok, TokenUser, nullptr, 0, &tokOwnerBuffLen);
    if (ret == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
      tokOwner.resize(tokOwnerBuffLen);
      ret = GetTokenInformation(
          tok, TokenUser, tokOwner.data(), tokOwnerBuffLen, &tokOwnerBuffLen);
    }

    // Check if the process is using an elevated token
    auto elevated = FALSE;
    TOKEN_ELEVATION Elevation;
    DWORD cbSize = sizeof(TOKEN_ELEVATION);
    if (GetTokenInformation(
            tok, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) {
      elevated = Elevation.TokenIsElevated;
    }

    r["is_elevated_token"] = elevated ? INTEGER(1) : INTEGER(0);
  }
  if (uid != 0 && ret != 0 && !tokOwner.empty()) {
    auto sid = PTOKEN_OWNER(tokOwner.data())->Owner;
    r["uid"] = INTEGER(getUidFromSid(sid));
    r["gid"] = INTEGER(getGidFromSid(sid));
  } else {
    r["uid"] = INTEGER(uid);
    r["gid"] = INTEGER(gid);
  }

  if (hProcess != nullptr) {
    CloseHandle(hProcess);
  }
  if (tok != nullptr) {
    CloseHandle(tok);
    tok = nullptr;
  }
  results_data.push_back(r);
}
Exemple #16
0
static Bool get_default_install_path(char *file_path, u32 path_type)
{
	FILE *f;
	char *sep;
	char szPath[GF_MAX_PATH];


#ifdef _WIN32_WCE
	TCHAR w_szPath[GF_MAX_PATH];
	GetModuleFileName(NULL, w_szPath, GF_MAX_PATH);
	CE_WideToChar((u16 *) w_szPath, file_path);
#else
	GetModuleFileNameA(NULL, file_path, GF_MAX_PATH);
#endif

	/*remove exe name*/
	if (strstr(file_path, ".exe")) {
		sep = strrchr(file_path, '\\');
		if (sep) sep[0] = 0;
	}

	strcpy(szPath, file_path);
	strlwr(szPath);

	/*if this is run from a browser, we do not get our app path - fortunately on Windows, we always use 'GPAC' in the
	installation path*/
	if (!strstr(file_path, "gpac")) {
		HKEY hKey = NULL;
		DWORD dwSize = GF_MAX_PATH;

		/*locate the key in current user, then in local machine*/
#ifdef _WIN32_WCE
		DWORD dwType = REG_SZ;
		u16 w_path[1024];
		RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\GPAC"), 0, KEY_READ, &hKey);
#ifdef _DEBUG
		if (RegQueryValueEx(hKey, TEXT("DebugDir"), 0, &dwType, (LPBYTE) w_path, &dwSize) != ERROR_SUCCESS)
#endif
			RegQueryValueEx(hKey, TEXT("InstallDir"), 0, &dwType, (LPBYTE) w_path, &dwSize);
		CE_WideToChar(w_path, (char *)file_path);
		RegCloseKey(hKey);
#else
		if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\GPAC", 0, KEY_READ, &hKey) != ERROR_SUCCESS)
			RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\GPAC", 0, KEY_READ, &hKey);

		dwSize = GF_MAX_PATH;

#ifdef _DEBUG
		if (RegQueryValueEx(hKey, "DebugDir", NULL, NULL,(unsigned char*) file_path, &dwSize) != ERROR_SUCCESS)
#endif
			RegQueryValueEx(hKey, "InstallDir", NULL, NULL,(unsigned char*) file_path, &dwSize);

		RegCloseKey(hKey);
#endif
	}


	if (path_type==GF_PATH_APP) return 1;

	if (path_type==GF_PATH_GUI) {
		char *sep;
		strcat(file_path, "\\gui");
		if (check_file_exists("gui.bt", file_path, file_path)) return 1;
		sep = strstr(file_path, "\\bin\\");
		if (sep) {
			sep[0] = 0;
			strcat(file_path, "\\gui");
			if (check_file_exists("gui.bt", file_path, file_path)) return 1;
		}
		return 0;
	}
	/*modules are stored in the GPAC directory (should be changed to GPAC/modules)*/
	if (path_type==GF_PATH_MODULES) return 1;

	/*we are looking for the config file path - make sure it is writable*/
	assert(path_type == GF_PATH_CFG);

	strcpy(szPath, file_path);
	strcat(szPath, "\\gpaccfgtest.txt");
	f = gf_f64_open(szPath, "wb");
	if (f != NULL) {
		fclose(f);
		gf_delete_file(szPath);
		return 1;
	}
#ifdef _WIN32_WCE
	return 0;
#else
	/*no write access, get user home directory*/
	SHGetFolderPath(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, file_path);
	if (file_path[strlen(file_path)-1] != '\\') strcat(file_path, "\\");
	strcat(file_path, "GPAC");
	/*create GPAC dir*/
	_mkdir(file_path);
	strcpy(szPath, file_path);
	strcat(szPath, "\\gpaccfgtest.txt");
	f = gf_f64_open(szPath, "wb");
	/*COMPLETE FAILURE*/
	if (!f) return 0;

	fclose(f);
	gf_delete_file(szPath);
	return 1;
#endif
}
Exemple #17
0
/**
 * @brief
 *		main - the initialization and main loop of pbs_comm
 *
 * @param[in]	argc	- argument count.
 * @param[in]	argv	- argument values.
 *
 * @return	int
 * @retval	0	- success
 */
main(int argc, char *argv[])
{
	SC_HANDLE schManager;
	SC_HANDLE schSelf;
	int reg = 0;
	int unreg = 0;
	TCHAR	  szFileName[MAX_PATH];

	/*the real deal or just pbs_version and exit*/

	execution_mode(argc, argv);

	if (argc > 1) {
		if (strcmp(argv[1], "-R") == 0)
			reg = 1;
		else if (strcmp(argv[1], "-U") == 0)
			unreg = 1;
		else if (strcmp(argv[1], "-N") == 0)
			stalone = 1;
	}

	if (reg || unreg) {
		schManager = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
		if (schManager == 0) {
			ErrorMessage("OpenSCManager");
		}

		if (reg) {
			GetModuleFileName(0, szFileName, sizeof(szFileName)/sizeof(*szFileName));
			printf("Installing service %s\n", g_PbsCommName);
			schSelf =
				CreateService(schManager, g_PbsCommName, __TEXT("PBS COMM"),
				SERVICE_ALL_ACCESS,
				SERVICE_WIN32_OWN_PROCESS,
				SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
				replace_space(szFileName, ""), 0, 0, 0, 0, 0);

			if (schSelf) {
				printf("Service %s installed succesfully!\n", g_PbsCommName);
			} else {
				ErrorMessage("CreateService");
			}

			if (schSelf != 0)
				CloseServiceHandle(schSelf);
		} else if (unreg) {
			schSelf = OpenService(schManager, g_PbsCommName, DELETE);

			if (schSelf) {
				if (DeleteService(schSelf)) {
					printf("Service %s uninstalled successfully!\n", g_PbsCommName);
				} else {
					ErrorMessage("DeleteService");
				}
			} else {
				ErrorMessage("OpenService failed");
			}
			if (schSelf != 0)
				CloseServiceHandle(schSelf);
		}

		if (schManager != 0)
			CloseServiceHandle(schManager);
	} else if (stalone) {
		struct arg_param *pap;
		int	i, j;

		pap = create_arg_param();
		if (pap == NULL)
			ErrorMessage("create_arg_param");

		pap->argc = argc-1;	/* don't pass the second argument */
		for (i=j=0; i < argc; i++) {
			if (i == 1)
				continue;
			pap->argv[j] = strdup(argv[i]);
			j++;
		}
		main_thread((void *)pap);

		free_arg_param(pap);
	} else {	/* running as a service */
		SERVICE_TABLE_ENTRY rgste[] = { {(TCHAR*)g_PbsCommName, PbsCommMain },
			{ 0, 0 } };

		if (getenv("PBS_CONF_FILE") == NULL) {
			char conf_path[80];
			char conf_env[80];
			char *p;
			char psave;
			struct stat sbuf;

			if (p = strstr(argv[0], "exec")) {
				psave = *p;
				*p = '\0';
				_snprintf(conf_path, 79, "%spbs.conf", argv[0]);
				*p = psave;
				if (stat(conf_path, &sbuf) == 0) {
					_snprintf(conf_env, 79, "PBS_CONF_FILE=%s",
						conf_path);
					putenv(conf_env);
				}
			}
		}
		if (!StartServiceCtrlDispatcher(rgste)) {
			ErrorMessage("StartServiceCntrlDispatcher");
		}
	}
	return (0);
}
DWORD CreateInstallInfo(_In_ HANDLE hHeap, _Out_ PINSTALLERINFO pInstallerInfo, _Outptr_result_maybenull_ LPVOID *plpData)
{
	TCHAR szModuleFileName[MAX_PATH + 1];
	LPTSTR lpszSubBlock, lpszValue;
	LPWORD lpwLanguage;
	DWORD dwLen, dwHandle;
	size_t cbSubBlock;
	HMODULE hModule;
	UINT cbSize;
	HRESULT hr;
	BOOL res;

	if (!pInstallerInfo || !plpData)
		return ERROR_INVALID_PARAMETER;

	ZeroMemory(pInstallerInfo, sizeof(INSTALLERINFO));
	*plpData = NULL;

	hModule = GetModuleInstance();
	if (!hModule)
		return ERROR_OUTOFMEMORY;

	dwLen = GetModuleFileName(hModule, szModuleFileName, MAX_PATH);
	if (!dwLen)
		return GetLastError();

	dwLen = GetFileVersionInfoSize(szModuleFileName, &dwHandle);
	if (!dwLen)
		return GetLastError();

	*plpData = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwLen);
	if (!*plpData)
		return ERROR_OUTOFMEMORY;

	LoadString(hModule, IDS_APPLICATION_ID, (LPWSTR) &pInstallerInfo->pApplicationId, 0);

	res = GetFileVersionInfo(szModuleFileName, dwHandle, dwLen, *plpData);
	if (res) {
		res = VerQueryValue(*plpData, TEXT("\\VarFileInfo\\Translation"), (LPVOID*) &lpwLanguage, &cbSize);
		if (res) {
			Trace(TEXT("Translation: %04x%04x (%d)"), lpwLanguage[0], lpwLanguage[1], cbSize);

			hr = StringCbAPrintf(hHeap, &lpszSubBlock, &cbSubBlock, TEXT("\\StringFileInfo\\%04x%04x\\ProductName"), lpwLanguage[0], lpwLanguage[1]);
			if (SUCCEEDED(hr)) {
				Trace(TEXT("SubBlock: %s (%d)"), lpszSubBlock, cbSubBlock);

				res = VerQueryValue(*plpData, lpszSubBlock, (LPVOID*) &lpszValue, &cbSize);
				if (res) {
					pInstallerInfo->pDisplayName = lpszValue;
					pInstallerInfo->pProductName = lpszValue;
				} else
					Trace(TEXT("VerQueryValue 2 failed: %08X"), GetLastError());

				HeapSafeFree(hHeap, 0, lpszSubBlock);
			} else
				Trace(TEXT("StringCbAPrintf 1 failed: %08X"), hr);

			hr = StringCbAPrintf(hHeap, &lpszSubBlock, &cbSubBlock, TEXT("\\StringFileInfo\\%04x%04x\\CompanyName"), lpwLanguage[0], lpwLanguage[1]);
			if (SUCCEEDED(hr)) {
				Trace(TEXT("SubBlock: %s (%d)"), lpszSubBlock, cbSubBlock);

				res = VerQueryValue(*plpData, lpszSubBlock, (LPVOID*) &lpszValue, &cbSize);
				if (res) {
					pInstallerInfo->pMfgName = lpszValue;
				} else
					Trace(TEXT("VerQueryValue 3 failed: %08X"), GetLastError());

				HeapSafeFree(hHeap, 0, lpszSubBlock);
			} else
				Trace(TEXT("StringCbAPrintf 2 failed: %08X"), hr);
		} else
			Trace(TEXT("VerQueryValue 1 failed: %08X"), GetLastError());
	} else
		Trace(TEXT("GetFileVersionInfo failed: %08X"), GetLastError());

	Trace(TEXT("ApplicationID: %s"), pInstallerInfo->pApplicationId);
	Trace(TEXT("DisplayName:   %s"), pInstallerInfo->pDisplayName);
	Trace(TEXT("ProductName:   %s"), pInstallerInfo->pProductName);
	Trace(TEXT("MfgName:       %s"), pInstallerInfo->pMfgName);

	return ERROR_SUCCESS;
}
Exemple #19
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
  TCHAR *cmdline;
  TCHAR seekchar = _T(' ');
  TCHAR *keyname, *file;

  // These are turned into heap memory to avoid _chkstk
  keyname = (TCHAR*) GlobalAlloc(GPTR, STR_SIZE*sizeof(TCHAR));
  file    = (TCHAR*) GlobalAlloc(GPTR, STR_SIZE*sizeof(TCHAR));

  cmdline = GetCommandLine();
  if (*cmdline == _T('\"'))
    seekchar = *cmdline++;

  while (*cmdline && *cmdline != seekchar)
    cmdline = CharNext(cmdline);
  cmdline = CharNext(cmdline);
  while (*cmdline == _T(' '))
    cmdline++;

  if (*cmdline++ != _T('/'))
  {
    ExitProcess(1);
    return 0;
  }

  if (*cmdline == _T('S'))
  {
    HKEY rootkey;

    if (SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NSIS.Library.RegTool.v3"), 0, KEY_READ, &rootkey)))
    {
      while (RegEnumKey(rootkey, 0, keyname, STR_SIZE) == ERROR_SUCCESS)
      {
        HKEY key;

        if (SUCCEEDED(RegOpenKeyEx(rootkey, keyname, 0, KEY_READ, &key)))
        {
          DWORD t, count, l = sizeof(DWORD);

          if (SUCCEEDED(RegQueryValueEx(key, _T("count"), NULL, &t, (LPBYTE) &count, &l)) && t == REG_DWORD)
          {
            DWORD j;
            TCHAR valname[128], mode[3];

            for (j = 1; j <= count; j++)
            {
              wsprintf(valname, _T("%u.mode"), j);
              l = sizeof(mode);
              if (FAILED(RegQueryValueEx(key, valname, NULL, &t, (LPBYTE) mode, &l)) || t != REG_SZ)
                continue;

              wsprintf(valname, _T("%u.file"), j);
              l = STR_SIZE*sizeof(TCHAR);
              if (FAILED(RegQueryValueEx(key, valname, NULL, &t, (LPBYTE) file, &l)) || t != REG_SZ)
                continue;

              file[STR_SIZE - 1] = 0;

              // JP: Note, if this mode[1] is used as anything but a boolean later on,
              // we'll need to consider the next line carefully.
              RegFile(mode[0], file, mode[1] == 'X');
            }
          }

          RegCloseKey(key);
          RegDeleteKey(rootkey, keyname);
        }
      }

      RegCloseKey(rootkey);
      RegDeleteKey(HKEY_LOCAL_MACHINE, _T("Software\\NSIS.Library.RegTool.v3"));
    }

    {
      if (GetModuleFileName(GetModuleHandle(NULL), file, STR_SIZE))
      {
        DeleteFileOnReboot(file);
      }
    }
  }
  else
  {
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
    OleInitialize(NULL);

    if (*cmdline == _T('D'))
    {
      RegDll(cmdline + 1);
    }
    else if (*cmdline == _T('T'))
    {
      RegTypeLib(cmdline + 1);
    }

    OleUninitialize();
    SetErrorMode(0);
  }

  GlobalFree(keyname);
  GlobalFree(file);
  ExitProcess(0);
  return 0;
}
//-----------------------------------------------------------------------------
// Name: StartDriver
// Object: Install and start procmon driver
// Parameters :
//     in  : 
//     out : 
//     return : TRUE on success, FALSE on error or if driver is already running
//-----------------------------------------------------------------------------
BOOL CProcMonInterface::StartDriver()
{
    BOOL bAlreadyLoaded=FALSE;
    BOOL bForceContinue=FALSE;
    BOOL bAlreadyInstalled=FALSE;
    DWORD dwCurrentState=0;
    CDriver Driver;

    TCHAR szDir[MAX_PATH];
    TCHAR* pos;

    // Get current application directory
    GetModuleFileName(GetModuleHandle(NULL),szDir,MAX_PATH);
    pos=_tcsrchr(szDir,'\\');
    if (pos)
        *(pos+1)=0;

    // put full path of ProcMon.sys in szDir
    _tcscat(szDir,PROC_MON_SYS);

    // install the driver querying if it is already installed
    if (!Driver.Install(szDir,SERVICE_DEMAND_START,&bAlreadyInstalled))
        return FALSE;
    
    // open the driver
    if (!Driver.Open(PROC_MON_NAME))
        return FALSE;

    // if driver is already installed, 2 things may append
    // - another soft is using it
    // - driver hasn't been uninstalled for unknown reason (software/computer crash, bad programming ...)
    if (bAlreadyInstalled)
    {
        // query the state of driver
        if (!Driver.GetState(&dwCurrentState))
            return FALSE;
        // another application is using it
        if ((dwCurrentState!=SERVICE_STOPPED)&&(dwCurrentState!=SERVICE_STOP_PENDING))
        {
#if (!defined(TOOLS_NO_MESSAGEBOX))
            if (MessageBox(NULL,MSG_DRIVER_ALREADY_RUNNING,_T("Warning"),MB_YESNO|MB_ICONWARNING|MB_TOPMOST)==IDYES)
                bForceContinue=TRUE;
            else
#endif
                return FALSE;
        }
    }

    // try to start the driver (still check if another app is using it)
    if (!Driver.Start(&bAlreadyLoaded))
        return FALSE;

    // if used by another application
    if (bAlreadyLoaded&&(!bForceContinue))
    {
#if (!defined(TOOLS_NO_MESSAGEBOX))
        if (MessageBox(NULL,MSG_DRIVER_ALREADY_RUNNING,_T("Warning"),MB_YESNO|MB_ICONWARNING|MB_TOPMOST)!=IDYES)
#endif
            return FALSE;
    }

    // reset stop events
    ResetEvent(this->hEvtStopDriver);
    ResetEvent(this->hEvtStopMonitoring);

    // create watching thread
    this->hWatchingThread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)CProcMonInterface::ThreadProc,this,0,NULL);
    if (!this->hWatchingThread)
        return FALSE;

    this->bStarted=TRUE;

    return TRUE;
}
void InitNx()
{
    // Create the physics SDK
	gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &gErrorStream);
    if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);	
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_AXES, 1);

	gPhysicsSDK->setParameter(NX_VISUALIZE_CONTACT_POINT, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_CONTACT_NORMAL, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
	sceneDesc.simType				= NX_SIMULATION_HW;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
 if(!gScene){ 
		sceneDesc.simType				= NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	NxU32 set = 0;

#ifdef WIN32
	set = SetCurrentDirectory(&fname[0]);
	if (!set) set = SetCurrentDirectory(&fname1[0]);
	if (!set)
	{
		char basePath[256];
		GetModuleFileName(NULL, basePath, 256);
		char* pTmp = strrchr(basePath, '\\');
		basePath[pTmp-basePath+1] = 0;
		SetCurrentDirectory(basePath);//for running from start menu

		set = SetCurrentDirectory(&fname2[0]);
	}
	if (!set) set = SetCurrentDirectory(&fname3[0]);
#elif LINUX
	set = chdir(&fname[0]);
	if (set != 0) set = chdir(&fname2[0]);
	if (set != 0) set = chdir(&fname3[0]);
#endif

	// Create the default material
	NxMaterialDesc defaultMaterial;
	defaultMaterial.restitution		= 0;
	defaultMaterial.staticFriction	= 0.5;
	defaultMaterial.dynamicFriction	= 0.5;
	NxMaterial* m = gScene->getMaterialFromIndex(0);
	m->loadFromDesc(defaultMaterial);

	// Load the ramp scene
	char buffer[512];
	FindMediaFile("Ramp.pml", buffer);
	nxmlLoadScene(buffer, gPhysicsSDK, gScene);

	// Switch from Max Coordinate System to
	// Training Program Coordinate System
	NxMat34 mat;
    NxMat33 orient;
	orient.setColumn(0, NxVec3(-1,0,0));
	orient.setColumn(1, NxVec3(0,0,1));
	orient.setColumn(2, NxVec3(0,1,0));
	mat.M = orient;
	SwitchCoordinateSystem(gScene, mat);

	// Reset wheel material
	wsm = NULL;

	// Create board actor
	board = CreateBoard(NxVec3(0,3,0));
	board->wakeUp(1e30);

    AddUserDataToActors(gScene);

	gSelectedActor = board;

	// Initialize HUD
	InitializeHUD();
	InitializeSpecialHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
Exemple #22
0
int HookSystem() {
    if (keyhook && msghook) {
        // System already hooked
        return 1;
    }

    // Load library
    if (!hinstDLL) {
        wchar_t path[MAX_PATH];
        GetModuleFileName(NULL, path, ARRAY_SIZE(path));
        PathRemoveFileSpec(path);
        wcscat(path, L"\\hooks.dll");
        hinstDLL = LoadLibrary(path);
        if (hinstDLL == NULL) {
            Error(L"LoadLibrary('hooks.dll')", L"This probably means that the file hooks.dll is missing. You can try reinstalling "APP_NAME".", GetLastError());
            return 1;
        }
    }

    // Load keyboard hook
    HOOKPROC procaddr;
    if (!keyhook) {
        // Get address to keyboard hook (beware name mangling)
        procaddr = (HOOKPROC) GetProcAddress(hinstDLL, "LowLevelKeyboardProc@12");
        if (procaddr == NULL) {
            Error(L"GetProcAddress('LowLevelKeyboardProc@12')", L"This probably means that the file hooks.dll is from an old version or corrupt. You can try reinstalling "APP_NAME".", GetLastError());
            return 1;
        }
        // Set up the keyboard hook
        keyhook = SetWindowsHookEx(WH_KEYBOARD_LL, procaddr, hinstDLL, 0);
        if (keyhook == NULL) {
            Error(L"SetWindowsHookEx(WH_KEYBOARD_LL)", L"Could not hook keyboard. Another program might be interfering.", GetLastError());
            return 1;
        }
    }

    // HookWindows
    wchar_t txt[10];
    GetPrivateProfileString(L"Advanced", L"HookWindows", L"0", txt, ARRAY_SIZE(txt), inipath);
    if (!msghook && _wtoi(txt)) {
        // Get address to message hook (beware name mangling)
        procaddr = (HOOKPROC) GetProcAddress(hinstDLL, "CallWndProc@12");
        if (procaddr == NULL) {
            Error(L"GetProcAddress('CallWndProc@12')", L"This probably means that the file hooks.dll is from an old version or corrupt. You can try reinstalling "APP_NAME".", GetLastError());
            return 1;
        }
        // Set up the message hook
        msghook = SetWindowsHookEx(WH_CALLWNDPROC, procaddr, hinstDLL, 0);
        if (msghook == NULL) {
            Error(L"SetWindowsHookEx(WH_CALLWNDPROC)", L"Could not hook message hook. Another program might be interfering.", GetLastError());
            return 1;
        }

        // x64
        if (x64) {
            wchar_t path[MAX_PATH];
            GetModuleFileName(NULL, path, ARRAY_SIZE(path));
            PathRemoveFileSpec(path);
            wcscat(path, L"\\HookWindows_x64.exe");
            ShellExecute(NULL, L"open", path, L"nowarning", NULL, SW_SHOWNORMAL);
        }
    }

    // Success
    UpdateTray();
    return 0;
}
CEngine::CEngine(void)
	: m_Root(NULL)
{
	TCHAR szPath[MAX_PATH];

	CString ApplicationName = "Mirror.exe";

	GetModuleFileName(NULL, szPath, MAX_PATH);
    Ogre::ConfigFile OgreConfigFile;
	CString ApplicationPath(szPath);

	ApplicationPath = ApplicationPath.Left(ApplicationPath.GetLength() - ApplicationName.GetLength());

	m_Root = new Ogre::Root("", "", Ogre::String(ApplicationPath + "OgreInMfc.log")); 

	OgreConfigFile.load(Ogre::String(ApplicationPath + "ogre.cfg"), "\t:=", false);

	Ogre::String RenderSystemName;
	RenderSystemName = OgreConfigFile.getSetting("Render System");

		if (RenderSystemName == "Direct3D9 Rendering Subsystem")
		{
#ifdef _DEBUG
			m_Root->loadPlugin("RenderSystem_Direct3D9_d");
#else
		    m_Root->loadPlugin("RenderSystem_Direct3D9");
#endif
		}
		else			
		if(RenderSystemName == "OpenGL Rendering Subsystem")
		{
#ifdef _DEBUG
			m_Root->loadPlugin("RenderSystem_GL_d");
#else
		    m_Root->loadPlugin("RenderSystem_GL");
#endif
		}
		else
		{
#ifdef _DEBUG		 
			m_Root->loadPlugin("RenderSystem_Direct3D9_d");
#else
			m_Root->loadPlugin("RenderSystem_Direct3D9");
#endif
		}

#ifdef _DEBUG
		m_Root->loadPlugin("Plugin_ParticleFX_d");
#else
        m_Root->loadPlugin("Plugin_ParticleFX");
#endif

		Ogre::RenderSystemList RendersList = m_Root->getAvailableRenderers();
		m_Root->setRenderSystem(RendersList[0]);

    //
    // Initialize the system, but don't create a render window.
    //

		// Load resource paths from config file
        Ogre::ConfigFile cf;
		Ogre::String ResourcePath = ApplicationPath + "resources.cfg";
        cf.load(ResourcePath);

        // Go through all sections & settings in the file
        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

        Ogre::String secName, typeName, archName;

		while (seci.hasMoreElements())
        {
            secName = seci.peekNextKey();
            Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
            Ogre::ConfigFile::SettingsMultiMap::iterator i;

			for (i = settings->begin(); i != settings->end(); ++i)
            {
                typeName = i->first;
                archName = i->second;
				archName = Ogre::String(ApplicationPath) + archName;
                Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
            }
        }

    m_Root->initialise(false);
}
Exemple #24
0
// Entry point
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, char *szCmdLine, int iCmdShow) {
    g_hinst = hInst;
    IsWow64Process(GetCurrentProcess(), &x64);

    // Get ini path
    GetModuleFileName(NULL, inipath, ARRAY_SIZE(inipath));
    PathRemoveFileSpec(inipath);
    wcscat(inipath, L"\\"APP_NAME".ini");
    wchar_t txt[10];

    // Convert szCmdLine to argv and argc (max 10 arguments)
    char *argv[10];
    int argc = 1;
    argv[0] = szCmdLine;
    while ((argv[argc]=strchr(argv[argc-1],' ')) != NULL) {
        *argv[argc] = '\0';
        if (argc == ARRAY_SIZE(argv)) break;
        argv[argc++]++;
    }

    // Check arguments
    int i;
    int elevate=0, quiet=0, config=-1, multi=0;
    for (i=0; i < argc; i++) {
        if (!strcmp(argv[i],"-hide") || !strcmp(argv[i],"-h")) {
            // -hide = do not add tray icon, hide it if already running
            hide = 1;
        }
        else if (!strcmp(argv[i],"-quiet") || !strcmp(argv[i],"-q")) {
            // -quiet = do nothing if already running
            quiet = 1;
        }
        else if (!strcmp(argv[i],"-elevate") || !strcmp(argv[i],"-e")) {
            // -elevate = create a new instance with administrator privileges
            elevate = 1;
        }
        else if (!strcmp(argv[i],"-config") || !strcmp(argv[i],"-c")) {
            // -config = open config (with requested page)
            config = (i+1 < argc)?atoi(argv[i+1]):0;
        }
        else if (!strcmp(argv[i],"-multi")) {
            // -multi = allow multiple instances, used internally when elevating via config window
            multi = 1;
        }
    }

    // Check if elevated if in >= Vista
    OSVERSIONINFO vi = { sizeof(OSVERSIONINFO) };
    GetVersionEx(&vi);
    vista = (vi.dwMajorVersion >= 6);
    if (vista) {
        HANDLE token;
        TOKEN_ELEVATION elevation;
        DWORD len;
        if (OpenProcessToken(GetCurrentProcess(),TOKEN_READ,&token) && GetTokenInformation(token,TokenElevation,&elevation,sizeof(elevation),&len)) {
            elevated = elevation.TokenIsElevated;
        }
    }

    // Register some messages
    WM_UPDATESETTINGS = RegisterWindowMessage(L"UpdateSettings");
    WM_OPENCONFIG = RegisterWindowMessage(L"OpenConfig");
    WM_CLOSECONFIG = RegisterWindowMessage(L"CloseConfig");
    WM_ADDTRAY = RegisterWindowMessage(L"AddTray");
    WM_HIDETRAY = RegisterWindowMessage(L"HideTray");

    // Look for previous instance
    GetPrivateProfileString(L"Advanced", L"MultipleInstances", L"0", txt, ARRAY_SIZE(txt), inipath);
    if (!_wtoi(txt) && !multi) {
        HWND previnst = FindWindow(APP_NAME, NULL);
        if (previnst != NULL) {
            if (quiet) {
                return 0;
            }
            PostMessage(previnst, WM_UPDATESETTINGS, 0, 0);
            PostMessage(previnst, (hide && !config?WM_CLOSECONFIG:WM_OPENCONFIG), config, 0);
            PostMessage(previnst, (hide?WM_HIDETRAY:WM_ADDTRAY), 0, 0);
            return 0;
        }
    }

    // Check AlwaysElevate
    if (!elevated) {
        GetPrivateProfileString(L"Advanced", L"AlwaysElevate", L"0", txt, ARRAY_SIZE(txt), inipath);
        if (_wtoi(txt)) {
            elevate = 1;
        }

        // Handle request to elevate to administrator privileges
        if (elevate) {
            wchar_t path[MAX_PATH];
            GetModuleFileName(NULL, path, ARRAY_SIZE(path));
            int ret = (INT_PTR) ShellExecute(NULL, L"runas", path, (hide?L"-hide":NULL), NULL, SW_SHOWNORMAL);
            if (ret > 32) {
                return 0;
            }
        }
    }

    // Language
    memset(&l10n_ini, 0, sizeof(l10n_ini));
    UpdateLanguage();

    // Create window
    WNDCLASSEX wnd = { sizeof(WNDCLASSEX), 0, WindowProc, 0, 0, hInst, NULL, NULL, (HBRUSH)(COLOR_WINDOW+1), NULL, APP_NAME, NULL };
    RegisterClassEx(&wnd);
    g_hwnd = CreateWindowEx(WS_EX_TOOLWINDOW|WS_EX_TOPMOST|WS_EX_LAYERED, wnd.lpszClassName, NULL, WS_POPUP, 0, 0, 0, 0, NULL, NULL, hInst, NULL);
    SetLayeredWindowAttributes(g_hwnd, 0, 1, LWA_ALPHA); // Almost transparent

    // Tray icon
    InitTray();
    UpdateTray();

    // Hook system
    HookSystem();

    // Add tray if hook failed, even though -hide was supplied
    if (hide && !keyhook) {
        hide = 0;
        UpdateTray();
    }

    // Check for update
    GetPrivateProfileString(L"Update", L"CheckOnStartup", L"0", txt, ARRAY_SIZE(txt), inipath);
    if (_wtoi(txt)) {
        CheckForUpdate(0);
    }

    // Open config if -config was supplied
    if (config != -1) {
        PostMessage(g_hwnd, WM_OPENCONFIG, config, 0);
    }

    // Message loop
    MSG msg;
    while (GetMessage(&msg,NULL,0,0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}
Exemple #25
0
/* Redirect to an executable located in a sub folder relative to
   this starter executable. Name of the stub executable has to
   match with the one in the sub folder.
   The command line parameters are passed along.
 */
int main( int argc, char *argv[] )
{
    int err = ERROR_SUCCESS;
    TCHAR szPath[MAX_PATH];

    /* Get the full path of the running executable */
    if ( GetModuleFileName( NULL, szPath, MAX_PATH ) )
    {
        size_t len = _tcslen(szPath);
        size_t offset = len + CONST_STRLEN(SUBFOLDER) + 1;

        err = ERROR_BAD_PATHNAME;
        if (offset < MAX_PATH)
        {
             /* Move file name part of full path by length of sub folder
                name and thereafter fill in the sub folder name in the
                newly created gap.
              */
             register TCHAR *p = szPath + len;
             register TCHAR *q = szPath + offset;

             while (p > szPath)
             {
                *(q--) = *(p--);
                if (*p == '\\')
                {
                    /* Fill in sub folder name */
                    *q = *p;
                    q = ++p;
                    p = (TCHAR *)SUBFOLDER;
                    while (*p)
                    {
                       *(q++) = *(p++);
                    }
                    err = ERROR_SUCCESS;
                    break;
                }
             }   
        }
       
        if (err) 
        {
            _tprintf( _T("Path too long: %s\n"), szPath );
        }
        else
        {
            STARTUPINFO si;
            PROCESS_INFORMATION pi;

            ZeroMemory( &si, sizeof(si) );
            si.cb = sizeof(si);

            /* Start and wait for a process with the same filename as
               ourself located in SUBFOLDER.
               
               WARNING: The subprocess can't parse GetCommandLine()
               to find its own path since we pass the wrong path! */
            if ( CreateProcess( szPath, GetCommandLine(), NULL, NULL,
                FALSE, 0, NULL, NULL, &si, &pi ) )
            {
                WaitForSingleObject( pi.hProcess, INFINITE );
                GetExitCodeProcess( pi.hProcess, &err );
                CloseHandle( pi.hProcess );
                CloseHandle( pi.hThread );
            }
            else
            {
                err = GetLastError();
                _tprintf( _T("CreateProcess (%s) failed (%d).\n"), szPath, err );
            }
        }
    }
    else
    {
        err = GetLastError();
        _tprintf( _T("GetModuleFileName failed (%d).\n"), err );
    }

    return err;
}
Exemple #26
0
//////////////////////////////////////////////////////////////////////////
// Returns type of exe file. i.e. whether it's a console application or a
// windows application or an MS-DOS application
// RETRUN:
// WIN_TYPE_APP     :  Windows Application.
// WIN_TYPE_CONSOLE :  Win32 Console Application
// WIN_TYPE_MS_DOS  :  MS-DOS .exe, .com or .bat file
// WIN_TYPE_UNKNOWN : Unknown file type.
// pszTypeName : should be 80 chars.
//////////////////////////////////////////////////////////////////////////
CFileAssoc_i::ENUM_WIN_TYPE CFileAssoc_i::GetExeType( LPCTSTR pszFilePath, OUT TCHAR* pszTypeName)
{
  TCHAR szFile[MAX_PATH] = {0,};
    
    if(pszFilePath == NULL)
    {
      GetModuleFileName(NULL, szFile, MAX_PATH-1);
      pszFilePath = &szFile[0];
    }
    
    SHFILEINFO shFileInfo = { 0 };
    
    // Second call is for retrieving file type
    const DWORD dwRetVal = SHGetFileInfo( pszFilePath, 
      FILE_ATTRIBUTE_NORMAL, 
      &shFileInfo, 
      sizeof( shFileInfo ), 
      SHGFI_EXETYPE );

    if( dwRetVal )
    {
    /************************************************************************
    dwRetVal is interpreted as follows...
    LOWORD = NE or PE and HIWORD = 3.0, 3.5, or 4.0  Windows application 
    LOWORD = MZ and HIWORD = 0  MS-DOS .exe, .com, or .bat file 
    LOWORD = PE and HIWORD = 0  Win32 console application 
      ************************************************************************/
      const WORD wLowWord =  LOWORD( dwRetVal );
      const WORD wHiWord = HIWORD( dwRetVal );
      const WORD wPEWord = MAKEWORD( 'P', 'E' );
      const WORD wMZWord = MAKEWORD( 'M', 'Z' );
      const WORD wNEWord = MAKEWORD( 'N', 'E' );
      
      // Read above comments to understand what's happening
      if( wLowWord == wPEWord || wLowWord == wNEWord )
      {
        if( wHiWord == 0 )
        {
          return WIN_TYPE_CONSOLE_E; // "Win32 Console Application"
        }
        else
        {
          return WIN_TYPE_APP_E; // "Windows application" 
        }// End if
      }
      else if( wLowWord == wMZWord && wHiWord == 0 )
      {
        return WIN_TYPE_MS_DOS_E; // "MS-DOS .exe, .com or .bat file"
      }
      else
      {
        return WIN_TYPE_UNKNOWN_E; //"Unknown file type"
      }// End if

      if(pszTypeName)
      {
        lstrcpy(pszTypeName, shFileInfo.szTypeName);
      }
    }// End if
    else
    {
      return WIN_TYPE_UNKNOWN_E;
    }
}
Exemple #27
0
/** Print out a stacktrace. */
static void Stacktrace(LPEXCEPTION_POINTERS e, HANDLE hThread = INVALID_HANDLE_VALUE) {
	PIMAGEHLP_SYMBOL pSym;
	STACKFRAME sf;
	HANDLE process, thread;
	DWORD dwModBase, Disp;
	BOOL more = FALSE;
	int count = 0;
	char modname[MAX_PATH];

	pSym = (PIMAGEHLP_SYMBOL)GlobalAlloc(GMEM_FIXED, 16384);

	BOOL suspended = FALSE;
	CONTEXT c;
	if (e) {
		c = *e->ContextRecord;
		thread = GetCurrentThread();
	} else {
		SuspendThread(hThread);
		suspended = TRUE;
		memset(&c, 0, sizeof(CONTEXT));
		c.ContextFlags = CONTEXT_FULL;
		// FIXME: This does not work if you want to dump the current thread's stack
		if (!GetThreadContext(hThread, &c)) {
			ResumeThread(hThread);
			return;
		}
		thread = hThread;
	}

	ZeroMemory(&sf, sizeof(sf));
	sf.AddrPC.Offset = c.Eip;
	sf.AddrStack.Offset = c.Esp;
	sf.AddrFrame.Offset = c.Ebp;
	sf.AddrPC.Mode = AddrModeFlat;
	sf.AddrStack.Mode = AddrModeFlat;
	sf.AddrFrame.Mode = AddrModeFlat;

	process = GetCurrentProcess();

	// use globalalloc to reduce risk for allocator related deadlock
	char* printstrings = (char*)GlobalAlloc(GMEM_FIXED, 0);

	bool containsOglDll = false;
	while (true) {
		more = StackWalk(
			IMAGE_FILE_MACHINE_I386, // TODO: fix this for 64 bit windows?
			process,
			thread,
			&sf,
			&c,
			NULL,
			SymFunctionTableAccess,
			SymGetModuleBase,
			NULL
		);
		if (!more || sf.AddrFrame.Offset == 0) {
			break;
		}

		dwModBase = SymGetModuleBase(process, sf.AddrPC.Offset);

		if (dwModBase) {
			GetModuleFileName((HINSTANCE)dwModBase, modname, MAX_PATH);
		} else {
			strcpy(modname, "Unknown");
		}

		pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
		pSym->MaxNameLength = MAX_PATH;

		char *printstringsnew = (char *)GlobalAlloc(GMEM_FIXED, (count + 1) * BUFFER_SIZE);
		memcpy(printstringsnew, printstrings, count * BUFFER_SIZE);
		GlobalFree(printstrings);
		printstrings = printstringsnew;

		if (SymGetSymFromAddr(process, sf.AddrPC.Offset, &Disp, pSym)) {
			// This is the code path taken on VC if debugging syms are found.
			SNPRINTF(printstrings + count * BUFFER_SIZE, BUFFER_SIZE, "(%d) %s(%s+%#0lx) [0x%08lX]", count, modname, pSym->Name, Disp, sf.AddrPC.Offset);
		} else {
			// This is the code path taken on MinGW, and VC if no debugging syms are found.
			SNPRINTF(printstrings + count * BUFFER_SIZE, BUFFER_SIZE, "(%d) %s [0x%08lX]", count, modname, sf.AddrPC.Offset);
		}

		// OpenGL lib names (ATI): "atioglxx.dll" "atioglx2.dll"
		containsOglDll = containsOglDll || strstr(modname, "atiogl");
		// OpenGL lib names (Nvidia): "nvoglnt.dll" "nvoglv32.dll" "nvoglv64.dll" (last one is a guess)
		containsOglDll = containsOglDll || strstr(modname, "nvogl");

		++count;
	}

	if (containsOglDll) {
		PRINT("This stack trace indicates a problem with your graphic card driver. "
		      "Please try upgrading or downgrading it. "
		      "Specifically recommended is the latest driver, and one that is as old as your graphic card. "
		      "Make sure to use a driver removal utility, before installing other drivers.");
	}

	if (suspended) {
		ResumeThread(hThread);
	}

	for (int i = 0; i < count; ++i) {
		PRINT("%s", printstrings + i * BUFFER_SIZE);
	}

	GlobalFree(printstrings);

	GlobalFree(pSym);
}
Exemple #28
0
    _Check_return_ VOODOO_METHODDEF(VSCore::Init)(_In_z_ CONST wchar_t * config)
    {
        if (config)
        {
            m_Parser->Add(VSTR("config"), config, VSVar_System);
        }
        else
        {
            m_Parser->Add(VSTR("config"), VSTR("VoodooShader.xml"), VSVar_System);
        }

        // Load variables, built-in first
        {
            wchar_t buffer[MAX_PATH];	ZeroMemory(buffer, MAX_PATH);

            // Global path
            GetVoodooPath(buffer);
            m_Parser->Add(VSTR("path"), buffer, VSVar_System);

            // Bin prefix
            GetVoodooBinPrefix(buffer);
            m_Parser->Add(VSTR("prefix"), buffer, VSVar_System);

            // Framework bin path
            GetVoodooBinPath(buffer);
            m_Parser->Add(VSTR("binpath"), buffer, VSVar_System);

            // Target
            HMODULE pTarget = GetModuleHandle(NULL);
            GetModuleFileName(pTarget, buffer, MAX_PATH);
            m_Parser->Add(VSTR("target"), buffer, VSVar_System);

            // Local path
            PathRemoveFileSpec(buffer);
            PathAddBackslash(buffer);
            m_Parser->Add(VSTR("local"), buffer, VSVar_System);

            // Startup path
            GetCurrentDirectory(MAX_PATH, buffer);
            PathAddBackslash(buffer);
            m_Parser->Add(VSTR("startup"), buffer, VSVar_System);

            GetModuleFileName(gCoreHandle, buffer, MAX_PATH);
            m_Parser->Add(VSTR("core"), buffer, VSVar_System);
        }

        // Command line processing
        LPWSTR cmdline = GetCommandLine();
        m_Parser->Add(VSTR("args"), cmdline, VSVar_System);

        int cmdargc = 0;
        LPWSTR * cmdargv = CommandLineToArgvW(cmdline, &cmdargc);
        m_Parser->Add(VSTR("argc"), StringFormat(VSTR("%d")) << cmdargc, VSVar_System);
        for (int i = 0; i < cmdargc; ++i)
        {
            m_Parser->Add(StringFormat(VSTR("argv_%d")) << i, cmdargv[i], VSVar_System);
        }

        // Load the config
        try
        {
            m_ConfigFile = new pugi::xml_document();

            // Try loading the config file from each major location
            String configPath = m_Parser->Parse(VSTR("$(config)"), VSParse_PathCanon);
            pugi::xml_parse_result result = m_ConfigFile->load_file(configPath.GetData());

            if (!result)
            {
                configPath = m_Parser->Parse(VSTR("$(startup)\\$(config)"), VSParse_PathCanon);
                result = m_ConfigFile->load_file(configPath.GetData());
                if (!result)
                {
                    configPath = m_Parser->Parse(VSTR("$(local)\\$(config)"), VSParse_PathCanon);
                    result = m_ConfigFile->load_file(configPath.GetData());
                    if (!result)
                    {
                        configPath = m_Parser->Parse(VSTR("$(path)\\$(config)"), VSParse_PathCanon);
                        result = m_ConfigFile->load_file(configPath.GetData());
                        if (!result)
                        {
                            Throw(VOODOO_CORE_NAME, VSTR("Unable to find or parse config file."), nullptr);
                        }
                    }
                }
            }

            // Start setting things up
            pugi::xml_node configRoot = static_cast<pugi::xml_node>(*m_ConfigFile);
            pugi::xml_node globalNode = configRoot.select_single_node(L"/VoodooConfig/Global").node();
            if (!globalNode)
            {
                Throw(VOODOO_CORE_NAME, VSTR("Could not find global config node."), nullptr);
            }

            // Create query for node text, used multiple times
            pugi::xpath_query xpq_getName(L"./@name");
            pugi::xpath_query xpq_getText(L"./text()");

            // Load variables
            {
                pugi::xpath_query xpq_getVariables(L"./Variables/Variable");
                pugi::xpath_node_set nodes = xpq_getVariables.evaluate_node_set(globalNode);
                pugi::xpath_node_set::const_iterator iter = nodes.begin();

                while (iter != nodes.end())
                {
                    String name = xpq_getName.evaluate_string(*iter).c_str();
                    String value = xpq_getText.evaluate_string(*iter).c_str();

                    m_Parser->Add(name, value);

                    ++iter;
                }
            }

            // Open the logger as early as possible
            pugi::xpath_query logfQuery(L"./Log/File/text()");
            pugi::xpath_query logaQuery(L"./Log/Append/text()");
            pugi::xpath_query loglQuery(L"./Log/Level/text()");

            String logFile  = m_Parser->Parse(logfQuery.evaluate_string(globalNode));
            String logLevelStr = m_Parser->Parse(loglQuery.evaluate_string(globalNode));
            String logAppendStr = m_Parser->Parse(logaQuery.evaluate_string(globalNode));

            LogLevel logLevel = VSLog_Default;
            try
            {
                logLevel = (LogLevel)stoi(logLevelStr.ToString());
            }
            catch (const std::exception & exc)
            {
                UNREFERENCED_PARAMETER(exc);
                logLevel = VSLog_Default;
            }

            bool logAppend = logAppendStr.Compare(VSTR("true"), false) || logAppendStr.StartsWith("1");

            m_Logger->Open(logFile, logAppend);
            m_Logger->SetFilter(logLevel);

            // Log extended build information
            String configMsg = m_Parser->Parse(VSTR("Config loaded from '$(config)'."));
            m_Logger->LogMessage(VSLog_CoreNotice, VOODOO_CORE_NAME, configMsg);
            m_Logger->LogMessage(VSLog_CoreNotice, VOODOO_CORE_NAME, VOODOO_GLOBAL_COPYRIGHT_FULL);


            // Load plugins, starting with the core
            m_Server->LoadPlugin(this, VSTR("$(core)"));

            {
                pugi::xpath_query xpq_getPluginPaths(L"./Plugins/Path");
                pugi::xpath_query xpq_getFilter(L"./@filter");
                pugi::xpath_node_set nodes = xpq_getPluginPaths.evaluate_node_set(globalNode);
                pugi::xpath_node_set::const_iterator iter = nodes.begin();

                while (iter != nodes.end())
                {
                    String filter = xpq_getFilter.evaluate_string(*iter);
                    String path = xpq_getText.evaluate_string(*iter);

                    m_Server->LoadPath(this, path, filter);

                    ++iter;
                }
            }

            {
                pugi::xpath_query xpq_getPluginFiles(L"./Plugins/File");
                pugi::xpath_node_set nodes = xpq_getPluginFiles.evaluate_node_set(globalNode);
                pugi::xpath_node_set::const_iterator iter = nodes.begin();

                while (iter != nodes.end())
                {
                    String file = xpq_getText.evaluate_string(*iter);

                    m_Server->LoadPlugin(this, file);

                    ++iter;
                }
            }

            // Lookup classes
            pugi::xpath_query fsQuery(L"./Classes/FileSystem/text()");
            pugi::xpath_query hookQuery(L"./Classes/HookManager/text()");
            String fsClass = m_Parser->Parse(fsQuery.evaluate_string(globalNode).c_str());
            String hookClass = m_Parser->Parse(hookQuery.evaluate_string(globalNode).c_str());

            // Load less vital classes
            ObjectRef coreplugin = m_Server->CreateObject(this, hookClass);
            IHookManager * phm = nullptr;
            if (coreplugin && SUCCEEDED(coreplugin->QueryInterface(IID_IHookManager, (IObject**)&phm)) && phm)
            {
                m_HookManager = phm;
                phm->Release();
            }
            else
            {
                StringFormat fmt(VSTR("Unable to create hook manager (class %1%).")); fmt << hookClass;
                Throw(VOODOO_CORE_NAME, fmt, this);
            }

            coreplugin = m_Server->CreateObject(this, fsClass);
            IFileSystem * pfs = nullptr;
            if (coreplugin && SUCCEEDED(coreplugin->QueryInterface(IID_IFileSystem, (IObject**)&pfs)) && pfs)
            {
                m_FileSystem = pfs;
                pfs->Release();
            }
            else
            {
                StringFormat fmt(VSTR("Unable to create file system (class %1%).")); fmt << fsClass;
                Throw(VOODOO_CORE_NAME, fmt, this);
            }

            // ICore done loading
            m_Logger->LogMessage(VSLog_CoreInfo, VOODOO_CORE_NAME, VSTR("Core initialization complete."));

            // Call finalization events
            this->CallEvent(EventIds::Finalize, 0, nullptr);

            // Return
            return VSF_OK;
        }
        catch (const Exception & exc)
        {
            if (m_Logger)
            {
                m_Logger->LogMessage(VSLog_CoreError, VOODOO_CORE_NAME, 
                    StringFormat(VSTR("Exception during Core creation: %1%")) << exc.strwhat());
            } else {
                GlobalLog(VSTR("Unlogged exception during core creation: %S\n"), exc.what());
            }

            return VSF_FAIL;
        }
        catch (const std::exception & exc)
        {
            if (m_Logger)
            {
                m_Logger->LogMessage(VSLog_CoreError, VOODOO_CORE_NAME, 
                    StringFormat(VSTR("Error during Core creation: %1%")) << exc.what());
			} else {
				GlobalLog(VSTR("Unlogged exception during core creation: %S\n"), exc.what());
			}

            return VSF_FAIL;
        }
    }
Exemple #29
0
//
//	Wrapper around WM_SETCONSOLEINFO. We need to create the
//  necessary section (file-mapping) object in the context of the
//  process which owns the console, before posting the message
//
BOOL SetConsoleInfo(HWND hwndConsole, CONSOLE_INFO *pci)
{
	DWORD   dwConsoleOwnerPid, dwCurProcId;
	PVOID   ptrView = 0;
	DWORD   dwLastError=0;
	WCHAR   ErrText[255];
	//
	//	Retrieve the process which "owns" the console
	//
	dwCurProcId = GetCurrentProcessId();
	
	DEBUGTEST(DWORD dwConsoleThreadId =)
	GetWindowThreadProcessId(hwndConsole, &dwConsoleOwnerPid);

	// We'll fail, if console was created by other process
	if (dwConsoleOwnerPid != dwCurProcId)
	{
		#ifdef _DEBUG
		// Wine related
		PROCESSENTRY32W pi = {};
		GetProcessInfo(dwConsoleOwnerPid, &pi);
		if (lstrcmpi(pi.szExeFile, L"wineconsole.exe")!=0)
		{
			wchar_t szDbgMsg[512], szTitle[128];
			szDbgMsg[0] = 0;
			GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg));
			msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId());
			msprintf(szDbgMsg, countof(szDbgMsg), L"GetWindowThreadProcessId()\nPID=%u, TID=%u, %s\n%s",
				dwConsoleOwnerPid, dwConsoleThreadId,
				pi.szExeFile, szTitle);
			MessageBox(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL);
		}
		//_ASSERTE(dwConsoleOwnerPid == dwCurProcId);
		#endif

		return FALSE;
	}

	//
	// Create a SECTION object backed by page-file, then map a view of
	// this section into the owner process so we can write the contents
	// of the CONSOLE_INFO buffer into it
	//
	if (!ghConsoleSection)
	{
		ghConsoleSection = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, gnConsoleSectionSize, 0);

		if (!ghConsoleSection)
		{
			dwLastError = GetLastError();
			_wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't CreateFileMapping(ghConsoleSection). ErrCode=%i", dwLastError);
			MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
			return FALSE;
		}

		_ASSERTE(OnShutdownConsole==NULL || OnShutdownConsole==ShutdownConsole);
		OnShutdownConsole = ShutdownConsole;
	}

	//
	//	Copy our console structure into the section-object
	//
	ptrView = MapViewOfFile(ghConsoleSection, FILE_MAP_WRITE|FILE_MAP_READ, 0, 0, gnConsoleSectionSize);

	if (!ptrView)
	{
		dwLastError = GetLastError();
		_wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't MapViewOfFile. ErrCode=%i", dwLastError);
		MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
	}
	else
	{
		_ASSERTE(pci->Length==sizeof(CONSOLE_INFO));
		//2010-09-19 что-то на XP стало окошко мелькать.
		// при отсылке WM_SETCONSOLEINFO консоль отображается :(
		BOOL lbWasVisible = IsWindowVisible(hwndConsole);
		RECT rcOldPos = {0}, rcAllMonRect = {0};

		if (!lbWasVisible)
		{
			GetWindowRect(hwndConsole, &rcOldPos);
			// В много-мониторных конфигурациях координаты на некоторых могут быть отрицательными!
			rcAllMonRect = GetAllMonitorsWorkspace();
			pci->AutoPosition = FALSE;
			pci->WindowPosX = rcAllMonRect.left - 1280;
			pci->WindowPosY = rcAllMonRect.top - 1024;
		}

		memcpy(ptrView, pci, pci->Length); //-V106
		UnmapViewOfFile(ptrView);

		//  Send console window the "update" message
		DEBUGTEST(LRESULT dwConInfoRc =)
		SendMessage(hwndConsole, WM_SETCONSOLEINFO, (WPARAM)ghConsoleSection, 0);

		DEBUGTEST(DWORD dwConInfoErr = GetLastError());

		if (!lbWasVisible && IsWindowVisible(hwndConsole))
		{
			//DEBUGTEST(Sleep(10));

			apiShowWindow(hwndConsole, SW_HIDE);
			//SetWindowPos(hwndConsole, NULL, rcOldPos.left, rcOldPos.top, 0,0, SWP_NOSIZE|SWP_NOZORDER);
			// -- чтобы на некоторых системах не возникала проблема с позиционированием -> {0,0}
			// Issue 274: Окно реальной консоли позиционируется в неудобном месте
			SetWindowPos(hwndConsole, NULL, 0, 0, 0,0, SWP_NOSIZE|SWP_NOZORDER);
		}
	}

	return TRUE;
}
Exemple #30
0
/*********************************************************************
*	Function: LRESULT CALLBACK InitMenuHookProc(int nCode, WPARAM wParam, LPARAM lParam)
*	Author:	Chau Nguyen
*	Created On: 2003/10/24
* --------------------------------------------------------------------
*	Purpose: Intercept InitPopupMenu message to change menu before its displaying
* --------------------------------------------------------------------
*	Input Parameters: No
*
*	Output Parameters: No
*
*	Return Value: No
*
* --------------------------------------------------------------------
* NOTE:
*	- 
*
* --------------------------------------------------------------------
* REVISION HISTORY:
*	Version		Date		Author		Description
*
*********************************************************************/
LRESULT CALLBACK InitMenuHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
	// return immediately if system required
    if (nCode < 0){
        return CallNextHookEx(g_hInitMenuHook, nCode, wParam, lParam); 
	}
 
	// get window procedure struct
	CWPSTRUCT *wps = (CWPSTRUCT*)lParam;
	
	// check if this message is not the my own registered message (it is a system message)
	if(wps->message != SWM_TRAYMSG) {		
		switch (wps->message) {
		case WM_MENUSELECT:
			// menu is being closed
			if(wps->lParam == NULL && HIWORD(wps->wParam) == 0xFFFF){
				// determine what window
				for(UINT i = 0; i < g_iLastIndex; i++){
					if(g_listWnd[i].m_hWnd == (HWND)wps->hwnd){
						// remove menu item if it was added
						if(g_listWnd[i].m_bHooked){
							RemoveMenu(GetSystemMenu(g_listWnd[i].m_hWnd, FALSE), SC_TRAYME, MF_BYCOMMAND);
						}
						
						break;
					}
				}
			}
			break;
		case WM_INITMENUPOPUP:{
			// get the menu handle
			HMENU hMenu = (HMENU)wps->wParam;

			// check if it is a menu
			if(IsMenu(hMenu)){
				// is system menu
				if(HIWORD(wps->lParam) == TRUE){ 
					// check if this window was hooked or not
					for(UINT i = 0; i < g_iLastIndex; i++){
						if(g_listWnd[i].m_hWnd == (HWND)wps->hwnd){
							break; // exit the for loop
						}
					}
					
					// not hooked yet
					if(i == g_iLastIndex){
						// store the window handle
						g_listWnd[i].m_hWnd = (HWND)wps->hwnd;
						g_listWnd[i].m_bMinimized = FALSE;

						// get title od that window
						char szText[255];
						GetWindowText(g_listWnd[i].m_hWnd, szText, 255);
												
						// prepare a NotifyData struct for this winfow
						ZeroMemory(&(g_listWnd[i].m_niData), sizeof(NOTIFYICONDATA));
						g_listWnd[i].m_niData.cbSize = sizeof(NOTIFYICONDATA);
						g_listWnd[i].m_niData.hWnd = (HWND)wps->hwnd;
						
						HICON hIcon = (HICON)SendMessage(g_listWnd[i].m_hWnd, WM_GETICON, ICON_SMALL,0);					
						if(!hIcon){
							char szPath[255];
							HMODULE hModule = (HMODULE)OpenProcess(0, FALSE, GetWindowThreadProcessId(g_listWnd[i].m_hWnd, 0));
							GetModuleFileName(hModule, szPath, 255);
							hIcon = GetFileIconHandle(szPath, TRUE);
						}
						
						
						if(hIcon){
							g_listWnd[i].m_niData.hIcon = CopyIcon(hIcon);
						}
						else{
							g_listWnd[i].m_niData.hIcon = LoadIcon(NULL, IDI_QUESTION);
						}
						g_listWnd[i].m_niData.uID = TRAYICONID;
						g_listWnd[i].m_niData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
						strcpy(g_listWnd[i].m_niData.szTip, szText);
						g_listWnd[i].m_niData.uCallbackMessage = SWM_TRAYMSG;
		
						// append our own menu item
						AppendMenu(GetSystemMenu(g_listWnd[i].m_hWnd, FALSE), MF_BYPOSITION|MF_STRING, SC_TRAYME, "&Tray Me");					

						// set the flag on
						g_listWnd[i].m_bHooked = TRUE;
						
						// increase count
						g_iLastIndex++;
					}
					else if(i < g_iLastIndex){// hook allready
						// append our own menu item
						AppendMenu(GetSystemMenu(g_listWnd[i].m_hWnd, FALSE), MF_BYPOSITION|MF_STRING, SC_TRAYME, "&Tray Me");					

						// set the flag on
						g_listWnd[i].m_bHooked = TRUE;
					}
				}
			}
			break;
		}			
		
		}
		
	}
	else{ // this is my registered message
		switch(wps->lParam)
		{
		case WM_LBUTTONDOWN:
			// determine what window
			for(UINT i = 0; i < g_iLastIndex; i++){
				if(g_listWnd[i].m_hWnd == (HWND)wps->hwnd){
					Shell_NotifyIcon(NIM_DELETE, &g_listWnd[i].m_niData);
					ShowWindow(g_listWnd[i].m_hWnd, SW_SHOW);

					g_listWnd[i].m_bMinimized = FALSE;
					break;
				}
			}
			
			break;
		}
	}
		
    return CallNextHookEx(g_hInitMenuHook, nCode, wParam, lParam); 
}