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

☆樱花仙子☆ 提交于 2019-12-12 12:24:54

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/20575739/how-to-read-registers-rax-rbx-rcx-rdx-rsp-rbp-rsi-rdi-in-c-or-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!