How to access C variable for inline assembly manipulation?

邮差的信 提交于 2019-12-01 07:12:11

问题


Given this code:

#include <stdio.h>

int main(int argc, char **argv)
{
    int x = 1;
    printf("Hello x = %d\n", x);
}

I'd like to access and manipulate the variable x in inline assembly. Ideally, I want to change its value using inline assembly. GNU assembler, and using the AT&T syntax.


回答1:


In GNU C inline asm, with x86 AT&T syntax:
(But https://gcc.gnu.org/wiki/DontUseInlineAsm if you can avoid it).

// this example doesn't really need volatile: the result is the same every time
asm volatile("movl $0, %[some]"
    : [some] "=r" (x)
);

after this, x contains 0.

Note that you should generally avoid mov as the first or last instruction of an asm statement. Don't copy from %[some] to a hard-coded register like %%eax, just use %[some] as a register, letting the compiler do register allocation.

See https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html and https://stackoverflow.com/tags/inline-assembly/info for more docs and guides.


Not all compilers support GNU syntax. For example, for MSVC you do this:

__asm mov x, 0 and x will have the value of 0 after this statement.

Please specify the compiler you would want to use.

Also note, doing this will restrict your program to compile with only a specific compiler-assembler combination, and will be targeted only towards a particular architecture.

In most cases, you'll get as good or better results from using pure C and intrinsics, not inline asm.




回答2:


asm("mov $0, %1":"=r" (x):"r" (x):"cc");
-- this may get you on the right track. Specify register use as much as possible for performance and efficiency. However, as Aniket points out, highly architecture dependent and requires gcc.



来源:https://stackoverflow.com/questions/14617953/how-to-access-c-variable-for-inline-assembly-manipulation

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