x86_64 nasm inline assembly that adds two numbers in rust

main.rs
fn add_numbers(a: i32, b: i32) -> i32 {
    let result: i32;
    unsafe {
        // Inline assembly block, using NASM syntax
        asm!(
            "add {}, {}", // Add a and b
            in(reg) a, // Input register: a
            in(reg) b, // Input register: b
            lateout(reg) result, // Output register: result (late defined)
        ) // No ";" required here
    }
    result // Return result
}
414 chars
14 lines

In this example, we declare a Rust function that takes two 32-bit integers as input parameters and returns their sum as a 32-bit integer. To perform the actual addition, we make use of inline assembly.

The unsafe block is required because inline assembly is inherently unsafe, as it can easily cause memory corruption or other undefined behavior.

Inside the assembly block, we use the add instruction to add the values of a and b. The input values are passed via the in operator, and the result is returned via the lateout operator, which tells the Rust compiler to define the output register after the input registers have been used.

Finally, we return the result value as the function's return value.

gistlibby LogSnag