2016-04-28 32 views
2

是否可以修改C++中的调用栈? (我知道这是一个可怕的想法和我真的只是想知道----我不打算实际上这样做)修改调用栈

例如:

void foo(){ 
    other(); 
    cout << "You never see this" << endl; //The other() function modifies the stack to 
          //point to what ever called this function...so this is not displayed 
} 
void other(){ 
    //modify the stack pointer here somehow to go down 2 levels 
} 

//Elsewhere 
foo(); 
+0

是的,你可以。但是你需要知道堆栈帧是什么样的。这是编译器和平台的依赖。你使用的是什么操作系统和编译器? –

+2

1.抛出一个异常,2'setjmp' /'longjmp' –

+0

@RichardHodges我真的只要求好奇的缘故(所以我实际上没有一个需要解决的问题) – DarthRubik

回答

1

当一个函数调用另外一台典型的C实现中,使用处理器堆栈并使用调用操作码。这与将处理器堆栈上的下一个执行处理器指令指针一样有效。除了返回地址之外,通常还会使用堆栈帧指针的值。 所以堆栈包含:
... free_space ... [local_variables] [framePtr] [returnAddr] PREVIOUS_STACK。

所以为了改变返回地址(你应该知道它有多大 - 如果你通过-m64编译它将有64位大小),你可以得到一个变量的地址并添加一些为了到达返回指针的地址并改变它。 下面的代码已经在m64模式下用g ++编译。 如果它也适用于您,您可能会看到效果。

#include <stdio.h> 


void changeRetAddr(long* p){ 
    p-=2; 
    *p+=0x11; 
} 


void myTest(){ 
    long a=0x1122334455667788; 
    changeRetAddr(&a); 
    printf("hi my friend\n"); 
    printf("I didn't showed the salutation\n"); 
} 


int main(int argc, char **argv) 
{ 
    myTest(); 
    return 0; 
} 
+0

你从哪里得到了神奇的数字? – DarthRubik

+0

通过汇编调试:-) –