### Example Output of Supported Crate Types Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/print-supported-crate-types.html This is an example of the output you can expect when querying supported crate types for the `x86_64-unknown-linux-gnu` target. ```text bin cdylib dylib lib proc-macro rlib staticlib ``` -------------------------------- ### Example Output Format Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/print-crate-root-lint-levels.html Shows the expected output format for `print=crate-root-lint-levels`, where each line is `LINT_NAME=LINT_LEVEL`. ```text __ unknown_lint=warn arithmetic_overflow=deny ``` -------------------------------- ### Usage Example Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/print-crate-root-lint-levels.html Demonstrates how to use the `rustc --print=crate-root-lint-levels` command with the `-Zunstable-options` flag. ```bash rustc --print=crate-root-lint-levels -Zunstable-options lib.rs ``` -------------------------------- ### Install rustc-dev and llvm-tools Source: https://doc.rust-lang.org/beta/unstable-book/language-features/rustc-private.html Install the necessary components for using the `rustc-private` feature with official toolchains. Without `llvm-tools`, you may encounter linking errors. ```bash rustup component add rustc-dev llvm-tools ``` -------------------------------- ### Running Cargo Bench Source: https://doc.rust-lang.org/beta/unstable-book/library-features/test.html Example output of running `cargo bench` to execute benchmark tests. ```bash $ cargo bench Compiling adder v0.0.1 (file:///home/steve/tmp/adder) Running target/release/adder-91b3e234d4ed382a running 2 tests test tests::it_works ... ignored test tests::bench_add_two ... bench: 1 ns/iter (+/- 0) test result: ok. 0 passed; 0 failed; 1 ignored; 1 measured ``` -------------------------------- ### Benchmark Results with black_box Source: https://doc.rust-lang.org/beta/unstable-book/library-features/test.html Example output showing benchmark results after using `test::black_box` to prevent optimizer interference. ```bash running 1 test test bench_xor_1000_ints ... bench: 131 ns/iter (+/- 3) test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured ``` -------------------------------- ### Basic Benchmark Test Setup Source: https://doc.rust-lang.org/beta/unstable-book/library-features/test.html Demonstrates setting up a basic benchmark test using the unstable `test` crate. Requires the `test` feature gate and imports `test::Bencher`. ```rust #![allow(unused)] #![feature(test)] fn main() { extern crate test; pub fn add_two(a: i32) -> i32 { a + 2 } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn it_works() { assert_eq!(4, add_two(2)); } #[bench] fn bench_add_two(b: &mut Bencher) { b.iter(|| add_two(2)); } } } ``` -------------------------------- ### Enabling Autodiff via Cargo and Rustc Source: https://doc.rust-lang.org/beta/unstable-book/print.html Examples of enabling autodiff using Cargo with a specific toolchain and directly with rustc. Includes an example for printing Type Analysis and Activity Analysis. ```bash # Enable autodiff via cargo, assuming `enzyme` being a toolchain that supports autodiff "RUSTFLAGS=-Zautodiff=Enable" cargo +enzyme build # Enable autodiff directly via rustc rustc -Z autodiff=Enable # Print TypeAnalysis updates for the function `foo`, as well as Activity Analysis for all differentiated code. rustc -Z autodiff=Enable,PrintTAFn=foo,PrintAA ``` -------------------------------- ### Custom Test Runner Example Source: https://doc.rust-lang.org/beta/unstable-book/language-features/custom-test-frameworks.html This example demonstrates a custom test runner using `#![test_runner]` and `#[test_case]`. The runner iterates through provided test cases and prints 'PASSED' or 'FAILED' based on their value. Note that the `main` function here is only for demonstration and would typically not contain the runner definition. ```rust #![allow(unused)] #![feature(custom_test_frameworks)] #![test_runner(my_runner)] fn main() { fn my_runner(tests: &[&i32]) { for t in tests { if **t == 0 { println!("PASSED"); } else { println!("FAILED"); } } } #[test_case] const WILL_PASS: i32 = 0; #[test_case] const WILL_FAIL: i32 = 4; } ``` -------------------------------- ### Example of Nop Padding with `patchable-function-entry` Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/patchable-function-entry.html Illustrates the nop padding generated by the `-Z patchable-function-entry=total_nops,prefix_nops` flag. This is useful for hotpatching scenarios. ```assembly __ nop nop function_label: nop //Actual function code begins here ``` -------------------------------- ### Build Standard Library with CFG Enabled (PowerShell) Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/control-flow-guard.html To enable CFG in the standard library, recompile it with the same configuration as the main program. This example uses PowerShell. ```powershell rustup toolchain install --force nightly rustup component add rust-src $Env:RUSTFLAGS = "-Z control-flow-guard" cargo +nightly build -Z build-std --target x86_64-pc-windows-msvc ``` -------------------------------- ### Coroutine Control Flow Example Source: https://doc.rust-lang.org/beta/unstable-book/language-features/coroutines.html Illustrates the execution order of a coroutine using `println!` statements and `yield`. This example requires enabling the `coroutines` and `coroutine_trait` features. It shows how `resume` calls interleave execution between the main function and the coroutine. ```rust #![feature(coroutines, coroutine_trait, stmt_expr_attributes)] use std::ops::Coroutine; use std::pin::Pin; fn main() { let mut coroutine = #[coroutine] || { println!("2"); yield; println!("4"); }; println!("1"); Pin::new(&mut coroutine).resume(()) ; println!("3"); Pin::new(&mut coroutine).resume(()) ; println!("5"); } ``` -------------------------------- ### Build Standard Library with CFG Enabled (Windows CMD) Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/control-flow-guard.html To enable CFG in the standard library, recompile it with the same configuration as the main program. This example uses Windows Command Prompt. ```shell rustup toolchain install --force nightly rustup component add rust-src SET RUSTFLAGS=-Z control-flow-guard cargo +nightly build -Z build-std --target x86_64-pc-windows-msvc ``` -------------------------------- ### C Library Example Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/sanitizer.html A simple C library function that doubles the result of another function. This is used to demonstrate FFI interactions. ```c #include int do_twice(int (*fn)(int), int arg) { return fn(arg) + fn(arg); } ``` -------------------------------- ### Example Panic Output with `-Z location-detail=line` Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/location-detail.html Demonstrates the panic output format when only the line number is tracked. This can be useful for reducing binary size by omitting file paths. ```text __ panicked at 'Process blink had a fault', :323:0 ``` -------------------------------- ### Using asm_goto_with_outputs with Labels and Outputs Source: https://doc.rust-lang.org/beta/unstable-book/language-features/asm-goto-with-outputs.html This example demonstrates how to use label operands with output operands in an `asm!` block. The output operand `a` is assigned a value before the `label` block is executed. ```rust unsafe { let a: usize; asm!( "mov {}, 1" "jmp {}", out(reg) a, label { println!("Jumped from asm {}!", a); } ); } ``` -------------------------------- ### Rust ThreadSanitizer Data Race Example Source: https://doc.rust-lang.org/beta/unstable-book/print.html This example demonstrates a data race scenario in Rust that can be detected by ThreadSanitizer. Ensure RUSTFLAGS and RUSTDOCFLAGS are set correctly and use `cargo run -Zbuild-std` for compilation. ```rust static mut A: usize = 0; fn main() { let t = std::thread::spawn(|| { unsafe { A += 1 }; }); unsafe { A += 1 }; t.join().unwrap(); } ``` ```shell $ export RUSTFLAGS=-Zsanitizer=thread RUSTDOCFLAGS=-Zsanitizer=thread $ cargo run -Zbuild-std --target x86_64-unknown-linux-gnu ================== WARNING: ThreadSanitizer: data race (pid=10574) Read of size 8 at 0x5632dfe3d030 by thread T1: #0 example::main::_$u7b$$u7b$closure$u7d$$u7d$::h23f64b0b2f8c9484 ../src/main.rs:5:18 (example+0x86cec) ... Previous write of size 8 at 0x5632dfe3d030 by main thread: #0 example::main::h628ffc6626ed85b2 /.../src/main.rs:7:14 (example+0x868c8) ... #11 main (example+0x86a1a) Location is global 'example::A::h43ac149ddf992709' of size 8 at 0x5632dfe3d030 (example+0x000000bd9030) ``` -------------------------------- ### Negative Impl Example Source: https://doc.rust-lang.org/beta/unstable-book/language-features/negative-impls.html Demonstrates the basic syntax for a negative implementation using the `negative_impls` feature gate. This indicates that `&T` will never implement `DerefMut`. ```rust #![allow(unused)] #![feature(negative_impls)] fn main() { trait DerefMut { } impl !DerefMut for &T { } } ``` -------------------------------- ### Using Frontmatter for Cargo-Script Dependencies Source: https://doc.rust-lang.org/beta/unstable-book/language-features/frontmatter.html This example demonstrates how to use the frontmatter feature in a Rust file executed by cargo-script. It specifies dependencies that cargo-script will resolve before compiling and running the code. ```rust #!/usr/bin/env -S cargo -Zscript --- [dependencies] libc = "0.2.172" --- #![feature(frontmatter)] mod libc { pub type c_int = i32; } fn main() { let x: libc::c_int = 1i32; } ``` -------------------------------- ### Basic Coroutine Example in Rust Source: https://doc.rust-lang.org/beta/unstable-book/print.html Demonstrates a simple coroutine that yields a value and then returns a string. Requires nightly Rust with the `coroutines` and `coroutine_trait` features enabled. ```rust #![feature(coroutines, coroutine_trait, stmt_expr_attributes)] use std::ops::{Coroutine, CoroutineState}; use std::pin::Pin; fn main() { let mut coroutine = #[coroutine] || { yield 1; return "foo" }; match Pin::new(&mut coroutine).resume(()) { CoroutineState::Yielded(1) => {} _ => panic!("unexpected value from resume"), } match Pin::new(&mut coroutine).resume(()) { CoroutineState::Complete("foo") => {} _ => panic!("unexpected value from resume"), } } ``` -------------------------------- ### Examples of `annotate-moves` Usage Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/annotate-moves.html Demonstrates different ways to invoke `rustc` with the `-Z annotate-moves` flag, including enabling it with the default threshold, a custom threshold, a larger threshold, and explicitly disabling it. ```bash # Enable annotation with default threshold (65 bytes) rustc -Z annotate-moves main.rs # Enable with custom 128-byte threshold rustc -Z annotate-moves=128 main.rs # Only annotate very large moves (1KB+) rustc -Z annotate-moves=1024 main.rs # Explicitly disable rustc -Z annotate-moves=false main.rs ``` -------------------------------- ### Disassembling Object File and Inspecting `.stack_sizes` Section Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/emit-stack-sizes.html This example uses `objdump` to disassemble the code sections and inspect the contents of the `.stack_sizes` section, showing the raw data generated by the compiler. ```bash $ objdump -d foo.o foo.o: file format elf64-x86-64 Disassembly of section .text._ZN3foo3foo17he211d7b4a3a0c16eE: 0000000000000000 <_ZN3foo3foo17he211d7b4a3a0c16eE>: 0: c3 retq Disassembly of section .text._ZN3foo3bar17h1acb594305f70c2eE: 0000000000000000 <_ZN3foo3bar17h1acb594305f70c2eE>: 0: 48 83 ec 10 sub $0x10,%rsp 4: 48 8d 44 24 08 lea 0x8(%rsp),%rax 9: 48 89 04 24 mov %rax,(%rsp) d: 48 8b 04 24 mov (%rsp),%rax 11: 48 83 c4 10 add $0x10,%rsp 15: c3 retq $ objdump -s -j .stack_sizes foo.o foo.o: file format elf64-x86-64 Contents of section .stack_sizes: 0000 00000000 00000000 00 ......... Contents of section .stack_sizes: 0000 00000000 00000000 10 ......... ``` -------------------------------- ### Example Macro Expansion Output Source: https://doc.rust-lang.org/beta/unstable-book/library-features/trace-macros.html The output shows the detailed steps of a macro expansion, including the original macro call and the resulting code. This output is generated when `trace_macros!(true)` is active during compilation. ```text note: trace_macro --> src/main.rs:5:5 | 5 | println!("Hello, Rust!"); | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: expanding `println! { "Hello, Rust!" }` = note: to `print ! ( concat ! ( "Hello, Rust!" , "\n" ) )` = note: expanding `print! { concat ! ( "Hello, Rust!" , "\n" ) }` = note: to `$crate :: io :: _print ( format_args ! ( concat ! ( "Hello, Rust!" , "\n" ) ) )` ``` -------------------------------- ### Rust Coroutine Example Source: https://doc.rust-lang.org/beta/unstable-book/the-unstable-book.html Demonstrates the basic usage of Rust's coroutine feature, requiring specific feature flags. It shows how to define, resume, and handle yielded and completed states. ```rust #![feature(coroutines, coroutine_trait, stmt_expr_attributes)] use std::ops::{Coroutine, CoroutineState}; use std::pin::Pin; fn main() { let mut coroutine = #[coroutine] || { yield 1; return "foo" }; match Pin::new(&mut coroutine).resume(()) { CoroutineState::Yielded(1) => {} _ => panic!("unexpected value from resume"), } match Pin::new(&mut coroutine).resume(()) { CoroutineState::Complete("foo") => {} _ => panic!("unexpected value from resume"), } } ``` -------------------------------- ### Summarize Profiling Data Source: https://doc.rust-lang.org/beta/unstable-book/print.html Use the `summarize` tool from the `measureme` repository to get a summary of where the compiler is spending its time, based on the generated profiling files. ```bash $ ../measureme/target/release/summarize summarize foo-1234 ``` -------------------------------- ### Configure Rustflags for a Specific Dependency Source: https://doc.rust-lang.org/beta/unstable-book/print.html Example of using cargo features to apply rustflags to a specific dependency, such as enabling the -Zhint-mostly-unused flag for 'mostly-unused-dependency'. ```toml cargo-features = ["profile-rustflags"] # ... [dependencies] mostly-unused-dependency = "1.2.3" [profile.release.package.mostly-unused-dependency] rustflags = ["-Zhint-mostly-unused"] ``` -------------------------------- ### Example: Compile with -Zon-broken-pipe=kill Source: https://doc.rust-lang.org/beta/unstable-book/print.html Compiles the `main.rs` file using the `-Zon-broken-pipe=kill` flag. This sets `SIGPIPE` to `SIG_DFL` before `fn main()`, causing the program to terminate if it writes to a closed pipe. ```bash $ rustc -Zon-broken-pipe=kill main.rs $ ./main | head -n1 hello world ``` -------------------------------- ### Example: Default SIGPIPE Behavior Source: https://doc.rust-lang.org/beta/unstable-book/print.html Demonstrates the default behavior when `-Zon-broken-pipe` is not used. `SIGPIPE` is ignored before `fn main()`, leading to `BrokenPipe` errors, and defaults to `SIG_DFL` before child `exec()`. ```rust fn main() { loop { println!("hello world"); } } ``` -------------------------------- ### Registering External Tools: register_tool for Lints Source: https://doc.rust-lang.org/beta/unstable-book/print.html Shows how to use the `register_tool` attribute to enable linting for external tools. This example registers the `bevy` tool and sets a deny level for `bevy::duplicate_bevy_dependencies`. ```rust #![feature(register_tool)] #![register_tool(bevy)] #![deny(bevy::duplicate_bevy_dependencies)] ``` -------------------------------- ### Rust: Nop Padding for Function Entry with -Z patchable-function-entry Source: https://doc.rust-lang.org/beta/unstable-book/print.html This example illustrates the use of the `-Z patchable-function-entry` flag to add nop instructions before the actual function code. This is primarily used for hotpatching, particularly in the Linux kernel, and mimics Clang/gcc's `-fpatchable-function-entry` flag. ```assembly __ nop nop function_label: nop //Actual function code begins here ``` -------------------------------- ### Indirect Call with Mismatched Parameters (CFI Enabled) Source: https://doc.rust-lang.org/beta/unstable-book/print.html This example demonstrates the effect of LLVM CFI. When enabled, attempts to call functions with incompatible signatures via transmute will result in an 'Illegal instruction' error, terminating the program. ```bash $ RUSTFLAGS="-Clinker-plugin-lto -Clinker=clang -Clink-arg=-fuse-ld=lld -Zsanitizer=cfi" cargo run -Zbuild-std -Zbuild-std-features --release --target x86_64-unknown-linux-gnu ... Compiling rust-cfi-2 v0.1.0 (/home/rcvalle/rust-cfi-2) Finished release [optimized] target(s) in 1m 08s Running `target/release/rust-cfi-2` The answer is: 12 With CFI enabled, you should not see the next answer Illegal instruction $ ``` -------------------------------- ### Registering External Tools: register_tool Attribute Source: https://doc.rust-lang.org/beta/unstable-book/print.html Demonstrates the use of the `register_tool` attribute to inform the compiler about external tools. This example registers the `c2rust` tool and uses its attributes for header and source location information. ```rust #![allow(unused)] #![feature(register_tool)] #![register_tool(c2rust)] fn main() { // Mark which C header file this module was generated from. #[c2rust::header_src = "operations.h"] pub mod operations_h { use std::ffi::c_int; // Mark which source line this struct was generated from. #[c2rust::src_loc = "11:0"] pub struct Point { pub x: c_int, pub y: c_int, } } } ``` -------------------------------- ### Enable Control Flow Guard (CFG) on Windows (PowerShell) Source: https://doc.rust-lang.org/beta/unstable-book/print.html Enables the Windows Control Flow Guard (CFG) security feature for the Rust compiler using PowerShell. This command installs the nightly toolchain, adds the source component, sets the RUSTFLAGS environment variable, and builds the project with the specified target. ```powershell rustup toolchain install --force nightly rustup component add rust-src $Env:RUSTFLAGS = "-Z control-flow-guard" cargo +nightly build -Z build-std --target x86_64-pc-windows-msvc ``` -------------------------------- ### Enable Control Flow Guard (CFG) on Windows (Bash) Source: https://doc.rust-lang.org/beta/unstable-book/print.html Enables the Windows Control Flow Guard (CFG) security feature for the Rust compiler. This command installs the nightly toolchain, adds the source component, sets the RUSTFLAGS environment variable, and builds the project with the specified target. ```bash rustup toolchain install --force nightly rustup component add rust-src SET RUSTFLAGS=-Z control-flow-guard cargo +nightly build -Z build-std --target x86_64-pc-windows-msvc ``` -------------------------------- ### Linking error without llvm-tools Source: https://doc.rust-lang.org/beta/unstable-book/language-features/rustc-private.html Example of a linking error that can occur when the `llvm-tools` component is not installed. ```text error: linking with `cc` failed: exit status: 1 | = note: rust-lld: error: unable to find library -lLLVM-{version} ``` -------------------------------- ### Rust: Handling Broken Pipes with -Zon-broken-pipe=error Source: https://doc.rust-lang.org/beta/unstable-book/print.html This example demonstrates how to set the SIGPIPE handler to SIG_IGN, causing writes to a closed pipe to result in an ErrorKind::BrokenPipe. This is useful for network applications. The output shows the program panicking with a 'Broken pipe' error after piping its output to `head`. ```rust __ fn main() { loop { println!("hello world"); } } ``` ```shell __ $ rustc -Zon-broken-pipe=error main.rs $ ./main | head -n1 hello world thread 'main' panicked at library/std/src/io/stdio.rs:1118:9: failed printing to stdout: Broken pipe (os error 32) note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` -------------------------------- ### RealtimeSanitizer Error Report Example Source: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/sanitizer.html This is an example of an error report generated by RealtimeSanitizer when an unsafe library call, such as `malloc`, is detected within a real-time context. ```text ==8670==ERROR: RealtimeSanitizer: unsafe-library-call Intercepted call to real-time unsafe function `malloc` in real-time context! #0 0x00010107b0d8 in malloc rtsan_interceptors_posix.cpp:792 #1 0x000100d94e70 in alloc::alloc::Global::alloc_impl::h9e1fc3206c868eea+0xa0 (realtime_vec:arm64+0x100000e70) #2 0x000100d94d90 in alloc::alloc::exchange_malloc::hd45b5788339eb5c8+0x48 (realtime_vec:arm64+0x100000d90) #3 0x000100d95020 in realtime_vec::main::hea6bd69b03eb9ca1+0x24 (realtime_vec:arm64+0x100001020) #4 0x000100d94a28 in core::ops::function::FnOnce::call_once::h493b6cb9dd87d87c+0xc (realtime_vec:arm64+0x100000a28) #5 0x000100d949b8 in std::sys::backtrace::__rust_begin_short_backtrace::hfcddb06c73c19eea+0x8 (realtime_vec:arm64+0x1000009b8) #6 0x000100d9499c in std::rt::lang_start::_$u7b$$u7b$closure$u7d$$u7d$::h202288c05a2064f0+0xc (realtime_vec:arm64+0x10000099c) #7 0x000100d9fa34 in std::rt::lang_start_internal::h6c763158a05ac05f+0x6c (realtime_vec:arm64+0x10000ba34) #8 0x000100d94980 in std::rt::lang_start::h1c29cc56df0598b4+0x38 (realtime_vec:arm64+0x100000980) #9 0x000100d95118 in main+0x20 (realtime_vec:arm64+0x100001118) #10 0x000183a46b94 in start+0x17b8 (dyld:arm64+0xfffffffffff3ab94) SUMMARY: RealtimeSanitizer: unsafe-library-call rtsan_interceptors_posix.cpp:792 in malloc ```