我想在没有编写内联汇编的情况下读取堆栈指针寄存器值。我想这样做的原因是因为我想将堆栈指针寄存器值分配给数组的元素,我觉得访问数组很麻烦使用内联汇编。所以我想做那样的事情。
register "rsp" long rsp_alias; <--- How do I achieve something like that in gcc?
long current_rsp_value[NUM_OF_THREADS];
current_rsp_value[tid] = rsp_alias;
gcc有什么可能吗?
答案 0 :(得分:16)
有一条捷径:
register long rsp asm ("rsp");
演示:
#include<stdio.h>
void foo(void)
{
register long rsp asm ("rsp");
printf("RSP: %lx\n", rsp);
}
int main()
{
register long rsp asm ("rsp");
printf("RSP: %lx\n", rsp);
foo();
return 0;
}
给出:
$ gdb ./a.out
GNU gdb (Gentoo 7.2 p1) 7.2
...
Reading symbols from /home/user/tmp/a.out...done.
(gdb) break foo
Breakpoint 1 at 0x400538: file t.c, line 7.
(gdb) r
Starting program: /home/user/tmp/a.out
RSP: 7fffffffdb90
Breakpoint 1, foo () at t.c:7
7 printf("RSP: %lx\n", rsp);
(gdb) info registers
....
rsp 0x7fffffffdb80 0x7fffffffdb80
....
(gdb) n
RSP: 7fffffffdb80
8 }
答案 1 :(得分:8)
register const long rsp_alias asm volatile("rsp");
答案 2 :(得分:1)
为什么不能在GCC编译的C函数中使用asm
指令?见GCC Inline Assembly Howto