Repository navigation
Valid-value checks: check reads of untyped bytes, not untyped writes - #5205
Conversation
Writing bytes that are invalid for a type is not undefined behavior; reading them as that type is. -Z valid-value-checks used to check `write_bytes` at the write, so it rejected valid programs (model-checking#5190), and it reported every `copy_nonoverlapping` and every cast of `*mut T` to a pointer to a less restrictive type as unsupported (model-checking#3762). It didn't check `ptr::copy` at all, so copying an invalid value into a typed place and reading it verified. Kani now records, for one byte chosen nondeterministically per harness (as -Z uninit-checks does), whether its last write was untyped: a copy, `write_bytes`, a volatile copy or set, a typed swap, or a store through a pointer of a type without validity requirements. A store of a type with validity requirements clears it. A typed read through a pointer, or of a local whose address is taken, checks the value it reads if it covers that byte and the byte was written untyped. Types whose validity Kani can't express are reported as unsupported only in that case. Reads of a closure's captured values are not checked: closure environments are built by typed aggregates, and quantifier predicates, which can't contain checks, read their captures this way.
…ingful The pass read the number of blocks once, so the blocks that instrumentation creates were never visited: after the first check in a basic block, the rest of the block went unchecked. On main, a second invalid raw-pointer read in the same block verifies when debug assertions don't split the block. Untyped-write tracking needs a write and a later read in the same block to both be instrumented (model-checking#5021's reproducers, now a test). A quantifier predicate that reads a restricted type through a captured reference now contains a check and is rejected (model-checking#5193). indirect_call.rs captures its function pointer by `move`, so it still reaches the error it tests, and captured_reference.rs records the rejection.
…s field A struct whose layout is a single scalar, such as the packed Unaligned<bool> that ptr::write_unaligned casts to, got its own scalar range and its field's, so its validity compared unequal to bool's and the mutable cast in write_unaligned::<bool> was reported as unsupported.
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical gaps in validity tracking and validation allow invalid values to escape detection through restricted aliases, closure captures, borrows, nested proof calls, and volatile operations.
6 open issues
Prevent nested proof calls from resetting pending validation · New Validate captures that can be corrupted through untyped writes · New Track restricted stores across differently restricted aliases · New Track volatile and atomic accesses to restricted values · New Validate pointees when borrowing or dropping restricted locals · New Record call-result stores to clear stale untyped-read state · New
What changed in this PR
Moves Kani’s opt-in validity checks from untyped byte writes to subsequent typed reads, addressing write-time false positives and missed invalid-value reads.
Changes:
- Adds a per-harness byte-tracking model and integrates it with compiler instrumentation, contracts, and initialization checks.
- Fixes instrumentation traversal after block splitting and deduplicates scalar-layout validity requirements.
- Adds regression tests, records quantifier limitations, and updates soundness documentation.
| File | Description |
|---|---|
tests/ui/quantifier-safety-checks/indirect_call.rs |
Uses move capture to preserve the indirect-call diagnostic test. |
tests/ui/quantifier-safety-checks/indirect_call.expected |
Updates the expected diagnostic location. |
tests/ui/quantifier-safety-checks/captured_reference.rs |
Tests rejection of restricted-value reads through captured references. |
tests/ui/quantifier-safety-checks/captured_reference.expected |
Records the expected quantifier rejection. |
tests/kani/ValidValues/write_unaligned_scalar_struct.rs |
Tests unaligned bool writes and scalar-wrapper casts. |
tests/expected/valid-value-checks/write_invalid.rs |
Updates documented semantics and renames the no-read harness. |
tests/expected/valid-value-checks/write_invalid.expected |
Expects failure only when invalid bytes are read. |
tests/expected/valid-value-checks/write_bytes.rs |
Adds read-after-write and zero-count cases. |
tests/expected/valid-value-checks/write_bytes.expected |
Updates expected byte-write outcomes. |
tests/expected/valid-value-checks/untyped_store.rs |
Adds pointer-cast and transmuted-reference regressions. |
tests/expected/valid-value-checks/untyped_store.expected |
Records invalid-bool failures and valid-byte success. |
tests/expected/valid-value-checks/custom_niche.rs |
Reads copied bytes to exercise custom validity requirements. |
tests/expected/valid-value-checks/custom_niche.expected |
Removes unsupported-copy expectations. |
tests/expected/valid-value-checks/copies.rs |
Adds copy, swap, byte-write, and collection cases. |
tests/expected/valid-value-checks/copies.expected |
Records outcomes for the 13 new harnesses. |
library/kani_core/src/valid_value.rs |
Defines the tracked-byte state and access helpers. |
library/kani_core/src/lib.rs |
Includes the validity model in generated Kani libraries. |
kani-compiler/src/kani_middle/transform/mod.rs |
Supplies model functions to the validity pass. |
kani-compiler/src/kani_middle/transform/check_values.rs |
Implements write tracking, conditional read checks, and traversal fixes. |
kani-compiler/src/kani_middle/transform/check_uninit/mod.rs |
Excludes validity-model functions from initialization instrumentation. |
kani-compiler/src/kani_middle/kani_functions.rs |
Registers the new validity-model functions. |
kani-compiler/src/codegen_cprover_gotoc/codegen/contract.rs |
Allows contracts to modify validity-tracking state. |
docs/src/soundness.md |
Documents read-time validation and nondeterministic byte tracking. |
Review effort: Balanced
Address the review of model-checking#5205: - Initialize the tracking state once: a harness can call another harness, and the nested call forgot the untyped writes made before it. - Check forming a reference, as for `&*ptr`; a closure is called through a borrow or a move of its value, so its captures are checked there. Compute the validity of closures from their captures. - Record stores of restricted types through a pointer as untyped: the pointer may alias memory of another restricted type. Types whose validity can't be expressed still clear the mark. - Treat volatile loads as typed reads, volatile stores as stores through the pointer, and atomic writes as untyped writes. The new test untyped_paths.rs has a harness for each path; Miri reports UB for each `ub_*` one.
…t borrow checks An unaligned volatile load can't be read as its type in place: check the loaded value after the call instead, if the source bytes were written untyped. An unaligned volatile store records the bytes it writes as untyped through the pointer. A borrow through a raw pointer is already checked unconditionally, so it doesn't need the check for untyped bytes too; the duplicate made two Challenge 2 harnesses on [bool; 32] run out of memory.
rajath-mk
left a comment
There was a problem hiding this comment.
Re-ran my 21 cases on 7d06f83 (same results as before), plus 19 new ones for this commit. The unaligned volatile store/load cases after untyped writes are caught, and the five borrow-through-raw-pointer cases (&(*p).flag, &(*p)[i] on [bool; 32] and on *const [bool], &mut *p, &*p) are still caught through DerefValidity, with no false alarms. One gap, also on main and still in #5216: a volatile load of a bool over plain u8 bytes, like read_volatile(bytes.as_ptr() as *const bool) with bytes = [2u8], or the unaligned version here, isn't reported, since both paths are gated on the bytes having been written untyped. read_unaligned of the same bytes is caught. Is it worth checking volatile loads unconditionally like DerefValidity does, or a follow-up? Not blocking. Heads-up: this now conflicts with main in check_uninit/mod.rs, because #4230 added the panic-permission models to the same skip list; keep both.
# Conflicts: # kani-compiler/src/kani_middle/transform/check_uninit/mod.rs


-Z valid-value-checksreports UB in the wrong place for byte-level writes, and misses some UBaltogether. Writing bytes that aren't a valid value of the memory's type is not UB; producing or
reading such a value is (Rust Reference, "Behavior considered undefined"; the
ptr::write_bytesdocs). Before this change:
write_bytesof an invalid pattern was reported at the write, even when nothing read it, andeven with
count == 0(-Z valid-value-checks:write_bytesreported as producing an invalid value, even withcount == 0#5190).copy_nonoverlappingand mutable casts to other pointee types were reported as unsupported, soevery harness that reached them failed (Add support to validity checks in the presence of
copy_nonoverlapping,copy. #3762).ptr::copyof invalid bytes into acharwas not checked at all (a missed UB that Miri reports).*const u8round-trip or a transmuted&mut u8that wrote an invalidboolwas not reported (
-Z valid-value-checks: writing an invalidboolthrough a*constround-trip or a transmuted&mut u8is not reported #5021).This change tracks one nondeterministically chosen byte, as
-Z uninit-checksdoes, and recordswhether its last write was untyped: copies,
write_bytes, volatile copies and sets,typed_swap_nonoverlapping, and stores through a pointer to a type without validity requirementsmark it; typed stores of restricted types clear it. A read of a restricted type through a
dereference, or of a local whose address is taken, checks validity when the bytes it reads are
marked. Types whose validity Kani can't express yet (e.g.
Option<char>) are reported asunsupported only when the bytes are marked, instead of on every copy. The model is in
library/kani_core/src/valid_value.rs.It also fixes #5194: the pass inserted only the first check of each basic block, because the
instrumentation loop used the block count from before it started splitting blocks. That bug hid
#5021's reproducers, and fixing it is part of what makes the new checks effective. And it stops
reporting
ptr::write_unaligned::<bool>as unsupported: a struct whose layout is a single scalar,like
Unaligned<bool>, listed that scalar's requirement twice, so its validity compared unequal tobool's.Effect on verify-rust-std's Challenge 2 harnesses (PR #649, filters
intrinsics,ptr,memandcopy_from_slice; 721 harnesses; with--object-bits 12as in its CI, on Kani c5e65fd with #5057and this change ported):
-Z valid-value-checks-Z valid-value-checksMost of the 65 harnesses that now verify failed on unsupported
copy_nonoverlappingor mutablecasts. The four that still fail (
check_transmute{,_unchecked}_{ref_address,slice_metadata}) take areference to
PointerGeneratormemory that may be uninitialized; that's UB under Miri's recursivevalidation and needs
kani::assume(arb.is_initialized)in the harnesses. Stock Kani looks cheaperbecause many of its harnesses stop at the first unsupported check.
Where I'd like input:
env.field,(*env).field) are not checked inside the closure's body. Instead, borrowing or moving a closure value is checked, which is how every call reaches it, so quantifier predicates don't contain checks. Predicates that read restricted types through a captured reference are still rejected (Quantifier predicates that read restricted types through captured references are rejected under -Z valid-value-checks #5193).&*ptr. That's stricter than Miri's default and matches-Zmiri-recursive-validation. Stores of restricted types through a pointer mark the bytes too, because the pointer may alias memory of another restricted type; that adds checks on reads after such stores.-Z uninit-checks, and it's what keeps the cost to about 1.9x of an unchecked run onChallenge 2.
is_instrumentation_modeland the uninit pass's
SKIPPED_ITEMS); without that, the quantifier tests didn't terminate.Not fixed here: slice element reads (#5022, PR #5073) and aggregate-layout enum discriminants
(#5023, PR #5069).
Resolves #3762, #5021, #5190, #5194.
Testing: new
tests/expected/valid-value-checks/copies.rs(13 harnesses, Miri-checked: 4 reportUB, 9 verify) and
untyped_store.rs(#5021), updatedwrite_bytes.rs,write_invalid.rsandcustom_niche.rs,tests/kani/ValidValues/write_unaligned_scalar_struct.rs, and a UI test for thequantifier rejection. On the rebased branch: the
expected,ui,kaniandcargo-kanisuites pass, as do fmt and clippy.By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.