5

Lets say I want to read values from those registers (and pretty all thats it) on dual core x64 CPU. How can I do this? Can I simply write something like:

uint64_t rax = 0, rbx = 0;
__asm__ __volatile__ (
    /* read value from rbx into rbx */
    "movq %%rdx, %0;\n"
    /* read value from rax into rax*/
    "movq %%rax, %1;\n"
    /* output args */
    : "=r" (rbx), "=r" (rax)
    : /* no input */
    /* clear both rdx and rax */
    : "%rdx", "%rax"
);

and then just print out rax and rbx? Cheers

Brian Brown
  • 3,873
  • 16
  • 48
  • 79

1 Answers1

4

The right way to do this with gcc is with register contraints:

uint64_t rax = 0, rbx = 0;
__asm__("" : "=a"(rax), "=b"(rbx) ::); /* make rax and rbx take on the current values in those registers */

Note that you don't need any actual instructions -- the constraints tell gcc that after doing nothing, the value rax will be in rax and the value of rbx will be in rbx.

You can use the constraints a, b, c, d, S, and D (the latter two are for %rsi and %rdi). You can also use Yz for %xmm0. Unfortunately, there don't seem to be constraints for other specific registers.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • 1
    Of course, with no inputs, the `__asm__` block could be reordered somewhat freely by the compiler. – Dietrich Epp Dec 13 '13 at 22:22
  • 1
    @DietrichEpp, you could add `__volatile__`, but the point is - what does reading these registers at any given point mean, given other compiler optimizations.. – Leeor Dec 13 '13 at 23:08
  • @ChrisDodd: Thanks for the answer! Im using gcc and in the example I posted I used `gcc's` syntax for inline assembly. You wrote: `you don't need any actual instructions` but can I use them? I mean, is my example the right way of doing this? If so, I could pull out values from other registers I need to, doing it the same way I did, right? – Brian Brown Dec 14 '13 at 09:08
  • @ChrisDodd: another issue came out. When I tried to compile my code on x64 Windows 7 on x64 CPU with Code::Blocks (MinGW), I got this error: `Error: bad register name `%rbx'` and `Error: bad register name `%rax'`, heres the code: http://pastie.org/private/f2ai9qiizpo2s2lsnmtpg – Brian Brown Dec 14 '13 at 10:16