在 Visual C++ 中查找调用函数地址(安全)

Finding the calling functions address in Visual C++ (safely)

我正在尝试找到一种安全的方法来获取调用函数地址,而无需做任何骇人听闻的事情(比如将函数地址作为参数)。寻找适用于 x86 和 x64 的解决方案。谢谢

void callingFunction() {
    helloWorld();
}

void helloWorld() {
    printf("Hello world! This function was called by 0x%X!\n", /* CALLING FUNCTION ADDRESS HERE */);
}

helloWorld()不能直接得到callingFunction()本身的地址,只有helloWorld()会return的地址到它退出的时候。 Visual C++ 具有 _AddressOfReturnAddress() and _ReturnAddress() 编译器内部函数,您可以使用它来获取该地址,例如:

#include <stdio.h> 
#include <intrin.h>  

void callingFunction() {
    helloWorld();
}

void helloWorld() {
    printf("Hello world! This function was called by %p!\n", *((void**) _AddressOfReturnAddress()));
}

#include <stdio.h> 
#include <intrin.h>  

#pragma intrinsic(_ReturnAddress)

void callingFunction() {
    helloWorld();
}

void helloWorld() {
    printf("Hello world! This function was called by %p!\n", _ReturnAddress());
}

如果helloWorld()具体需要知道return地址是否属于callingFunction(),项目将不得不生成一个map filehelloWorld()可以然后在运行时解析以获取 callingFunction() 的起始地址和结束地址,然后它可以检查 return 地址是否在该范围内。