如何修改返回地址栈上在C语言或汇编 [英] How to modify return address on Stack in C or Assembly
问题描述
如你所知,当一个子程序调用,当前PC(程序计数器)的堆栈值店。我想修改它的子程序里面,像下面。我想这样做使用gcc编译英特尔酷睿,酷睿i7 3632QM。
无效的主要()
{
富();
}
无效美孚()
{
从堆栈中弹出返回地址;
修改返回地址;
推栈;
}
这是几乎可以肯定的XY问题,你没有说你真正想做的事情。
总之,这里是样本code来修改返回地址:
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;空巴()
{
看跌期权(进入酒吧;));
出口(0);
}无效**搜索(无效**地址,无效*值)__attribute __((noinline始终));
无效**搜索(无效**地址,无效*值)
{
而(!*地址=值)地址++;
返回地址;
}无效美孚()__attribute __((noinline始终));
无效美孚()
{
无效** P =搜索((无效**)及P,__builtin_return_address(0));
* P =栏;
}诠释的main()
{
富();
返回0;
}
显然富
必须不能被内联为它甚至有一个回邮地址,我不得不打出搜索
到它自己的函数一些模糊的优化问题,编译器,否则除去在写寄信人地址。寻找这样的返回地址使它更宽容的栈布局的差异比,如果你只是很难codeD一些具体的从一个局部变量的偏移量。
As you know, when a subroutine calls, current PC (program counter) value stores in stack. I want to modify it inside the subroutine, like below. I want do this on Intel Core-i7 3632QM using gcc compiler.
void main()
{
foo();
}
void foo()
{
pop return address from stack;
modify return address;
push it to stack;
}
This is almost certainly an XY problem, you didn't say what you really want to do. Anyway, here is sample code that modifies the return address:
#include <stdio.h>
#include <stdlib.h>
void bar()
{
puts("entered the bar ;)");
exit(0);
}
void** search(void** addr, void* value) __attribute__((noinline));
void** search(void** addr, void* value)
{
while(*addr != value) addr++;
return addr;
}
void foo() __attribute__((noinline));
void foo()
{
void** p = search((void**)&p, __builtin_return_address(0));
*p = bar;
}
int main()
{
foo();
return 0;
}
Obviously foo
must not be inlined for it to even have a return address, and I had to split out search
into its own function for some obscure optimization issue whereby the compiler would otherwise remove the write to the return address. Searching for the return address like this makes it more tolerant of stack layout differences than if you just hardcoded some specific offset from a local variable.
这篇关于如何修改返回地址栈上在C语言或汇编的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!