如何在 C 或汇编中修改堆栈上的返回地址 [英] How to modify return address on Stack in C or Assembly

查看:11
本文介绍了如何在 C 或汇编中修改堆栈上的返回地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,当子程序调用时,当前 PC(程序计数器)值存储在堆栈中.我想在子程序中修改它,如下所示.我想使用 gcc 编译器在 Intel Core-i7 3632QM 上执行此操作.

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;
}

推荐答案

这几乎可以肯定是一个 XY 问题,你没有说你真正想要做什么.无论如何,这里是修改返回地址的示例代码:

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;
}

查看实际操作.

显然 foo 不能被内联,它甚至有一个返回地址,我不得不将 search 拆分成它自己的函数来解决一些模糊的优化问题,即否则编译器将删除对返回地址的写入.像这样搜索返回地址使得它更能容忍堆栈布局的差异,而不是硬编码某个局部变量的特定偏移量.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆