首页 > 代码库 > _ReturnAddress 使用

_ReturnAddress 使用

msdn:

The _ReturnAddress intrinsic provides the address of the instruction in the calling function that will be executed after control returns to the caller.

_ReturnAddress 返回当前调用函数返回的地址,即函数吓一跳指令地址

读起来有些拗口,我们通过实例观察下

代码:

// compiler_intrinsics__ReturnAddress.cpp
#include <stdio.h>
#include <windows.h>
#include <intrin.h>

#pragma intrinsic(_ReturnAddress)
__declspec(noinline) ULONG_PTR caller( VOID ) { return (ULONG_PTR)_ReturnAddress(); }

	__declspec(noinline)
	void noinline_func(void)
{
	 void *callerAddress = _ReturnAddress();
	printf("Return address from %s: %p\n", __FUNCTION__, callerAddress);
}

__forceinline
	void inline_func(void)
{
	 void *callerAddress = _ReturnAddress();
	printf("Return address from %s: %p\n", __FUNCTION__, callerAddress);
}

int main(void)
{
	noinline_func(); 
	ULONG_PTR uiLibraryAddress = caller();
	__asm
	{
		nop
		nop
		nop
		nop
	}
	inline_func();
	printf("Return address from %s: %p\n", __FUNCTION__, _ReturnAddress());
	printf("noinlineaddr = %p, inline_funcaddr = %p,uiLibraryAddress = %p \n",noinline_func,inline_func,uiLibraryAddress);
	system("pause");
	return 0;
}

技术分享

程序中函数noinline_func()调用了 ReturnAddress(), ReturnAddress()返回调用函数noinline_func()的下条指令的地址,即001D1483

程序中函数inline_func()调用了 ReturnAddress(), ReturnAddress()返回调用函数inline_func()的下条指令的地址,即001D1494

caller()函数调用了 ReturnAddress()函数,返回地址为caller()下一条指令地址,001D1488

其他同样。。。。,

运行结果如下:

技术分享


_ReturnAddress 使用