Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read registers: RAX, RBX, RCX, RDX, RSP. RBP, RSI, RDI in C or C++? [duplicate]

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

like image 882
Brian Brown Avatar asked Oct 02 '22 04:10

Brian Brown


1 Answers

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.

like image 66
Chris Dodd Avatar answered Oct 13 '22 11:10

Chris Dodd