私はこの問題を抱えています.Cで関数を再帰的に呼び出していますが、Cはレキシカルスコープであるため、現在のスタックフレームにしかアクセスできません。現在のスタック フレームにいる間に、前の関数呼び出しで作成された前のスタック フレームから引数とローカル変数を抽出したい
前の再帰呼び出しの値がまだスタック上にあることはわかっていますが、アクティブなスタック フレームの下に「埋もれている」ため、これらの値にアクセスできませんか?
前のスタックから引数とローカル変数を抽出し、それらを copy_of_bured_arg と copy_of_bured_loc にコピーしたいと考えています。
変数を抽出するために GAS を使用してインライン アセンブリを使用する必要があります。スタックがきれいになるように、printfへの呼び出しも削除しようとしましたが、正しい算術演算がわかりません。これまでのコードは次のとおりです。私の関数は2回目の反復で停止します
#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;
}