Bill Richard Bill Richard - 21 days ago 9
C++ Question

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

I am trying to find a safe way to get a calling functions address without doing any hacky stuff (like giving function address as an argument). Looking for a solution that should work for x86 and x64. Thanks.

void callingFunction() {
helloWorld();
}

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

Answer Source

helloWorld() can't directly get the address of callingFunction() itself, only the address that helloWorld() will return to when it exits. Visual C++ has _AddressOfReturnAddress() and _ReturnAddress() compiler intrinsic functions you can use to get that address, eg:

#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());
}

If helloWorld() needs to know whether the return address belongs to callingFunction() specifically, the project will have to generate a map file that helloWorld() can then parse at runtime to get the starting and ending addresses of callingFunction(), and then it can check if the return address falls within that range or not.