Last active
November 22, 2024 00:20
-
-
Save jkriegshauser/25a18ae1f81d5bcf3324e9ab08780d92 to your computer and use it in GitHub Desktop.
Intercepting GetSystemInfo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <windows.h> | |
#include <detours.h> | |
// Our maximum number of CPUs visible to the application | |
// | |
#define NUM_CPUS 8u | |
// Type declaration | |
// | |
typedef void (WINAPI *GetSystemInfo_t)(LPSYSTEM_INFO); | |
// Target pointer for the uninstrumented API. | |
// | |
static GetSystemInfo_t OrigGetSystemInfo; | |
// Detour function that replaces the GetSystemInfo API. | |
// | |
VOID WINAPI MyGetSystemInfo(LPSYSTEM_INFO info) | |
{ | |
// Call the original to populate `info` | |
OrigGetSystemInfo(info); | |
// Override the number of CPUs if there are more than we want. | |
info->dwNumberOfProcessors = min(info->dwNumberOfProcessors, NUM_CPUS); | |
} | |
static void InstallDetours() | |
{ | |
HINSTANCE hKernel32 = GetModuleHandleW(L"Kernel32.dll"); | |
DetourTransactionBegin(); | |
// Conceivably we could just assign OrigGetSystemInfo = GetSystemInfo, but this | |
// didn't work in practice. Look up the function from the Kernel32.dll module. | |
OrigGetSystemInfo = (GetSystemInfo_t)GetProcAddress(hKernel32, "GetSystemInfo"); | |
DetourAttach((PVOID*)&OrigGetSystemInfo, (PVOID)MyGetSystemInfo); | |
DetourTransactionCommit(); | |
} | |
static void RestoreDetours() | |
{ | |
DetourTransactionBegin(); | |
DetourDetach((PVOID*)&OrigGetSystemInfo, (PVOID)MyGetSystemInfo); | |
DetourTransactionCommit(); | |
} | |
// DllMain function attaches and detaches the MyGetSystemInfo detour to the | |
// GetSystemInfo target function. The Sleep target function is referred to | |
// through the OrigGetSystemInfo target pointer. | |
// | |
BOOL WINAPI DllMain(HINSTANCE hInst, DWORD dwReason, LPVOID reserved) | |
{ | |
if (DetourIsHelperProcess()) | |
return TRUE; | |
if (dwReason == DLL_PROCESS_ATTACH) | |
{ | |
DetourRestoreAfterWith(); | |
InstallDetours(); | |
} | |
else if (dwReason == DLL_PROCESS_DETACH) | |
{ | |
RestoreDetours(); | |
} | |
return TRUE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment