Uncovering the Secrets of Rust Compilation
The Power of Assembly
Rust provides various types of output, including assembly code. This guide explores the tools and facilities available for extracting and embedding assembly code in your Rust projects.
Viewing Assembly Code
To view assembly output, we’ll use a simple example program. The quickest way to generate assembly is by using the Rust compiler itself, rustc
, with the --emit asm
option. You can also format the output with Intel syntax by passing the -C llvm-args=-x86-asm-syntax=intel
option.
rustc --emit asm -C llvm-args=-x86-asm-syntax=intel example.rs
A simpler way to examine short snippets of code is to run them through the Godbolt Compiler Explorer, a web application that compiles code to assembly and displays it in a side-by-side view. This tool allows you to easily identify the assembly corresponding to specific lines of code.
cargo-asm: A Cargo Subcommand
cargo-asm
is a Cargo subcommand that displays the assembly for a single function at a time. This tool resolves symbol names and displays the source code interleaved with the corresponding assembly, making it particularly useful for developers learning assembly.
cargo asm --example example.rs
Including Assembly in Your Code
Rust provides facilities for embedding assembly code into your projects. Until recently, the official method was the llvm_asm!
macro, which required Rust nightly. However, since rustc-nightly-2022-01-17, the llvm_asm!
macro has been replaced by the new asm!
macro.
The New asm! Macro
The asm!
macro provides a more user-friendly syntax for using inline assembly than the deprecated llvm_asm!
macro. It allows you to specify the assembly template, input and output operands, clobbers, and options, making it easier to include assembly code in your projects.
asm!("nop" : : : : "intel");
Armed with the Right Tools
With the tools and facilities discussed above, you can explore the assembly code generated by your Rust projects. By combining these tools with a debugger, you’ll gain a deeper understanding of how your code manipulates the CPU directly.
- Rust compiler (
rustc
): generates assembly code with the--emit asm
option. - Godbolt Compiler Explorer: a web application for examining short snippets of code.
- cargo-asm: a Cargo subcommand for displaying assembly code for a single function at a time.
- asm! macro: a user-friendly way to include inline assembly in your projects.