也谈C++中THUNK的一种实现技术
来源:互联网 发布:网络推广交流论坛 编辑:程序博客网 时间:2024/05/16 15:04
看了“我对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));
- 也谈C++中THUNK的一种实现技术
- thunk技术实现窗口类的封装
- thunk技术实现窗口类的封装
- 什么是thunk技术实现?
- C++ 的THUNK技术
- C++ 的THUNK技术
- QT中使用THUNK技术实现回调问题
- Thunk 技术的一个改进
- Thunk 技术的一个改进
- Thunk 技术的一个改进
- Thunk 技术的一个改进
- Thunk技术
- thunk技术!
- thunk技术
- Thunk 技术的一个改进(转)
- Thunk技术的一些理解(一)
- 一种实现Win32消息处理处理函数的新方法 - 基于Thunk实现的类成员消息处理函数
- 一种实现Win32消息处理处理函数的新方法 - 基于Thunk实现的类成员消息处理函数 .
- PHP是一种没有前途的嵌入式脚本语
- 编程的苦与乐(摘自《人月神话》)
- SM3D的OpenGL教程(一):超酷三维汉字特效
- 《实用算法的分析与程序设计》的读书笔记(第1天)
- 《实用算法的分析与程序设计》的读书笔记(第2天)
- 也谈C++中THUNK的一种实现技术
- Internet worm入门教程
- ACCESS技巧集(DELPHI AND SQL)
- 程序设计和调试中的几点总结
- 实用的存储过程之一
- 构建企业级报表设计方案
- 项目设计和客户的关系
- 办公之星控件OA应用开发方案
- 办公之星控件与数据库的交互