21,487
社区成员
发帖
与我相关
我的任务
分享
LRESULT CALLBACK wndProc(UINT msg, WPARAM wpa, LPARAM lpa)
{
// hWnd 通过Thunk代码保存到窗口类的第一个数据成员:HWND _wnd; 中
}
struct ThunkData
{
#if defined(_M_IX86)
#pragma pack(push, 1)
unsigned char m_szMachineCode[22];
void* init(DWORD_PTR proc, void* pthis)
{
*((WORD *) &m_szMachineCode[ 0]) = 0xB851;
*((DWORD *) &m_szMachineCode[ 2]) = (DWORD)pthis;
*((DWORD *) &m_szMachineCode[ 6]) = 0x08244C8B;
*((DWORD *) &m_szMachineCode[10]) = 0x44890889;
*((DWORD *) &m_szMachineCode[14]) = 0xE9590824;
*((DWORD *) &m_szMachineCode[18]) = proc - reinterpret_cast<DWORD>(this) - sizeof(ThunkData);
// write block from data cache and flush from instruction cache
FlushInstructionCache(GetCurrentProcess(), this, sizeof(ThunkData));
return this;
}
#pragma pack(pop)
#elif defined(_M_AMD64)
#pragma pack(push, 1)
unsigned char m_szMachineCode[27];
void* init(DWORD_PTR proc, void *pthis)
{
*((WORD *)&m_szMachineCode[0]) =0xB848;
*((INT_PTR*)&m_szMachineCode[2]) =reinterpret_cast<INT_PTR>(pthis);
*((DWORD *)&m_szMachineCode[10]) =0x89480848;
*((DWORD *)&m_szMachineCode[14]) =0x00B848C1;
*((INT_PTR*)&m_szMachineCode[17]) =proc;
*((WORD *)&m_szMachineCode[25]) =0xE0FF;
FlushInstructionCache(GetCurrentProcess(), this, sizeof(ThunkData));
return this;
}
#pragma pack(pop)
#endif
void* getCode()
{
return this;
}
void* operator new(size_t)
{
return VirtualAlloc(NULL, sizeof(ThunkData), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
}
void operator delete(void* thunk)
{
VirtualFree(thunk, 0, MEM_RELEASE);
}
};
mov qword ptr [rax], rcx ; _wnd = [this] = rcx
有问题?/*
For x64 calling convention, rcx hold the 'HWND',copy the 'HWND' to Window object,
then insert 'this pointer' into rcx,so perfectly!!!
Stack frame before modify Stack frame after modify
: : : :
|---------------| |----------------|
| lpa | <-R9(lpa) | lpa | <-R9(lpa)
|---------------| |----------------|
| wpa | <-R8(wpa) | wpa | <-R8(wpa)
|---------------| |----------------|
| msg | <-rdx(msg) | msg | <-rdx(msg)
|---------------| |----------------|
| wnd | <-rcx(wnd) | this | <-rcx(this)
|---------------| |----------------|
| (return addr) | <-rsp | (return addr) | <-rsp
|---------------| |----------------|
: : : :
machine code assembly instruction comment
------------------- ----------------------- ----
48B8 ???????????????? mov rax, pthis
4808 mov qword ptr [rax], rcx ; _wnd = [this] = rcx
4889C1 mov rcx, rax ; rcx = pthis
48B8 ???????????????? mov rax, proc
FFE0 jmp rax
*/
BYTE _machineCode[27];
void* init(DWORD_PTR proc, void *pthis)
{
printf("%d", sizeof(ThunkData));
*((WORD *) &_machineCode[ 0]) = 0xB848;
*((ULONG64*) &_machineCode[ 2]) = reinterpret_cast<ULONG64>(pthis);
*((DWORD *) &_machineCode[10]) = 0x89480848;
*((DWORD *) &_machineCode[14]) = 0x00B848C1;
*((ULONG64*) &_machineCode[17]) = proc;
*((WORD *) &_machineCode[25]) = 0xE0FF;
FlushInstructionCache(GetCurrentProcess(), this, sizeof(ThunkData));
return this;
}