Skip to content

Fix value-validity checks for initialization stores and field projections - #5057

Merged
feliperodri merged 10 commits into
model-checking:mainfrom
v3risec:fix/value-validity-place-access
Nov 13, 2026
Merged

feliperodri merged 10 commits into
model-checking:mainfrom
v3risec:fix/value-validity-place-access

Conversation

@v3risec

@v3risec v3risec commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix false positives in -Z valid-value-checks when initializing storage, forming raw pointers to fields, or accessing initialized fields of partially initialized structures.

Previously, the checker validated an entire raw-pointer pointee whenever it encountered a ProjectionElem::Deref, even when the operation did not consume the old value.

This caused valid operations such as Box::new initialization and &raw mut (*inner).strong to fail with spurious invalid-value checks.

Changes

  • Classify MIR Place accesses by their operation semantics: read, store, raw address, shared/mutable borrow, and drop.
  • Avoid checking unconsumed destination values during stores and raw address formation.
  • Check the final projected field rather than the entire enclosing structure for supported struct/tuple projections.
  • Preserve validity checks for actual reads, reference creation, intermediate pointer/reference loads, and drops.
  • Support precise access to pattern-type fields while avoiding unsupported stable type-kind conversions.
  • Retain conservative checking for unsupported projection forms.

Tests

Added 7 regression test files (.rs and .expected pairs), containing 25 proof harnesses:

  • 16 positive harnesses covering initialization, field access, nested projections, packed fields, pattern types, and call destinations.
  • 9 negative harnesses covering invalid values, reference construction, intermediate reference loads, and drops.

The tests were consolidated from independently tested regression cases.

Limitations

This change does not address existing unsupported checks for mutable casts, copy_nonoverlapping, trait objects, or the separate limitations of -Z uninit-checks.

An earlier full regression attempt encountered a Z3 timeout in Quantifiers/gcd_invariant.rs; the same test also timed out on the unmodified baseline.

Resolves #5056

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.

@v3risec

v3risec commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

The branch is up to date with current main. CI on the latest head is waiting for workflow approval.

This fixes false positives in -Z valid-value-checks during initialization stores, raw field-address formation, and access to initialized fields of partially initialized structures (#5056).

Would appreciate workflow approval when convenient. Happy to rebase again if needed. Thanks!

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.

🔵 Needs a closer look

Soundness-critical MIR validity instrumentation relies on runtime-MIR access classification and projection guarantees that require compiler-expert validation and regression execution with the pinned Rust/CBMC toolchain before approval.

No open issues 🎉

What changed in this PR

This PR addresses #5056 by making Kani’s experimental value-validity checks distinguish operations that consume existing values from stores and raw-address formation, reducing false positives during initialization and partial-structure access.

Changes:

  • Classifies place accesses by operation while preserving checks for reads, borrows, intermediate loads, and drops.
  • Checks final projected fields for supported projections, including pattern-type fields, while retaining conservative handling elsewhere.
  • Adds 25 regression harnesses across seven test pairs covering valid operations and invalid-value detection.
File Description
tests/​expected/​valid-value-checks/​place_access_valid.rs Tests initialization and access to initialized fields.
tests/​expected/​valid-value-checks/​place_access_valid.expected Requires successful verification of 12 harnesses.
tests/​expected/​valid-value-checks/​place_access_pattern.rs Tests raw addresses and invalid reads of pattern-type fields.
tests/​expected/​valid-value-checks/​place_access_pattern.expected Records expected pattern-field successes and failure.
tests/​expected/​valid-value-checks/​place_access_packed.rs Tests packed-field reads and raw addresses.
tests/​expected/​valid-value-checks/​place_access_packed.expected Requires successful packed-field verification.
tests/​expected/​valid-value-checks/​place_access_invalid.rs Tests invalid boolean reads and borrows.
tests/​expected/​valid-value-checks/​place_access_invalid.expected Requires validity failures for five harnesses.
tests/​expected/​valid-value-checks/​place_access_intermediate.rs Tests invalid intermediate reference loads.
tests/​expected/​valid-value-checks/​place_access_intermediate.expected Requires failures for both intermediate-reference cases.
tests/​expected/​valid-value-checks/​place_access_drop.rs Tests dropping an invalid value before replacement.
tests/​expected/​valid-value-checks/​place_access_drop.expected Requires detection of the invalid dropped value.
tests/​expected/​valid-value-checks/​place_access_call_destination.rs Tests initialization through a projected MIR call destination.
tests/​expected/​valid-value-checks/​place_access_call_destination.expected Requires successful call-destination verification.
kani-compiler/​src/​kani_middle/​transform/​check_values.rs Adds operation-aware validity checks and precise field handling.

Review effort: Balanced

@feliperodri feliperodri self-assigned this Nov 13, 2026

@feliperodri feliperodri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @v3risec. Classifying place accesses is the right fix: a store or &raw doesn't consume the old value, and a read of (*p).f only loads f, so checking the whole pointee was too strict. Everything outside the supported shape (one leading raw deref plus struct/tuple fields) still falls back to the existing checks, and unclassified rvalues reset to conservative rather than inheriting Store.

I built the head and ran the validity suites (expected/valid-value-checks, the related expected tests, kani ValidValues and kani Uninit); all pass, and 4 of the 7 new tests fail on the base checker. Both repros from #5056 now verify. To check that real invalid values are still caught, I tried whole-struct reads after a partial field store, and enum, char, nested and tuple field reads through a raw pointer with invalid bytes; all are still reported.

Optional: a negative test for the whole-struct read after a partial store would pin the main boundary of this change, e.g. write (*p).a = true with b holding 2, then let v: Pair = *p; must fail. For Rc<bool> from the issue, Rc::new still stops at the mutable-cast unsupported check, which you listed as out of scope.

I've approved the CI runs; please make sure they pass.

@feliperodri feliperodri added [F] Spurious Failure Issues that cause Kani verification to fail despite the code being correct. Z-UnstableFeature Issues that only occur if a unstable feature is enabled labels Nov 13, 2026
@feliperodri feliperodri removed their assignment Nov 13, 2026
@feliperodri
feliperodri added this pull request to the merge queue Nov 13, 2026
Merged via the queue into model-checking:main with commit 7be389c Nov 13, 2026
23 of 29 checks passed
@feliperodri feliperodri added this to the Valid value checks milestone Nov 18, 2026
feliperodri added a commit to feliperodri/kani that referenced this pull request Nov 25, 2026
…odel-checking#5205)

`-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:

- `write_bytes` of an invalid pattern was reported at the write, even
when nothing read it, and
  even with `count == 0` (model-checking#5190).
- `copy_nonoverlapping` and mutable casts to other pointee types were
reported as unsupported, so
  every harness that reached them failed (model-checking#3762).
- `ptr::copy` of invalid bytes into a `char` was not checked at all (a
missed UB that Miri reports).
- A store through a `*const u8` round-trip or a transmuted `&mut u8`
that wrote an invalid `bool`
  was not reported (model-checking#5021).

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 model-checking#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
model-checking#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 model-checking#649, filters
`intrinsics`, `ptr`, `mem` and
`copy_from_slice`; 721 harnesses; with `--object-bits 12` as in its CI,
on Kani c5e65fd with model-checking#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
(model-checking#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 (model-checking#5022, PR model-checking#5073) and
aggregate-layout enum discriminants
(model-checking#5023, PR model-checking#5069).

Resolves model-checking#3762, model-checking#5021, model-checking#5190, model-checking#5194.

Testing: new `tests/expected/valid-value-checks/copies.rs` (13
harnesses, Miri-checked: 4 report
UB, 9 verify) and `untyped_store.rs` (model-checking#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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[F] Spurious Failure Issues that cause Kani verification to fail despite the code being correct. Z-CompilerBenchCI Tag a PR to run benchmark CI Z-EndToEndBenchCI Tag a PR to run benchmark CI Z-UnstableFeature Issues that only occur if a unstable feature is enabled

Projects

None yet

Development

Successfully merging this pull request may close these issues.

-Z valid-value-checks reports invalid values during initialization and raw field-address formation

3 participants