Skip to content

Instantly share code, notes, and snippets.

@bczhc
Created March 6, 2026 12:52
Show Gist options
  • Select an option

  • Save bczhc/888d57174794aa7e16b0e3270aaade22 to your computer and use it in GitHub Desktop.

Select an option

Save bczhc/888d57174794aa7e16b0e3270aaade22 to your computer and use it in GitHub Desktop.
内联x86汇编

Hello world

C

// demo.c
void _start() {
    // 1. 调用 write(1, "Hello\n", 6)
    const char *msg = "Hello\n";
    long syscall_nr = 1; // write 的系统调用号
    long fd = 1;         // stdout
    long len = 6;

    asm volatile (
            "movq %0, %%rax\n\t"  // 系统调用号放入 rax
            "movq %1, %%rdi\n\t"  // 参数1: fd
            "movq %2, %%rsi\n\t"  // 参数2: 缓冲区地址
            "movq %3, %%rdx\n\t"  // 参数3: 长度
            "syscall"
            :
            : "r"(syscall_nr), "r"(fd), "r"(msg), "r"(len)
            : "rax", "rdi", "rsi", "rdx", "rcx", "r11"
        // 注意:syscall 指令会破坏 rcx 和 r11 寄存器,必须声明
            );

    // 2. 调用 exit(0)
    asm volatile (
            "movq $60, %%rax\n\t" // exit 系统调用号
            "movq $0, %%rdi\n\t"  // 退出码 0
            "syscall"
            :
            :
            : "rax", "rdi"
            );
}

编译

cc -nostdlib demo.c -o hello_raw

Rust

#![no_std]
#![no_main]

use core::panic::PanicInfo;

#[unsafe(no_mangle)]
pub unsafe extern "C" fn _start() -> ! {
    let msg = "Hello\n";
    let len = msg.len();

    // 1. 调用 write(1, msg, len)
    core::arch::asm!(
        "syscall",
        in("rax") 1,          // 系统调用号: write
        in("rdi") 1,          // 参数1: fd (stdout)
        in("rsi") msg.as_ptr(), // 参数2: 缓冲区地址
        in("rdx") len,        // 参数3: 长度
        out("rcx") _,         // syscall 会破坏 rcx
        out("r11") _,         // syscall 会破坏 r11
        clobber_abi("system") // 告诉编译器该调用遵循系统调用规范
    );

    // 2. 调用 exit(0)
    core::arch::asm!(
    "syscall",
    in("rax") 60,         // 系统调用号: exit
    in("rdi") 0,          // 退出码: 0
    options(noreturn)     // 告诉编译器此段汇编不会返回
    );
    loop {}
}

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

编译

rustc --crate-type bin --target x86_64-unknown-linux-gnu -C link-args="-nostartfiles -nodefaultlibs" -C panic=abort demo.rs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment