### Install mdbook and required preprocessors Source: https://github.com/anssi-fr/rust-guide/blob/master/README.md Install the custom mdbook and preprocessors needed to build the guide. Use the exact commit and flags shown. ```bash cargo install mdbook --git https://github.com/hg-anssi/mdBook.git --rev c5a35b9296c6d5e48570e30022bd69403050a9f4 --locked cargo install --path ./mdbook-checklist --locked cargo install --path ./mdbook-code-align --locked cargo install --path ./mdbook-extensions --locked ``` -------------------------------- ### Build and open the book with mdbook serve Source: https://github.com/anssi-fr/rust-guide/blob/master/README.md Build and open the guide locally using mdbook's serve command. ```bash $ mdbook serve -o ``` -------------------------------- ### Install mdbook-checklist with cargo install Source: https://github.com/anssi-fr/rust-guide/blob/master/mdbook-plugins/mdbook-checklist/README.md Install the preprocessor using Cargo. ```bash cargo install mdbook-checklist ``` -------------------------------- ### Rustfmt configuration example (rustfmt.toml) Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/devenv.md Example configuration for rustfmt to override default style guidelines. Sets maximum line width to 120 and single-line if-else max width to 40. ```toml # Set the maximum line width to 120 max_width = 120 # Maximum line length for single line if-else expressions single_line_if_else_max_width = 40 ``` -------------------------------- ### List Rust targets with rustup target list Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/devenv.md Use this command to display the list of supported Rust targets. The output shows installed targets with an '(installed)' marker, such as wasm32-unknown-unknown and x86_64-unknown-linux-gnu. ```shell $ rustup target list ... wasm32-unknown-emscripten wasm32-unknown-unknown (installed) wasm32-wasip1 ... x86_64-unknown-illumos x86_64-unknown-linux-gnu (installed) x86_64-unknown-linux-gnux32 ... ``` -------------------------------- ### Check default and overridden toolchains with rustup Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/devenv.md Use `rustup toolchain list` and `rustup override list` to see the default toolchain and any directory-specific overrides. The example shows `/tmp/foo` overridden to nightly while stable remains the default. ```shell $ pwd /tmp/foo $ rustup toolchain list stable-x86_64-unknown-linux-gnu (default) beta-x86_64-unknown-linux-gnu nightly-x86_64-unknown-linux-gnu $ rustup override list /tmp/foo nightly-x86_64-unknown-linux-gnu $ ``` -------------------------------- ### Declaring dependencies in Cargo.toml Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/libraries.md Example of a dependency declaration in the Cargo.toml file, showing how to specify crates with versions and features. ```toml [dependencies] mdbook = { version = "0.4.52" } anyhow = "1.0.99" clap = { version = "4.5.47", features = ["derive"] } markdown = { version = "1.0.0", features = ["serde"] } semver = "1.0.26" serde_json = "1.0.143" serde = "1.0.219" ``` -------------------------------- ### Specifying a Git dependency in Cargo.toml Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/libraries.md Example of a dependency declaration in the Cargo.toml file that refers to a Git repository. ```toml [dependencies] regex = { git = "https://github.com/rust-lang/regex.git" } ``` -------------------------------- ### Rust C-compatible API for a counter (src/lib.rs) Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Defines an opaque Counter struct with a C-compatible API using #[unsafe(no_mangle)] and extern "C" functions. The functions create, increment, get, and destroy a counter, returning error codes for invalid pointers or overflow. This is the Rust side of the FFI example. ```rust /// Opaque counter pub struct Counter(u32); impl Counter { /// Create a counter (initially at 0) fn new() -> Self { Self(0) } /// Get the current value of the counter fn get(&self) -> u32 { self.0 } /// Increment the value of the counter if there's no overflow fn incr(&mut self) -> bool { if let Some(n) = self.0.checked_add(1) { self.0 = n; true } else { false } } } // C-compatible API #[unsafe(no_mangle)] pub unsafe extern "C" fn counter_create() -> *mut Counter { Box::into_raw(Box::new(Counter::new())) } #[unsafe(no_mangle)] pub unsafe extern "C" fn counter_incr(counter: *mut Counter) -> std::os::raw::c_int { if let Some(counter) = unsafe { counter.as_mut() } { if counter.incr() { 0 } else { -1 } } else { -2 } } #[unsafe(no_mangle)] pub unsafe extern "C" fn counter_get(counter: *const Counter) -> u32 { if let Some(counter) = unsafe { counter.as_ref() } { counter.get() } else { 0 } } #[unsafe(no_mangle)] pub unsafe extern "C" fn counter_destroy(counter: *mut Counter) -> std::os::raw::c_int { if !counter.is_null() { let _ = unsafe { Box::from_raw(counter) }; // get box and drop 0 } else { -1 } } ``` -------------------------------- ### Rust: Opaque type with constructor and destructor Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Example of an opaque Rust type exposed to C/C++ with dedicated constructor and destructor. The constructor catches panics and returns a null pointer on failure; the destructor drops the boxed value only if the pointer is non-null. ```rust pub struct Opaque { // (...) hide details } #[unsafe(no_mangle)] pub unsafe extern "C" fn new_opaque() -> *mut Opaque { catch_unwind(|| // Catch panics, see below Box::into_raw(Box::new(Opaque { // (...) construction }))) .unwrap_or(std::ptr::null_mut()) } #[unsafe(no_mangle)] pub unsafe extern "C" fn destroy_opaque(o: *mut Opaque) { catch_unwind(|| { if !o.is_null() { // only necessary when `Opaque` or any of its fields is `Drop` drop(unsafe { Box::from_raw(o) }) } }) .unwrap_or_default(); } ``` -------------------------------- ### C: Function pointer declaration for repeat Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md C-side declaration for the repeat function that accepts a function pointer. This is the foreign counterpart to the Rust example. ```c uint32_t repeat(uint32_t start, uint32_t n, uint32_t (*f)(uint32_t)); ``` -------------------------------- ### Rust wrapper over external opaque type with Drop Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Wraps a foreign opaque type in a Rust struct with a Drop implementation that calls the foreign deallocation routine. The example defines a private raw C API and a public Foo wrapper. Note that panics may prevent Drop::drop from running, so this is not sufficient for sensitive deallocation. ```rust /// Private “raw” opaque foreign type Foo #[repr(C)] struct RawFoo { _private: [u8; 0], } // Private “raw” C API unsafe extern "C" { fn foo_create() -> *mut RawFoo; fn foo_do_something(this: *const RawFoo); fn foo_destroy(this: *mut RawFoo); } /// Foo pub struct Foo(*mut RawFoo); impl Foo { /// Create a Foo pub fn new() -> Option { let raw_ptr = unsafe { foo_create() }; if raw_ptr.is_null() { None } else { Some(Foo(raw_ptr)) } } /// Do something on a Foo pub fn do_something(&self) { unsafe { foo_do_something(self.0) } } } impl Drop for Foo { fn drop(&mut self) { if !self.0.is_null() { unsafe { foo_destroy(self.0) } } } } ``` -------------------------------- ### Derive comparison traits for struct T2 Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/standard.md Shows a second struct with reversed field order to illustrate that derived comparisons depend on field order, not names. The example demonstrates that T2 {a:1,b:0} < T2 {a:0,b:1}. ```rust #[derive(PartialEq, Eq, PartialOrd, Ord)] struct T2{ b: u8, a: u8 }; ``` -------------------------------- ### Call C function from Rust via extern block Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Imports the C `abs` function using an `unsafe extern "C"` block. Any foreign function imported this way is automatically unsafe, so calls must be inside an `unsafe` context. The example prints the absolute value of -1. ```rust use std::os::raw::c_int; // import C function unsafe extern "C" { fn abs(args: c_int) -> c_int; } fn use_abs() { let x = -1; println!("{} {}\n", x, unsafe { abs(x) }); } ``` -------------------------------- ### Access foreign static variable with #[link_name] Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Declares a foreign global variable `environ` (on Unix) using `#[link_name = "environ"]` inside an `unsafe extern "C"` block. The example iterates over the environment variables, printing each one. Note that this is not thread-safe and should not be used in practice; prefer `std::env`. ```rust // A direct way to access environment variables (on Unix) // should not be used! Not thread safe, have a look at `std::env`! unsafe extern "C" { // Global variable #[link_name = "environ"] static libc_environ: *const *const std::os::raw::c_char; } fn use_static_extern() { let mut next = unsafe { libc_environ }; while !next.is_null() && !unsafe { *next }.is_null() { let env = unsafe { std::ffi::CStr::from_ptr(*next) } .to_str() .unwrap_or(""); println!("{}", env); next = unsafe { next.offset(1) }; } } ``` -------------------------------- ### Run cargo fix Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/devenv.md Fixes compiler warnings and eases edition transitions. Run in project root. ```shell $ cargo fix ``` -------------------------------- ### Run nightly rustfmt locally with rustup run or cargo +nightly Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/devenv.md To use a nightly-only component like the latest `rustfmt`, switch the toolchain only for that command instead of globally. Both `rustup run nightly cargo fmt` and `cargo +nightly fmt` achieve this. ```shell $ rustup toolchain list stable-x86_64-unknown-linux-gnu (default) beta-x86_64-unknown-linux-gnu nightly-x86_64-unknown-linux-gnu $ rustup run nightly cargo fmt $ # or $ cargo +nightly fmt $ ``` -------------------------------- ### C main program using the counter (counter_main.c) Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md C program that includes the generated header, creates a counter, increments it a number of times from command-line argument, prints the value, and handles overflow. It demonstrates usage of the FFI functions. ```c #include #include #include #include #include "counter.h" int main(int argc, const char **argv) { if (argc < 2) { return -1; } size_t n = (size_t)strtoull(argv[1], NULL, 10); Counter *c = counter_create(); for (size_t i = 0; i < n; i++) { if (counter_incr(c) != 0) { printf("overflow\n"); counter_destroy(c); return -1; } } printf("%" PRIu32 "\n", counter_get(c)); counter_destroy(c); return 0; } ``` -------------------------------- ### Switch to Rust 2024 with cargo fix --edition-idioms Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/devenv.md Applies edition idioms for the transition to Rust 2024. Note: provides few guarantees on soundness; some corrections may break compilation or change program semantics. ```shell $ cargo fix --edition-idioms ``` -------------------------------- ### Add preprocessor to book.toml Source: https://github.com/anssi-fr/rust-guide/blob/master/mdbook-plugins/mdbook-checklist/README.md Configure the preprocessor in the book's configuration file. ```toml [book] authors = ["Me"] multilingual = false src = "src" title = "The Book" [preprocessor.checklist] ``` -------------------------------- ### Rust: Using integer overflow methods and wrapper types Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/integer.md Demonstrates the behavior of default operators, overflowing_add, wrapping_add, and the Wrapping wrapper type. Shows that default addition panics in debug builds but wraps in release, while the specialized methods and wrapper provide consistent behavior. Also shows a custom panic on overflow detection. ```rust #![allow(dead_code)] use std::num::Wrapping; use std::panic; fn use_integer() { let x: u8 = 242; let result = panic::catch_unwind(|| { println!("{}", x + 50); // panics in debug, prints 36 in release. }); if result.is_err() { println!("panic"); } // always prints 36. println!("{}", x.overflowing_add(50).0); // always prints 36. println!("{}", x.wrapping_add(50)); // always prints 36. println!("{}", Wrapping(x) + Wrapping(50)); // always panics: let (res, c) = x.overflowing_add(50); let result = panic::catch_unwind(|| { if c { panic!("custom error"); } else { println!("{}", res); } }); if result.is_err() { println!("panic"); } } ``` -------------------------------- ### C structs matching Rust repr(C) and packed layouts Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md C definitions of the structs that are compatible with the Rust types in the previous snippet. The first uses default alignment, the second uses the packed attribute to match the Rust packed layout. ```c struct Data { uint32_t a; uint16_t b; uint64_t c; }; __attribute__((packed)) struct PackedData { uint32_t a; uint16_t b; uint64_t c; }; ``` -------------------------------- ### Rust FFI resource wrapper with Drop and C API Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Defines XtraResource with Drop, and a C-compatible API using catch_unwind, tags, and heap allocation to safely manage resources across FFI. The C callback receives a pointer to a heap-allocated CXtraResource; the tag prevents accidental reuse and corruption is handled by forgetting the box. ```rust pub struct XtraResource {/* fields */} impl XtraResource { pub fn new() -> Self { XtraResource { /* ... */ } } pub fn dosthg(&mut self) { /* ... */ } } impl Drop for XtraResource { fn drop(&mut self) { println!("xtra drop"); } } pub mod c_api { use super::XtraResource; use std::panic::catch_unwind; const INVALID_TAG: u32 = 0; const VALID_TAG: u32 = 0xDEAD_BEEF; const ERR_TAG: u32 = 0xDEAF_CAFE; static mut COUNTER: u32 = 0; pub struct CXtraResource { tag: u32, // to detect accidental reuse id: u32, inner: XtraResource, } #[unsafe(no_mangle)] pub unsafe extern "C" fn xtra_with(cb: Option ()>) { let inner = if let Ok(res) = catch_unwind(XtraResource::new) { res } else { return; }; let id = unsafe { COUNTER }; let tag = VALID_TAG; unsafe { COUNTER = COUNTER.wrapping_add(1) }; // Use heap memory and do not provide pointer to stack to C code! let mut boxed = Box::new(CXtraResource { tag, id, inner }); if let Some(cb) = cb { unsafe { cb(boxed.as_mut() as *mut CXtraResource) }; } if boxed.id == id && (boxed.tag == VALID_TAG || boxed.tag == ERR_TAG) { boxed.tag = INVALID_TAG; // prevent accidental reuse // implicit boxed drop } else { // (...) error handling (should be fatal) boxed.tag = INVALID_TAG; // prevent reuse std::mem::forget(boxed); // boxed is corrupted it should not be } } #[unsafe(no_mangle)] pub unsafe extern "C" fn xtra_dosthg(cxtra: *mut CXtraResource) { let do_it = || { if let Some(cxtra) = unsafe { cxtra.as_mut() } && cxtra.tag == VALID_TAG { cxtra.inner.dosthg(); return; } println!("do noting with {:p}", cxtra); }; if catch_unwind(do_it).is_err() && let Some(cxtra) = unsafe { cxtra.as_mut() } { cxtra.tag = ERR_TAG; }; } } ``` -------------------------------- ### Rust C-compatible data layout with repr(C) and repr(C, packed) Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Defines Rust structs with explicit C-compatible memory layout using the repr attribute. The first struct uses default alignment, the second uses packed layout to avoid padding. These are compatible with the corresponding C structs shown in the next snippet. ```rust #[repr(C)] struct Data { a: u32, b: u16, c: u64, } #[repr(C, packed)] struct PackedData { a: u32, b: u16, c: u64, } ``` -------------------------------- ### Derive comparison traits for struct T1 Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/standard.md Shows how to derive PartialEq, Eq, PartialOrd, and Ord for a struct with two u8 fields. All assertions hold, demonstrating lexicographical comparison based on field order. ```rust #[derive(PartialEq, Eq, PartialOrd, Ord)] struct T1 { a: u8, b: u8 } # fn main() { assert!(&T1 { a: 0, b: 0 } == Box::new(T1 { a: 0, b: 0 }).as_ref()); assert!(T1 { a: 1, b: 0 } > T1 { a: 0, b: 0 }); assert!(T1 { a: 1, b: 1 } > T1 { a: 1, b: 0 }); # println!("all tests passed."); # } ``` -------------------------------- ### C caller for xtra_with Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Shows a compatible C caller that defines a callback and invokes xtra_with. The callback receives a pointer to the XtraResource and calls xtra_sthg on it. ```c struct XtraResource; void xtra_with(void (*cb)(struct XtraResource *xtra)); void xtra_sthg(struct XtraResource *xtra); void cb(struct XtraResource *xtra) { // ()...) do anything with the proposed C API for XtraResource xtra_sthg(xtra); } int use_xtra() { xtra_with(cb); } ``` -------------------------------- ### Convert Box into raw pointer and back with Box::from_raw Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/memory.md Shows the safe pattern of converting a Box into a raw pointer with Box::into_raw and then reclaiming it with Box::from_raw inside an unsafe block. This ensures the memory is freed properly. ```rust let boxed = Box::new(String::from("Crab")); let raw_ptr = Box::into_raw(boxed); let _ = unsafe { Box::from_raw(raw_ptr) }; // will be freed ``` -------------------------------- ### Prepare Rust 2021 project for Rust 2024 with cargo fix --edition Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/devenv.md Fixes code to be compatible with Rust 2024 or prints a warning explaining the problem. Run until no warnings remain to ensure compatibility with both Rust 2021 and Rust 2024. ```shell $ cargo fix --edition ``` -------------------------------- ### Manual cleanup of Box::into_raw pointer (discouraged) Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/memory.md Illustrates manual deallocation of a raw pointer obtained from Box::into_raw, using drop_in_place and dealloc. This approach is more complicated than re-boxing and should be avoided. ```rust // Excerpt from the standard library documentation use std::alloc::{Layout, dealloc}; use std::ptr; let x = Box::new(String::from("Hello")); let p = Box::into_raw(x); unsafe { ptr::drop_in_place(p); dealloc(p as *mut u8, Layout::new::()); } ``` -------------------------------- ### Custom Vec implementation with unsafe push Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/generalities.md This code from the Rustonomicon shows a custom Vec type with an unsafe push method. It relies on the invariant that bytes from self.ptr to self.ptr + self.cap * size_of() are allocated. Note that this implementation does not correctly handle zero-sized types. ```rust use std::ptr; pub struct Vec { ptr: *mut T, len: usize, cap: usize, } // Note this implementation does not correctly handle zero-sized types. impl Vec { pub fn push(&mut self, elem: T) { if self.len == self.cap { // reallocate new array with bigger capacity } unsafe { ptr::write(self.ptr.add(self.len), elem); self.len += 1; } } } ``` -------------------------------- ### Rust FFI function add_in_place using raw pointer Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Exported Rust function that takes a raw pointer and adds a value in place, with nullity check via as_mut. Must be called from C with a valid pointer. ```rust /// Add in place #[unsafe(no_mangle)] unsafe extern "C" fn add_in_place(a: *mut u32, b: u32) { // checks for nullity of `a` // and takes a mutable reference on it if it's non-null if let Some(a) = unsafe { a.as_mut() } { *a += b } } ``` -------------------------------- ### Deny clippy::mem_forget lint Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/memory.md Add this line at the top of the root file (usually src/lib.rs or src/main.rs) to enforce the absence of mem::forget in a crate via the Clippy lint mem_forget. ```rust #![deny(clippy::mem_forget)] ``` -------------------------------- ### Insert a check mark in a chapter Source: https://github.com/anssi-fr/rust-guide/blob/master/mdbook-plugins/mdbook-checklist/README.md Use the {{#check | }} format to insert a check mark. The mark is replaced by the name with an anchor. ```markdown # Chapter 1 {{#check Note-1 | This is an important note}} ``` -------------------------------- ### Cargo checksum verification error Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/devenv.md Error message shown when Cargo detects a checksum mismatch for a dependency, indicating possible corruption or a changed lock file. ```text error: checksum for `sha256 v1.6.0` changed between lock files this could be indicative of a few possible errors: * the lock file is corrupt * a replacement source in use (e.g., a mirror) returned a different checksum * the source itself may be corrupt in one way or another unable to verify that `sha256 v1.6.0` is the same as when the lockfile was generated ``` -------------------------------- ### C caller for add_in_place Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md C code that declares and calls the exported Rust function add_in_place, printing the result. Requires linking with the Rust library. ```c #include #include //! Add in place void add_in_place(uint32_t *a, uint32_t b); int use_add_in_place() { uint32_t x = 25; add_in_place(&x, 17); printf("%" PRIu32 " == 42", x); return 0; } ``` -------------------------------- ### Cargo.toml: Enable overflow checks in release profile Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/integer.md Sets overflow-checks to true in the release profile to enable overflow checks in release builds, overriding the default wrap-around behavior. ```toml [profile.release] overflow-checks = true # enable overflow checks in release builds ``` -------------------------------- ### Generated C header (counter.h) Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md C header generated by cbindgen from the Rust C-compatible API. It declares the Counter struct and the four exported functions with their signatures. ```c #include #include #include #include typedef struct Counter Counter; Counter *counter_create(void); int counter_destroy(Counter *counter); uint32_t counter_get(const Counter *counter); int counter_incr(Counter *counter); ``` -------------------------------- ### Rust: Safe wrapper for inc_wrap Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Safe wrapper function that takes a mutable reference and calls the unsafe inc_wrap, enforcing non-aliasing and mutability constraints. The C code does not free or retain the pointer beyond the call. ```rust fn safe_inc_wrap(a: &mut u8) { unsafe { inc_wrap(a); } } ``` -------------------------------- ### Unsafe make_room method that breaks invariant Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/generalities.md This safe code breaks the invariant by increasing capacity without allocating memory, leading to undefined behavior. It should not be exposed in the API or should be marked unsafe. ```rust impl Vec { pub fn make_room(&mut self) { // grow the capacity self.cap += 1; } } ``` -------------------------------- ### Rust and C: swap function causing UB due to aliasing Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Rust function that swaps two bytes via mutable references, and C code that calls it with the same pointer for both arguments. This violates Rust's aliasing rules and produces undefined behaviour. ```rust extern "C" fn swap(a: *mut u8, b: *mut u8) { let a = unsafe { a.as_mut() }.unwrap(); let b = unsafe { b.as_mut() }.unwrap(); std::mem::swap(a, b); } ``` ```c void use_swap() { uint8_t a = 42; swap(&a, &a); } ``` -------------------------------- ### Change the index title in book.toml Source: https://github.com/anssi-fr/rust-guide/blob/master/mdbook-plugins/mdbook-checklist/README.md Override the default 'Checklist' title of the generated index. ```toml [preprocessor.checklist] title = "A list of notes" ``` -------------------------------- ### C: inc_wrap function increments a byte Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md C function that increments a uint8_t variable, wrapping from 255 to 0. Used to illustrate how Rust code must respect the memory model when passing pointers to C. ```c void inc_wrap(uint8_t *a) { if (*a == 255) { *a = 0; } else { *a = *a + 1; } } ``` -------------------------------- ### Rust: Option-wrapped function pointer in FFI Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Use an Option-wrapped function pointer to check against null at the FFI boundary. The function pointer type is marked extern and unsafe as required by the rule FFI-MARKEDFUNPTR. ```rust #[unsafe(no_mangle)] pub unsafe extern "C" fn repeat( start: u32, n: u32, f: Option u32>, ) -> u32 { if let Some(f) = f { let mut value = start; for _ in 0..n { value = unsafe { f(value) }; } value } else { start } } ``` -------------------------------- ### Export C-compatible function with #[unsafe(no_mangle)] Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Declares an extern "C" function that can be called from C code. The #[unsafe(no_mangle)] attribute preserves the function name for linking. Returns 0 if the parameter equals 0xCAFEBABE, otherwise -1. ```rust /// Export C-compatible function #[unsafe(no_mangle)] extern "C" fn mylib_f(param: u32) -> i32 { if param == 0xCAFEBABE { 0 } else { -1 } } ``` -------------------------------- ### Rust: Unsafe binding to inc_wrap and call with immutable pointer Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Rust code that declares an unsafe extern function inc_wrap and calls it with a pointer cast from an immutable variable, violating Rust's memory model and resulting in undefined behaviour. ```rust unsafe extern "C" { fn inc_wrap(a: *mut u8); } fn run_inc() { let val: u8 = 6; let p = (&val as *const u8) as *mut u8; unsafe { inc_wrap(p) }; } ``` -------------------------------- ### Rust: Define foreign opaque type with dedicated struct Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Recommended way to bind foreign opaque types using a dedicated Rust type instead of c_void. The struct is marked #[repr(C)] and contains a zero-sized private array to prevent instantiation. ```rust #[repr(C)] pub struct OpaqueFoo { _private: [u8; 0], } unsafe extern "C" { fn handle_opaque_foo(arg: *mut OpaqueFoo); } ``` -------------------------------- ### Drop a tuple with mem::drop Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/memory.md Shows the safe use of mem::drop to trigger early memory reclamation and call associated destructors. This is memory safe in Rust. ```rust let pair = ('↑', 0xBADD_CAFEu32); drop(pair); ``` -------------------------------- ### Leak memory with mem::forget Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/memory.md Demonstrates the unsafe use of mem::forget, which skips destructor calls and leaks memory. This is marked as bad and unsecure because it can lead to deadlocks or not erasing sensitive data. ```rust let s = String::from("Hello"); forget(s); // Leak memory ``` -------------------------------- ### Memory leak with cyclic Rc and Cell in safe Rust Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/standard.md Shows a memory leak in safe Rust by combining Rc, Cell, and a recursive type. The cycle prevents reference counts from reaching zero, causing a leak. The output from valgrind confirms the leak. ```rust use std::{cell::Cell, rc::Rc}; struct LinkedStruct { other: Cell>>, } fn main() { println!("Hello, world!"); let a = Rc::new(LinkedStruct { other: Cell::new(None), }); let b = Rc::new(LinkedStruct { other: Cell::new(None), }); let aa = a.clone(); let bb = b.clone(); a.other.set(Some(bb)); b.other.set(Some(aa)); } ``` ```text $ valgrind --leak-check=full target/release/safe-rust-leak ==153637== Memcheck, a memory error detector ==153637== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al. ==153637== Using Valgrind-3.19.0 and LibVEX; rerun with -h for copyright info ==153637== Command: target/release/safe-rust-leak ==153637== Hello, world! ==153637== ==153637== HEAP SUMMARY: ==153637== in use at exit: 48 bytes in 2 blocks ==153637== total heap usage: 10 allocs, 8 frees, 3,144 bytes allocated ==153637== ==153637== 48 (24 direct, 24 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2 ==153637== at 0x48417B4: malloc (vg_replace_malloc.c:381) ==153637== by 0x10F8D4: safe_rust_leak::main (in /home/toto/src/safe-rust-leak/target/release/safe-rust-leak) ==153637== by 0x10F7E2: std::sys::backtrace::__rust_begin_short_backtrace (in /home/toto/src/safe-rust-leak/target/release/safe-rust-leak) ==153637== by 0x10F7D8: std::rt::lang_start::{{closure}} (in /home/toto/src/safe-rust-leak/target/release/safe-rust-leak) ==153637== by 0x12A90F: std::rt::lang_start_internal (in /home/toto/src/safe-rust-leak/target/release/safe-rust-leak) ==153637== by 0x10FA54: main (in /home/toto/src/safe-rust-leak/target/release/safe-rust-leak) ==153637== ==153637== LEAK SUMMARY: ==153637== definitely lost: 24 bytes in 1 blocks ==153637== indirectly lost: 24 bytes in 1 blocks ==153637== possibly lost: 0 bytes in 0 blocks ==153637== still reachable: 0 bytes in 0 blocks ==153637== suppressed: 0 bytes in 0 blocks ==153637== ==153637== For lists of detected and suppressed errors, rerun with: -s ==153637== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) ``` -------------------------------- ### Prevent automatic Send/Sync implementation with PhantomData Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/standard.md Use a PhantomData<*const ()> field to opt out of automatic Send and Sync implementations for a type. The raw pointer type is neither Send nor Sync, so the compiler will not auto-implement these traits for the struct. ```rust # use std::marker::PhantomData; # struct SpecialType(u8, PhantomData<*const ()>); ``` -------------------------------- ### Catch panics in FFI with catch_unwind Source: https://github.com/anssi-fr/rust-guide/blob/master/src/en/unsafe/ffi.md Use std::panic::catch_unwind to handle panics in Rust code called from foreign code. The function returns 0 on success and -1 on panic. Note that catch_unwind only catches unwinding panics, not aborts. ```rust fn may_panic() { /* Something may panic... */ } #[unsafe(no_mangle)] pub unsafe extern "C" fn no_panic() -> i32 { let result = catch_unwind(may_panic); match result { Ok(_) => 0, Err(_) => -1, } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.