Skip to content

Check slice element reads under -Z valid-value-checks - #5073

Open
kasimte wants to merge 3 commits into
model-checking:mainfrom
kasimte:fix-5022-slice-element-validity
Open

kasimte wants to merge 3 commits into
model-checking:mainfrom
kasimte:fix-5022-slice-element-validity

Conversation

@kasimte

@kasimte kasimte commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #5022.

-Z valid-value-checks did not report an invalid value read as one element through a slice pointer. A slice [T] carries no static length, so the whole-slice dereference checks no elements, and the indexed read was checked nowhere.

The fix checks the element in the Index/ConstantIndex arm of visit_place when the base is a slice. It fires only on a direct load of the whole element: a reading_value flag (set in visit_operand) restricts the check to Copy/Move operands, and the index must be the last projection. So an address-of, a partial sub-element read, and a nested write are not falsely rejected. A symbolic index makes CBMC cover every element, so no length loop is needed.

A nested invalid sub-element read (e.g. (*p)[i][j]) is still not reported; this matches main, where the Index arm checked nothing.

Testing

tests/expected/valid-value-checks/slice_element.rs: an invalid bool read through *const [bool] fails Invalid value of type `bool` at a concrete and a symbolic index; valid elements, an address-only &raw const borrow, a partial read, and a nested write all verify.

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

@kasimte
kasimte requested review from a team as code owners October 27, 2026 18:11
@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 Oct 27, 2026
@feliperodri
feliperodri requested a balanced review from Copilot October 31, 2026 00:21

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

Critical validity-checking issues reject valid address-only raw borrows, partial reads, and nested assignments by validating values that are not actually read.

2 open issues
What changed in this PR

This PR addresses #5022 by extending Kani’s -Z valid-value-checks instrumentation to check indexed slice elements, whose validity is not checked by a whole-slice dereference.

Changes:

  • Add element validity checks for slice Index and ConstantIndex projections.
  • Add regression harnesses for invalid bool reads at concrete and symbolic indices, plus a valid-element control.
  • Record expected verification results for all three harnesses.
File Description
tests/​expected/​valid-value-checks/​slice_element.rs Adds slice-element validity regression harnesses.
tests/​expected/​valid-value-checks/​slice_element.expected Specifies two invalid-value failures and one successful verification.
kani-compiler/​src/​kani_middle/​transform/​check_values.rs Instruments indexed slice elements with validity checks.

Review effort: Balanced

The Index/ConstantIndex arm fired for any non-mutating use and for nested
writes, reporting false positives: an address-of (`&raw const (*p)[i]`) loads
no value, a partial read (`(*p)[i][j]`) reads only a subplace, and a nested
write (`(*p)[i][j] = x`) validated old contents. Track whether the operand
reads the value (Copy/Move) and fire only on a direct read of the whole
element. Add positive regressions for each case.
@feliperodri
feliperodri requested a balanced review from Copilot November 6, 2026 19:12
@feliperodri feliperodri self-assigned this Nov 6, 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.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

3 open issues
2 resolved since last review

Review effort: Lite

Comment on lines +590 to +609
let validity = ty_validity_per_offset(self.tcx, &self.machine, elem_ty, 0);
match validity {
Ok(ranges) if !ranges.is_empty() => {
self.push_target(SourceOp::BytesValidity {
target_ty: elem_ty,
rvalue: Rvalue::Use(
Operand::Copy(Place {
local: place.local,
projection: place.projection[..=idx].to_vec(),
}),
WithRetag::No,
),
ranges,
})
}
Err(_msg) => self.push_target(SourceOp::UnsupportedCheck {
check: "slice element read".to_string(),
ty: elem_ty,
}),
_ => {}
Comment on lines +506 to +513
fn visit_operand(&mut self, operand: &Operand, location: Location) {
// `Copy`/`Move` read the operand's value; other uses (`&raw`, `&`, stores) don't.
let prev = self.reading_value;
self.reading_value = matches!(operand, Operand::Copy(_) | Operand::Move(_));
self.super_operand(operand, location);
self.reading_value = prev;
}

})
}
Err(_msg) => self.push_target(SourceOp::UnsupportedCheck {
check: "slice element read".to_string(),

@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.

The fix covers the gap, and the replies show the address-only and deeper-projection cases are handled.

Before merge:

  1. This is a soundness gap, so please add [F] Soundness and [C] Bug.
  2. BytesValidity always builds an Operand::Copy, and the test only reads bools, which are Copy. Please test a move of a non-Copy element, or handle Move explicitly.
  3. Nit: keep the _msg reason from ty_validity_per_offset so UnsupportedCheck reports stay actionable.
  4. compile-timer-short failed. Please confirm it's the same CI issue as the other PRs.

@feliperodri feliperodri assigned kasimte and unassigned feliperodri Nov 7, 2026
@feliperodri feliperodri added [C] Bug This is a bug. Something isn't working. [F] Soundness Kani failed to detect an issue labels Nov 13, 2026
@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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[C] Bug This is a bug. Something isn't working. [F] Soundness Kani failed to detect an issue Z-CompilerBenchCI Tag a PR to run benchmark CI Z-EndToEndBenchCI Tag a PR to run benchmark CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

-Z valid-value-checks: reading an invalid element through a slice pointer is not reported

3 participants