Skip to content

Valid-value checks: check multi-variant enums, function items, vtables, trait objects, references and Box - #5216

Draft
feliperodri wants to merge 15 commits into
model-checking:mainfrom
feliperodri:valid-value-gaps
Draft

feliperodri wants to merge 15 commits into
model-checking:mainfrom
feliperodri:valid-value-gaps

Conversation

@feliperodri

Copy link
Copy Markdown
Member

This is stacked on #5205 and should be reviewed after it: the first commits in this PR are #5205's. It stays a draft until #5205 merges.

With -Z valid-value-checks, Kani reported an unsupported check for several kinds of types, or missed invalid values in them. verify-rust-std's Challenge 2 job (model-checking/verify-rust-std#777) lists these as the limits of what it can claim, and verify-rust-std#639's Box challenge is blocked on the dyn case. This PR makes Kani check them.

Enums.

Function pointers were already checked to be non-null. A function item, which is a zero-sized type, no longer makes the struct or closure that holds it unsupported (#3760).

Vtables. The metadata of a pointer to dyn Trait must be a vtable the program created for Trait (#3738).

  • Kani records every vtable it generates, and every cast that reuses a vtable for another trait object type.
  • The check calls one function per trait. Its body, generated at the end of codegen, compares the metadata with those vtables.
  • It applies to references, Box, raw pointers (as Miri checks them) and ptr::from_raw_parts.

Trait objects. Dereferencing a pointer to a trait object is checked at its dynamic type instead of being reported unsupported (#5215): the generated function also checks the value at the type its vtable was generated for. Casting a *mut dyn Trait to a restricted pointer type is allowed, because #5205 already checks the reads that cover a store through it.

References and Box must be aligned to their pointee's static alignment, and a slice behind one must keep its size under isize::MAX (part of #3759). Kani still requires the target of a reference to be valid.

Checks that existed before are kept or made stricter. Cases this can't express are still reported as unsupported. What is not checked:

The vtable check is keyed by the principal trait only, so it ignores projection bounds. This can only miss a report, never add a false one.

Testing.

Fixes #3738, #3760, #3761, #5023, #5215. Part of #3759.

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.
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.
The validity of a directly tagged enum was the valid range of the first
scalar of its layout. An enum whose layout is not a scalar or a scalar
pair, such as `#[repr(u8)] enum G { A(u32, u32), B }`, has none, so an
invalid tag was not reported at all (model-checking#5023).

Take the tag from the enum's layout instead: its scalar and its offset
(`VariantsShape::Multiple { tag, tag_field }`). The tag must also be the
discriminant of an inhabited variant, not just in the range that spans
the discriminants, which matters for sparse discriminants
(`enum E { A = 1, B = 5 }`). The valid tags are checked as a few ranges,
so `ValidityRange::Multiple` now holds any number of them; an enum with
more than 16 gaps falls back to the tag's valid range.

Enums whose variants' fields have requirements are still reported as
unsupported here; the next commit checks them.

Fixes model-checking#5023.

Signed-off-by: Felipe R. Monteiro <[email protected]>
…ects

A multi-variant enum whose variants' fields have validity requirements
(`enum E { A(bool), B(char) }`, `Option<char>`, nested enums) was
reported as unsupported (model-checking#3761). The requirements were a flat list of
byte ranges, which can't say that a field only has to be valid in the
variant that the tag selects.

Add guards to a requirement: it applies only if the value of the tag at
the guard's offset is in the guard's range. The fields of each variant
get the guard of the tag values that encode the variant:
 - for a directly tagged enum, the variant's discriminant;
 - for a niche-encoded enum, the niche value of the variant, or every
   value outside the niche values for the untagged variant, as rustc
   decodes it.
Nested enums stack one guard per enum. A requirement without guards is
encoded as before, so the common case costs nothing more; a guarded one
becomes `!guard_1 || ... || valid`. The tag of a niche-encoded enum is
checked against its valid range, and a variant that is uninhabited but
not absent from the layout is invalid.

The niche-encoded enums whose layout is a scalar with a single-range
payload keep the cheaper check of the enum's scalar range.

Fixes model-checking#3761.

Signed-off-by: Felipe R. Monteiro <[email protected]>
Function pointers are already checked to be non-null, alone, in an
`Option` (whose `None` is null) and in structs and enums, through the
valid range of their layout's scalar. A function item, however, is a
zero-sized type and was reported as unsupported, which made any struct,
tuple or closure that holds one unsupported. Any value of it is valid.

Add tests for function pointers in all these positions.

Fixes model-checking#3760.

Signed-off-by: Felipe R. Monteiro <[email protected]>
…vtable

The metadata of a pointer to a `dyn Trait` must be a pointer to a vtable
the compiler generated for `Trait` (model-checking#3738). Nothing checked it, so
`ptr::from_raw_parts` with forged metadata, or a transmute or a typed
read of a wide pointer, verified.

The vtables a program can create are the ones Kani generates while it
codegens the program: one for each unsizing coercion (and for the
supertraits its vtable points to), and the vtables in constants. A
vtable can also be reused for another trait object type: a cast of
`dyn A + Send` to `dyn A` or to `dyn Send`, or of `dyn Sub` to a
supertrait whose vtable is a prefix of `Sub`'s. Valid metadata is then
the address of one of these vtables, at offset 0, and CBMC can check it
with pointer equality.

The set is only complete once the whole harness has been codegened, so
the instrumentation calls the hook `valid_vtable::<dyn Trait>(vtable)`,
which codegen turns into a call to a function per trait, keyed by the
principal trait with its regions erased. Its body, generated at the end
of codegen, compares the vtable with each vtable recorded for the trait
and for the traits whose vtables the program reuses for it.

The requirement applies to the metadata of references, `Box` (through
its `NonNull`) and raw pointers, as Miri checks it for raw pointers too,
and to a wide pointer built from its parts (`AggregateKind::RawPtr`).

Fixes model-checking#3738.

Signed-off-by: Felipe R. Monteiro <[email protected]>
A dereference of a raw pointer or a `Box` to a `dyn Trait` was reported
as unsupported, since the pointee's type is only known from its vtable
(model-checking#5215). This blocked every harness that calls a method through a
`Box<dyn Any>`, such as `downcast`.

Kani requires the target of a reference to be valid, and a dereference
of a raw pointer to a sized type checks its pointee. Do the same for a
trait object, at the type its vtable was generated for: the
instrumentation calls the hook `valid_dyn_value::<T>(ptr, tail_offset)`,
which codegen turns into a function per trait whose body, generated
with the vtables, checks
`vtable == &vtable_i && valid_i(data + align_up(tail_offset, align_i))`
for each vtable of the trait, where `valid_i` is the validity of the
type the vtable is for, from the same requirements as the MIR checks.
A vtable that is not one of them is invalid. A type the requirements
can't express is reported as unsupported in its branch only.

The trait object at the tail of a struct (`RcInner<dyn Trait>`) is
checked at its offset rounded up to its dynamic alignment. A struct
with an unsized tail at the tail of another is still reported as
unsupported, since its offset depends on the trait object's alignment.

A cast of a pointer to a trait object to a pointer to a type with
validity requirements (`*mut dyn Any` to `*mut bool` in
`Box::downcast_unchecked`) was a "mutable cast" Kani can't check. A trait
object is only read at its dynamic type: by a dereference of a raw
pointer to it, checked as above, or by the code its vtable points to,
through references to the concrete type. A store through the cast
pointer is recorded as untyped, so the reads that cover it are checked;
allow the cast if Kani can express the validity of the target type.

Fixes model-checking#5215.

Signed-off-by: Felipe R. Monteiro <[email protected]>
…ices

A reference or a `Box` must be non-null, which was checked, aligned, and
point to a value whose size, for a slice, doesn't exceed `isize::MAX`
(model-checking#3759). Check the alignment against the static alignment of the
pointee, and the length of a slice (or `str`) tail against
`(isize::MAX - prefix) / size_of::<Elem>()`, where the prefix is the
size of the pointee's sized fields. Both are necessary conditions, never
stronger than the real ones: a trait object's dynamic alignment is not
checked, and the bound doesn't round the size up to the alignment.

`Box<T>` gets the same requirements as `&T`. With the previous commits,
this checks `&Box<T>` and `Box<T>` read from memory, and `Box<dyn Trait>`,
which were the gaps verify-rust-std's Challenge 2 harnesses could reach.
The target of a reference is still required to be valid where Kani
checks it (a reference formed through a raw pointer), the stricter
reading of UCG#77. Whether a reference dangles is not checked.

Fixes model-checking#3759.

Signed-off-by: Felipe R. Monteiro <[email protected]>
List the requirements the checks cover now (enum tags and variant
fields, function pointers, references and `Box`, vtables and trait
objects), and what they don't (dangling references, slices behind a
pointer).

Signed-off-by: Felipe R. Monteiro <[email protected]>
@feliperodri feliperodri added [F] Soundness Kani failed to detect an issue [C] Feature / Enhancement A new feature request or enhancement to an existing feature. labels Nov 21, 2026
@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 21, 2026

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] Feature / Enhancement A new feature request or enhancement to an existing feature. [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

1 participant