在不使用gcc的内联汇编的情况下访问寄存器

时间:2021-09-08 03:10:22

I want to read the stack pointer register value without writing inline assembly.The reason I want to do this is because I want to assign the stack pointer register value to an element of an array and I find it cumbersome to access an array using inline assembly. So I would want to do something like that.

我想在不编写内联汇编的情况下读取堆栈指针寄存器值。我想这样做的原因是因为我想将堆栈指针寄存器值分配给数组元素,我发现使用内联汇编访问数组很麻烦。所以我想做那样的事情。

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;

Is there anything like that possible with gcc?

gcc有什么可能吗?

3 个解决方案

#1


16  

There's a shortcut:

有一条捷径:

register long rsp asm ("rsp");

Demo:

#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;
}

Gives:

 $ 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   }

Taken from the Variables in Specified Registers documentation.

取自Specified Registers中的变量文档。

#2


8  

register const long rsp_alias asm volatile("rsp");

#3


1  

Why can't you use an asm instruction inside a C function compiled by GCC? See GCC Inline Assembly Howto

为什么不能在GCC编译的C函数中使用asm指令?请参阅GCC内联汇编指南

#1


16  

There's a shortcut:

有一条捷径:

register long rsp asm ("rsp");

Demo:

#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;
}

Gives:

 $ 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   }

Taken from the Variables in Specified Registers documentation.

取自Specified Registers中的变量文档。

#2


8  

register const long rsp_alias asm volatile("rsp");

#3


1  

Why can't you use an asm instruction inside a C function compiled by GCC? See GCC Inline Assembly Howto

为什么不能在GCC编译的C函数中使用asm指令?请参阅GCC内联汇编指南