Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing assembly in C++ without using other variables

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

like image 507
Syntax_Error Avatar asked Mar 14 '17 08:03

Syntax_Error


2 Answers

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;");
}
like image 145
alexeykuzmin0 Avatar answered Oct 19 '22 10:10

alexeykuzmin0


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.

like image 28
old_timer Avatar answered Oct 19 '22 11:10

old_timer