13

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?

2
  • 1
    see stackoverflow.com/questions/2114163/… Commented Nov 20, 2011 at 11:47
  • Will taking the address of a local variable be good enough for your application? Commented Nov 20, 2011 at 11:49

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Mat, this was the answer I was looking for.
Isn't this just a shorthand for inline assembly? :-) I think the docs have moved to: gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Explicit-Reg-Vars.html
how do i access accumulator data ??
Woth noting GCC very explicitly does not support this. Pinning register is only supported for use in extended assembly: gcc.gnu.org/onlinedocs/gcc-6.1.0/gcc/…
9
register const long rsp_alias asm volatile("rsp");

5 Comments

Christoph, where should the const be placed, before register or after it?
@MetallicPriest: between register and long would be the most "natural" way, and indeed, it's a good idea.
yup -- I've noticed compiler optimizing away the selected register, thats why I included volatile.
I get a syntax error with volatile there (gcc 4.3)
@Eric same, and ` warning: optimization may eliminate reads and/or writes to register variables [-Wvolatile-register-var]` if I move it to a syntatically valid position.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.