使不安全的 Rust 稍微更安全一些:用于验证不安全代码的工具,包括 C 和 C++ 中的库

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.
阅读 4
0 条评论