Rust has become popular for systems programming due to excellent performance and compile-time error elimination. Unsafe Rust can bypass these checks but is used in some libraries. Tools for verifying unsafe Rust code include sanitizers and Miri.
Sanitizers:
- Detect various programming errors at run-time by instrumenting code.
- Work with Rust's
rustc
using the LLVM compiler infrastructure. - For example, the AddressSanitizer can detect out-of-bounds access on the stack and heap. It inserts red-zones and tracks illegal memory access.
- To use, install the nightly toolchain and run with the appropriate flags. Compile-time optimizations can affect detection.
Miri:
- An interpreter that deterministically finds undefined behaviors in unsafe code.
- Works by interpreting Rust's Mid-Level Intermediate Representation.
- Can find out-of-bounds access, memory leaks, use of uninitialized data, etc.
- Like sanitizers, it relies on the nightly toolchain and is easy to install.
- Output is more specific and easier to interpret than sanitizers.
Libraries in C and C++:
- Miri can't interpret code called through the Rust Foreign Function Interface (FFI).
- For C or C++ libraries, compile them with the appropriate sanitizer enabled before calling from Rust.
- An example shows how to compile a C function with the AddressSanitizer and call it from Rust.
Conclusion:
- Most systems programmers shouldn't write unsafe code.
- Use sanitizers or Miri to test unsafe code to avoid errors.
- The next article will continue exploring tools for finding errors in Rust.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。