本文列出的代码用于表示在 x86 环境下,如何通过 RETN 指令调用函数,这类方法调用函数有一些迷惑性,但意义并不是很大,而且相对麻烦一点,CALL 指令帮你处理了很多事情,例如 push 当前的 eip,栈放大,cookie,调用的目标函数执行到 retn 指令时“平衡堆栈”后 pop eip 回到 caller 的下一指令位置。
#include <stdio.h>
static char format[] = "n=%d\n";
int add(int x, int y)
{
return x + y;
}
int main()
{
_asm
{
sub esp, 12 // 4+4+4
push 2 // [ebp+4]
push 1 // [ebp+8]
push __reteip_addproc // [ebp+4]
push add // push
retn 0 // RETN 0 = RETN = RET = C3
}
__reteip_addproc:
_asm
{
add esp, 12 // reduce stack
// call printf proc
push eax // 3
lea eax, dword ptr[format]
push eax
call printf
}
return 0;
}
JMP 指令调用函数与 RETN 指令调用函数类似,但唯一的不同就是,JMP 指令并不需要在调用 RETN 指令前 在手动的 push 要调用的函数的地址,JMP 目标函数的相对地址就可以了。
#include <stdio.h>
static char format[] = "n=%d\n";
int add(int x, int y)
{
return x + y;
}
int main()
{
_asm
{
sub esp, 12 // 4+4+4
push 2 // [ebp+4]
push 1 // [ebp+8]
push __reteip_addproc // [ebp+4]
jmp add // push
}
__reteip_addproc:
_asm
{
add esp, 12 // reduce stack
// call printf proc
push eax // 3
lea eax, dword ptr[format]
push eax
call printf
}
return 0;
}