【发布时间】:2013-11-22 02:51:34
【问题描述】:
我有一个要解决的特定问题,我需要找到一个类方法的位置(在内存中)。我想我遇到了语法约束,因为指向方法的指针被处理为member pointer 示例:
class Foo {
public:
int targetFunction(int value) { return value + 5; }
};
DWORD findLocation() { // ignore the fact that DWORD might not equal pointer size.
int (Foo::*address)(int) = &(Foo::targetFunction); // member function pointer
void* typeHide = (void*)&address; // Remove type
DWORD targetAddress = *(DWORD*)typeHide; // Convert type from void* to DWORD* and dereference to DWORD
return targetAddress;
}
int (Foo::*address)(int) = 也可以写成 auto address =
现在,在 VS2008 中,Foo::targetFunction 的地址是“0x000F B890”,但 &Foo::targetFunction 是“0x000F 1762”
首先,成员指针使用成员指针运算符.* 和->* 可以正常工作。如果我将 targetAddress 转换回成员指针,它仍然有效!
其次,位置可以是一个thunk函数!
最后,如果我使用 VS2008 的调试器将 targetFunction 的值从member pointer 的地址 1762 更改为 VS 调试器报告的值 B890,我的代码可以正常工作!
是否有特定于 C++ 的方法来获取地址值(B890)而不是成员指针值(1762)?
根据要求,这是我正在尝试制作的代码:
BYTE overwriteStorage[300][2];
void NOP(void)
{
// hackish, but works for now.
}
void disableOlderVersions(DWORD _address, int index)
{
//...
_address = findLocation();
DWORD protectionStorage = 0;
VirtualProtect((void *)_address, 1+4, PAGE_WRITECOPY, &protectionStorage); // windows.h: Make Read/Write the location in code
{
BYTE *edit = (BYTE*)_address;
overwriteStorage[index][0] = *(edit+0); // store previous value to revert if needed
*(edit+0) = 0XE9; // JUMP (32-bit)
overwriteStorage[index][1] = *(edit+1); // store second value
signed int correctOffset = (signed int)NOP - (signed int)_address - 5; // calculate 0xE9 relative jump
*(signed int*)(edit+1) = correctOffset; // set jump target
}
VirtualProtect((void *)_address, 1+4, PAGE_EXECUTE, &protectionStorage);
}
如果我将findLocation 的第一行从member pointer 替换为实际的function pointer,它将完美运行。但是,我还需要读写几个类方法,这个方法被奇怪的member pointers 破坏了。
另外,我有一些本地函数也没有报告正确的地址(最近)。是否有另一种方法可以在不受编译器行为约束的情况下找到函数地址?
【问题讨论】:
-
I think I've hit a syntax constraint如果你在 C++ 中这样做,你就知道你做错了什么 -
这看起来像一个 XY 问题。您要解决的根本问题是什么?
-
@aaronman,坦率地说,
member pointers似乎“覆盖”了我正在寻找的功能,而不是限制它们。 -
这就是我的观点,c++ 的约束很少,几乎可以让你做任何你想做的事情
-
@Johnsyweb,我的问题没有其他可能的解决方案。虽然考虑到,但我有大量通过接口类定义的动态链接代码。我需要函数的地址,以便比较不同的版本和类型。
标签: c++ visual-studio function-pointers member-pointers