简体   繁体   中英

Bad Instruction - Inline Assembly Language in C Code

I'm trying to exit a program with assembly instructions, but when I compile with gcc it says that mov is a bad instruction, even when I use movl which I don't even know what it is. Is it even possible to exit a program with assembly instructions?

int main(void)
{
    __asm__("movl %rax, $60\n\t"
        "movl %rdi, $0\n\t"
        "syscall\n");
}
// cc main.c -o main && ./main

You need movq for 64 bit. Also, your operations are not in the correct order.

The following compiles:

int main(void)
{
    __asm__("movq $60, %rax\n\t"
        "movq $0, %rdi\n\t"
        "syscall\n");
}

Note that for any other system call (which doesn't terminate the whole program), it's necessary to tell the compiler which registers are clobbered, and usually to use a "memory" clobber to make sure memory is in sync with C values before a system call reads or writes memory.

Also, to pass operands, you'll need Extended asm syntax. See How to invoke a system call via sysenter in inline assembly? for an example my_write wrapper. (Which has only "syscall" inside the asm template; we ask the compiler to put the call number and args in the right registers instead of writing mov )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM