Skip to content

Uninit checks: support unions nested in other types and raw pointers to unions - #5196

Open
feliperodri wants to merge 10 commits into
model-checking:mainfrom
feliperodri:uninit-nested-unions
Open

feliperodri wants to merge 10 commits into
model-checking:mainfrom
feliperodri:uninit-nested-unions

Conversation

@feliperodri

@feliperodri feliperodri commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Resolves #5151.

Depends on #5192 (pointers to trait objects). Until it merges, this PR's diff includes its two commits; the change of this PR is the last commit.

-Z uninit-checks gave up, as unsupported, on any type with a union inside it: [MaybeUninit<T>; N] buffers, structs with a MaybeUninit field, and Kani's own PointerGenerator. It also gave up on raw pointers to unions. These are common in the standard library, so most of verify-rust-std's raw-pointer proofs stopped on them. This PR supports them, and fixes the precision bugs that showed up once those proofs could run.

Design

Union bytes are a third kind of byte. A type's layout used to split its bytes into data and padding. Now a union nested in a type contributes union bytes, recorded in a separate mask (UnionMask, in ty_layout.rs):

  • Checks: union bytes are not data bytes, so checking a value never requires them to be initialized. A union may hold uninitialized bytes in a valid value (MaybeUninit::uninit()).
  • Writes of a whole value: a union's bytes take the state of the source. Copies and moves of a place copy the state (AssignUnion). An aggregate built from union values (S { u }, [a, b], tuples) copies the state of each operand into its field. Any other write (e.g. [MaybeUninit::uninit(); N]) marks the union bytes uninitialized, which can only cause false alarms.
  • Marking without a write: when a value is marked initialized without being written (e.g. creating a pointer from a reference), its union bytes keep their state. New *_keep models in kani_core do this.

Raw pointers to unions. Reading or copying a whole union through a pointer needs no initialization. Writing one through a pointer (*p = u) copies its state. Reading a field checks the field's bytes at its address, as for a local.

Across calls. Arguments and return values that contain unions pass their state through the existing argument buffer. Return values use slot 0, loaded by the caller after the call (LoadReturnValue).

Transmutes out of a union. MaybeUninit::assume_init is a transmute from MaybeUninit<T> to T on this toolchain. The static check used to reject it as a transmute between incompatible layouts. Now, when the target's data bytes are union bytes in the source, the transmute checks those bytes of the source's memory at run time (CheckMasked).

Layouts that were missing. Closures (laid out as the tuple of their captures), and niche-encoded enums whose value is a single initialized scalar, such as Option<NonZero<usize>> (used by NonZero::new).

Bugs fixed along the way

Each was found while running verify-rust-std's Challenge 2 proofs, and has a regression test.

  • copy of several elements from untracked, hence initialized, memory marked only the first destination element initialized. Every multi-element copy could report a false uninitialized read. (multi-element-copy)
  • An overlapping copy could leave the tracked byte with the state of the source byte that used to be at that position. (multi-element-copy)
  • Copying the tracked offset to a lower destination offset underflowed.
  • In contract harnesses, statics start with arbitrary values, so the argument buffer could hold garbage and fail an assertion in load_argument. It is now emptied with the shadow memory. It is also now a field of the shadow memory static MEM_INIT_STATE, which every contract's write set already includes, so writes to it are not reported as assignments outside the write set. It stores the saved location as an object and an offset, like the tracked byte.
  • Assignments to a union place through a deref (*p = u) were not recognized as union assignments.
  • Operations inserted after an instruction do not run in the order they are pushed. A reset that must precede a copy now runs before the instruction.
  • Layout equality, which decides whether a pointer cast is a target of the delayed UB checks, treated a union byte and a padding byte as equal. It now compares union bytes too.

Tests

  • New: nested-unions (17 harnesses, including six moved from fixme_unions.rs), multi-element-copy, closure-and-niche-layouts, and fixme-contract-unions. Each _ok harness verifies and each _ub harness reports an uninitialized read.
  • fixme-contract-unions passes unions to and from a function under contract. Its results are correct, but each harness needs 10–25 GB, more than a CI runner has, so it is a fixme test until -Z uninit-checks: contract harnesses that pass unions across calls need 10–25 GB #5199 is fixed. That cost applies to any contract harness that passes unions across calls under -Z uninit-checks.
  • intrinsics: check_typed_swap_nonoverlapping_safe now verifies, as its name says it should. It failed only on unions behind raw pointers and on the NonZero::new transmute.
  • delayed-ub-unsupported-call: the cast that used to trigger the delayed UB analysis came from a type whose layout Kani could not compute before. Each harness now makes its own cast, so the test keeps covering calls through function pointers and vtables.
  • Still unsupported, kept in fixme_unions.rs: unions nested in unions, and transmutes into a union. Both are reported as unsupported, not passed silently.
  • Full regression: all suites pass except script-based-pre/cbmc_truncated_results and compiler_defaults, which fail identically without this change (jq is missing from my test image).

Effect on verify-rust-std

On a backport of #5192 and this PR to the Kani version verify-rust-std pins (c5e65fd), running Challenge 2's (model-checking/verify-rust-std#649) harnesses with -Z uninit-checks:

Before After
The 146 harnesses #649 added or changed 51 pass 128 pass; all 146 with the harness changes below
All 394 intrinsics::verify harnesses 303 pass (#733) all 394 with the harness changes below

The harness changes are in a verify-rust-std follow-up, model-checking/verify-rust-std#775. Some harnesses relied on can_dereference returning whether a byte is initialized. Under -Z uninit-checks it asserts it instead, so they failed on inputs their contracts exclude. With CI's flags, all 459 harnesses also pass on the pinned Kani with those changes.

@feliperodri
feliperodri requested review from a team as code owners November 18, 2026 20:36
@feliperodri feliperodri added [E] Unsupported Construct Add support to an unsupported construct Z-UnstableFeature Issues that only occur if a unstable feature is enabled Z-EndToEndBenchCI Tag a PR to run benchmark CI Z-CompilerBenchCI Tag a PR to run benchmark CI labels Nov 18, 2026
-Z uninit-checks reported any pointer to a trait object as unsupported, even where
nothing uninitialized is involved, e.g. size_of_val on a &dyn (model-checking#5166).

- Nothing is read at type dyn Trait: an unsized value cannot be loaded, copied or
  stored. Checks on a trait object pointee have nothing to check, so emit none; the
  concrete type's code that the vtable dispatches to is checked with its own layout.
- Marking a trait object pointee initialized only happens where a pointer to an
  existing value is created (from a reference, or for a drop). Creating a pointer does
  not change which bytes are initialized, so skip it: at worst, untracked bytes stay
  uninitialized, a false alarm rather than a missed one. Marking it uninitialized
  cannot be skipped soundly and stays unsupported.
- Unsizing a pointer to a sized value into a raw pointer to a trait object marks the
  value initialized with its concrete layout, as for other raw pointers created from
  references, instead of reporting it as unsupported.
- Reading a trait object's metadata marks its vtable header (size, alignment, drop)
  initialized: the vtable is constant data that the code generator emits, so its
  memory was never marked initialized.

Resolves model-checking#5166

Signed-off-by: Felipe R. Monteiro <[email protected]>
Address review comments:

- Creating a reference from a raw pointer to a trait object skipped the
  check, but the value behind it must be valid, and reads through the
  reference in the concrete method are not checked. Report it as unsupported,
  as for a transmute from such a pointer to a reference. A `Box`, like a
  reference, points to a valid value, so pointers read out of a `Box` are
  exempt. Taking the address of `*p` and reading its metadata stay unchecked:
  they read nothing.
- Unsizing a raw pointer to a sized value into a raw pointer to a trait
  object marked the pointee initialized. Only do so for references; a raw
  pointer keeps its pointee's state.

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

`-Z uninit-checks` reported as unsupported any type with a union inside it
(`[MaybeUninit<T>; N]`, structs with a `MaybeUninit` field, `PointerGenerator`)
and raw pointers to unions. Support them:

- Layouts record the bytes of nested unions in a separate mask. They are not
  data bytes, so checks never require them to be initialized. Writes of a whole
  value copy their state from the source, aggregates copy it from each operand,
  other writes reset it, and marking a value initialized without a write keeps
  it (new `*_keep` models).
- Reading or copying a whole union through a pointer needs no initialization;
  writing one copies its state; reading a field checks the field's bytes.
- Arguments and return values containing unions pass their state through the
  argument buffer (`LoadReturnValue` for return values).
- A transmute whose target's data bytes are union bytes in the source
  (`MaybeUninit::assume_init`) checks them in the source's memory
  (`CheckMasked`) instead of failing the static layout check.
- Layouts for closures and for niche-encoded enums whose value is a single
  initialized scalar (`Option<NonZero<usize>>`, used by `NonZero::new`).

Fix the precision bugs that surfaced once verify-rust-std's Challenge 2
harnesses could run:

- `copy` from untracked memory marked only the first destination element
  initialized; an overlapping `copy` could keep a stale state for the tracked
  byte; the tracked offset could underflow on a copy to a lower offset.
- In contract harnesses statics start arbitrary, so empty the argument buffer
  at initialization and add it to every contract's write set, like the shadow
  memory.
- Recognize union assignments through a deref (`*p = u`).
- Reset union bytes before the write, since operations inserted after an
  instruction do not run in push order.
- Layout equality, used to find delayed-UB targets, now compares union bytes.

Resolves model-checking#5151.

Signed-off-by: Felipe R. Monteiro <[email protected]>
The argument buffer that passes the state of unions across calls was a
static of its own, added to every contract's write set. Make it a field of
`MEM_INIT_STATE`, which every contract's write set already includes, so the
contract code generation no longer needs to know about it, and store the
saved location as an object and an offset rather than a pointer.

Contract harnesses that pass unions across calls still need 10-25 GB under
`-Z uninit-checks` (model-checking#5199), more than a CI runner has, so move
`contract-unions` to `fixme-contract-unions` until that is fixed. Its
expected results are unchanged.

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

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 gaps in union shadow-state propagation and reference-producing transmute checks can allow uninitialized reads to incorrectly verify.

5 open issues
What changed in this PR

Extends Kani’s -Z uninit-checks to support unions nested in other types and raw pointers to unions, addressing #5151. The diff also includes trait-object pointer support from #5192.

Changes:

  • Tracks union bytes separately from data and padding, preserving initialization state across assignments, calls, and returns.
  • Adds runtime checks for transmutes out of unions and fixes shadow-state handling for multi-element and overlapping copies.
  • Adds regression coverage for nested unions, trait objects, closures, and niche layouts; contract-union tests remain deferred under #5199.
File Description
tests/​expected/​uninit/​trait-objects/​main.rs Adds trait-object pointer regression harnesses.
tests/​expected/​uninit/​trait-objects/​expected Records trait-object verification results.
tests/​expected/​uninit/​nested-unions/​main.rs Tests nested unions, raw pointers, and transmutes.
tests/​expected/​uninit/​nested-unions/​expected Records nested-union verification results.
tests/​expected/​uninit/​multi-element-copy/​main.rs Tests multi-element and overlapping copies.
tests/​expected/​uninit/​multi-element-copy/​expected Records copy verification results.
tests/​expected/​uninit/​intrinsics/​expected Updates the safe typed-swap result.
tests/​expected/​uninit/​fixme-contract-unions/​main.rs Adds deferred contract argument and return tests.
tests/​expected/​uninit/​fixme-contract-unions/​expected Records intended contract-union results.
tests/​expected/​uninit/​fixme_unions.rs Retains unsupported cases and relocates supported tests.
tests/​expected/​uninit/​dyn-pointee-write/​main.rs Updates comments to describe supported reborrowing.
tests/​expected/​uninit/​dyn-pointee-write/​expected Changes the expected result to success.
tests/​expected/​uninit/​delayed-ub-unsupported-call/​main.rs Adds explicit casts to retain delayed-check coverage.
tests/​expected/​uninit/​closure-and-niche-layouts/​main.rs Tests closure captures and scalar niche layouts.
tests/​expected/​uninit/​closure-and-niche-layouts/​expected Records closure and niche verification results.
library/​kani_core/​src/​mem_init.rs Adds union-preserving models and revises copy and argument state.
kani-compiler/​src/​kani_middle/​transform/​kani_intrinsics.rs Adapts layout matching to union-mask fields.
kani-compiler/​src/​kani_middle/​transform/​check_uninit/​ty_layout.rs Adds union masks, transmute requirements, and layout support.
kani-compiler/​src/​kani_middle/​transform/​check_uninit/​relevant_instruction.rs Defines masked checks, return transfers, and pointer-marking operations.
kani-compiler/​src/​kani_middle/​transform/​check_uninit/​ptr_uninit/​uninit_visitor.rs Selects instrumentation for unions and trait-object pointers.
kani-compiler/​src/​kani_middle/​transform/​check_uninit/​mod.rs Generates the expanded initialization instrumentation.
kani-compiler/​src/​kani_middle/​kani_functions.rs Registers union-preserving initialization models.

Review effort: Balanced

model-checking#5192 merged as a squash of the two commits this branch already has, and main
has no other changes to the uninit-checks files, so the conflicts resolve to
this branch's version.

Signed-off-by: Felipe R. Monteiro <[email protected]>
Address review comments:

- A volatile store only marked the destination initialized, so storing
  `MaybeUninit::uninit()` over an initialized value hid the store. Copy the
  stored value's state into the destination, as for an assignment.
- Copying a value whose type contains unions copied the whole layout, and the
  data and padding bytes were then marked by a separate operation, whose
  order relative to the copy is not fixed: the source's padding state could
  overwrite the destination's. Copy only the union bytes
  (`copy_init_state_masked`), so the two operations are independent.
- A transmute from a union that can hold a raw pointer to a reference checked
  the union's bytes, but not the value the reference points to, and reads
  through references are not checked. Check it, and report other targets that
  contain references as unsupported. A union that only holds references
  (`MaybeUninit<&T>`) needs no check.
- Assigning a constant containing a union, or passing one to a function,
  crashed: the operations take the address of a place. Give an assigned place
  the constant's known bytes' state (`SetMasked`), and pass a fully
  initialized constant without the argument buffer; passing one with
  uninitialized bytes is reported as unsupported.

`typed_swap_nonoverlapping` needs no change: it runs its fallback body,
`ptr::swap_nonoverlapping`, whose copies already move the state.

Signed-off-by: Felipe R. Monteiro <[email protected]>
Signed-off-by: Felipe R. Monteiro <[email protected]>
Tiramisu-Cake added a commit to Tiramisu-Cake/kani that referenced this pull request Nov 22, 2026
Tiramisu-Cake pushed a commit to Tiramisu-Cake/kani that referenced this pull request Nov 23, 2026
# Conflicts:
#	kani-compiler/src/kani_middle/transform/check_uninit/mod.rs
#	kani-compiler/src/kani_middle/transform/check_uninit/ptr_uninit/uninit_visitor.rs
A call to a closure passes its arguments as one tuple (Fn::call(&c, (u, x)), resolved to the closure), while the closure body receives them as separate parameters. The tuple was stored as argument 2, so with the union first the callee found an argument of another size (a false alarm), and with the union second it found no state for argument 3 and treated it as initialized, missing an uninitialized read. When the callee's parameters after the ordinary arguments are the tuple's fields, store each field that contains a union as its own argument. A callee that takes the tuple as one parameter, like a call_once shim, still gets the whole tuple.

Signed-off-by: Felipe R. Monteiro <[email protected]>
# Conflicts:
#	kani-compiler/src/kani_middle/transform/check_uninit/mod.rs
@Tiramisu-Cake

Copy link
Copy Markdown
Contributor

Two more false alarms with -Z uninit-checks on this PR's head (1c6e63b1f7, nightly-2026-11-23, CBMC 6.11.0). Both harnesses verify without the flag. With the flag, all their own assertions pass and all covers are satisfied, but Kani reports uninitialized reads inside core.

1. Iterating an array by value

#[kani::proof]
fn iter_by_value() {
    let mut iter: core::array::IntoIter<usize, 2> = IntoIterator::into_iter([0usize, 1]);
    let first = iter.next();
    assert!(first == Some(0));
    let second = iter.next();
    assert!(second == Some(1));
    let end = iter.next();
    assert!(end.is_none());
    kani::cover!(end.is_none(), "iter completed");
}

Two failed checks, both in std::ptr::read::<usize> at core/src/ptr/mod.rs:1763:9:

  • Reading from an uninitialized pointer of type *const usize
  • Reading from an uninitialized pointer of type usize

Reading the same values with assume_init_read from [MaybeUninit::new(0usize), MaybeUninit::new(1usize)] verifies with the flag. This case has no Rvalue::Repeat, so it looks separate from #5229.

2. select_unpredictable between two pointers to initialized values

use core::mem::MaybeUninit;

const LEFT: u64 = 17;
const RIGHT: u64 = 43;

#[inline(never)]
fn inputs(left: &u64, right: &u64) -> (bool, *const u64, *const u64) {
    let condition = kani::any::<bool>();
    kani::cover!(condition, "select true arm entered");
    kani::cover!(!condition, "select false arm entered");
    (condition, left, right)
}

#[inline(never)]
fn observe(condition: bool, left: *const u64, right: *const u64, selected: *const u64) {
    assert!(selected == if condition { left } else { right });
    assert!(unsafe { *selected } == if condition { LEFT } else { RIGHT });
    kani::cover!(condition, "select true arm returned");
    kani::cover!(!condition, "select false arm returned");
}

#[kani::proof]
fn select_pointer() {
    let (left, right) = (LEFT, RIGHT);
    let (condition, left_ptr, right_ptr) = inputs(&left, &right);
    let selected = core::hint::select_unpredictable(condition, left_ptr, right_ptr);
    observe(condition, left_ptr, right_ptr, selected);
}

#[kani::proof]
fn select_initialized() {
    let (left, right) = (LEFT, RIGHT);
    let (condition, left_ptr, right_ptr) = inputs(&left, &right);
    let plain = if condition { left_ptr } else { right_ptr };
    let selected = unsafe { MaybeUninit::new(plain).assume_init() };
    observe(condition, left_ptr, right_ptr, selected);
}

select_pointer has one failed check, in std::mem::transmute_neo::<MaybeUninit<*const u64>, *const u64> at core/src/mem/mod.rs:1279:14: Reading from an uninitialized pointer of type *const MaybeUninit<*const u64>. The read through the selected pointer in observe is checked and passes. select_initialized, which wraps the selected pointer in MaybeUninit and unwraps it directly, verifies with the flag.

On main at 5d80a641d, both harnesses fail earlier on unsupported-operation checks (the [MaybeUninit<usize>; 2] layout in into_iter, the raw pointer and union use in select_unpredictable), and their assertions are unreachable. These reports only become visible with the support added here.

Both options are fine with us: fixing this in this PR, or a separate issue after merge, whichever is easier for you. I can open the issue.

Arguments used: --harness <name> --exact --default-unwind 16 -Z uninit-checks --cbmc-args --object-bits 12.

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

[E] Unsupported Construct Add support to an unsupported construct 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 uninit-checks: arrays of MaybeUninit<T> with non-trivial T are unsupported

4 participants