Exemple #1
0
void
ase_install_malloc_hook()
{
  _set_new_mode(1);
  _set_new_handler(mhook_handle_oom);
}
Exemple #2
0
int main(int argc,char*argv[]) { 

#ifdef _DEBUG
    Test_DoAllTests();
#endif
    
    int res;
    main_init();
    
    res = main_preprocess_cmdline(argc, argv);
    if (res != RETURN_CONTINUE) {
        return res;
    }

    initialize_debug_system();

    Out::FPrint("Adventure Game Studio v%s Interpreter\n"
           "Copyright (c) 1999-2011 Chris Jones and 2011-2014 others\n"
#ifdef BUILD_STR
           "ACI version %s (Build: %s)\n",
           EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr(), EngineVersion.BuildInfo.GetCStr());
#else
           "ACI version %s\n", EngineVersion.ShortString.GetCStr(), EngineVersion.LongString.GetCStr());
#endif

    if ((argc>1) && (stricmp(argv[1],"--help") == 0 || argv[1][1]=='?')) {
        main_print_help();
        return 0;
    }

    Out::FPrint("*** ENGINE STARTUP ***");

#if defined(WINDOWS_VERSION)
    _set_new_handler(malloc_fail_handler);
    _set_new_mode(1);
    printfworkingspace=(char*)malloc(7000);
#endif
    debug_flags=0;

    res = main_process_cmdline(argc, argv);
    if (res != RETURN_CONTINUE) {
        return res;
    }

    main_init_crt_report();

    main_set_gamedir(argc, argv);    

    // Update shell associations and exit
    if (debug_flags & DBG_REGONLY)
        exit(0);

#ifndef USE_CUSTOM_EXCEPTION_HANDLER
    usetup.disable_exception_handling = 1;
#endif

    if (usetup.disable_exception_handling)
    {
        int result = initialize_engine(argc, argv);
        platform->PostAllegroExit();
        return result;
    }
    else
    {
        return initialize_engine_with_exception_handling(argc, argv);
    }
}
Exemple #3
0
void DoMain (HINSTANCE hInstance)
{
	LONG WinWidth, WinHeight;
	int height, width, x, y;
	RECT cRect;
	TIMECAPS tc;
	DEVMODE displaysettings;

	try
	{
#ifdef _MSC_VER
		_set_new_handler (NewFailure);
#endif

		Args = new DArgs(__argc, __argv);

		// Under XP, get our session ID so we can know when the user changes/locks sessions.
		// Since we need to remain binary compatible with older versions of Windows, we
		// need to extract the ProcessIdToSessionId function from kernel32.dll manually.
		HMODULE kernel = GetModuleHandle ("kernel32.dll");

		if (Args->CheckParm("-stdout"))
		{
			// As a GUI application, we don't normally get a console when we start.
			// If we were run from the shell and are on XP+, we can attach to its
			// console. Otherwise, we can create a new one. If we already have a
			// stdout handle, then we have been redirected and should just use that
			// handle instead of creating a console window.

			StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
			if (StdOut != NULL)
			{
				// It seems that running from a shell always creates a std output
				// for us, even if it doesn't go anywhere. (Running from Explorer
				// does not.) If we can get file information for this handle, it's
				// a file or pipe, so use it. Otherwise, pretend it wasn't there
				// and find a console to use instead.
				BY_HANDLE_FILE_INFORMATION info;
				if (!GetFileInformationByHandle(StdOut, &info))
				{
					StdOut = NULL;
				}
			}
			if (StdOut == NULL)
			{
				// AttachConsole was introduced with Windows XP. (OTOH, since we
				// have to share the console with the shell, I'm not sure if it's
				// a good idea to actually attach to it.)
				typedef BOOL (WINAPI *ac)(DWORD);
				ac attach_console = kernel != NULL ? (ac)GetProcAddress(kernel, "AttachConsole") : NULL;
				if (attach_console != NULL && attach_console(ATTACH_PARENT_PROCESS))
				{
					StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
					DWORD foo; WriteFile(StdOut, "\n", 1, &foo, NULL);
					AttachedStdOut = true;
				}
				if (StdOut == NULL && AllocConsole())
				{
					StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
				}
				FancyStdOut = true;
			}
		}

		// Set the timer to be as accurate as possible
		if (timeGetDevCaps (&tc, sizeof(tc)) != TIMERR_NOERROR)
			TimerPeriod = 1;	// Assume minimum resolution of 1 ms
		else
			TimerPeriod = tc.wPeriodMin;

		timeBeginPeriod (TimerPeriod);

		/*
		killough 1/98:

		This fixes some problems with exit handling
		during abnormal situations.

		The old code called I_Quit() to end program,
		while now I_Quit() is installed as an exit
		handler and exit() is called to exit, either
		normally or abnormally.
		*/

		atexit (call_terms);

		atterm (I_Quit);

		// Figure out what directory the program resides in.
		char *program;

#ifdef _MSC_VER
		if (_get_pgmptr(&program) != 0)
		{
			I_FatalError("Could not determine program location.");
		}
#else
		char progbuff[1024];
		GetModuleFileName(0, progbuff, sizeof(progbuff));
		progbuff[1023] = '\0';
		program = progbuff;
#endif

		progdir = program;
		program = progdir.LockBuffer();
		*(strrchr(program, '\\') + 1) = '\0';
		FixPathSeperator(program);
		progdir.Truncate((long)strlen(program));
		progdir.UnlockBuffer();

		width = 512;
		height = 384;

		// Many Windows structures that specify their size do so with the first
		// element. DEVMODE is not one of those structures.
		memset (&displaysettings, 0, sizeof(displaysettings));
		displaysettings.dmSize = sizeof(displaysettings);
		EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &displaysettings);
		x = (displaysettings.dmPelsWidth - width) / 2;
		y = (displaysettings.dmPelsHeight - height) / 2;

		if (Args->CheckParm ("-0"))
		{
			x = y = 0;
		}

		WNDCLASS WndClass;
		WndClass.style			= 0;
		WndClass.lpfnWndProc	= LConProc;
		WndClass.cbClsExtra		= 0;
		WndClass.cbWndExtra		= 0;
		WndClass.hInstance		= hInstance;
		WndClass.hIcon			= LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1));
		WndClass.hCursor		= LoadCursor (NULL, IDC_ARROW);
		WndClass.hbrBackground	= NULL;
		WndClass.lpszMenuName	= NULL;
		WndClass.lpszClassName	= (LPCTSTR)WinClassName;
		
		/* register this new class with Windows */
		if (!RegisterClass((LPWNDCLASS)&WndClass))
			I_FatalError ("Could not register window class");
		
		/* create window */
		char caption[100];
		mysnprintf(caption, countof(caption), "" GAMESIG " %s " X64 " (%s)", GetVersionString(), GetGitTime());
		Window = CreateWindowEx(
				WS_EX_APPWINDOW,
				(LPCTSTR)WinClassName,
				(LPCTSTR)caption,
				WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CLIPCHILDREN,
				x, y, width, height,
				(HWND)   NULL,
				(HMENU)  NULL,
						hInstance,
				NULL);

		if (!Window)
			I_FatalError ("Could not open window");

		if (kernel != NULL)
		{
			typedef BOOL (WINAPI *pts)(DWORD, DWORD *);
			pts pidsid = (pts)GetProcAddress (kernel, "ProcessIdToSessionId");
			if (pidsid != 0)
			{
				if (!pidsid (GetCurrentProcessId(), &SessionID))
				{
					SessionID = 0;
				}
				hwtsapi32 = LoadLibraryA ("wtsapi32.dll");
				if (hwtsapi32 != 0)
				{
					FARPROC reg = GetProcAddress (hwtsapi32, "WTSRegisterSessionNotification");
					if (reg == 0 || !((BOOL(WINAPI *)(HWND, DWORD))reg) (Window, NOTIFY_FOR_THIS_SESSION))
					{
						FreeLibrary (hwtsapi32);
						hwtsapi32 = 0;
					}
					else
					{
						atterm (UnWTS);
					}
				}
			}
		}

		GetClientRect (Window, &cRect);

		WinWidth = cRect.right;
		WinHeight = cRect.bottom;

		CoInitialize (NULL);
		atterm (UnCOM);

		C_InitConsole (((WinWidth / 8) + 2) * 8, (WinHeight / 12) * 8, false);

		I_DetectOS ();
		D_DoomMain ();
	}
	catch (class CNoRunExit &)
	{
		I_ShutdownGraphics();
		if (FancyStdOut && !AttachedStdOut)
		{ // Outputting to a new console window: Wait for a keypress before quitting.
			DWORD bytes;
			HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE);

			ShowWindow (Window, SW_HIDE);
			WriteFile(StdOut, "Press any key to exit...", 24, &bytes, NULL);
			FlushConsoleInputBuffer(stdinput);
			SetConsoleMode(stdinput, 0);
			ReadConsole(stdinput, &bytes, 1, &bytes, NULL);
		}
		else if (StdOut == NULL)
		{
			ShowErrorPane(NULL);
		}
		exit(0);
	}
	catch (class CDoomError &error)
	{
		I_ShutdownGraphics ();
		RestoreConView ();
		if (error.GetMessage ())
		{
			ShowErrorPane (error.GetMessage());
		}
		exit (-1);
	}
}
}

#endif



// ------ MEMORY MANAGEMENT HANDLER

#ifndef NEED_DJVU_MEMORY
// This is not activated when C++ memory management
// is overidden.  The overriding functions handle
// memory exceptions by themselves.
# if defined(_MSC_VER)
// Microsoft is different!
static int throw_memory_error(size_t) { G_THROW(GException::outofmemory); return 0; }
static int (*old_handler)(size_t) = _set_new_handler(throw_memory_error);
# else // !_MSC_VER
// Standard C++
static void throw_memory_error() { G_THROW(GException::outofmemory); }
#  if !defined(WIN32) && !defined(__CYGWIN32__) && !defined(OS2)
#   ifdef HAVE_STDINCLUDES
//static void (*old_handler)() = std::set_new_handler(throw_memory_error);
#   else
static void (*old_handler)() = set_new_handler(throw_memory_error);
#   endif // HAVE_STDINCLUDES
#  endif // ! WIN32
# endif // !_MSC_VER
#endif // !NEED_DJVU_MEMORY


#ifdef HAVE_NAMESPACES
Exemple #5
0
void InstallAllocationFunctions()
{
	_set_new_mode( 1 ); // so if malloc() fails, we exit.
	_set_new_handler( CmdLib_NewHandler );
}
Exemple #6
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;
}
Exemple #7
0
/**
 * @brief Initializes the application.
 */
bool App::OnInit()
{
    // initialize wxWidgets
    SetAppName(wxT("UltraDefrag"));
    wxInitAllImageHandlers();
    if(!wxApp::OnInit())
        return false;

    // initialize udefrag library
    if(::udefrag_init_library() < 0){
        wxLogError(wxT("Initialization failed!"));
        return false;
    }

    // set out of memory handler
#if !defined(__GNUC__)
    winx_set_killer(out_of_memory_handler);
    _set_new_handler(out_of_memory_handler);
    _set_new_mode(1);
#endif

    // initialize debug log
    wxFileName logpath(wxT(".\\logs\\ultradefrag.log"));
    logpath.Normalize();
    wxSetEnv(wxT("UD_LOG_FILE_PATH"),logpath.GetFullPath());
    ::udefrag_set_log_file_path();

    // initialize logging
    m_log = new Log();

    // use global config object for internal settings
    wxFileConfig *cfg = new wxFileConfig(wxT(""),wxT(""),
        wxT("gui.ini"),wxT(""),wxCONFIG_USE_RELATIVE_PATH);
    wxConfigBase::Set(cfg);

    // enable i18n support
    InitLocale();

    // save report translation on setup
    wxString cmdLine(GetCommandLine());
    if(cmdLine.Find(wxT("--setup")) != wxNOT_FOUND){
        SaveReportTranslation();
        ::winx_flush_dbg_log(0);
        delete m_log;
        return false;
    }

    // start web statistics
    m_statThread = new StatThread();

    // check for administrative rights
    if(!Utils::CheckAdminRights()){
        wxMessageDialog dlg(NULL,
            wxT("Administrative rights are needed to run the program!"),
            wxT("UltraDefrag"),wxOK | wxICON_ERROR
        );
        dlg.ShowModal(); Cleanup();
        return false;
    }

    // create synchronization event
    g_synchEvent = ::CreateEvent(NULL,TRUE,FALSE,NULL);
    if(!g_synchEvent){
        letrace("cannot create synchronization event");
        wxMessageDialog dlg(NULL,
            wxT("Cannot create synchronization event!"),
            wxT("UltraDefrag"),wxOK | wxICON_ERROR
        );
        dlg.ShowModal(); Cleanup();
        return false;
    }

    // keep things DPI-aware
    HDC hdc = ::GetDC(NULL);
    if(hdc){
        g_scaleFactor = (double)::GetDeviceCaps(hdc,LOGPIXELSX) / 96.0f;
        ::ReleaseDC(NULL,hdc);
    }
    g_iconSize = wxSystemSettings::GetMetric(wxSYS_SMALLICON_X);
    if(g_iconSize < 20) g_iconSize = 16;
    else if(g_iconSize < 24) g_iconSize = 20;
    else if(g_iconSize < 32) g_iconSize = 24;
    else g_iconSize = 32;

    // support taskbar icon overlay setup on shell restart
    g_TaskbarIconMsg = ::RegisterWindowMessage(wxT("TaskbarButtonCreated"));
    if(!g_TaskbarIconMsg) letrace("cannot register TaskbarButtonCreated message");

    // create main window
    g_mainFrame = new MainFrame();
    g_mainFrame->Show(true);
    SetTopWindow(g_mainFrame);
    return true;
}
 my_new_handler_obj()
 {
     //_old_new_mode = _set_new_mode(1); // cause malloc to throw like new
     _old_new_handler = _set_new_handler(my_new_handler);
 }
 ~my_new_handler_obj()
 {
     _set_new_handler(_old_new_handler);
     //_set_new_mode(_old_new_mode);
 }
Exemple #10
0
int main(int argc, char**argv)  {
    long inframes,framesread=0,total_framesread;
    double maxsamp = 0.0,startpos = 0.0,endpos;
    long startframe = 0,endframe;
    long halfsecframes = 0;
    int i,j,ifd = -1;
    int chans;
    int do_norm = 0;
	PSF_PROPS inprops;
    CH_RMSINFO* rmsinfo = NULL;
    double* rmsfac  = 0;
    double* ampsum  = 0;
    double* ampsumb = 0;
    double* inbuf   = 0;
    double* nrmsfac = 0;
    double* nampsum = 0;
    
    
    /* CDP version number */
    if(argc==2 && (stricmp(argv[1],"--version")==0)){
        printf("1.0.1\n");
        return 0;
    }
#ifdef WIN32    
# if _MSC_VER && _MSC_VER <= 1200
     _set_new_handler( newhandler );
# endif
#endif
    if(psf_init()){
		puts("unable to start portsf\n");
		return 1;
	}
    if(argc < 2){		 
		usage();
		return(1);
	}
    while(argv[1][0]=='-'){
		switch(argv[1][1]){
        case 'n':
            do_norm = 1;
            break;
        default:
            fprintf(stderr, "Unrecognised flag option %s\n",argv[1]);
            return 1;
        }
        argc--; argv++;
    }
    if(argc < 2){		 
		usage();
		return(1);
	}
    if((ifd = psf_sndOpen(argv[ARG_INFILE],&inprops, 0)) < 0){
		fprintf(stderr,"\nUnable to open input soundfile %s",argv[ARG_INFILE]);
		return(1);
	}
	inframes = psf_sndSize(ifd);  // m/c frames
    endframe = inframes;
    
	if(inframes <= 0)
        return 0;
	if(argc >= 3) {
        long lpos;
        startpos = atof(argv[ARG_INFILE+1]);
        if(startpos < 0.0){
            fprintf(stderr,"Error: startpos must be positive\n");
            return 1;
        }
        lpos = (long)( startpos * inprops.srate);
        if(lpos > inframes){
            fprintf(stderr,"Error: startpos value beyond end of file.\n");
            return 1;
        }
        startframe = lpos;
    }
    if(argc >= 4) {
        long lpos;
        endpos = atof(argv[ARG_INFILE+2]);
        
        lpos = (long)(endpos * inprops.srate);
        if(lpos > inframes){
            fprintf(stderr,"Warning: endpos value too large - reset to end of file.\n");
            return 1;
        }
        endframe = lpos;
        if(!(endframe > startframe)){
            fprintf(stderr,"Error: endpos must be beyond startpos.\n");
            return 1;
        }
    }
    if(startframe)
        printf("Starting at frame %ld, ending at frame %ld\n",startframe, endframe);
    
    chans   = inprops.chans;
    try {
        inbuf   = new double[BUFLEN * chans];
        rmsinfo = new CH_RMSINFO[chans];
        rmsfac  = new double[chans];
        ampsum  = new double[chans];
        ampsumb = new double[chans];
        nrmsfac = new double[chans];
        nampsum = new double[chans];
    }
    catch(...){
        fputs("no memory!\n",stderr);
        return 1;
    }
    for(i=0; i < chans; i++){
        rmsfac[i]  = 0.0;
        ampsum[i]  = 0.0;
        ampsumb[i] = 0.0;
        nrmsfac[i] = 0.0;
        nampsum[i] = 0.0;
    }
    halfsecframes = inprops.srate / 2; 
    signal(SIGINT,runhandler);
    long wanted = endframe - startframe;
    printf("Scanning %ld frames (%.3lf secs):\n",wanted, (double)wanted / inprops.srate);
    total_framesread = 0;
    if(startframe) {
        if(psf_sndSeek(ifd,startframe,PSF_SEEK_SET)){
            fprintf(stderr,"File Seek error.\n");
            return 1;
        }
    }
        
	while((framesread = psf_sndReadDoubleFrames(ifd,inbuf,BUFLEN)) > 0){
        double fval;
        for(i = 0;i < framesread;i++) {
            for(j = 0; j < chans; j++){
                double val = inbuf[i*chans + j];
                fval = fabs(val);
                maxsamp = fval >  maxsamp ? fval : maxsamp;
                ampsum[j]   += fval;
                rmsfac[j]   += val*val; 
                ampsumb[j]  += val;
            }
            total_framesread++;
            if(scanning==0)
                break;
            if(total_framesread == wanted) 
                break;
            if((total_framesread % halfsecframes) == 0){
                printf("%.2lf\r",total_framesread / (double) inprops.srate);
                fflush(stdout);
            }
        }
        if(total_framesread == wanted) {
            break;
        }
    }
    if(framesread < 0){
        fprintf(stderr,"Error reading file.\n");
        return 1;
    }
    for(i=0;i < chans;i++){
        rmsfac[i]  /= total_framesread;
        rmsfac[i]   = sqrt(rmsfac[i]);
        ampsum[i]  /= total_framesread;
        ampsumb[i] /= total_framesread;
    }

    double normfac = 1.0 / maxsamp;
    if(scanning==0)
        printf("\nScan stopped.\n");
    if(total_framesread < inframes){
        printf("Scanned %ld frames (%.2lf secs).\n",total_framesread,total_framesread / (double)inprops.srate);
    }
    
    printf("Maximum sample = %lf (%.2lfdB)\n",maxsamp,20.0 * log10(maxsamp));
    printf("Maximum normalisation factor = %.4f\n",normfac);
    
    for(i=0;i < chans;i++){
        rmsinfo[i].rmspower    = rmsfac[i];
        rmsinfo[i].abssum      = ampsum[i];
        rmsinfo[i].bisum       = ampsumb[i];
        rmsinfo[i].norm_rms    = normfac * rmsfac[i];
        rmsinfo[i].norm_abssum = normfac * ampsum[i];
    }
    if(do_norm){
        printf("\t   RMS LEVEL\t    AVG  \t   NET DC\t   NORM RMS\t  NORM AVG\n");
        printf("CH\t AMP\t DB\t AMP\t DB\t AMP\t DB\t AMP\t DB\t AMP\t DB     \n");
    }
    else{
        printf("\t   RMS LEVEL\t    AVG  \t   NET DC\n");
        printf("CH\t AMP\t DB\t AMP\t DB\t AMP\t DB\n"); 
    }
    for(i=0;i < chans;i++){
        double d1,d2,d3,d4,d5;
        
        d1 = 20*log10(rmsfac[i]);
        d2 = 20*log10(ampsum[i]);
        d3 = 20*log10(fabs(ampsumb[i]));
        d4 = 20*log10(normfac * rmsfac[i]);
        d5 = 20*log10(normfac * ampsum[i]);
        if(do_norm){
            printf("%d\t%.5lf\t%.2lf\t%.5lf\t%.2lf\t%+.4lf\t%.2lf\t%.5lf\t%.2lf\t%.5lf\t%.2lf\n",i+1,
               rmsinfo[i].rmspower,d1,
               rmsinfo[i].abssum,d2,
               rmsinfo[i].bisum,d3,
               rmsinfo[i].norm_rms,d4,
               rmsinfo[i].norm_abssum,d5
            );
        }
        else {
            printf("%d\t%.5lf\t%.2lf\t%.5lf\t%.2lf\t%+.4lf\t%.2lf\n",i+1,
                   rmsinfo[i].rmspower,d1,
                   rmsinfo[i].abssum,d2,
                   rmsinfo[i].bisum,d3
            );
        }
    }
        
    delete [] inbuf;
    delete [] rmsfac;
    delete [] ampsum;
    delete [] ampsumb;
    delete [] rmsinfo;
    psf_sndClose(ifd);
    psf_finish();

	return 0;
}
Exemple #11
0
extern "C" BOOL WINAPI
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
        CWinApp* pApp = AfxGetApp();
        if (dwReason == DLL_PROCESS_ATTACH)
        {
                // initialize MFC exception handling
#ifndef _AFX_OLD_EXCEPTIONS
                set_terminate(&AfxStandardTerminate);
#endif
                _set_new_handler(&AfxNewHandler);

                // initialize DLL's instance(/module) not the app's
                if (!AfxWinInit(hInstance, NULL, &afxChNil, 0))
                {
                        AfxWinTerm();
                        return FALSE;   // Init Failed
                }

                // initialize the single instance DLL
                if (pApp != NULL && !pApp->InitInstance())
                {
                        pApp->ExitInstance();
                        AfxWinTerm();
                        return FALSE;   // Init Failed
                }
        }
        else if (dwReason == DLL_PROCESS_DETACH)
        {
                if (pApp != NULL)
                        pApp->ExitInstance();

#ifdef _DEBUG
                // check for missing AfxLockTempMap calls
                if (AfxGetThreadState()->m_nTempMapLock != 0)
                        TRACE1("Warning: Temp map lock count non-zero (%ld).\n",
                                AfxGetThreadState()->m_nTempMapLock);
#endif
                // terminate the library before destructors are called
                AfxWinTerm();

                // free safety pool buffer
                AFX_THREAD_STATE* pThreadState = AfxGetThreadState();
                if (pThreadState->m_pSafetyPoolBuffer != NULL)
                {
                        free(pThreadState->m_pSafetyPoolBuffer);
                        pThreadState->m_pSafetyPoolBuffer = NULL;
                }

#ifdef _DEBUG
                // trace any memory leaks that may have occurred
                AfxDumpMemoryLeaks();
#endif

                // clean up map objects before it is too late
                delete pThreadState->m_pmapHWND;
                pThreadState->m_pmapHWND = NULL;
                delete pThreadState->m_pmapHMENU;
                pThreadState->m_pmapHMENU = NULL;
                delete pThreadState->m_pmapHDC;
                pThreadState->m_pmapHDC = NULL;
                delete pThreadState->m_pmapHGDIOBJ;
                pThreadState->m_pmapHGDIOBJ = NULL;
                delete pThreadState->m_pmapHIMAGELIST;
                pThreadState->m_pmapHIMAGELIST = NULL;

                pThreadState->m_mapSocketHandle.CMapPtrToPtr::~CMapPtrToPtr();
                pThreadState->m_mapDeadSockets.CMapPtrToPtr::~CMapPtrToPtr();
                pThreadState->m_listSocketNotifications.CPtrList::~CPtrList();
        }
        return TRUE;    // ok
}
Exemple #12
0
void DoMain (HINSTANCE hInstance)
{
	LONG WinWidth, WinHeight;
	int height, width;
	RECT cRect;
	TIMECAPS tc;

	try
	{
#ifdef _MSC_VER
		_set_new_handler (NewFailure);
#endif

		Args.SetArgs (__argc, __argv);

		// Under XP, get our session ID so we can know when the user changes/locks sessions.
		// Since we need to remain binary compatible with older versions of Windows, we
		// need to extract the ProcessIdToSessionId function from kernel32.dll manually.
		HMODULE kernel = GetModuleHandle ("kernel32.dll");

		// NASM does not support creating writeable code sections (even though this
		// is a perfectly valid configuration for Microsoft's COFF format), so I
		// need to make the self-modifying code writeable after it's already loaded.
#ifdef USEASM
	{
		BYTE *module = (BYTE *)GetModuleHandle (NULL);
		IMAGE_DOS_HEADER *dosHeader = (IMAGE_DOS_HEADER *)module;
		IMAGE_NT_HEADERS *ntHeaders = (IMAGE_NT_HEADERS *)(module + dosHeader->e_lfanew);
		IMAGE_SECTION_HEADER *sections = IMAGE_FIRST_SECTION (ntHeaders);
		int i;
		LPVOID *start = NULL;
		SIZE_T size = 0;
		DWORD oldprotect;

		for (i = 0; i < ntHeaders->FileHeader.NumberOfSections; ++i)
		{
			if (memcmp (sections[i].Name, ".rtext\0", 8) == 0)
			{
				start = (LPVOID *)(sections[i].VirtualAddress + module);
				size = sections[i].Misc.VirtualSize;
				break;
			}
		}

		// I think these pages need to be mapped PAGE_EXECUTE_WRITECOPY (based on the
		// description of PAGE_WRITECOPY), but PAGE_EXECUTE_READWRITE seems to work
		// just as well; two instances of the program can be running with different
		// resolutions at the same time either way. Perhaps the file mappings for
		// executables are created with PAGE_WRITECOPY, so any attempts to give them
		// write access are automatically transformed to copy-on-write?
		//
		// This used to be PAGE_EXECUTE_WRITECOPY until Timmie found out Win9x doesn't
		// support it, although the MSDN does not indicate it.
		if (!VirtualProtect (start, size, PAGE_EXECUTE_READWRITE, &oldprotect))
		{
			I_FatalError ("The self-modifying code section code not be made writeable.");
		}
	}
#endif

		// Set the timer to be as accurate as possible
		if (timeGetDevCaps (&tc, sizeof(tc)) != TIMERR_NOERROR)
			TimerPeriod = 1;	// Assume minimum resolution of 1 ms
		else
			TimerPeriod = tc.wPeriodMin;

		timeBeginPeriod (TimerPeriod);

		/*
		killough 1/98:

		This fixes some problems with exit handling
		during abnormal situations.

		The old code called I_Quit() to end program,
		while now I_Quit() is installed as an exit
		handler and exit() is called to exit, either
		normally or abnormally.
		*/

		atexit (call_terms);

		atterm (I_Quit);

		// Figure out what directory the program resides in.
		GetModuleFileName (NULL, progdir, 1024);
		*(strrchr (progdir, '\\') + 1) = 0;
		FixPathSeperator (progdir);

		// [BC] When hosting, spawn a console dialog box instead of creating a window.
		if ( Args.CheckParm( "-host" ))
		{
			// This never returns.
			DialogBox( g_hInst, MAKEINTRESOURCE( IDD_SERVERDIALOG ), NULL/*(HWND)Window*/, SERVERCONSOLE_ServerDialogBoxCallback );
		}
		else
		{
			height = GetSystemMetrics (SM_CYFIXEDFRAME) * 2 +
					GetSystemMetrics (SM_CYCAPTION) + 12 * 32;
			width  = GetSystemMetrics (SM_CXFIXEDFRAME) * 2 + 8 * 78;

			TheInvisibleCursor = LoadCursor (hInstance, MAKEINTRESOURCE(IDC_INVISIBLECURSOR));
			TheArrowCursor = LoadCursor (NULL, IDC_ARROW);

			WndClass.style			= 0;
			WndClass.lpfnWndProc	= WndProc;
			WndClass.cbClsExtra		= 0;
			WndClass.cbWndExtra		= 0;
			WndClass.hInstance		= hInstance;
			WndClass.hIcon			= LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON5));
			WndClass.hCursor		= TheArrowCursor;
			WndClass.hbrBackground	= NULL;
			WndClass.lpszMenuName	= NULL;
			WndClass.lpszClassName	= (LPCTSTR)WinClassName;
			
			/* register this new class with Windows */
			if (!RegisterClass((LPWNDCLASS)&WndClass))
				I_FatalError ("Could not register window class");
			
			/* create window */
			Window = CreateWindow((LPCTSTR)WinClassName,
					(LPCTSTR) GAMESIG " v" DOTVERSIONSTR " (" __DATE__ ")",
					WS_OVERLAPPEDWINDOW,
					0/*CW_USEDEFAULT*/, 1/*CW_USEDEFAULT*/, width, height,
					(HWND)   NULL,
					(HMENU)  NULL,
							hInstance,
					NULL);

			if (!Window)
				I_FatalError ("Could not open window");

			WndClass.lpfnWndProc = LConProc;
			WndClass.lpszClassName = (LPCTSTR)ConClassName;
			if (RegisterClass ((LPWNDCLASS)&WndClass))
			{
				ConWindow = CreateWindowEx (
					WS_EX_PALETTEWINDOW & (~WS_EX_TOPMOST),
					(LPCTSTR)ConClassName,
					(LPCTSTR) "Skulltag Startup Viewer",
					WS_OVERLAPPEDWINDOW/* | WS_VISIBLE*/,
					CW_USEDEFAULT, CW_USEDEFAULT,
					512, 384,
					Window, NULL, hInstance, NULL);
			}

			if (kernel != 0)
			{
				typedef BOOL (WINAPI *pts)(DWORD, DWORD *);
				pts pidsid = (pts)GetProcAddress (kernel, "ProcessIdToSessionId");
				if (pidsid != 0)
				{
					if (!pidsid (GetCurrentProcessId(), &SessionID))
					{
						SessionID = 0;
					}
					hwtsapi32 = LoadLibraryA ("wtsapi32.dll");
					if (hwtsapi32 != 0)
					{
						FARPROC reg = GetProcAddress (hwtsapi32, "WTSRegisterSessionNotification");
						if (reg == 0 || !((BOOL(WINAPI *)(HWND, DWORD))reg) (Window, NOTIFY_FOR_THIS_SESSION))
						{
							FreeLibrary (hwtsapi32);
							hwtsapi32 = 0;
						}
						else
						{
							atterm (UnWTS);
						}
					}
				}
			}

			GetClientRect (Window, &cRect);

			WinWidth = cRect.right;
			WinHeight = cRect.bottom;
		}

		CoInitialize (NULL);
		atterm (UnCOM);

		C_InitConsole (((WinWidth / 8) + 2) * 8, (WinHeight / 12) * 8, false);

		I_DetectOS ();
		D_DoomMain ();
	}
	catch (class CDoomError &error)
	{
		I_ShutdownHardware ();
		SetWindowPos (Window, NULL, 0, 0, 0, 0, SWP_HIDEWINDOW);
		if (ConWindow != NULL)
		{
			ShowWindow (ConWindow, SW_SHOW);
		}
		if (error.GetMessage ())
			MessageBox (Window, error.GetMessage(),
				"Skulltag Fatal Error", MB_OK|MB_ICONSTOP|MB_TASKMODAL);
		exit (-1);
	}
}
Exemple #13
0
void TestSpeed(ScopedLogMessage& msg)
{
ElapsedTimeRec timeRec[3];

	msg.Message("--- TestSpeed ---");

	int numMaxAlloc = kNumMaxAlloc_Speed;
	{	// adjust number of max allocation for low memory machine
		bool memoryAvailable = false;
		char* tempPtr = NULL;

#if defined(POCO_OS_FAMILY_WINDOWS)
		_set_new_handler(ThrowBadAlloc);
#endif

		while(!memoryAvailable)
		{
			try
			{
				tempPtr = new char [kBlockSize * numMaxAlloc];
				memoryAvailable = true;
			}
			catch(...)
			{
				numMaxAlloc /= 2;
			}
			delete [] tempPtr;
			tempPtr = NULL;
		}
		msg.Message(Poco::format(" number of allocation blocks = %d", numMaxAlloc));
	}

	{
		msg.Message(" measuring new/delete...");
		MeasureAllocDeallocTime<Poco::Void> measure(timeRec[0], kBlockSize, 0, numMaxAlloc);
	}
	{
		msg.Message(Poco::format(" measuring Poco::MemoryPool(%z, %d, %d)..."
								, kBlockSize
								, 0
								, numMaxAlloc));
		MeasureAllocDeallocTime<Poco::MemoryPool>
			measure(timeRec[1], kBlockSize, 0, numMaxAlloc);
	}
	{
		msg.Message(Poco::format(" measuring Poco::MemoryPool(%z, %d, %d)..."
								, kBlockSize
								, numMaxAlloc
								, numMaxAlloc));
		MeasureAllocDeallocTime<Poco::MemoryPool>
			measure(timeRec[2], kBlockSize, numMaxAlloc, numMaxAlloc);
	}

	msg.Message("                 new/delete   non pre-allocated   pre-allocated");
	msg.Message("================================================================");
	msg.Message(Poco::format("  init          %8.3fmSec    %8.3fmSec      %8.3fmSec"
								, timeRec[0].timeInit
								, timeRec[1].timeInit
								, timeRec[2].timeInit));
	for(std::size_t loop=0; loop<kNumLoop; ++loop)
	{
		msg.Message(Poco::format("  allocate #%z   %8.3fmSec    %8.3fmSec      %8.3fmSec"
								, loop+1
								, timeRec[0].timeAlloc[loop]
								, timeRec[1].timeAlloc[loop]
								, timeRec[2].timeAlloc[loop]));
		msg.Message(Poco::format("deallocate #%z   %8.3fmSec    %8.3fmSec      %8.3fmSec"
								, loop+1
								, timeRec[0].timeDealloc[loop]
								, timeRec[1].timeDealloc[loop]
								, timeRec[2].timeDealloc[loop]));
	}
	msg.Message(Poco::format("  cleanup       %8.3fmSec    %8.3fmSec      %8.3fmSec"
								, timeRec[0].timeCleanup
								, timeRec[1].timeCleanup
								, timeRec[2].timeCleanup));
	msg.Message("================================================================");
	msg.Message(Poco::format("  total time    %8.3fmSec    %8.3fmSec      %8.3fmSec"
								, timeRec[0].timeTotal
								, timeRec[1].timeTotal
								, timeRec[2].timeTotal));
}
//  Called from MyApp() immediately upon entry to MyApp::OnInit()
void OCPNPlatform::Initialize_1( void )
{
    
#ifdef OCPN_USE_CRASHRPT
#ifndef _DEBUG
    // Install Windows crash reporting
    
    CR_INSTALL_INFO info;
    memset(&info, 0, sizeof(CR_INSTALL_INFO));
    info.cb = sizeof(CR_INSTALL_INFO);
    info.pszAppName = _T("OpenCPN");
    
    wxString version_crash = str_version_major + _T(".") + str_version_minor + _T(".") + str_version_patch;
    info.pszAppVersion = version_crash.c_str();
    
    int type = MiniDumpWithDataSegs;  // Include the data sections from all loaded modules.
    // This results in the inclusion of global variables
    
    type |=  MiniDumpNormal;// | MiniDumpWithPrivateReadWriteMemory | MiniDumpWithIndirectlyReferencedMemory;
    info.uMiniDumpType = (MINIDUMP_TYPE)type;
    
    // Install all available exception handlers....
    info.dwFlags = CR_INST_ALL_POSSIBLE_HANDLERS;
    
    //  Except memory allocation failures
    info.dwFlags &= ~CR_INST_NEW_OPERATOR_ERROR_HANDLER;
    
    //  Allow user to attach files
    info.dwFlags |= CR_INST_ALLOW_ATTACH_MORE_FILES;
    
    //  Allow user to add more info
    info.dwFlags |= CR_INST_SHOW_ADDITIONAL_INFO_FIELDS;
    
    
    // URL for sending error reports over HTTP.
    if(g_bEmailCrashReport){
        info.pszEmailTo = _T("*****@*****.**");
        info.pszSmtpProxy = _T("mail.bigdumboat.com:587");
        info.pszUrl = _T("http://bigdumboat.com/crashrpt/ocpn_crashrpt.php");
        info.uPriorities[CR_HTTP] = 1;  // First try send report over HTTP
    }
    else{
        info.dwFlags |= CR_INST_DONT_SEND_REPORT;
        info.uPriorities[CR_HTTP] = CR_NEGATIVE_PRIORITY;       // don't send at all
    }
    
    info.uPriorities[CR_SMTP] = CR_NEGATIVE_PRIORITY;  // Second try send report over SMTP
    info.uPriorities[CR_SMAPI] = CR_NEGATIVE_PRIORITY; //1; // Third try send report over Simple MAPI
    
    wxStandardPaths& crash_std_path = g_Platform->GetStdPaths();
    
    wxString crash_rpt_save_locn = crash_std_path.GetConfigDir();
    if( g_bportable ) {
        wxFileName exec_path_crash( crash_std_path.GetExecutablePath() );
        crash_rpt_save_locn = exec_path_crash.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR );
    }
    
    wxString locn = crash_rpt_save_locn + _T("\\CrashReports");
    
    if(!wxDirExists( locn ) )
        wxMkdir( locn );
    
    if(wxDirExists( locn ) ){
        wxCharBuffer buf = locn.ToUTF8();
        wchar_t wlocn[256];
        if(buf && (locn.Length() < sizeof(wlocn)) ){
            MultiByteToWideChar( 0, 0, buf.data(), -1, wlocn, sizeof(wlocn)-1);
            info.pszErrorReportSaveDir = (LPCWSTR)wlocn;
        }
    }
    
    // Provide privacy policy URL
    wxFileName exec_path_crash( crash_std_path.GetExecutablePath() );
    wxString policy_file =  exec_path_crash.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR );
    policy_file += _T("PrivacyPolicy.txt");
    policy_file.Prepend(_T("file:"));
    
    info.pszPrivacyPolicyURL = policy_file.c_str();;
    
    int nResult = crInstall(&info);
    if(nResult!=0) {
        TCHAR buff[256];
        crGetLastErrorMsg(buff, 256);
        MessageBox(NULL, buff, _T("crInstall error, Crash Reporting disabled."), MB_OK);
    }
    
    // Establish the crash callback function
    crSetCrashCallback( CrashCallback, NULL );
    
    // Take screenshot of the app window at the moment of crash
    crAddScreenshot2(CR_AS_PROCESS_WINDOWS|CR_AS_USE_JPEG_FORMAT, 95);
    
    //  Mark some files to add to the crash report
    wxString home_data_crash = crash_std_path.GetConfigDir();
    if( g_bportable ) {
        wxFileName f( crash_std_path.GetExecutablePath() );
        home_data_crash = f.GetPath();
    }
    appendOSDirSlash( &home_data_crash );
    
    wxString config_crash = _T("opencpn.ini");
    config_crash.Prepend( home_data_crash );
    crAddFile2( config_crash.c_str(), NULL, NULL, CR_AF_MISSING_FILE_OK | CR_AF_ALLOW_DELETE );
    
    wxString log_crash = _T("opencpn.log");
    log_crash.Prepend( home_data_crash );
    crAddFile2( log_crash.c_str(), NULL, NULL, CR_AF_MISSING_FILE_OK | CR_AF_ALLOW_DELETE );
    
#endif
#endif

    
#ifdef LINUX_CRASHRPT
#if wxUSE_ON_FATAL_EXCEPTION
    // fatal exceptions handling
    wxHandleFatalExceptions (true);
#endif
#endif

#ifdef __WXMSW__
    //  Invoke my own handler for failures of malloc/new
    _set_new_handler( MyNewHandler );
    //  configure malloc to call the New failure handler on failure
    _set_new_mode(1);
#endif    
    
    //    On MSW, force the entire process to run on one CPU core only
    //    This resolves some difficulty with wxThread syncronization
#if 0
#ifdef __WXMSW__
    //Gets the current process handle
    HANDLE hProc = GetCurrentProcess();
    DWORD procMask;
    DWORD sysMask;
    HANDLE hDup;
    DuplicateHandle( hProc, hProc, hProc, &hDup, 0, FALSE, DUPLICATE_SAME_ACCESS );
    
    //Gets the current process affinity mask
    GetProcessAffinityMask( hDup, &procMask, &sysMask );
    
    // Take a simple approach, and assume up to 4 processors
    DWORD newMask;
    if( ( procMask & 1 ) == 1 ) newMask = 1;
    else
        if( ( procMask & 2 ) == 2 ) newMask = 2;
        else
            if( ( procMask & 4 ) == 4 ) newMask = 4;
            else
                if( ( procMask & 8 ) == 8 ) newMask = 8;
                
                //Set te affinity mask for the process
                BOOL res = SetProcessAffinityMask( hDup, (DWORD_PTR) newMask );
            
            if( res == 0 ) {
                //Error setting affinity mask!!
            }
#endif
#endif
            
#ifdef __WXMSW__
            
            //    Handle any Floating Point Exceptions which may leak thru from other
            //    processes.  The exception filter is in cutil.c
            //    Seems to only happen for W98
            
            wxPlatformInfo Platform;
            if( Platform.GetOperatingSystemId() == wxOS_WINDOWS_9X ) SetUnhandledExceptionFilter (&MyUnhandledExceptionFilter);
#endif
            
#ifdef __WXMSW__
            //     _CrtSetBreakAlloc(25503);
#endif
            

#ifndef __WXMSW__
            //      Setup Linux SIGNAL handling, for external program control
            
            //      Build the sigaction structure
            sa_all.sa_handler = catch_signals;// point to my handler
            sigemptyset(&sa_all.sa_mask);// make the blocking set
            // empty, so that all
            // other signals will be
            // unblocked during my handler
            sa_all.sa_flags = 0;
            
            sigaction(SIGUSR1, NULL, &sa_all_old);// save existing action for this signal
            
            //      Register my request for some signals
            sigaction(SIGUSR1, &sa_all, NULL);
            
            sigaction(SIGUSR1, NULL, &sa_all_old);// inspect existing action for this signal
            
            sigaction(SIGTERM, &sa_all, NULL);
            sigaction(SIGTERM, NULL, &sa_all_old);
#endif
            
}