私はこの問題を抱えています。再帰的にCで関数を呼び出しており、Cは字句的にスコープされているので、現在のスタックフレームにしかアクセスできません。以前の関数呼び出しで作成された前回のスタックフレームから現在のスタックフレームに引数とローカル変数を抽出したい以前のスタック変数
以前の再帰呼び出しの値がまだスタックにあることがわかっていますが、アクティブなスタックフレームの下に埋め込まれているため、これらの値にアクセスすることはできません。
私は、以前のスタックから引数とローカル変数を抽出したいとcopy_of_buried_argとcopy_of_buried_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;
}
直前の呼び出しのローカルのアドレスを次の関数に渡すことはできませんか?アセンブリ言語がうまくいけば、ここでは良いことにつながることはありません。 –
あなたのデバッガでそれを実行し、そこから数値を取得するのはどうですか? –
@GregHewgill私はアセンブリを使用して前のスタックから変数を掘ることになっています。その必要条件は – David