~ActivationContext() {
     if (hactctx != INVALID_HANDLE_VALUE)
     {
         DeactivateActCtx(0, actctx_cookie);
         ReleaseActCtx(hactctx);
     }
 }
Beispiel #2
0
void ReleaseActContext(void)
{
    void (WINAPI *ReleaseActCtx)(HANDLE);
    BOOL (WINAPI *DeactivateActCtx)(DWORD dwFlags, ULONG_PTR ulCookie);
    HANDLE k32;

    if (!IsXPOrLater())
        return;

    k32 = LoadLibrary("kernel32");
    ReleaseActCtx = (void*)GetProcAddress(k32, "ReleaseActCtx");
    DeactivateActCtx = (void*)GetProcAddress(k32, "DeactivateActCtx");
    if (!ReleaseActCtx || !DeactivateActCtx)
    {
        VS("Cannot find ReleaseActCtx/DeactivateActCtx exports in kernel32.dll\n");
        return;
    }
    __try
    {
        VS("Deactivating activation context\n");
        if (!DeactivateActCtx(0, actToken))
            VS("Error deactivating context!\n!");
        
        VS("Releasing activation context\n");
        if (hCtx != INVALID_HANDLE_VALUE)
            ReleaseActCtx(hCtx);
        VS("Done\n");
    }
    __except (STATUS_SXS_EARLY_DEACTIVATION)
    {
    	VS("XS early deactivation; somebody left the activation context dirty, let's ignore the problem\n");
    }
}
Beispiel #3
0
	bool Deactivate()
	{
		if ( m_uCookie != 0 )
		{
			ULONG_PTR uCookie = m_uCookie;
			m_uCookie = 0;
			return ( DeactivateActCtx(0, uCookie) == TRUE );
		}
		return true;
	}
Beispiel #4
0
    void DeActivate()
    {
        if ( ActivationCtxHandle == INVALID_HANDLE_VALUE )
        {
            return ;
        }

        if ( ActivationCtxCookie == 0 )
        {
            // Already Deactivated
            return ;
        }
        ULONG_PTR cookie = ActivationCtxCookie;
        ActivationCtxCookie = 0;
        if ( DeactivateActCtx( 0, cookie ) == FALSE )
        {
            ErrorMessage = L"The C++ module failed to Deactivate WinSXS Activation Context.\n";
            ThrowModuleLoadException(ErrorMessage);
        }
    }
Beispiel #5
0
static void wxPyClearActivationContext(ULONG_PTR cookie)
{
    if (! DeactivateActCtx(0, cookie))
        wxLogLastError(wxT("DeactivateActCtx"));
}
Beispiel #6
0
bool CPython::init()
{
	//
	// Initialize the python environment
	//
	std::wstring path; int iRslt = 0; DWORD nrslt = 0;
	std::vector<wchar> vetbuf; wchar buffer[MAX_PATH+1] = {0};

	// First of all, get the python path from options .
	for (; GetOption(text("Python Path"), path); ) {
		nrslt = ::GetFullPathName (	// ...
			path.c_str(), _countof(buffer), buffer, nullptr
		);
		if (nrslt == 0) { path.clear(); break; }
		if (nrslt < _countof(buffer)) { path = buffer; break; }
		vetbuf.resize(nrslt+1);		// Allocate buffer ...
		nrslt = ::GetFullPathName (	// ...
			path.c_str(), vetbuf.size(), vetbuf.data(), nullptr
		);
		if (!nrslt || nrslt >= vetbuf.size()) path.clear();
		else path.assign(vetbuf.begin(), vetbuf.end()); break;
	}

	// Use the directory of the exe file if we fail to get python 
	// path from options.
	for (std::size_t pos = 0; path.length() <= 0; ) {
		nrslt = GetModuleFileName (	// Try the first time .......
			nullptr, buffer, _countof(buffer)
		);
		if (nrslt == 0) { path.clear(); break; }
		if (nrslt < _countof(buffer)) { path = buffer; 
			pos = path.find_last_not_of(text("\\/"));
			pos = path.find_last_of(text("\\/"),pos);
			path.replace( pos, -1, text("\\python"));
			break;
		}
		vetbuf.resize(nrslt*2);		// Allocate buffer ..........
		nrslt = GetModuleFileName (	// Try the second time ......
			nullptr, vetbuf.data(), vetbuf.size()
		);
		if (nrslt != 0 && nrslt <= vetbuf.size()) {
			path.assign(vetbuf.begin(), vetbuf.end());
			pos = path.find_last_not_of(text("\\/"));
			pos = path.find_last_of(text("\\/"),pos);
			path.replace( pos, -1, text("\\python"));
		} else path.clear(); break;
	}

	// Use current directory if we still can't get the python path .
	for (; path.length() <= 0; ) {
		nrslt = ::GetCurrentDirectory(_countof(buffer), buffer);
		if (nrslt == 0) { path.clear(); break; }
		if (nrslt < _countof(buffer)) { 
			path = buffer; path += text("\\python");
		}
		vetbuf.resize(nrslt+1);		// Allocate buffer ...
		nrslt = ::GetCurrentDirectory(vetbuf.size(),vetbuf.data());
		if (nrslt != 0 && nrslt <= vetbuf.size()) {
			path.assign(vetbuf.begin(), vetbuf.end());
			path.append(text("\\python"));
		} else path.clear(); break;
	}

	// We return false if we still can't get the python path ...
	if(path.length()<=0) return false; path.push_back(text('\\')); 

	// Now, We overwrite the environment variable PYTHONHOME..
	// It's not a necessuary operation ..
	::SetEnvironmentVariable(text("PYTHONHOME"), path.c_str());

	// Locate the python kernel file "pythonxx.dll" ..
	WIN32_FIND_DATA fData = {0}; HANDLE hFile = nullptr; 
	hFile = FindFirstFile((path+text("*.dll")).c_str(), &fData); 
	if (hFile != INVALID_HANDLE_VALUE) {
		do {
			if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) 
				continue;		// We skip all directory .
			_wcslwr_s(fData.cFileName, _countof(fData.cFileName));
			if (wcsstr(fData.cFileName, text("python"))) break;
			else fData.cFileName[0] = text('\0');
		} while (FindNextFile(hFile, &fData));
		FindClose(hFile);		// Finish finding ..
	} else fData.cFileName[0] = text('\0');

	///
	// Now, initialize all python interface dynamically.
	// The reason we query python interface dynamically is to 
	// make sure our plugin can work without python ..
	///
	m_pyModule = ::GetModuleHandle(fData.cFileName);
	if (m_pyModule == nullptr) {
		m_pyModule = ::LoadLibrary((path+fData.cFileName).c_str());
		if (m_pyModule == nullptr) {
			m_pyModule = ::GetModuleHandle(text("python27.dll"));
			if (m_pyModule == nullptr) {
				m_pyModule = ::LoadLibrary(text("python27.dll"));
				if (m_pyModule == nullptr) return false;
			}
		}
	}

	if ( (Py_Finalize = reinterpret_cast<py_finalize>(
		::GetProcAddress(m_pyModule, "Py_Finalize")
	)) == nullptr ) return false;
	if ( (Py_Initialize = reinterpret_cast<py_initialize>(
		::GetProcAddress(m_pyModule, "Py_Initialize")
	)) == nullptr ) return false;
	if ( (Py_SetPythonHome = reinterpret_cast<py_setpythonhome>(
		::GetProcAddress(m_pyModule, "Py_SetPythonHome")
	)) == nullptr ) return false;
	if ( (Py_SetProgramName = reinterpret_cast<py_setprogramname>(
		::GetProcAddress(m_pyModule, "Py_SetProgramName")
	)) == nullptr ) return false;

	if ( (PyFile_AsFile = reinterpret_cast<pyfile_asfile>(
		::GetProcAddress(m_pyModule, "PyFile_AsFile")
	)) == nullptr ) return false;
	if ( (PyFile_FromFile = reinterpret_cast<pyfile_fromfile>(
		::GetProcAddress(m_pyModule, "PyFile_FromFile")
	)) == nullptr ) return false;
	if ( (PyFile_FromString = reinterpret_cast<pyfile_fromstring>(
		::GetProcAddress(m_pyModule, "PyFile_FromString")
	)) == nullptr ) return false;

	if ( (PyEval_InitThreads = reinterpret_cast<pyeval_initthreads>(
		::GetProcAddress(m_pyModule, "PyEval_InitThreads")
	)) == nullptr ) return false;

	if ( (PySys_SetArgv = reinterpret_cast<pysys_setargv>(
		::GetProcAddress(m_pyModule, "PySys_SetArgv")
	)) == nullptr ) return false;
	if ( (PySys_GetObject = reinterpret_cast<pysys_getobject>(
		::GetProcAddress(m_pyModule, "PySys_GetObject")
	)) == nullptr ) return false;
	if ( (PySys_SetObject = reinterpret_cast<pysys_setobject>(
		::GetProcAddress(m_pyModule, "PySys_SetObject")
	)) == nullptr ) return false;
	
	if ( (PyObject_SetAttrString = reinterpret_cast<pyobject_setattrstring>(
		::GetProcAddress(m_pyModule, "PyObject_SetAttrString")
	)) == nullptr ) return false;

	if ( (PyImport_ImportModule = reinterpret_cast<pyimport_importmodule>(
		::GetProcAddress(m_pyModule, "PyImport_ImportModule")
	)) == nullptr ) return false;
	if ( (PyImport_AddModule = reinterpret_cast<pyimport_addmodule>(
		::GetProcAddress(m_pyModule, "PyImport_AddModule")
	)) == nullptr ) return false;

	if ( (PyRun_SimpleString = reinterpret_cast<pyrun_simplestring>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleString")
	)) == nullptr ) return false;
	if ( (PyRun_SimpleStringFlags = reinterpret_cast<pyrun_simplestringflags>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleStringFlags")
	)) == nullptr ) return false;
	if ( (PyRun_SimpleFile = reinterpret_cast<pyrun_simplefile>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleFile")
	)) == nullptr ) return false;
	/*if ( (PyRun_SimpleFileFlags = reinterpret_cast<pyrun_simplefileflags>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleFileFlags")
	)) == nullptr ) return false;*/
	if ( (PyRun_SimpleFileEx = reinterpret_cast<pyrun_simplefileex>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleFileEx")
	)) == nullptr ) return false;
	if ( (PyRun_SimpleFileExFlags = reinterpret_cast<pyrun_simplefileexflags>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleFileExFlags")
	)) == nullptr ) return false;

	// Initialize the python environment, prepare the hooks
	//if (Py_SetPythonHome) Py_SetPythonHome(cvt.to_bytes(path).c_str());
	//if (Py_SetProgramName) Py_SetProgramName(cvt.to_bytes(buffer).c_str());
	if (Py_Initialize) Py_Initialize();
	if (PyEval_InitThreads) PyEval_InitThreads();
	// ...

	///
	// Now, initialize all MSVCR90 interface dynamically.
	///
	ACTCTX ctx = {sizeof(ACTCTX), 0}; ULONG_PTR actToken = 0;
	ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID|ACTCTX_FLAG_HMODULE_VALID;
	ctx.hModule = m_pyModule; ctx.lpResourceName = MAKEINTRESOURCE(2);
	HANDLE hCtx = CreateActCtx(&ctx);
	if(hCtx != INVALID_HANDLE_VALUE) {
		if ( ActivateActCtx(hCtx, &actToken) ) {
			m_vcModule = ::GetModuleHandle(text("MSVCR90.dll"));
			if (m_vcModule == NULL) {
				m_vcModule = ::LoadLibrary(text("MSVCR90.dll"));
				if (m_vcModule == NULL) return false;
			}
			if ( (open_osfhandle = reinterpret_cast<__open_osfhandle>(
				::GetProcAddress(m_vcModule, "_open_osfhandle")
			)) == nullptr ) return false;
			if ( (setvbuf = reinterpret_cast<__setvbuf>(
				::GetProcAddress(m_vcModule, "setvbuf")
			)) == nullptr ) return false;
			if ( (fdopen = reinterpret_cast<__fdopen>(
				::GetProcAddress(m_vcModule, "_fdopen")
			)) == nullptr ) return false;
			if ( (fclose = reinterpret_cast<__fclose>(
				::GetProcAddress(m_vcModule, "fclose")
			)) == nullptr ) return false;
			// Deactive active context after finished ..
			DeactivateActCtx(0, actToken);
		}
		// Now close context ...
		ReleaseActCtx(hCtx); 
	}

	return true;	// All done, return true ...
}
Beispiel #7
0
PVOID
WINAPI
GetServiceDllFunction (
    _In_ PSVCHOST_DLL pDll,
    _In_ LPCSTR lpProcName,
    _Out_ PDWORD lpdwError
    )
{
    HMODULE hModule;
    PVOID lpAddress = NULL;
    ULONG_PTR ulCookie = 0;

    /* Activate the context */
    if (ActivateActCtx(pDll->hActCtx, &ulCookie) != TRUE)
    {
        /* We couldn't, bail out */
        if (lpdwError) *lpdwError = GetLastError();
        DBG_ERR("ActivateActCtx for %ws failed.  Error %d.\n",
                pDll->pszDllPath,
                GetLastError());
        return lpAddress;
    }

    /* Check if we already have a loaded module for this service */
    hModule = pDll->hModule;
    if (!hModule)
    {
        /* We don't -- load it */
        hModule = LoadLibraryExW(pDll->pszDllPath,
                                    NULL,
                                    LOAD_WITH_ALTERED_SEARCH_PATH);
        if (!hModule)
        {
            /* We failed to load it, bail out */
            if (lpdwError) *lpdwError = GetLastError();
            DBG_ERR("LoadLibrary (%ws) failed.  Error %d.\n",
                    pDll->pszDllPath,
                    GetLastError());
            DeactivateActCtx(0, ulCookie);
            return lpAddress;
        }

        /* Loaded! */
        pDll->hModule = hModule;
    }

    /* Next, get the address being looked up*/
    lpAddress = GetProcAddress(hModule, lpProcName);
    if (!lpAddress)
    {
        /* We couldn't find it, write the error code and a debug statement */
        if (lpdwError) *lpdwError = GetLastError();
        DBG_ERR("GetProcAddress (%s) failed on DLL %ws.  Error %d.\n",
                lpProcName,
                pDll->pszDllPath,
                GetLastError());
    }

    /* All done, get rid of the activation context */
    DeactivateActCtx(0, ulCookie);
    return lpAddress;
}
	Win32UIBinding::~Win32UIBinding()
	{
   		DeactivateActCtx(0, this->lpCookie); 
		ReleaseActCtx(this->pActCtx);
	}
Beispiel #9
0
int WINAPI _tWinMain(
  HINSTANCE hInstance,
  HINSTANCE hPrevInstance,
  LPTSTR lpCmdLine,
  int nCmdShow
)
{
    int argc;
    TCHAR szMsg[RC_STRING_MAX_SIZE];

    LPTSTR *argv;
    LPTSTR lptCmdLine,lptDllName,lptFuncName,lptMsgBuffer;
    LPSTR lpFuncName,lpaCmdLine;
    LPWSTR lpwCmdLine;
    HMODULE hDll;
    DllWinMainW fnDllWinMainW;
    DllWinMainA fnDllWinMainA;
    HWND hWindow;
    int i;
    size_t nStrLen;

    ACTCTXW ActCtx = {sizeof(ACTCTX), ACTCTX_FLAG_RESOURCE_NAME_VALID};
    HANDLE hActCtx;
    ULONG_PTR cookie;
    BOOL bActivated;

    // Get command-line in argc-argv format
    argv = CommandLineToArgv(GetCommandLine(),&argc);

    // Skip all beginning arguments starting with a slash (/)
    for (i = 1; i < argc; i++)
        if (*argv[i] != _T('/')) break;

    // If no dll was specified, there is nothing to do
    if (i >= argc) {
        if (argv) free(argv);
        return 0;
    }

    lptDllName = argv[i++];

    // The next argument, which specifies the name of the dll function,
    // can either have a comma between it and the dll filename or a space.
    // Using a comma here is the preferred method
    if (i < argc)
        lptFuncName = argv[i++];
    else
        lptFuncName = _T("");

    // If no function name was specified, nothing needs to be done
    if (!*lptFuncName) {
        if (argv) free(argv);
        return 0;
    }

    // The rest of the arguments will be passed to dll function
    if (i < argc)
        lptCmdLine = argv[i];
    else
        lptCmdLine = _T("");

    ActCtx.lpSource = lptDllName;
    ActCtx.lpResourceName = (LPCWSTR)123;
    hActCtx = CreateActCtx(&ActCtx);
    bActivated = (hActCtx != INVALID_HANDLE_VALUE ? ActivateActCtx(hActCtx, &cookie) : FALSE);

    // Everything is all setup, so load the dll now
    hDll = LoadLibrary(lptDllName);
    if (hDll) {
        nStrLen = _tcslen(lptFuncName);
        // Make a non-unicode version of the function name,
        // since that is all GetProcAddress accepts
        lpFuncName = DuplicateToMultiByte(lptFuncName,nStrLen + 2);

#ifdef UNICODE
        lpFuncName[nStrLen] = 'W';
        lpFuncName[nStrLen+1] = 0;
        // Get address of unicode version of the dll function if it exists
        fnDllWinMainW = (DllWinMainW)GetProcAddress(hDll,lpFuncName);
        fnDllWinMainA = 0;
        if (!fnDllWinMainW) {
            // If no unicode function was found, get the address of the non-unicode function
            lpFuncName[nStrLen] = 'A';
            fnDllWinMainA = (DllWinMainA)GetProcAddress(hDll,lpFuncName);
            if (!fnDllWinMainA) {
                // If first non-unicode function was not found, get the address
                // of the other non-unicode function
                lpFuncName[nStrLen] = 0;
                fnDllWinMainA = (DllWinMainA)GetProcAddress(hDll,lpFuncName);
            }
        }
#else
        // Get address of non-unicode version of the dll function if it exists
        fnDllWinMainA = (DllWinMainA)GetProcAddress(hDll,lpFuncName);
        fnDllWinMainW = 0;
        if (!fnDllWinMainA) {
            // If first non-unicode function was not found, get the address
            // of the other non-unicode function
            lpFuncName[nStrLen] = 'A';
            lpFuncName[nStrLen+1] = 0;
            fnDllWinMainA = (DllWinMainA)GetProcAddress(hDll,lpFuncName);
            if (!fnDllWinMainA) {
                // If non-unicode function was not found, get the address of the unicode function
                lpFuncName[nStrLen] = 'W';
                fnDllWinMainW = (DllWinMainW)GetProcAddress(hDll,lpFuncName);
            }
        }
#endif

        free(lpFuncName);

        if (!RegisterBlankClass(hInstance, hPrevInstance))
        {
            FreeLibrary(hDll);
            if (bActivated)
                DeactivateActCtx(0, cookie);
            return 0;
        }
        // Create a window so we can pass a window handle to
        // the dll function; this is required
        hWindow = CreateWindowEx(0,rundll32_wclass,rundll32_wtitle,0,CW_USEDEFAULT,0,CW_USEDEFAULT,0,0,0,hInstance,0);

        if (fnDllWinMainW) {
            // Convert the command-line string to unicode and call the dll function
            lpwCmdLine = ConvertToWideChar(lptCmdLine);
            fnDllWinMainW(hWindow,hInstance,lpwCmdLine,nCmdShow);
            FreeConvertedWideChar(lpwCmdLine);
        }
        else if (fnDllWinMainA) {
            // Convert the command-line string to ansi and call the dll function
            lpaCmdLine = ConvertToMultiByte(lptCmdLine);
            fnDllWinMainA(hWindow,hInstance,lpaCmdLine,nCmdShow);
            FreeConvertedMultiByte(lpaCmdLine);
        }
        else {
            // The specified dll function was not found; display an error message
            GetModuleTitle();
            LoadString( GetModuleHandle(NULL), IDS_MissingEntry, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);

            lptMsgBuffer = (LPTSTR)malloc((_tcslen(szMsg) - 4 + _tcslen(lptFuncName) + _tcslen(lptDllName) + 1) * sizeof(TCHAR));
            _stprintf(lptMsgBuffer,szMsg,lptFuncName,lptDllName);
            MessageBox(0,lptMsgBuffer,ModuleTitle,MB_ICONERROR);
            free(lptMsgBuffer);
        }

        DestroyWindow(hWindow);
        UnregisterClass(rundll32_wclass,hInstance);

        // The dll function has finished executing, so unload it
        FreeLibrary(hDll);
    }
    else {
        // The dll could not be loaded; display an error message
        GetModuleTitle();
        LoadString( GetModuleHandle(NULL), IDS_DllNotLoaded, (LPTSTR) szMsg,RC_STRING_MAX_SIZE);

        lptMsgBuffer = (LPTSTR)malloc((_tcslen(szMsg) - 2 + _tcslen(lptDllName) + 1) * sizeof(TCHAR));
        _stprintf(lptMsgBuffer,szMsg,lptDllName);

        MessageBox(0,lptMsgBuffer,ModuleTitle,MB_ICONERROR);
        free(lptMsgBuffer);
    }

    if (bActivated)
        DeactivateActCtx(0, cookie);

    if (argv) free(argv);
    return 0; /* rundll32 always returns 0! */
}
Beispiel #10
0
winstd::actctx_activator::~actctx_activator()
{
    if (m_cookie)
        DeactivateActCtx(0, m_cookie);
}