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

时间:2017-09-26 00:21:41

标签: c++ visual-c++ stack-trace

我正在尝试找到一种安全的方法来获取调用函数地址而不做任何hacky的东西(比如给函数地址作为参数)。寻找适用于x86和x64的解决方案。感谢。

void callingFunction() {
    helloWorld();
}

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

1 个答案:

答案 0 :(得分:0)

helloWorld()无法直接获取callingFunction()本身的地址,只有helloWorld()退出时会返回的地址。 Visual C ++具有_AddressOfReturnAddress()_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()需要知道返回地址是否具体属于callingFunction(),那么项目必须生成map filehelloWorld()然后可以在运行时解析callingFunction()的起始和结束地址,然后它可以检查返回地址是否在该范围内。