Chinaunix首页 | 论坛 | 博客
  • 博客访问: 355337
  • 博文数量: 60
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 1138
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-20 16:18
个人简介

最多140个字

文章分类

全部博文(60)

文章存档

2016年(1)

2015年(34)

2014年(25)

分类: C/C++

2014-05-07 12:59:18


点击(此处)折叠或打开

  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. }

阅读(2467) | 评论(0) | 转发(0) |
0

上一篇:二叉查找树

下一篇:operator delete异常分析

给主人留下些什么吧!~~