Skip to content

Valid-value checks: check reads of untyped bytes, not untyped writes - #5205

Merged
feliperodri merged 7 commits into
model-checking:mainfrom
feliperodri:valid-value-untyped-writes
Nov 25, 2026
Merged

feliperodri merged 7 commits into
model-checking:mainfrom
feliperodri:valid-value-untyped-writes

Conversation

@feliperodri

@feliperodri feliperodri commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

-Z valid-value-checks reports UB in the wrong place for byte-level writes, and misses some UB
altogether. 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_bytes
docs). Before this change:

This change tracks one nondeterministically chosen byte, as -Z uninit-checks does, and records
whether 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 requirements
mark 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 as
unsupported 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 to
bool's.

Effect on verify-rust-std's Challenge 2 harnesses (PR #649, filters intrinsics, ptr, mem and
copy_from_slice; 721 harnesses; with --object-bits 12 as in its CI, on Kani c5e65fd with #5057
and this change ported):

Verified Failed Wall time
Kani c5e65fd, -Z valid-value-checks 652 69 33 min
With this change, -Z valid-value-checks 717 4 51 min
With this change, no flag 721 0 27 min

Most of the 65 harnesses that now verify failed on unsupported copy_nonoverlapping or mutable
casts. The four that still fail (check_transmute{,_unchecked}_{ref_address,slice_metadata}) take a
reference to PointerGenerator memory that may be uninitialized; that's UB under Miri's recursive
validation and needs kani::assume(arb.is_initialized) in the harnesses. Stock Kani looks cheaper
because many of its harnesses stop at the first unsupported check.

Where I'd like input:

  • Reads of closure captures (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).
  • Forming a reference to bytes that may be untyped is checked, as Kani already does for &*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.
  • Tracking one nondeterministic byte means each run checks one byte per path. That matches
    -Z uninit-checks, and it's what keeps the cost to about 1.9x of an unchecked run on
    Challenge 2.
  • The validity and initialization models don't instrument each other (is_instrumentation_model
    and 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 report
UB, 9 verify) and untyped_store.rs (#5021), updated write_bytes.rs, write_invalid.rs and
custom_niche.rs, tests/kani/ValidValues/write_unaligned_scalar_struct.rs, and a UI test for the
quantifier rejection. On the rebased branch: the expected, ui, kani and cargo-kani suites 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.

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.
@feliperodri
feliperodri requested review from a team as code owners November 19, 2026 18:08
@feliperodri feliperodri added this to the Valid value checks milestone Nov 19, 2026
@feliperodri
feliperodri requested a balanced review from Copilot November 19, 2026 18:09
@github-actions github-actions Bot added Z-EndToEndBenchCI Tag a PR to run benchmark CI Z-CompilerBenchCI Tag a PR to run benchmark CI labels Nov 19, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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
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 rajath-mk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@feliperodri
feliperodri added this pull request to the merge queue Nov 25, 2026
Merged via the queue into model-checking:main with commit 8c6dba5 Nov 25, 2026
34 checks passed
@feliperodri
feliperodri deleted the valid-value-untyped-writes branch November 25, 2026 17:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Z-CompilerBenchCI Tag a PR to run benchmark CI Z-EndToEndBenchCI Tag a PR to run benchmark CI

Projects

None yet

3 participants