Esempio n. 1
0
//Returns true on success (and sets majorVersion and minorVersion). Returns false on failure.
bool GetOSVersion(DWORD* majorVersion, DWORD* minorVersion)
{
	bool success = false;

	if (IsWindowsVistaOrGreater())
	{
		success = true;
		*majorVersion = 6;
		*minorVersion = 0;
	}
	if (IsWindows7OrGreater())
	{
		*minorVersion = 1;
	}
	if (IsWindows8OrGreater())
	{
		*minorVersion = 2;
	}
	if (IsWindows8Point1OrGreater())
	{
		*minorVersion = 3;
	}

	return success;
}
Esempio n. 2
0
int ast_get_firmware_type (enum AST_FIRMWARE_TYPE *type)
{
    // NOTE: Since Windows 8, there's a WinAPI called GetFirmwareType
    //   (https://msdn.microsoft.com/en-us/library/windows/desktop/hh848321(v=vs.85).aspx),
    //   which can quickly determine the computer's firmware.
    //
    //   Use GetFirmwareType on newer Windows, or the traditional way -- passing dummy UUID
    //   and variable name to GetFirmwareEnvironmentVariable and check return value.
    if (IsWindows8OrGreater () == TRUE) {
        if (_ast_get_firmware_type_on_win8_or_greater (type) == EXIT_SUCCESS) {
            return EXIT_SUCCESS;
        } else {
            fprintf (stderr, " ** cannot get firmware type.\n");
            return EXIT_FAILURE;
        }
    } else {
        if (_ast_get_firmware_type_on_win8_lesser (type) == EXIT_SUCCESS) {
            return EXIT_SUCCESS;
        } else {
            fprintf(stderr, " ** cannot get firmware type.\n");
        }
    }

    // Whatever.
    return EXIT_FAILURE;
}
Esempio n. 3
0
/// <summary>
/// Gets VadPurge handle.
/// </summary>
/// <returns>Driver object handle, INVALID_HANDLE_VALUE if failed</returns>
HANDLE MMap::GetDriverHandle()
{
    HANDLE hFile = CreateFile( _T( "\\\\.\\VadPurge" ), GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL );

    // Load missing driver
    if (hFile == INVALID_HANDLE_VALUE)
    {
        std::wstring drvPath = Utils::GetExeDirectory() + L"\\";

        if (IsWindows8Point1OrGreater())
            drvPath += L"VadPurge81.sys";
        else if (IsWindows8OrGreater())
            drvPath += L"VadPurge8.sys";
        else if (IsWindows7OrGreater())
            drvPath += L"VadPurge7.sys";

        NTSTATUS status = Utils::LoadDriver( L"VadPurge", drvPath );

        if (status != ERROR_SUCCESS && status != STATUS_IMAGE_ALREADY_LOADED)
            return false;

        hFile = CreateFile( _T( "\\\\.\\VadPurge" ), GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL );
    }

    return hFile;
}
Esempio n. 4
0
EXPORT_C_(s32) SPU2test()
{
	if( !CheckSSE() ) return -1;

#ifdef _WIN32
	if (IsWindows8OrGreater())
	{
		for (int n = 0; mods[n] != nullptr; ++n)
		{
			if (mods[n] == XAudio2_27_Out)
			{
				mods[n] = XAudio2Out;
				break;
			}
		}
	}
#endif

	ReadSettings();
	if( SndBuffer::Test() != 0 )
	{
		// TODO : Implement a proper dialog that allows the user to test different audio out drivers.
		const wchar_t* wtf = mods[OutputModule]->GetIdent();
		SysMessage( L"The '%s' driver test failed.  Please configure\na different SoundOut module and try again.", wtf );
		return -1;
	}

	return 0;
}
Esempio n. 5
0
const char*
WMFDecoderDllNameFor(CodecType aCodec)
{
  if (aCodec == H264) {
    // For H.264 decoding, we need msmpeg2vdec.dll on Win 7 & 8,
    // and mfh264dec.dll on Vista.
    if (IsWindows7OrGreater()) {
      return "msmpeg2vdec.dll";
    } else {
      return "mfh264dec.dll";
    }
  } else if (aCodec == AAC) {
    // For AAC decoding, we need to use msauddecmft.dll on Win8,
    // msmpeg2adec.dll on Win7, and msheaacdec.dll on Vista.
    if (IsWindows8OrGreater()) {
      return "msauddecmft.dll";
    } else if (IsWindows7OrGreater()) {
      return "msmpeg2adec.dll";
    } else {
      return "mfheaacdec.dll";
    }
  } else {
    return "";
  }
}
Esempio n. 6
0
// https://blogs.msdn.microsoft.com/oldnewthing/20071008-00/?p=24863/
static bool is_alttab_window(HWND const Window)
{
	if (!IsWindowVisible(Window))
		return false;

	auto Try = GetAncestor(Window, GA_ROOTOWNER);
	HWND Walk = nullptr;
	while (Try != Walk)
	{
		Walk = Try;
		Try = GetLastActivePopup(Walk);
		if (IsWindowVisible(Try))
			break;
	}
	if (Walk != Window)
		return false;

	// Tool windows should not be displayed either, these do not appear in the task bar
	if (GetWindowLongPtr(Window, GWL_EXSTYLE) & WS_EX_TOOLWINDOW)
		return false;

	if (IsWindows8OrGreater())
	{
		int Cloaked = 0;
		if (SUCCEEDED(imports.DwmGetWindowAttribute(Window, DWMWA_CLOAKED, &Cloaked, sizeof(Cloaked))) && Cloaked)
			return false;
	}

	return true;
}
Esempio n. 7
0
static XnStatus GetOSName(xnOSInfo* pOSInfo)
{
	if (IsWindows8Point1OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "Windows8Point1OrGreater\n");
	else if (IsWindows8OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "Windows8\n");
	else if (IsWindows7SP1OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "Windows7SP1\n");
	else if (IsWindows7OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "Windows7\n");
	else if (IsWindowsVistaSP2OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "VistaSP2\n");
	else if (IsWindowsVistaSP1OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "VistaSP1\n");
	else if (IsWindowsVistaOrGreater())
		sprintf(pOSInfo->csOSName, "%s", "Vista\n");
	else if (IsWindowsXPSP3OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "XPSP3\n");
	else if (IsWindowsXPSP2OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "XPSP2\n");
	else if (IsWindowsXPSP1OrGreater())
		sprintf(pOSInfo->csOSName, "%s", "XPSP1\n");
	else if (IsWindowsXPOrGreater())
		sprintf(pOSInfo->csOSName, "%s", "XP\n");
	else
		sprintf(pOSInfo->csOSName, "%s", "Unknown win version\n");

	return (XN_STATUS_OK);
}
Esempio n. 8
0
/// <summary>
/// Unlink memory VAD node
/// </summary>
/// <param name="imageMem">Image to purge</param>
/// <returns>bool on success</returns>
bool MMap::UnlinkVad( const MemBlock& imageMem )
{
    HANDLE hFile = CreateFile( _T( "\\\\.\\VadPurge" ), GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL );

    // Load missing driver
    if (hFile == INVALID_HANDLE_VALUE)
    {
        std::wstring drvPath = Utils::GetExeDirectory() + L"\\";

        if (IsWindows8Point1OrGreater())
            drvPath += L"VadPurge81.sys";
        else if(IsWindows8OrGreater())
            drvPath += L"VadPurge8.sys";
        else if(IsWindows7OrGreater())
            drvPath += L"VadPurge7.sys";

        NTSTATUS status = Utils::LoadDriver( L"VadPurge", drvPath );

        if (status != ERROR_SUCCESS && status != STATUS_IMAGE_ALREADY_LOADED)
            return false;

        hFile = CreateFile( _T( "\\\\.\\VadPurge" ), GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL );
    }

    //
    // Lock pages in working set before unlinking
    // UserMode page faults can't be resolved without VAD record
    //
    if (hFile != INVALID_HANDLE_VALUE)
    {
        //
        // Adjust working set and lock pages
        //
        SIZE_T sizeMin = 0, sizeMax = 0;
        BOOL ret = FALSE;

        GetProcessWorkingSetSize( _process.core().handle(), &sizeMin, &sizeMax );
        SetProcessWorkingSetSize( _process.core().handle(), sizeMin + imageMem.size(), sizeMax + imageMem.size() );

        PVOID pBase = imageMem.ptr<PVOID>();
        ULONG size = static_cast<ULONG>(imageMem.size());
        NTSTATUS status = GET_IMPORT( NtLockVirtualMemory )(_process.core().handle(), &pBase, &size, 1);

        // Continue only if pages are locked
        if (status == STATUS_SUCCESS)
        {
            PURGE_DATA data = { _process.core().pid(), 1, { imageMem.ptr<ULONGLONG>(), imageMem.size() } };
            DWORD junk = 0;

            ret = DeviceIoControl( hFile, static_cast<DWORD>(IOCTL_VADPURGE_PURGE), &data, sizeof(data), NULL, 0, &junk, NULL );
        }

        CloseHandle( hFile );

        return (status == STATUS_SUCCESS && ret == TRUE) ? true : false;
    }

    return false;
}
Esempio n. 9
0
void
AutoSystemInfo::Initialize()
{
    Assert(!initialized);
#ifndef _WIN32
    PAL_InitializeDLL();
    majorVersion = CHAKRA_CORE_MAJOR_VERSION;
    minorVersion = CHAKRA_CORE_MINOR_VERSION;
#endif

    processHandle = GetCurrentProcess();
    GetSystemInfo(this);

    // Make the page size constant so calculation are faster.
    Assert(this->dwPageSize == AutoSystemInfo::PageSize);
#if defined(_M_IX86) || defined(_M_X64)
    get_cpuid(CPUInfo, 1);
    isAtom = CheckForAtom();
#endif
#if defined(_M_ARM32_OR_ARM64)
    armDivAvailable = IsProcessorFeaturePresent(PF_ARM_DIVIDE_INSTRUCTION_AVAILABLE) ? true : false;
#endif
    allocationGranularityPageCount = dwAllocationGranularity / dwPageSize;

    isWindows8OrGreater = IsWindows8OrGreater();

    binaryName[0] = _u('\0');

#if SYSINFO_IMAGE_BASE_AVAILABLE
    dllLoadAddress = (UINT_PTR)&__ImageBase;
    dllHighAddress = (UINT_PTR)&__ImageBase +
        ((PIMAGE_NT_HEADERS)(((char *)&__ImageBase) + __ImageBase.e_lfanew))->OptionalHeader.SizeOfImage;
#endif

    InitPhysicalProcessorCount();
#if DBG
    initialized = true;
#endif

    WCHAR DisableDebugScopeCaptureFlag[MAX_PATH];
    if (::GetEnvironmentVariable(_u("JS_DEBUG_SCOPE"), DisableDebugScopeCaptureFlag, _countof(DisableDebugScopeCaptureFlag)) != 0)
    {
        disableDebugScopeCapture = true;
    }
    else
    {
        disableDebugScopeCapture = false;
    }

    this->shouldQCMoreFrequently = false;
    this->supportsOnlyMultiThreadedCOM = false;
    this->isLowMemoryDevice = false;

    // 0 indicates we haven't retrieved the available commit. We get it lazily.
    this->availableCommit = 0;

    ChakraBinaryAutoSystemInfoInit(this);
}
QSV_Encoder_Internal::QSV_Encoder_Internal(mfxIMPL& impl, mfxVersion& version) :
	m_pmfxENC(NULL),
	m_nSPSBufferSize(100),
	m_nPPSBufferSize(100),
	m_nTaskPool(0),
	m_pTaskPool(NULL),
	m_nTaskIdx(0),
	m_nFirstSyncTask(0)
{
	mfxIMPL tempImpl;
	mfxStatus sts;

	m_bIsWindows8OrGreater = IsWindows8OrGreater();
	m_bUseD3D11 = false;

	if (m_bIsWindows8OrGreater) {
		tempImpl = impl | MFX_IMPL_VIA_D3D11;
		sts = m_session.Init(tempImpl, &version);
		if (sts == MFX_ERR_NONE) {
			m_session.QueryVersion(&version);
			m_session.Close();

			// Use D3D11 surface
			// m_bUseD3D11 = ((version.Major > 1) ||
			//	(version.Major == 1 && version.Minor >= 8));
			m_bUseD3D11 = true;
			if (m_bUseD3D11)
				blog(LOG_INFO, "\timpl:           D3D11\n"
				               "\tsurf:           D3D11");
			else
				blog(LOG_INFO, "\timpl:           D3D11\n"
				               "\tsurf:           SysMem");

			m_impl = tempImpl;
			m_ver = version;
			return;
		}
	}

	// Either windows 7 or D3D11 failed at this point.
	tempImpl = impl | MFX_IMPL_VIA_D3D9;
	sts = m_session.Init(tempImpl, &version);
	if (sts == MFX_ERR_NONE) {
		m_session.QueryVersion(&version);
		m_session.Close();

		blog(LOG_INFO, "\timpl:           D3D09\n"
		               "\tsurf:           SysMem");

		m_impl = tempImpl;
		m_ver = version;
	}

}
Esempio n. 11
0
/// <summary>
/// Execute code in context of our worker thread
/// </summary>
/// <param name="pCode">Cde to execute</param>
/// <param name="size">Code size.</param>
/// <param name="callResult">Execution result</param>
/// <returns>Status</returns>
NTSTATUS RemoteExec::ExecInWorkerThread( PVOID pCode, size_t size, uint64_t& callResult )
{
    NTSTATUS dwResult = STATUS_SUCCESS;

    // Create thread if needed
    CreateRPCEnvironment();

    // Write code
    dwResult = CopyCode( pCode, size );
    if (dwResult != STATUS_SUCCESS)
        return dwResult;

    if (_hWaitEvent)
        ResetEvent( _hWaitEvent );

    // Patch KiUserApcDispatcher 
#ifdef USE64
    if (!_apcPatched && IsWindows7OrGreater() && !IsWindows8OrGreater())
    {
        if (_proc.core().native()->GetWow64Barrier().type == wow_64_32)
        {
            auto patchBase = _proc.nativeLdr().APC64PatchAddress();

            if (patchBase != 0)
            {
                DWORD flOld = 0;
                _memory.Protect(patchBase, 6, PAGE_EXECUTE_READWRITE, &flOld);
                _memory.Write(patchBase + 0x2, (uint8_t)0x0C);
                _memory.Write( patchBase + 0x4, (uint8_t)0x90 );
                _memory.Protect( patchBase, 6, flOld, nullptr );
            }

            _apcPatched = true;
        }
        else
            _apcPatched = true;
    }
#endif

    // Execute code in thread context
    if (QueueUserAPC( _userCode.ptr<PAPCFUNC>(), _hWorkThd.handle(), _userCode.ptr<ULONG_PTR>() ))
    {
        dwResult = WaitForSingleObject( _hWaitEvent, INFINITE );
        callResult = _userData.Read<uint64_t>( RET_OFFSET, 0 );
    }
    else
        return LastNtStatus();

    // Ensure APC function fully returns
    Sleep( 1 );

    return dwResult;
}
Esempio n. 12
0
void MonitorLayerDialog::loadSettings()
{
	MonitorLayer *layer = static_cast<MonitorLayer *>(m_layer);

	// As we assume the monitor list hasn't changed since it was populated just
	// refresh it again to be safe
	refreshMonitorList();

	// Monitor combo
	int monitor = layer->getMonitor();
	for(int i = 0; i < m_ui.monitorCombo->count(); i++) {
		int friendlyId = m_ui.monitorCombo->itemData(i, Qt::UserRole).toInt();
		if(monitor == friendlyId) {
			m_ui.monitorCombo->setCurrentIndex(i);
			break;
		}
	}

	// Mouse cursor
	m_ui.showCursorBtn->setChecked(layer->getCaptureMouse());
	m_ui.hideCursorBtn->setChecked(!layer->getCaptureMouse());

	// Disable Windows Aero
	if(!IsWindows8OrGreater()) {
		m_ui.ignoreAeroBtn->setChecked(!layer->getDisableAero());
		m_ui.disableAeroBtn->setChecked(layer->getDisableAero());
	}

	// Cropping information
	const CropInfo &cropInfo = layer->getCropInfo();
	m_ui.leftCropEdit->setText(QString::number(cropInfo.getLeftMargin()));
	m_ui.rightCropEdit->setText(QString::number(cropInfo.getRightMargin()));
	m_ui.topCropEdit->setText(QString::number(cropInfo.getTopMargin()));
	m_ui.botCropEdit->setText(QString::number(cropInfo.getBottomMargin()));
	m_ui.leftCropAnchorBox->setCurrentIndex((int)cropInfo.getLeftAnchor());
	m_ui.rightCropAnchorBox->setCurrentIndex((int)cropInfo.getRightAnchor());
	m_ui.topCropAnchorBox->setCurrentIndex((int)cropInfo.getTopAnchor());
	m_ui.botCropAnchorBox->setCurrentIndex((int)cropInfo.getBottomAnchor());

	// Colour adjustment
	m_ignoreSignals = true;
	m_ui.gammaSlider->setValue(qRound(log10(layer->getGamma()) * 500.0f));
	m_ui.gammaBox->setValue(layer->getGamma());
	m_ui.brightnessSlider->setValue(layer->getBrightness());
	m_ui.brightnessBox->setValue(layer->getBrightness());
	m_ui.contrastSlider->setValue(layer->getContrast());
	m_ui.contrastBox->setValue(layer->getContrast());
	m_ui.saturationSlider->setValue(layer->getSaturation());
	m_ui.saturationBox->setValue(layer->getSaturation());
	m_ignoreSignals = false;
}
Esempio n. 13
0
/// <summary>
/// Reload driver
/// </summary>
/// <param name="path">Path to the driver file</param>
/// <returns>Status code</returns>
NTSTATUS DriverControl::Reload( std::wstring path /*= L"" */ )
{
    NTSTATUS status = STATUS_SUCCESS;

    Unload();

    // Use default path
    if (path.empty())
    {
        const wchar_t* filename = nullptr;

        if (IsWindows10OrGreater())
            filename = L"BlackBoneDrv10.sys";
        else if (IsWindows8Point1OrGreater())
            filename = L"BlackBoneDrv81.sys";
        else if (IsWindows8OrGreater())
            filename = L"BlackBoneDrv8.sys";
        else if (IsWindows7OrGreater())
            filename = L"BlackBoneDrv7.sys";
        else
            filename = L"BlackBoneDrv.sys";

        path = Utils::GetExeDirectory() + L"\\" + filename;
    }

    status = _loadStatus = LoadDriver( DRIVER_SVC_NAME, path );
    if (!NT_SUCCESS( status ))
    {
        BLACBONE_TRACE( L"Failed to load driver %ls. Status 0x%X", path.c_str(), status );
        return LastNtStatus( status );
    }

    _hDriver = CreateFileW(
                   BLACKBONE_DEVICE_FILE,
                   GENERIC_READ | GENERIC_WRITE,
                   FILE_SHARE_READ | FILE_SHARE_WRITE,
                   NULL, OPEN_EXISTING, 0, NULL
               );

    if (_hDriver == INVALID_HANDLE_VALUE)
    {
        status = LastNtStatus();
        BLACBONE_TRACE( L"Failed to open driver handle. Status 0x%X", status );
        return status;
    }

    return status;
}
Esempio n. 14
0
/// <summary>
/// Reload driver
/// </summary>
/// <param name="path">Path to the driver file</param>
/// <returns>Status code</returns>
NTSTATUS DriverControl::Reload( std::wstring path /*= L"" */ )
{
    Unload();

    // Use default path
    if (path.empty())
    {
        const wchar_t* filename = nullptr;

        if (IsWindows10OrGreater())
            filename = BLACKBONE_FILE_NAME_10;
        else if (IsWindows8Point1OrGreater())
            filename = BLACKBONE_FILE_NAME_81;
        else if (IsWindows8OrGreater())
            filename = BLACKBONE_FILE_NAME_8;
        else if (IsWindows7OrGreater())
            filename = BLACKBONE_FILE_NAME_7;
        else
            filename = BLACKBONE_FILE_NAME;

        path = Utils::GetExeDirectory() + L"\\" + filename;
    }

    _loadStatus = LoadDriver( DRIVER_SVC_NAME, path );
    if (!NT_SUCCESS( _loadStatus ))
    {
        BLACKBONE_TRACE( L"Failed to load driver %ls. Status 0x%X", path.c_str(), _loadStatus );
        return _loadStatus;
    }

    _hDriver = CreateFileW( 
        BLACKBONE_DEVICE_FILE, 
        GENERIC_READ | GENERIC_WRITE, 
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL, OPEN_EXISTING, 0, NULL
        );

    if (!_hDriver)
    {
        _loadStatus = LastNtStatus();
        BLACKBONE_TRACE( L"Failed to open driver handle. Status 0x%X", _loadStatus );
        return _loadStatus;
    }

    return _loadStatus;
}
Esempio n. 15
0
// determine the directory for a given pathname
// (wstring only for now; feel free to make this a template if needed)
/*static*/ wstring File::DirectoryPathOf(wstring path)
{
#ifdef _WIN32
    // Win32 accepts forward slashes, but it seems that PathRemoveFileSpec() does not
    // TODO:
    // "PathCchCanonicalize does the / to \ conversion as a part of the canonicalization, it's
    // probably a good idea to do that anyway since I suspect that the '..' characters might
    // confuse the other PathCch functions" [Larry Osterman]
    // "Consider GetFullPathName both for canonicalization and last element finding." [Jay Krell]
    path = msra::strfun::ReplaceAll<wstring>(path, L"/", L"\\");

    HRESULT hr;
    if (IsWindows8OrGreater()) // PathCchRemoveFileSpec() only available on Windows 8+
    {
        typedef HRESULT(*PathCchRemoveFileSpecProc)(_Inout_updates_(_Inexpressible_(cchPath)) PWSTR, _In_ size_t);
        HINSTANCE hinstLib = LoadLibrary(TEXT("api-ms-win-core-path-l1-1-0.dll"));
        if (hinstLib == nullptr)
            RuntimeError("DirectoryPathOf: LoadLibrary() unexpectedly failed.");
        PathCchRemoveFileSpecProc PathCchRemoveFileSpec = reinterpret_cast<PathCchRemoveFileSpecProc>(GetProcAddress(hinstLib, "PathCchRemoveFileSpec"));
        if (!PathCchRemoveFileSpec)
            RuntimeError("DirectoryPathOf: GetProcAddress() unexpectedly failed.");

        // this is the actual function call we care about
        hr = PathCchRemoveFileSpec(&path[0], path.size());

        FreeLibrary(hinstLib);
    }
    else // on Windows 7-, use older PathRemoveFileSpec() instead
        hr = PathRemoveFileSpec(&path[0]) ? S_OK : S_FALSE;

    if (hr == S_OK) // done
        path.resize(wcslen(&path[0]));
    else if (hr == S_FALSE) // nothing to remove: use .
        path = L".";
    else
        RuntimeError("DirectoryPathOf: Path(Cch)RemoveFileSpec() unexpectedly failed with 0x%08x.", (unsigned int)hr);
#else
    auto pos = path.find_last_of(L"/");
    if (pos != path.npos)
        path.erase(pos);
    else // if no directory path at all, use current directory
        return L".";
#endif
    return path;
}
Esempio n. 16
0
bool InstallD3DFix(void)
{
	char FixHighRes[256];
	if(!GothicReadIniString("DEBUG", "FixHighRes", "1", FixHighRes, 256, "SystemPack.ini"))
		GothicWriteIniString("DEBUG", "FixHighRes", "1", "SystemPack.ini");

	char FixAppCompat[256];
	if(!GothicReadIniString("DEBUG", "FixAppCompat", "1", FixAppCompat, 256, "SystemPack.ini"))
		GothicWriteIniString("DEBUG", "FixAppCompat", "1", "SystemPack.ini");

	HMODULE hDDraw = GetModuleHandle(_T("ddraw.dll"));
	if(hDDraw)
	{
		if(IsWindowsXPOrGreater() && (atoi(FixHighRes) == 1))
		{
			DeleteFile(_T("D3DIM700.dll"));
			if(hD3Dim = LoadLibrary(_T("D3DIM700.dll")))
				PatchD3D((uChar*)hD3Dim);
		}

		if(IsWindows8OrGreater())
		{
			int AppCompatFix = atoi(FixAppCompat);
			switch(AppCompatFix)
			{
			case 1:
				{
					SetAppCompatDataFunc SetAppCompatData = (SetAppCompatDataFunc)GetProcAddress(hDDraw, "SetAppCompatData"); // DXPrimaryEmulation -DisableMaxWindowedMode
					if(SetAppCompatData)
						SetAppCompatData(12, 0);
				}
				break;
			case 2:
				{
					uChar* codeBase = (uChar*)GetModuleHandle(NULL);
					PIMAGE_IMPORT_DESCRIPTOR importDesc = GetImportDescriptor(codeBase, "USER32.dll");
					if(importDesc)
						PatchImportFunctionAddress<FARPROC>(codeBase, importDesc, false, "CreateWindowExA", (FARPROC)MyCreateWindowExA);
				}
				break;
			}
		}
	}
	return true;
}
Esempio n. 17
0
void dectectOS() //TODO:Fix this as it doesn't know how to check version
{
    char *osVersion;
    //if(IsWindows10OrGreater()) osVersion = "Windows 10";
    if(IsWindows8Point1OrGreater()) osVersion = "Windows 8.1";
    else if(IsWindows8OrGreater()) osVersion = "Windows 8";
    else if(IsWindows7SP1OrGreater()) osVersion = "Windows 7 Service Pack 1";
    else if(IsWindowsVistaSP2OrGreater()) osVersion = "Windows Vista Service Pack 2";
    else if(IsWindowsVistaSP1OrGreater()) osVersion = "Windows Vista Service Pack 1";
    else if(IsWindowsVistaOrGreater()) osVersion = "Windows Vista";
    else if(IsWindowsXPSP3OrGreater()) osVersion = "Windows XP Service Pack 3";
    else if(IsWindowsXPSP2OrGreater()) osVersion = "Windows XP Service Pack 2";
    else if(IsWindowsXPSP1OrGreater()) osVersion = "Windows XP Service Pack 1";
    else if(IsWindowsXPOrGreater()) osVersion = "Windows XP";
    else if(IsWindowsServer()) osVersion = "Windows Server";

    printf("\nOS Version : %s", osVersion);
}
Esempio n. 18
0
void Host::initOS() {
#ifdef NUCLEUS_TARGET_ANDROID
    os.name = "Android";
#endif
#ifdef NUCLEUS_TARGET_IOS
    os.name = "iOS";
#endif
#ifdef NUCLEUS_TARGET_LINUX
    os.name = "Linux";
#endif
#ifdef NUCLEUS_TARGET_OSX
    os.name = "OSX";
#endif
#ifdef NUCLEUS_TARGET_UWP
    os.name = "Windows";
#endif
#ifdef NUCLEUS_TARGET_WINDOWS
    if (IsWindows10OrGreater()) {
        os.name = "Windows 10";
    } else if (IsWindows8Point1OrGreater()) {
        os.name = "Windows 8.1";
    } else if (IsWindows8OrGreater()) {
        os.name = "Windows 8";
    } else if (IsWindows7OrGreater()) {
        os.name = "Windows 7";
    } else if (IsWindowsVistaSP2OrGreater()) {
        os.name = "Windows Vista SP2";
    } else if (IsWindowsVistaSP1OrGreater()) {
        os.name = "Windows Vista SP1";
    } else if (IsWindowsVistaOrGreater()) {
        os.name = "Windows Vista";
    } else if (IsWindowsXPSP3OrGreater()) {
        os.name = "Windows XP SP3";
    } else if (IsWindowsXPSP2OrGreater()) {
        os.name = "Windows XP SP2";
    } else if (IsWindowsXPSP1OrGreater()) {
        os.name = "Windows XP SP1";
    } else if (IsWindowsXPOrGreater()) {
        os.name = "Windows XP";
    }
#endif
}
int wmain(void) {

    //if (IsWindows10OrGreater()) {
        
    //    wprintf(L"This is Windows 10+");
    // }
    if (IsWindows8Point1OrGreater()) {
        wprintf(L"This is Windows 8.1+\n");
    } else if (IsWindows8OrGreater()) {
        wprintf(L"This is Windows 8\n");
    } else if (IsWindows7OrGreater ()) {
        wprintf(L"This is Windows 7\n");
    } else if (IsWindowsVistaOrGreater ()) {
        wprintf(L"This is Windows Vista\n");
    } else if (IsWindowsXPOrGreater()) {
        wprintf(L"This is Windows XP\n");
    }

    return 0;
}
Esempio n. 20
0
/**
 * Makes sure a library named "Subversion" exists and has our template
 * set to it.
 * If the library already exists, the template is set.
 * If the library doesn't exist, it is created.
 */
void EnsureSVNLibrary(bool bCreate /* = true*/)
{
    // when running the 32-bit version of TortoiseProc on x64 OS,
    // we must not create the library! This would break
    // the library in the x64 explorer.
    BOOL bIsWow64 = FALSE;
    IsWow64Process(GetCurrentProcess(), &bIsWow64);
    if (bIsWow64)
        return;

    CComPtr<IShellLibrary> pLibrary = NULL;
    if (FAILED(OpenShellLibrary(L"Subversion", &pLibrary)))
    {
        if (!bCreate)
            return;
        if (FAILED(SHCreateLibrary(IID_PPV_ARGS(&pLibrary))))
            return;

        // Save the new library under the user's Libraries folder.
        CComPtr<IShellItem> pSavedTo = NULL;
        if (FAILED(pLibrary->SaveInKnownFolder(FOLDERID_UsersLibraries, L"Subversion", LSF_OVERRIDEEXISTING, &pSavedTo)))
            return;
    }

    if (SUCCEEDED(pLibrary->SetFolderType(IsWindows8OrGreater() ? FOLDERTYPEID_Documents : FOLDERTYPEID_SVNWC)))
    {
        // create the path for the icon
        CString path;
        CString appDir = CPathUtils::GetAppDirectory();
        if (appDir.GetLength() < MAX_PATH)
        {
            TCHAR buf[MAX_PATH] = {0};
            PathCanonicalize(buf, (LPCTSTR)appDir);
            appDir = buf;
        }
        path.Format(L"%s%s,-%d", (LPCTSTR)appDir, L"TortoiseProc.exe", IsWin10OrLater() ? IDI_LIBRARY_WIN10 : IDI_LIBRARY);
        pLibrary->SetIcon((LPCTSTR)path);
        pLibrary->Commit();
    }
}
Esempio n. 21
0
bool CodecInst::BindDLLs()
{
    if (hModRuntime && AMFInit)
        return true;

    hModRuntime = LoadLibraryW(AMF_DLL_NAME);
    if (hModRuntime)
    {
        AMFInit = (AMFInit_Fn)GetProcAddress(hModRuntime, AMF_INIT_FUNCTION_NAME);
        AMFQueryVersion = (AMFQueryVersion_Fn)GetProcAddress(hModRuntime, AMF_QUERY_VERSION_FUNCTION_NAME);
    }
    else
        LogMsg(true, L"Failed to load AMF runtime DLL (%s)!", AMF_DLL_NAME);

    if (IsWindows8OrGreater() && !hD3DCompiler)
    {
        hD3DCompiler = LoadLibraryA("D3DCOMPILER_47.DLL");
        if (hD3DCompiler)
            pfn_D3DCompile = (decltype(pfn_D3DCompile))GetProcAddress(hD3DCompiler, "D3DCompile");
    }
    return !!hModRuntime && !!AMFInit;
}
Esempio n. 22
0
bool win32_exception::ShouldHook()
{
  if (!IsWindows8OrGreater())
    return true;

  bool result = true;

  auto module = ::LoadLibrary(L"kernel32.dll");
  if (module)
  {
    auto func = reinterpret_cast<GCPFN>(::GetProcAddress(module, "GetCurrentPackageFullName"));
    if (func)
    {
      UINT32 length = 0;
      auto r = func(&length, nullptr);
      result = r == APPMODEL_ERROR_NO_PACKAGE;
    }

    ::FreeLibrary(module);
  }

  return result;
}
Esempio n. 23
0
// Force DWM process to recreate all its Direct3D objects.
static void
restartDwmComposition(HANDLE hProcess)
{
    HRESULT hr;

    HMODULE hModule = LoadLibraryA("dwmapi");
    assert(hModule);
    if (!hModule) {
        return;
    }

    typedef HRESULT (WINAPI *PFNDWMISCOMPOSITIONENABLED)(BOOL *pfEnabled);
    PFNDWMISCOMPOSITIONENABLED pfnDwmIsCompositionEnabled = (PFNDWMISCOMPOSITIONENABLED)GetProcAddress(hModule, "DwmIsCompositionEnabled");
    assert(pfnDwmIsCompositionEnabled);
    if (!pfnDwmIsCompositionEnabled) {
        return;
    }

    typedef HRESULT (WINAPI *PFNDWMENABLECOMPOSITION)(UINT uCompositionAction);
    PFNDWMENABLECOMPOSITION pfnDwmEnableComposition = (PFNDWMENABLECOMPOSITION)GetProcAddress(hModule, "DwmEnableComposition");
    assert(pfnDwmEnableComposition);
    if (!pfnDwmEnableComposition) {
        return;
    }


    BOOL bIsWindows8OrGreater = IsWindows8OrGreater();
    if (bIsWindows8OrGreater) {
        // Windows 8 ignores DwmEnableComposition(DWM_EC_DISABLECOMPOSITION).
        // It is however possible to force DWM to restart by restarting the
        // display device via the devcon utility 
        devconEnable(DEVCON_CLASS_DISPLAY);
    } else {

        BOOL fEnabled = FALSE;
        hr = pfnDwmIsCompositionEnabled(&fEnabled);
        if (FAILED(hr) || !fEnabled) {
            return;
        }

        fprintf(stderr, "info: restarting DWM composition\n");

        hr = pfnDwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
        assert(SUCCEEDED(hr));
        if (FAILED(hr)) {
            return;
        }

        Sleep(1000/30);

        hr = pfnDwmEnableComposition(DWM_EC_ENABLECOMPOSITION);
        assert(SUCCEEDED(hr));
        (void)hr;
    }

    fprintf(stderr, "Press any key when finished tracing\n");
    getchar();

    DWORD dwExitCode;
    if (GetExitCodeProcess(hProcess, &dwExitCode) &&
        dwExitCode != STILL_ACTIVE) {
        // DWM process has already terminated
        return;
    }

    fprintf(stderr, "info: restarting DWM process\n");
    if (bIsWindows8OrGreater) {
        // From Windows 8 onwards DWM no longer runs as a service.  We just
        // kill it and winlogon parent process will respawn it.
        if (!TerminateProcess(hProcess, 0)) {
            logLastError("failed to terminate DWM process");
        }
    } else {
        hr = pfnDwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
        assert(SUCCEEDED(hr));

        restartService("uxsms");
    }
}
Esempio n. 24
0
bool IsWindowsSevenOrLesser()
{
	return !IsWindows8OrGreater();
}
Esempio n. 25
0
RenderWindow::RenderWindow(Renderer* aRenderer, HWND hWnd, int aWidth, int aHeight, int flags)
	: RenderTarget(aRenderer->device(), aWidth, aHeight)
	, mHwnd(hWnd)
	, mInitFlags(flags)
{
	assert(mHwnd);

	mHwnd = hWnd;

	RECT rect;
	GetClientRect(hWnd, &rect);

	// these typically will be the same as aWidth and aHeight, which are by now stored in mWidth and mHeight
	// but it's possible that the user for some reason wants different dimensions, so let them
	int width = rect.right - rect.left;
	int height = rect.bottom - rect.top;

	DXGI_SWAP_EFFECT effect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // Win8 and greater
	if (!IsWindows8OrGreater())
		effect = DXGI_SWAP_EFFECT_DISCARD; // Win7 and Vista, and possibly XP

	DXGI_SWAP_CHAIN_DESC desc = { 0 };
	desc.BufferCount = 2;
	desc.SwapEffect = effect;
	desc.BufferDesc.Width = width;
	desc.BufferDesc.Height = height;
	desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
	desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	desc.OutputWindow = hWnd;
	desc.SampleDesc.Count = 1;
	desc.SampleDesc.Quality = 0;
	desc.Windowed = TRUE;

	ComPtr<IDXGIFactory> factory = aRenderer->factory();
	assert(factory);
	if (!factory)
		throw InvalidParameterException("Invalid 'factory' renderer property in Direct3D11::RenderWindow");

	HRESULT hr = E_FAIL;

	if (factory) {
		hr = factory->CreateSwapChain(
			mDevice.Get(),
			&desc,
			&mSwapChain
			);
	}

	if (FAILED(hr) || !mSwapChain)
		throw Exception("Could not create swap chain in Direct3D11::RenderWindow");

	hr = mSwapChain->GetBuffer(
		0,
		__uuidof(ID3D11Texture2D),
		&mBackBuffer
		);

	if (FAILED(hr))
		throw Exception("Could not obtain back buffer from swap chain in Direct3D11::RenderWindow");

	hr = mDevice->CreateRenderTargetView(
		mBackBuffer.Get(),
		nullptr,
		&mRenderTargetView
		);

	if (FAILED(hr))
		throw Exception("Could not create render target view in Direct3D11::RenderWindow");

	mBackBuffer->GetDesc(&mDesc);
}
int MachineInstaller::PerformMachineInstallSetup()
{
	wchar_t packageName[512];

	if (!findPackageFromEmbeddedZip(packageName, sizeof(packageName))) {
		MessageBox(NULL, L"Corrupt installer", L"Cannot find package name for installer, is it created correctly?", MB_OK);
		return ERROR_INVALID_PARAMETER;
	}

	wchar_t machineInstallFolder[MAX_PATH];
	SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, machineInstallFolder);
	wcscat(machineInstallFolder, L"\\SquirrelMachineInstalls");

	// NB: This is the DACL for Program Files
	wchar_t sddl[512] = L"D:PAI(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;CIIO;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;;0x1301bf;;;SY)(A;OICIIO;GA;;;SY)(A;;0x1301bf;;;BA)(A;OICIIO;GA;;;BA)(A;;0x1200a9;;;BU)(A;OICIIO;GXGR;;;BU)(A;OICIIO;GA;;;CO)";

	if (IsWindows8OrGreater()) {
		// Add ALL APPLICATION PACKAGES account (Only available on Windows 8 and greater)
		wcscat(sddl, L"(A;;0x1200a9;;;AC)(A;OICIIO;GXGR;;;AC)");
	}

	PSECURITY_DESCRIPTOR descriptor;
	ConvertStringSecurityDescriptorToSecurityDescriptor(
		sddl,
		SDDL_REVISION_1,
		&descriptor, NULL);

	SECURITY_ATTRIBUTES attrs;
	attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
	attrs.bInheritHandle = false;
	attrs.lpSecurityDescriptor = descriptor;

	if (!CreateDirectory(machineInstallFolder, &attrs) && GetLastError() != ERROR_ALREADY_EXISTS) {
		LocalFree(descriptor);
		return GetLastError();
	}

	LocalFree(descriptor);

	wcscat(machineInstallFolder, L"\\");
	wcscat(machineInstallFolder, packageName);
	wcscat(machineInstallFolder, L".exe");

	wchar_t ourFile[MAX_PATH];
	HMODULE hMod = GetModuleHandle(NULL);
	GetModuleFileName(hMod, ourFile, _countof(ourFile));

	if (!CopyFile(ourFile, machineInstallFolder, false)) {
		return GetLastError();
	}

	HKEY runKey;
	DWORD dontcare;
	if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, &dontcare) != ERROR_SUCCESS) {
		return GetLastError();
	}

	wcscat_s(machineInstallFolder, L" --checkInstall");

	if (RegSetValueEx(runKey, packageName, 0, REG_SZ, (BYTE*)machineInstallFolder, (wcsnlen(machineInstallFolder, sizeof(machineInstallFolder)) + 1) * sizeof(wchar_t)) != ERROR_SUCCESS) {
		return GetLastError();
	}

	RegCloseKey(runKey);
	return 0;
}
Esempio n. 27
0
version get_version()
{
#if (_MSC_VER >= oVS2015_VER)

	bool is_server = IsWindowsServer();

	//if (IsWindows10OrGreater())             return is_server ? windows::version::win10             : windows::version::win10;
	if (IsWindows8Point1OrGreater())        return is_server ? windows::version::server_2012_sp1   : windows::version::win8_1;
	if (IsWindows8OrGreater())              return is_server ? windows::version::server_2012       : windows::version::win8;
	if (IsWindows7SP1OrGreater())           return is_server ? windows::version::server_2008r2_sp1 : windows::version::win7_sp1;
	if (IsWindows7OrGreater())              return is_server ? windows::version::server_2008r2     : windows::version::win7;
	if (IsWindowsVistaSP2OrGreater())       return is_server ? windows::version::server_2008_sp2   : windows::version::vista_sp2;
	if (IsWindowsVistaSP1OrGreater())       return is_server ? windows::version::server_2008_sp1   : windows::version::vista_sp1;
	if (IsWindowsVistaOrGreater())          return is_server ? windows::version::server_2008       : windows::version::vista;
	if (IsWindowsXPSP3OrGreater())          return is_server ? windows::version::xp								 : windows::version::xp;
	if (IsWindowsXPSP2OrGreater())		      return is_server ? windows::version::xp_sp1						 : windows::version::xp_sp1;
	if (IsWindowsXPSP1OrGreater())		      return is_server ? windows::version::xp_sp2						 : windows::version::xp_sp2;
	if (IsWindowsXPOrGreater())				      return is_server ? windows::version::xp_sp3						 : windows::version::xp_sp3;
	if (IsWindowsVersionOrGreater(5, 2, 0)) return is_server ? windows::version::server_2003       : windows::version::xp_pro_64bit;
	if (IsWindowsVersionOrGreater(5, 0, 0)) return is_server ? windows::version::win2000           : windows::version::win2000;

#else
	OSVERSIONINFOEX osvi;
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	if (GetVersionEx((OSVERSIONINFO*)&osvi))
	{
		if (osvi.dwMajorVersion == 6)
		{
			if (osvi.dwMinorVersion == 2)
			{
				if (osvi.wServicePackMajor == 1)
					return osvi.wProductType == VER_NT_WORKSTATION ? version::win8_1 : version::server_2012_sp1;
				else if (osvi.wServicePackMajor == 0)
					return osvi.wProductType == VER_NT_WORKSTATION ? version::win8 : version::server_2012;
			}

			else if (osvi.dwMinorVersion == 1)
			{
				if (osvi.wServicePackMajor == 0)
					return osvi.wProductType == VER_NT_WORKSTATION ? version::win7 : version::server_2008r2;
				else if (osvi.wServicePackMajor == 1)
					return osvi.wProductType == VER_NT_WORKSTATION ? version::win7_sp1 : version::server_2008r2_sp1;
			}
			else if (osvi.dwMinorVersion == 0)
			{
				if (osvi.wServicePackMajor == 2)
					return osvi.wProductType == VER_NT_WORKSTATION ? version::vista_sp2 : version::server_2008_sp2;
				else if (osvi.wServicePackMajor == 1)
					return osvi.wProductType == VER_NT_WORKSTATION ? version::vista_sp1 : version::server_2008_sp1;
				else if (osvi.wServicePackMajor == 0)
					return osvi.wProductType == VER_NT_WORKSTATION ? version::vista : version::server_2008;
			}
		}

		else if (osvi.dwMajorVersion == 5)
		{
			if (osvi.dwMinorVersion == 2)
			{
				SYSTEM_INFO si;
				GetSystemInfo(&si);
				if ((osvi.wProductType == VER_NT_WORKSTATION) && (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64))
					return version::xp_pro_64bit;
				else if (osvi.wSuiteMask & 0x00008000 /*VER_SUITE_WH_SERVER*/)
					return version::home_server;
				else
					return GetSystemMetrics(SM_SERVERR2) ? version::server_2003r2 : version::server_2003;
			}

			else if (osvi.dwMinorVersion == 1)
				return version::xp;
			else if (osvi.dwMinorVersion == 0)
				return version::win2000;
		}
	}
#endif

	return version::unknown;
}
Esempio n. 28
0
bool SFSystemInfo::InitializeOSInfo()
{
	// 2014.07.02 최흥배 GetVersionEx를 MS에서 비추천 API로 지정되어서 새 API로 OS의 간단한 정보만 얻었습니다.
	// MSDN의 OS 버전 번호 http://msdn.microsoft.com/en-us/library/ms724832(v=vs.85).aspx

	if (IsWindowsServer())
	{
		m_OSInfo.isServer = true;
	}

	if (IsWindows8Point1OrGreater())
	{
		if (m_OSInfo.isServer)
			m_OSInfo.szOperatingSystem = "Windows Server 2012 R2 or Grater";
		else
			m_OSInfo.szOperatingSystem = "Windows 8.1 or Grater";

		m_OSInfo.majorVer = 6;
		m_OSInfo.minorVer = 3;
	}
	else if (IsWindows8OrGreater())
	{
		if (m_OSInfo.isServer)
			m_OSInfo.szOperatingSystem = "Windows Server 2012";
		else
			m_OSInfo.szOperatingSystem = "Windows 8";

		m_OSInfo.majorVer = 6;
		m_OSInfo.minorVer = 2;
	}
	else if (IsWindows7OrGreater())
	{
		if (m_OSInfo.isServer)
			m_OSInfo.szOperatingSystem = "Windows Server 2008 R2";
		else
			m_OSInfo.szOperatingSystem = "Windows 7";

		m_OSInfo.majorVer = 6;
		m_OSInfo.minorVer = 1;
	}
	else if (IsWindowsVistaOrGreater())
	{
		if (m_OSInfo.isServer)
			m_OSInfo.szOperatingSystem = "Windows Server 2008";
		else
			m_OSInfo.szOperatingSystem = "Windows Vista";

		m_OSInfo.majorVer = 6;
		m_OSInfo.minorVer = 0;
	}
	else if (IsWindowsXPOrGreater())
	{
		if (m_OSInfo.isServer)
			m_OSInfo.szOperatingSystem = "Windows Server 2003";
		else
			m_OSInfo.szOperatingSystem = "Windows XP";

		m_OSInfo.majorVer = 5;
		m_OSInfo.minorVer = 1;
	}

	return true; 
}
Esempio n. 29
0
int
main(int argc, char *argv[])
{
    if (argc < 3) {
        fprintf(stderr,
                "usage:\n"
                "  inject <dllname.dll> <command> [args] ...\n"
                "  inject <dllname.dll> <process-id>\n"
                "  inject <dllname.dll> !<process-name>\n"
        );
        return 1;
    }

    BOOL bAttach = FALSE;
    DWORD dwProcessId = ~0;
    if (isNumber(argv[2])) {
        dwProcessId = atol(argv[2]);
        bAttach = TRUE;
    } else if (argv[2][0] == '!') {
        const char *szProcessName = &argv[2][1];
        if (!getProcessIdByName(szProcessName, &dwProcessId)) {
            fprintf(stderr, "error: failed to find process %s\n", szProcessName);
            return 1;
        }
        bAttach = TRUE;
        fprintf(stderr, "dwProcessId = %lu\n", dwProcessId);
    }

    HANDLE hSemaphore = NULL;
    const char *szDll = argv[1];
    if (!USE_SHARED_MEM) {
        SetEnvironmentVariableA("INJECT_DLL", szDll);
    } else {
        hSemaphore = CreateSemaphore(NULL, 1, 1, "inject_semaphore");
        if (hSemaphore == NULL) {
            fprintf(stderr, "error: failed to create semaphore\n");
            return 1;
        }

        DWORD dwWait = WaitForSingleObject(hSemaphore, 0);
        if (dwWait == WAIT_TIMEOUT) {
            fprintf(stderr, "info: waiting for another inject instance to finish\n");
            dwWait = WaitForSingleObject(hSemaphore, INFINITE);
        }
        if (dwWait != WAIT_OBJECT_0) {
            fprintf(stderr, "error: failed to enter semaphore gate\n");
            return 1;
        }

        SetSharedMem(szDll);
    }

    BOOL bAttachDwm = FALSE;
    PROCESS_INFORMATION processInfo;
    HANDLE hProcess;
    if (bAttach) {
        BOOL bRet;
        HANDLE hToken   = NULL;
        bRet = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken);
        if (!bRet) {
            fprintf(stderr, "error: OpenProcessToken returned %u\n", (unsigned)bRet);
            return 1;
        }

        LUID Luid;
        bRet = LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Luid);
        if (!bRet) {
            fprintf(stderr, "error: LookupPrivilegeValue returned %u\n", (unsigned)bRet);
            return 1;
        }

        TOKEN_PRIVILEGES tp;
        tp.PrivilegeCount = 1;
        tp.Privileges[0].Luid = Luid;
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        bRet = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof tp, NULL, NULL);
        if (!bRet) {
            fprintf(stderr, "error: AdjustTokenPrivileges returned %u\n", (unsigned)bRet);
            return 1;
        }

        DWORD dwDesiredAccess =
            PROCESS_CREATE_THREAD |
            PROCESS_QUERY_INFORMATION |
            PROCESS_QUERY_LIMITED_INFORMATION |
            PROCESS_VM_OPERATION |
            PROCESS_VM_WRITE |
            PROCESS_VM_READ |
            PROCESS_TERMINATE;
        hProcess = OpenProcess(
            dwDesiredAccess,
            FALSE /* bInheritHandle */,
            dwProcessId);
        if (!hProcess) {
            logLastError("failed to open process");
            return 1;
        }

        char szProcess[MAX_PATH];
        DWORD dwRet = GetModuleFileNameEx(hProcess, 0, szProcess, sizeof szProcess);
        assert(dwRet);
        if (dwRet &&
            stricmp(getBaseName(szProcess), "dwm.exe") == 0) {
            bAttachDwm = TRUE;
        }
    } else {
        std::string commandLine;
        char sep = 0;
        for (int i = 2; i < argc; ++i) {
            const char *arg = argv[i];

            if (sep) {
                commandLine.push_back(sep);
            }

            if (needsQuote(arg)) {
                quoteArg(commandLine, arg);
            } else {
                commandLine.append(arg);
            }

            sep = ' ';
        }

        STARTUPINFO startupInfo;
        memset(&startupInfo, 0, sizeof startupInfo);
        startupInfo.cb = sizeof startupInfo;

        // Create the process in suspended state
        if (!CreateProcessA(
               NULL,
               const_cast<char *>(commandLine.c_str()), // only modified by CreateProcessW
               0, // process attributes
               0, // thread attributes
               TRUE, // inherit handles
               CREATE_SUSPENDED,
               NULL, // environment
               NULL, // current directory
               &startupInfo,
               &processInfo)) {
            DWORD dwLastError = GetLastError();
            fprintf(stderr, "error: failed to execute %s (%lu)\n",
                    commandLine.c_str(), dwLastError);
            if (dwLastError == ERROR_ELEVATION_REQUIRED) {
                fprintf(stderr, "error: target program requires elevated priviledges and must be started from an Administrator Command Prompt, or UAC must be disabled\n");
            }
            return 1;
        }

        hProcess = processInfo.hProcess;
    }

    /*
     * XXX: Mixed architecture don't quite work.  See also
     * http://www.corsix.org/content/dll-injection-and-wow64
     */
    {
        typedef BOOL (WINAPI *PFNISWOW64PROCESS)(HANDLE, PBOOL);
        PFNISWOW64PROCESS pfnIsWow64Process;
        pfnIsWow64Process = (PFNISWOW64PROCESS)
            GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process");
        if (pfnIsWow64Process) {
            BOOL isParentWow64 = FALSE;
            BOOL isChildWow64 = FALSE;
            if (pfnIsWow64Process(GetCurrentProcess(), &isParentWow64) &&
                pfnIsWow64Process(hProcess, &isChildWow64) &&
                isParentWow64 != isChildWow64) {
                fprintf(stderr, "error: binaries mismatch: you need to use the "
#ifdef _WIN64
                        "32-bits"
#else
                        "64-bits"
#endif
                        " apitrace binaries to trace this application\n");
                TerminateProcess(hProcess, 1);
                return 1;
            }
        }
    }

    if (bAttachDwm && IsWindows8OrGreater()) {
        // Switch to Microsoft Basic Display Driver before injecting, so that
        // we don't trace with it.
        devconDisable(DEVCON_CLASS_DISPLAY);
        Sleep(1000);
    }

    const char *szDllName;
    szDllName = "injectee.dll";

    char szDllPath[MAX_PATH];
    GetModuleFileNameA(NULL, szDllPath, sizeof szDllPath);
    getDirName(szDllPath);
    strncat(szDllPath, szDllName, sizeof szDllPath - strlen(szDllPath) - 1);

#if 1
    if (!injectDll(hProcess, szDllPath)) {
        TerminateProcess(hProcess, 1);
        return 1;
    }
#endif

    DWORD exitCode;

    if (bAttach) {
        if (bAttachDwm) {
            restartDwmComposition(hProcess);
        }

        exitCode = 0;
    } else {
        // Start main process thread
        ResumeThread(processInfo.hThread);

        // Wait for it to finish
        WaitForSingleObject(hProcess, INFINITE);

        if (pSharedMem && !pSharedMem->bReplaced) {
            fprintf(stderr, "warning: %s was never used: application probably does not use this API\n", szDll);
        }

        exitCode = ~0;
        GetExitCodeProcess(hProcess, &exitCode);

        CloseHandle(processInfo.hThread);
    }

    CloseHandle(hProcess);

    if (hSemaphore) {
        ReleaseSemaphore(hSemaphore, 1, NULL);
        CloseHandle(hSemaphore);
    }

    return (int)exitCode;
}
Esempio n. 30
0
bool InitDDrawCapture()
{
    bool versionSupported = false;
    HMODULE hDDrawLib = NULL;
    if (hDDrawLib = GetModuleHandle(TEXT("ddraw.dll")))
    {
        bool isWinVistaMin = IsWindowsVistaOrGreater();
        bool isWin7min = IsWindows7OrGreater();
        bool isWin8min = IsWindows8OrGreater();

        UPARAM libBaseAddr = UPARAM(hDDrawLib);
        UPARAM surfCreateOffset;
        UPARAM surfUnlockOffset;
        UPARAM surfReleaseOffset;
        UPARAM surfRestoreOffset;
        UPARAM surfBltOffset;
        UPARAM surfFlipOffset;
        UPARAM surfSetPaletteOffset;
        UPARAM palSetEntriesOffset;

        if (isWinVistaMin)
        {
            if (!isWin7min)
            {
                RUNEVERYRESET logOutput << CurrentTimeString() << "Windows Vista not supported yet" << endl;
            }
            else if (isWin7min && !isWin8min)
            {
                surfCreateOffset = 0x617E;
                surfUnlockOffset = 0x4C40;
                surfReleaseOffset = 0x3239;
                surfRestoreOffset = 0x3E9CB;
                surfBltOffset = surfCreateOffset + 0x44F63;
                surfFlipOffset = surfCreateOffset + 0x37789;
                surfSetPaletteOffset = surfCreateOffset + 0x4D2D3;
                palSetEntriesOffset = surfCreateOffset + 0x4CE68;
                versionSupported = true;
            }
            else if (isWin8min)
            {
                surfCreateOffset = 0x9530 + 0xC00;
                surfUnlockOffset = surfCreateOffset + 0x2A1D0;
                surfReleaseOffset = surfCreateOffset - 0x1A80;
                surfRestoreOffset = surfCreateOffset + 0x36000;
                surfBltOffset = surfCreateOffset + 0x438DC;
                surfFlipOffset = surfCreateOffset + 0x33EF3;
                surfSetPaletteOffset = surfCreateOffset + 0x4D3B8;
                palSetEntriesOffset = surfCreateOffset + 0x4CF4C;
                versionSupported = false;	// some crash bugs remaining

                RUNEVERYRESET logOutput << CurrentTimeString() << "Windows 8 not supported yet" << endl;
            }
            else
            {
                RUNEVERYRESET logOutput << CurrentTimeString() << "Unknown OS version" << endl;
            }
        }
        else
        {
            RUNEVERYRESET logOutput << CurrentTimeString() << "OS version not supported" << endl;
        }

        if (versionSupported)
        {
            ddrawSurfaceCreate.Hook((FARPROC)(libBaseAddr + surfCreateOffset), (FARPROC)CreateSurface);
            ddrawSurfaceRestore.Hook((FARPROC)(libBaseAddr + surfRestoreOffset), (FARPROC)Restore);
            ddrawSurfaceRelease.Hook((FARPROC)(libBaseAddr + surfReleaseOffset), (FARPROC)Release);
            ddrawSurfaceUnlock.Hook((FARPROC)(libBaseAddr + surfUnlockOffset), (FARPROC)Unlock);
            ddrawSurfaceBlt.Hook((FARPROC)(libBaseAddr + surfBltOffset), (FARPROC)Blt);
            ddrawSurfaceFlip.Hook((FARPROC)(libBaseAddr + surfFlipOffset), (FARPROC)Flip);
            ddrawSurfaceSetPalette.Hook((FARPROC)(libBaseAddr + surfSetPaletteOffset), (FARPROC)SetPalette);
            ddrawPaletteSetEntries.Hook((FARPROC)(libBaseAddr + palSetEntriesOffset), (FARPROC)PaletteSetEntries);

            ddrawSurfaceUnlock.Rehook();
            ddrawSurfaceFlip.Rehook();
            ddrawSurfaceBlt.Rehook();
            /*
            ddrawSurfaceCreate.Rehook();
            ddrawSurfaceRestore.Rehook();
            ddrawSurfaceRelease.Rehook();
            ddrawSurfaceSetPalette.Rehook();
            ddrawPaletteSetEntries.Rehook();
            */
        }
    }

    return versionSupported;
}