也谈C++中THUNK的一种实现技术

类别:VC语言 点击:0 评论:0 推荐:

看了“我对C++中THUNK一种实现技术的分析”一文,有点不同的想法。
原代码如下:
#pragma pack(push,1)
// structure to store the machine code
struct Thunk
{
    char    m_jmp;          // op code of jmp instruction
    unsigned long   m_relproc;      // relative jmp

};
#pragma pack(pop)

//This type of structure can contain then thunk code, which can be executed on the fly. Let's take a look at the simple case in which we are going to execute our required function by thunk.

//Program 77

#include <iostream>

#include <windows.h>

using namespace std;

class C;

C* g_pC = NULL;

typedef void(*pFUN)();


class C

{

public:
 int a;
 int b;
 float bbj;
    Thunk    m_thunk;

       //virtual void g(){};

    void Init(pFUN pFun, void* pThis)

    {

        // op code of jump instruction

        m_thunk.m_jmp = 0xe9;

        // address of the appripriate function

/*@@@@*/  m_thunk.m_relproc = (int)pFun- ((int)&m_thunk+sizeof(Thunk));
    FlushInstructionCache(GetCurrentProcess(),

                                &m_thunk, sizeof(m_thunk));

    }

 

    // this is cour call back function

    static void CallBackFun()

    {

        C* pC = g_pC;
        // initilize the thunk

        pC->Init(StaticFun, pC);
        // get the address of thunk code

        pFUN pFun = (pFUN)&(pC->m_thunk);
        // start executing thunk code which will call StaticFun

        pFun();

        cout << "C::CallBackFun" << endl;

    }

 

    static void StaticFun()

    {

        cout << "C::StaticFun" << endl;

    }

};

 

int main()

{

    C objC;
    g_pC = &objC;
    C::CallBackFun();
    return 0;
}

首先我们知道段内直接跳转的JMP指令长5个字节,所以sizeof(Thunk)必须是五字节,这也是#pragma pack(push,1)保持struct 1字节对齐的原因。
再来看static member function StaticFun的地址pFun,在VC编译器下,实际上该地址指向一条段内JMP指令,该JMP指令跳转到StaticFun的执行代码,比如pFun=0040106E,即指向E9 ED 04 00 00,所以当前EIP=0040106E+5=401073(即下一条指令的地址),执行JMP,EIP=EIP+04ED=401560,401560即是StaticFun执行代码的起始地址。
接着看:
// get the address of thunk code
pFUN pFun = (pFUN)&(pC->m_thunk);
// start executing thunk code which will call StaticFun
pFun();
此处的段内直接函数call,将直接跳转到&m_thunk所指的代码执行,也即
JMP (int)pFun - ((int)this+sizeof(Thunk)),
而此时EIP=&m_thunk+5=this+5,所以这个JMP将跳转到
EIP=EIP+(int)pFun - ((int)this+sizeof(Thunk))=pFun,
这样就最终跳到StaticFun执行代码的起始地址。
所以如果m_thunk前还有其他变量,比如int a;则必须使
m_thunk.m_relproc = (int)pFun - ((int)this+sizeof(Thunk)+sizeof(int));
当pFun();时,EIP=&m_thunk+5=this+sizeof(int)+5,
EIP=EIP+(int)pFun - ((int)this+sizeof(Thunk)+sizeof(int))=pFun
这样才能最终跳到StaticFun执行代码的起始地址。
所以,最好写成:
m_thunk.m_relproc = (int)pFun - ((int)&m_thunk+sizeof(Thunk));

 

本文地址:http://com.8s8s.com/it/it2189.htm