Skip to content

Instantly share code, notes, and snippets.

@luqmana
Last active February 1, 2022 03:29
Show Gist options
  • Save luqmana/5150557 to your computer and use it in GitHub Desktop.
Save luqmana/5150557 to your computer and use it in GitHub Desktop.
How to use inline assembly in Rust.
fn main() {
    unsafe {
        do str::as_c_str(~"The answer is %d.\n") |c| {
            let a = 42;
            asm!("mov $0, %rdi\n\t\
                  mov $1, %rsi\n\t\
                  xorl %eax, %eax\n\t\
                  call _printf"
                 :
                 : "r"(c), "r"(a)
                 : "rdi", "rsi", "eax"
                 : "volatile", "alignstack"
                 );
        }
    }
}
% rustc foo.rs
% ./foo
The answer is 42.
fn add(a: int, b: int) -> int {
    let mut c = 0;
    unsafe {
        asm!("add $2, $0"
             : "=r"(c)
             : "0"(a), "r"(b)
             );
    }
    c
}

fn main() {
    io::println(fmt!("%d", add(1, 2)));
}
% rustc foo.rs
% ./foo
3
fn addsub(a: int, b: int) -> (int, int) {
    let mut c = 0;
    let mut d = 0;
    unsafe {
        asm!("\
              add $4, $0\n\t\
              sub $4, $1
             "
             : "=r"(c), "=r"(d)
             : "0"(a), "1"(a), "r"(b)
             );
    }
    (c, d)
}

fn main() {
    io::println(fmt!("%?", addsub(5, 1)));
}
% rustc foo.rs
% ./foo
(6, 4)
@phase
Copy link

phase commented Jul 6, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment