I am writing a simple C++ program that includes some asm instructions.
void call(){
__asm__("mov -0x10(%rbp),%eax;"
"add $0x10,%eax;"
"mov %eax,%edx;"
"shr $0x1f,%edx;"
"add %edx,%eax;"
"sar %eax;"
"add %eax,-0x4(%rbp);"
"mov $0x4c,%eax;"
"mov -0x8(%rbp),%eax;"
"add %eax,%eax;"
"sub -0x4(%rbp),%eax;"
"add %eax,-0xc(%rbp);");
}
However, from the execution behavior I realized that registers manipulated by this asm body are actually used by other variables in the function.
Is there anyway to invoke the compiler to isolate the registers used in asm tag and make sure they aren't effected?
OS: Linux Compiler: G++
Non-compiler approaches are also welcome
As a non-compiler approach: you could use pusha
/popa
instructions to push all the registers to the stack before execution of your own assembly and pop all of them afterwards.
Code example:
void callOne(){
__asm__(
"pusha;"
"mov -0x10(%rbp),%eax;"
"add $0x10,%eax;"
"mov %eax,%edx;"
"shr $0x1f,%edx;"
"add %edx,%eax;"
"sar %eax;"
"add %eax,-0x4(%rbp);"
"mov $0x4c,%eax;"
"mov -0x8(%rbp),%eax;"
"add %eax,%eax;"
"sub -0x4(%rbp),%eax;"
"add %eax,-0xc(%rbp);"
"popa;");
}
inline assembly is heavily compiler specific, most of the work is the compiler nuances, yes you can tell the compiler to avoid conflict with other registers used by copmiled code and/or you can interact with the high level language variables and pull those into the inline assembly. But it is very much compiler specific. If you want a whole function in assembly then just make an assembly function and avoid the compiler issues. An easy place to start is prototype the function in C/C++, compile it to asm or disassemble then use that as your skeleton for your asm function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With