How can one get the adress of a variable in inline asm?

Take this code as example:

let a: *const i32;
unsafe { std::arch::asm!{
    "mov {tmp}, 5",
    "lea {a}, [{tmp}]",

    a = out(reg) a,
    tmp = out(reg) _,
}};
println!("{a:p}");

lea should be getting the adress, but when compiling and running i get 0x5 as if it was just a mov. Since lea reg, [reg] is the only valid syntax, how can one push the adress of something to a register?

But what are you trying to get the address of? There are only registers in your code. Registers don't have memory addresses (in the sense of pointers-to-main-operative-memory; of course they are addressed internally in a completely independent and opaque manner). The lea instruction is simple arithmetic; it merely computes a base * stride + offset style affine operation. If you don't have an address to begin with, you won't be able to get the address of a variable based on exclusively some value in a register.

Anyway, this seems to work for passing an address into the asm block:

    let b: i32 = 42;
    let a: *const i32 = &b;
    let c: *const i32;
    
    unsafe {
        std::arch::asm! {
            "lea {a}, [{c}]",

            c = out(reg) c,
            a = in(reg) a,
        }
    };

Playground

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.