MFC thunk技术模拟


  1. //参考http://www.cnblogs.com/satng/archive/2010/12/30/2138833.html
  2. #include<iostream>
  3. using namespace std;

  4. //thunk技术模拟

  5. typedef void (*fun)(void*,int i);

  6. class CFun;//类声明。

  7. #pragma pack(push)
  8. #pragma pack(1)
  9. typedef struct Thunk{
  10.     unsigned char call;
  11.     int offset;
  12.     fun pf;//函数指针。
  13.     unsigned char code[5];
  14.     CFun *ths;//this指针。
  15.     unsigned char jmp;
  16.     unsigned char ecx;
  17. }Thunk;
  18. #pragma pack(pop)

  19. #define OFF(s,m)((unsigned int)&((s*)0)->m)//求结构体的偏移量,s为结构体的类型,m为结构体的数据成员。

  20. class CFun{
  21. public:
  22.     CFun()
  23.     {
  24.         createThunk();
  25.     }
  26.     ~CFun()
  27.     {
  28.         delete thunk;
  29.     }
  30. public:
  31.     void createThunk()
  32.     {
  33.         Thunk* tk=new Thunk;
  34.         //call des
  35.         tk->call=0xE8;//call
  36.         tk->offset=OFF(Thunk,code[0])-OFF(Thunk,pf);//des

  37.         tk->pf=CFun::funx;//函数地址。
  38.         //pop ecx
  39.         //等价于:
  40.         //mov ecx,[esp]
  41.         //sub esp,4
  42.         tk->code[0]=0x59;//pop ecx
  43.         //mov[esp+4],this
  44.         tk->code[1]=0xc7;//mov
  45.         tk->code[2]=0x44;//dword ptr
  46.         //4[esp]
  47.         tk->code[3]=0x24;//[esp]
  48.         tk->code[4]=0x04;//+4
  49.         tk->ths=this;//修改栈,设置this指针。

  50.         //jmp[ecx]
  51.         tk->jmp=0xFF;//jmp
  52.         tk->ecx=0x21;//[ecx]

  53.         thunk=(fun)tk;

  54.         return ;
  55.     }
  56.     static void funx(void *pFun,int i)
  57.     {
  58.         CFun *pf=(CFun*)pFun;
  59.         pf->print(i);
  60.     }
  61.     void print(int i)
  62.     {
  63.         cout<<"Recevie="<<i<<endl;
  64.     }

  65.     fun GetThunk()
  66.     {
  67.         return thunk;
  68.     }
  69. private:
  70.     fun thunk;
  71. };

  72. int main()
  73. {
  74.     CFun cf;
  75.     fun pf=cf.GetThunk();
  76.     pf("Hello",123);
  77.     return 0;
  78. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值