Sanitizers Support

The rustc compiler contains basic support for following sanitizers:

  • AddressSanitizer a faster memory error detector. Can detect out-of-bounds access to heap, stack, and globals, use after free, use after return, double free, invalid free, memory leaks.
  • LeakSanitizer a run-time memory leak detector.
  • MemorySanitizer a detector of uninitialized reads.
  • ThreadSanitizer a fast data race detector.

How to use the sanitizers?

To enable a sanitizer compile with -Zsanitizer=... option, where value is one of address, leak, memory or thread. For more details how to use sanitizers please refer to the unstable book.

How are sanitizers implemented in rustc?

The implementation of sanitizers relies entirely on LLVM. It consists of compile time instrumentation passes and runtime libraries. The role rustc plays in the implementation is limited to the execution of the following steps:

  1. The sanitizer runtime libraries are part of the compiler-rt project, and will be built as an LLVM subproject when enabled in config.toml:

    sanitizers = true

    The runtimes are placed into target libdir.

  2. During LLVM code generation, the functions intended for instrumentation are marked with SanitizeAddress, SanitizeMemory, or SanitizeThread attribute. Currently those attributes are applied in indiscriminate manner. but in principle they could be used to perform instrumentation selectively.

  3. The LLVM IR generated by rustc is instrumented by dedicated LLVM passes, different for each sanitizer. Instrumentation passes are invoked after optimization passes.

  4. When producing an executable, the sanitizer specific runtime library is linked in. The libraries are searched for in target libdir relative to default system root, so that this process is not affected by sysroot overrides used for example by cargo -Zbuild-std functionality.

Additional Information