Read value of ebx register in Rust with inline assembly ("rbx is used internally by LLVM and cannot be used as an operand for inline asm")

Viewed 593

I'm writing Rust code and need to get the value that is currently stored inside "ebx" register (x86).

My code [0] looks like this:

#![feature(asm)]

fn main() {
    let ebx: u32;
    unsafe { asm!("", out("ebx") ebx) };
    println!("current value of register ebx is: {}", ebx);
}

The error code from rustc 1.54.0-nightly is:

invalid register `ebx`: rbx is used internally by LLVM and cannot be used as an operand for inline asm

The only working workaround I found is the legacy way:

unsafe {
    llvm_asm!("" : "={ebx}"(ebx) : :);
}

Is there a way to achieve the desired functionality with the new asm! macro?

PS: Due to my research I came across this: https://github.com/rust-lang/rust/pull/84658. But it still doesn't offer a nice and simple solution.

[0] https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=8d0a322236cce1efbebedccc40ddbf71

1 Answers

You can move it to another register.

#![feature(asm)]

fn main() {
    let ebx: u32;
    unsafe { asm!("mov {:e}, ebx", out(reg) ebx) };
    println!("current value of register ebx is: {}", ebx);
}
Related