【发布时间】:2012-05-02 01:46:11
【问题描述】:
我有这个问题,我在 C 中递归调用一个函数,而 C 是词法范围的,所以我只能访问当前的堆栈帧。我想从前一个堆栈帧中提取参数和局部变量,该堆栈帧是在当前堆栈帧上时在前一个函数调用下创建的
我知道上一次递归调用的值仍在堆栈中,但我无法访问这些值,因为它们被“埋”在活动堆栈框架下?
我想从上一个堆栈中提取参数和局部变量,并将它们复制到copy_of_buried_arg和copy_of_buried_loc;
要求使用内联汇编使用GAS来提取变量,这是我目前为止的,我尝试了一天,我似乎无法弄清楚,我在纸上画了堆栈并进行了计算但没有任何效果,我也尝试删除对 printf 的调用,这样堆栈会更干净,但我无法找出正确的算法。这是到目前为止的代码,我的函数在第二次迭代时停止
#include <stdio.h>
char glo = 97; // just for fun 97 is ascii lowercase 'a'
int copy_of_buried_arg;
char copy_of_buried_loc;
void rec(int arg) {
char loc;
loc = glo + arg * 2; // just for fun, some char arithmetic
printf("inside rec() arg=%d loc='%c'\n", arg, loc);
if (arg != 0) {
// after this assembly code runs, the copy_of_buried_arg and
// copy_of_buried_loc variables will have arg, loc values from
// the frame of the previous call to rec().
__asm__("\n\
movl 28(%esp), %eax #moving stack pointer to old ebp (pointing it to old ebp)\n\
addl $8, %eax #now eax points to the first argument for the old ebp \n\
movl (%eax), %ecx #copy the value inside eax to ecx\n\
movl %ecx, copy_of_buried_arg # copies the old argument\n\
\n\
");
printf("copy_of_buried_arg=%u copy_of_buried_loc='%c'\n",
copy_of_buried_arg, copy_of_buried_loc);
} else {
printf("there is no buried stack frame\n");// runs if argument = 0 so only the first time
}
if (arg < 10) {
rec(arg + 1);
}
}
int main (int argc, char **argv) {
rec(0);
return 0;
}
【问题讨论】:
-
你不能把前一个调用的本地地址传递给下一个函数吗?乱用汇编语言在这里可能不会有什么好处。
-
如何在调试器中运行它并从那里获取数字?
-
@GregHewgill 我们应该使用汇编从前一个堆栈中挖掘变量,这是一个要求
-
我明白了。在问题中指出这类事情会很有用。
-
@Alex 我该怎么做。其实我也有这个问题,有没有程序可以图形化的显示堆栈?