简体   繁体   English

错误指令 - C 代码中的内联汇编语言

[英]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.我试图用汇编指令退出程序,但是当我用gcc编译时,它说mov是一条错误的指令,即使我使用movl ,我什至不知道它是什么。 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.您需要movq为 64 位。 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.请注意,对于任何其他系统调用(不会终止整个程序),有必要告诉编译器哪些寄存器被破坏,并且通常使用"memory"破坏器来确保内存与 C 值同步系统调用读取或写入内存。

Also, to pass operands, you'll need Extended asm syntax.此外,要传递操作数,您需要扩展 asm 语法。 See How to invoke a system call via sysenter in inline assembly?请参阅如何在内联汇编中通过 sysenter 调用系统调用? for an example my_write wrapper.例如my_write包装器。 (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 ) (在 asm 模板中只有"syscall" ;我们要求编译器将调用号和 args 放在正确的寄存器中,而不是编写mov

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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