FAQ - Help and questions

How do I write and review a SAFETY comment for an unsafe block?

#security#unsafe#code-reviewpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Each unsafe block needs a comment that names the condition the compiler cannot check and says why it holds there, and each unsafe function needs a Safety section for its callers. Reviewers check the claim against the surrounding code. Clippy can require the comment, and Miri can test the code.

Checked with rustc 1.93.0, Windows 11 (Clippy and Miri were not run for this thread)

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

unsafe means: "the compiler cannot prove this is sound, and I take responsibility". The comment is where that responsibility is written down, so a reviewer can check it. A good comment states the specific condition and where it was established, not "this is fine".

src/main.rsrust
/// Return the byte at `i`, or None when `i` is out of range.
fn byte_at(data: &[u8], i: usize) -> Option<u8> {
    if i >= data.len() {
        return None;
    }
    // SAFETY: `i < data.len()` was checked on the lines above, so the index is in bounds.
    Some(unsafe { *data.get_unchecked(i) })
}

fn main() {
    let data = [1u8, 2, 3];
    println!("{:?} {:?}", byte_at(&data, 2), byte_at(&data, 3));
}
text
Some(3) None

The block uses get_unchecked, which skips the bounds check; the comment names the condition (i < data.len()) and points to the lines that check it. If someone later deletes the if, the comment makes the mistake visible.

How to review one#

  1. Which condition does this operation require? (Pointer valid and aligned, index in range, value initialised, no overlapping mutable access, valid UTF-8, and so on. The documentation of the unsafe function lists them under "Safety".)
  2. Is that condition guaranteed by the code around it, for every possible input, including empty input and extreme values?
  3. Could another safe function in the same module break the condition (for example by changing a length field)? If so, the invariant belongs to the whole module: write it down and keep the fields private.
  4. Is there a safe alternative that is fast enough? get instead of get_unchecked is usually the answer; measure before choosing the unchecked form.
  5. Is there a test that would fail if the condition were broken?

Tools#

  • Clippy has an optional lint clippy::undocumented_unsafe_blocks that warns when an unsafe block has no // SAFETY: comment. Enable it in the crate with #![warn(clippy::undocumented_unsafe_blocks)]. It is listed in the Clippy lint index; this thread did not run it.
  • Miri is an interpreter that runs your tests and reports many kinds of undefined behaviour. It needs a nightly toolchain component: cargo +nightly miri test. It was not available on the toolchain used for this thread and was not run. Read its README for its limits: it checks what the test executes, nothing more.
  • Sanitizers and fuzzing (see the thread on fuzzing) find bugs that tests with expected inputs miss.

Common mistakes#

  • Comments that restate the code ("SAFETY: we dereference the pointer").
  • A comment on the block but no # Safety section on the function, so callers do not know what they promised.
  • Treating Miri as proof. It finds problems; a clean run does not show their absence.

Who is responsible when a safe function wraps unsafe code?#

The author of the wrapper. A safe function must be sound for all inputs. If it is not, it must be marked unsafe.

Do I need a SAFETY comment on a block inside a test?#

The lint applies to tests too if enabled. Keeping the habit costs little, and tests are where such code is first exercised.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet