Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a register without using inline assembly with gcc

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?

like image 877
MetallicPriest Avatar asked Nov 20 '11 11:11

MetallicPriest


People also ask

Does GCC support inline assembly?

GCC provides two forms of inline asm statements. A basic asm statement is one with no operands (see Basic Asm), while an extended asm statement (see Extended Asm) includes one or more operands.

When to use asm volatile?

If the C code that follows the asm makes no use of any of the output operands, use volatile for the asm statement to prevent the optimizers from discarding the asm statement as unneeded (see Volatile).

What is __ asm __ in C?

The __asm keyword invokes the inline assembler and can appear wherever a C or C++ statement is legal. It cannot appear by itself. It must be followed by an assembly instruction, a group of instructions enclosed in braces, or, at the very least, an empty pair of braces.


2 Answers

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.

like image 141
Mat Avatar answered Sep 23 '22 00:09

Mat


register const long rsp_alias asm volatile("rsp");
like image 23
Anthony Blake Avatar answered Sep 26 '22 00:09

Anthony Blake