Repository navigation
Add support for volatile_copy_memory, volatile_copy_nonoverlapping_memory and volatile_set_memory - #4672
Conversation
…mory and volatile_set_memory Implements three of the intrinsics still unchecked on tracking issue model-checking#1163. Why the existing placeholders could not simply be un-gated ---------------------------------------------------------- The two copy intrinsics already had arms, but behind `unstable_codegen!`: Intrinsic::VolatileCopyMemory => unstable_codegen!(codegen_intrinsic_copy!(Memmove)), Intrinsic::VolatileCopyNonOverlappingMemory => { unstable_codegen!(codegen_intrinsic_copy!(Memcpy)) } `unstable_codegen!` is declared `($($tt:tt)*)` and never expands its tokens -- it unconditionally emits a codegen_unimplemented_expr. Those bodies were therefore never type-checked, and they have since rotted: codegen_intrinsic_copy! no longer exists anywhere in kani-compiler. Removing the gate alone does not compile, so both arms are rewritten rather than un-gated. `volatile_set_memory` had no Intrinsic variant at all and fell through to the unsupported catch-all. Argument order -------------- The intrinsics take the destination first: volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize) volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize) whereas codegen_copy consumes source first (two successive fargs.remove(0), src then dst) and indexes farg_types[0]/farg_types[1] for the src and dst alignment assertions. Both fargs and farg_types are therefore swapped before delegating. Swapping only one silently applies each alignment check to the wrong pointer -- a defect no test using two equally-aligned buffers would catch. volatile_set_memory(dst, val, count) matches write_bytes(dst, val, count), so no swap is needed there. Soundness of reusing the non-volatile codegen --------------------------------------------- Volatility constrains what the optimizer may do -- it must not elide, duplicate or reorder the access. It is not a memory-safety property: the UB conditions for these three intrinsics are exactly those of copy, copy_nonoverlapping and write_bytes. Kani performs no optimization that volatility is meant to suppress, so there is nothing additional to model. This mirrors the existing treatment of volatile_load/volatile_store. Points-to analysis ------------------ points_to_analysis.rs matches exhaustively over Intrinsic with a terminal unimplemented!() wildcard; write_bytes is protected from it via is_identity_aliasing_intrinsic. Before this change volatile_set_memory reached that pass as Intrinsic::Unimplemented, which is explicitly handled as a no-op. Introducing the new variant would have routed it to the panicking wildcard, so it is listed alongside write_bytes in the same way. The two check_uninit visitors have non-panicking fallbacks and are unchanged. Tests ----- Layout follows model-checking#1347, which added volatile_load support. tests/kani/Intrinsics/Volatile/copy.rs both copy intrinsics move the expected bytes, including an overlapping case for volatile_copy_memory (memmove semantics) that distinguishes it from the non-overlapping variant tests/kani/Intrinsics/Volatile/set.rs volatile_set_memory fills the destination, full and partial tests/expected/intrinsics/volatile_copy/overlapping/ volatile_copy_nonoverlapping_memory on overlapping ranges fails, matching the existing copy-nonoverlapping test for the non-volatile intrinsic tests/expected/intrinsics/volatile_copy/unaligned/ a misaligned pointer fails the alignment check The unaligned pair is deliberately left out: unaligned_volatile_load's gated body is a plain dereference, which does not model the unaligned access itself, and unaligned_volatile_store has no codegen at all. Those need a separate decision about how unaligned accesses should be represented.
`docs/src/rust-feature-support/intrinsics.md` listed all three as `No`. They are now supported, so the table has to move. `Partial` rather than `Yes`, matching the neighbouring `volatile_load` and `volatile_store` rows and keeping the same Concurrency note. The memory-safety semantics are modelled exactly (they are those of the non-volatile counterparts), but the volatile guarantees themselves -- that the access is not elided or reordered, and really does touch memory -- are not, since Kani assumes sequential execution. Claiming `Yes` would overstate that and would disagree with how the two already-supported volatile intrinsics are documented.
…s comment
Two review findings on the previous commit.
1. The compiler matches on `Intrinsic` in three places -- codegen, the points-to
analysis, and the memory-initialization visitor -- and only the first two were
updated. `volatile_set_memory` therefore fell to the visitor's catch-all and
produced a spurious "Kani does not support reasoning about memory
initialization" failure under -Z uninit-checks, while the codegen comment
claimed it behaves exactly like `write_bytes`. It now shares that arm: same
argument shape (dst, val, count), same initialization effect.
2. The comment overclaimed. "The UB conditions are exactly those of the
non-volatile counterpart" is false as a generalisation: the volatile family's
docs additionally permit pointers outside any Rust allocation (the MMIO
carve-out on ptr::read_volatile), which the non-volatile ops do not. The
modelling is still sound, but for a different reason than the comment gave --
reusing codegen_copy/codegen_write_bytes checks AT LEAST the documented UB
conditions, so it is conservative rather than exact: a legal MMIO access can
be rejected by --pointer-check, but real UB is never missed. The comments now
say that, and anchor on what these intrinsics' own docs state ("consistent
with copy_nonoverlapping" / "consistent with write_bytes") rather than on a
blanket claim about volatility.
Also adds tests/expected/intrinsics/volatile_set/out-of-bounds, mirroring the
existing write_bytes test. The happy-path test alone did not pin that reusing
codegen_write_bytes actually carries its safety checks across.
|
Pushed two follow-up commits after a review pass, and corrected one claim in the description above. The comment about volatility overclaimed. It said the UB conditions are exactly those of the non-volatile counterparts. That is not right as a generalisation: the volatile family's docs additionally permit pointers outside any Rust allocation (the MMIO carve-out documented on
Also added Full regression run locally on CBMC 6.10.0: no failures introduced (the only failures are three pre-existing |
There was a problem hiding this comment.
Pull request overview
Adds Kani support for three previously-unchecked Rust volatile memory intrinsics by reusing the existing (non-volatile) copy/set codegen paths, extending internal analyses to understand the new intrinsic variant, and adding regression/expected-output tests to validate semantics and safety checks.
Changes:
- Implement
volatile_copy_memory/volatile_copy_nonoverlapping_memoryby delegating tocodegen_copywith correct(dst, src)argument/type swapping. - Add a new
Intrinsic::VolatileSetMemoryvariant and implement it viacodegen_write_bytes, plus update points-to and uninitialized-memory analyses. - Add new kani + expected tests for happy paths and key failures (overlap, unaligned, out-of-bounds), and update the intrinsics support documentation.
Reviewed changes
Copilot reviewed 13 out of 13 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| tests/kani/Intrinsics/Volatile/set.rs | New proof harnesses validating successful volatile_set_memory behavior. |
| tests/kani/Intrinsics/Volatile/copy.rs | New proof harnesses validating both volatile copy intrinsics, including an overlapping memmove case. |
| tests/expected/intrinsics/volatile_set/out-of-bounds/main.rs | Expected-failure test ensuring OOB volatile set is caught (mirrors write_bytes). |
| tests/expected/intrinsics/volatile_set/out-of-bounds/expected | Expected output for the volatile set OOB failure. |
| tests/expected/intrinsics/volatile_copy/unaligned/main.rs | Expected-failure test ensuring misaligned dst is caught and swap is correct. |
| tests/expected/intrinsics/volatile_copy/unaligned/expected | Expected output for the unaligned volatile copy failure. |
| tests/expected/intrinsics/volatile_copy/overlapping/main.rs | Expected-failure test ensuring nonoverlapping volatile copy rejects overlap. |
| tests/expected/intrinsics/volatile_copy/overlapping/expected | Expected output for the overlap failure. |
| kani-compiler/src/kani_middle/transform/check_uninit/ptr_uninit/uninit_visitor.rs | Treat VolatileSetMemory like WriteBytes for initialization tracking. |
| kani-compiler/src/kani_middle/points_to/points_to_analysis.rs | Mark VolatileSetMemory as identity-aliasing to avoid panicking wildcard handling. |
| kani-compiler/src/intrinsics.rs | Add VolatileSetMemory variant and map volatile_set_memory name/signature to it. |
| kani-compiler/src/codegen_cprover_gotoc/codegen/intrinsic.rs | Implement volatile copy intrinsics via codegen_copy (with swap) and volatile set via codegen_write_bytes. |
| docs/src/rust-feature-support/intrinsics.md | Update support status for the three intrinsics to “Partial”. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
All three `volatile_copy` tests formed their `dst` by casting a pointer derived from `arr.as_ptr()` (a shared borrow) to `*mut i32` and then wrote through it, which is undefined behavior in its own right. For the two `tests/expected` harnesses this weakened what they prove: each is meant to fail for exactly one reason -- the overlap precondition and the alignment precondition respectively -- and a second, unintended source of UB means the harness may fail for a reason nobody named. Both pointers are now derived from `arr.as_mut_ptr()`, leaving the intended precondition as the only thing violated. Checked with Miri on the non-volatile counterparts (`ptr::copy` / `ptr::copy_nonoverlapping`, whose aliasing and alignment requirements are the ones these intrinsics' docs defer to): before, the overlapping harness reported a SharedReadOnly write violation instead of the overlap it is named for; after, it reports `copy_nonoverlapping called on overlapping ranges`, the unaligned harness reports only the alignment violation, and the `tests/kani` overlap proof runs clean with its assertions intact.
|
Three test fixes from a review pass, all the same defect class. The For the two One of the three was not reported. The automated review found the instances in Also re-verified, since missing it caused two earlier defects here: all three places that match on Regression re-run locally on CBMC 6.10.0 (the version this tree's One correction to my earlier comment while I am here: it said "the only failures are three pre-existing |
|
One practical note for whoever reviews or lands this, from exercising the new codegen end-to-end. I ran the five now-supported intrinsics against real harnesses — the ones in That wall is the harness, not this PR's codegen. The harness was written as: let shift: usize = kani::any();
kani::assume(shift >= 1 && shift < N);
...
unsafe { volatile_copy_memory(dst_ptr, src_ptr, N - shift) };
for i in 0..(N - shift) {
assert_eq!(buf[i + shift], original[i]);
}A symbolic const SHIFT: usize = 3;
...
let i: usize = kani::any();
kani::assume(i < N - SHIFT);
assert_eq!(buf[i + SHIFT], original[i]);Same harness, same property, same build: no result in 40 minutes → 0.133 s. Worth flagging because the failure mode is misleading. This defect was invisible for months — Kani's "not currently supported" verdict fires before codegen, so the harness could never run far enough to blow up. Anyone who lands this PR and un-gates the obvious How this was measured, and its limits: on a build of |
|
The The emitted program is unchanged. benchcomp reports That matches the diff: the compiler-side changes are five hunks, each inside a match arm keyed on The same gate fires on unrelated PRs whose emitted programs are also unchanged. In the same week:
Both ratios are larger than the 1.5517× here. On this branch specifically, the job also failed on 2026-07-29, on a different benchmark ( The one thing that would settle it is a re-run: the failing ratio is I'm not proposing a code change, since I can't find a path from this diff to that benchmark — happy to be corrected if I've missed one. Whether the threshold itself is worth revisiting is entirely your call. |
|
Thanks for the contribution @ivmat! |
23ff373
|
thank you @feliperodri for checking the PR ! |
…re` (model-checking#4673) Completes the volatile intrinsic family on the tracking issue model-checking#1163, following model-checking#4672 (volatile copy/set), which has since landed. This branch is rebased onto `main` and now contains only its own work. With model-checking#4672 merged and these two arms implemented, `unstable_codegen!` has no remaining uses anywhere in `kani-compiler` and is removed — these volatile/unaligned entries were the last gated intrinsics in the codegen match. ## Modelling Neither intrinsic has an alignment requirement, so neither emits an alignment assertion — tolerating a misaligned pointer is the entire purpose of the `unaligned_*` variants. `unaligned_volatile_load` was already sketched behind the gate as a plain dereference; `unaligned_volatile_store` had no codegen and no `Intrinsic` variant at all, and is added mirroring `volatile_store` minus the alignment check, including the same zero-sized-type guard. That leaves two questions worth being explicit about, and the tests answer both rather than assume them. **Is a misaligned typed dereference modelled byte-precisely, or does it quietly assume alignment?** Each proof compares the accessed value against a byte-wise oracle at a deliberately misaligned offset, so an implementation that touched the aligned word instead would fail rather than silently pass. The oracle uses `u32::from_ne_bytes`, which keeps it byte-precise without baking in an endianness: reading a `u32` at byte offset 1 must equal the native-order interpretation of bytes 1..5, whereas an alignment-assuming read from offset 0 would give the interpretation of bytes 0..4 — different under either endianness. Both directions also have a **symbolic-offset** proof, so neither can be satisfied by constant folding, and the store proofs check that bytes outside the written range are untouched. **Is dereferenceability still checked, given this path builds the dereference directly rather than going through place codegen?** It is, by `--pointer-check`, and there is now a test that pins that down instead of asserting it in a comment. ## Tests - `tests/kani/Intrinsics/Volatile/unaligned.rs` — six proofs: byte-precise load and store, each at a constant and at a symbolic offset, plus two ZST stores — one through a valid pointer and one through a **dangling but aligned** pointer, `without_provenance_mut(align_of::<()>())`, which is the case the ZST guard actually exists for. - `tests/expected/intrinsics/unaligned_volatile/out_of_bounds/` — an expected-fail test for an out-of-bounds unaligned load and store. It accesses a `u32` at byte offset 1 of a 4-byte array, so the pointer arithmetic stays in bounds and it is the *access* that overruns the object; the failure is therefore attributable to the dereference rather than to the offset computation. The `expected` file pins that split for each harness separately — the offset safety check must report SUCCESS while `pointer_dereference` reports `dereference failure: pointer outside object bounds`. - `tests/kani/VolatileIntrinsics/core_intrinsics.rs` — this was marked `kani-verify-fail`, but that expectation existed only because `unaligned_volatile_store` (and `volatile_set_memory`) were unsupported. With both implemented the proof verifies, so the header is removed and it becomes a passing test. The two review-driven tests were fault-injected before being committed, in both directions. Deleting the ZST guard turns the dangling-ZST harness from 0 VCCs into 6, of which 5 fail with pointer dereference errors; restoring it returns the file to green. Running the out-of-bounds test with `--no-memory-safety-checks`, which drops CBMC's `--pointer-check`, turns both of its harnesses green and removes every `pointer_dereference` property — confirming that check is what catches them. ## One asymmetry worth pre-empting The ZST guard exists on the **store** paths only. `codegen_volatile_load` and this PR's `unaligned_volatile_load` both dereference unconditionally, so a zero-sized read through a dangling-but-aligned pointer — which is legal Rust — currently produces a spurious verification failure. I measured this: it fails identically on the already-merged `volatile_load`, with the guarded store passing on the same input, so it is pre-existing behaviour that the unaligned variant inherits rather than introduces. I have deliberately left it alone here rather than widen this PR into `codegen_volatile_load`, but I am happy to fix both in a follow-up, or here if you would prefer it. ## Note `tests/kani/VolatileIntrinsics/main_fixme.rs` is left untouched (it is skipped as a fixme test). Its `test_copy_volatile` names its arguments as though `volatile_copy_memory` were `(src, dst, count)`; the assertion it makes happens to hold under either argument order, so it neither catches nor is broken by the ordering. Worth a separate look if that suite is ever revived. By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.
… and arith_offset Addresses feliperodri's comment of 10 Nov: model-checking#649 (comment) - The five volatile/unaligned-volatile `*_model` wrappers now call the real intrinsics instead of their non-volatile equivalents. Kani supports them since model-checking/kani#4672 and rust-lang#4673. - compare_bytes: MAX_BYTES 8 -> 64, unwind 9 -> 65. - arith_offset: the harness now covers every base in [1, 2^52) and every offset whose result lands in [0, 2^52), instead of a base in [2^32, 2^45] and |offset| <= 2^20. The comment now names the real limit: CBMC's address encoding leaves 52 bits with --object-bits 12. All 146 harnesses of this PR pass with the PR's Kani pin (cd355b0b) and on the PR merged with current main (Kani c5e65fd). As a negative check, making each of the five intrinsic calls touch one element past its range makes all 15 affected harnesses fail.
) Towards model-checking#16. Solves [Challenge 2: Verify the memory safety of core intrinsics using raw pointers](https://model-checking.github.io/verify-rust-std/challenges/0002-intrinsics-memory.html): safety contracts and Kani harnesses for the raw-pointer intrinsics (Part 1), proofs that the std library's uses of them are safe (Part 2), and contracts on the raw-pointer functions exposing them (Part 3). All 146 harnesses added by this PR pass in a single `kani verify-std` invocation at the pinned Kani commit. ## Changes | File | Change | |---|---| | `intrinsics/mod.rs` | Contracts + `proof_for_contract` harnesses for 20 intrinsics, via thin wrappers (Kani cannot attach contracts to body-less `#[rustc_intrinsic]`s, model-checking/kani#3325; same pattern as the in-tree `transmute_unchecked_wrapper`); also fixes the pre-existing `check_copy_untyped` spec helper, which compared `src[0]`'s initialization state against `dst[elem]`'s instead of `src[elem]`'s | | `mem/mod.rs` | Usage proofs for `swap` and `align_of_val`; contract + harnesses for `align_of_val_raw` (Part 3) | | `mem/maybe_uninit.rs` | Usage proof for `zeroed` (reaches `write_bytes`), byte-level `ensures` | | `fmt/num.rs` | Contract + harnesses for `u64::_fmt`, the successor of the challenge-listed `parse_u64_into` (Part 2) | | `ptr/mod.rs` | Contracts + harnesses for `ptr::swap` and `ptr::write_bytes` (Part 3) | | `slice/mod.rs` | Contract + harnesses for `copy_from_slice` (Parts 2/3) | ## Part 1: the intrinsics All 21 listed intrinsics are contracted and verified: 20 by this PR, and the 21st, `typed_swap`, already carries a verified in-tree contract with passing harnesses (added by model-checking#37, before this challenge was tackled), so re-verifying it here would only duplicate upstream code. This PR still exercises that existing contract as part of the `mem::swap` usage proof (Part 2). One finding for the committee: `parse_u64_into` no longer exists anywhere in the tree (see Part 2). The five volatile intrinsics (`volatile_copy_memory`, `volatile_copy_nonoverlapping_memory`, `volatile_set_memory`, `unaligned_volatile_load`, `unaligned_volatile_store`) are verified directly: as for `volatile_load`/`volatile_store`, each contract sits on a thin `*_model` wrapper that calls the real intrinsic, which Kani supports since model-checking/kani#4672 and model-checking/kani#4673. Contracts state exactly the documented `# Safety` conditions. Where the documented condition is per-case, so is the contract: `size_of_val`/`align_of_val` get a `Sized` wrapper with no precondition (documented "always safe", proven with dangling pointers) and a slice wrapper requiring only that the total size fits `isize`. All remaining intrinsics are Kani-modeled; each harness pins the model with a concrete assertion (e.g. `vtable_size` returns exactly `size_of::<T>()`, store harnesses read the value back). | Intrinsics | Approach | |---|---| | `copy`, `copy_nonoverlapping`, `write_bytes`, volatile/unaligned family | Readable/writable-range + alignment + (where documented) non-overlap `requires`; untyped-copy `ensures`; byte-granular pointer offsets so misaligned inputs are generated, not avoided | | `vtable_size`, `vtable_align`, `size_of_val`, `align_of_val` | Metadata-only models; generic `ensures` (size fits `isize`, alignment is a power of two); per-type fidelity asserts in harnesses; the layout queries cover all three documented cases (`Sized`, slice tail, trait-object tail via real compiler-produced vtables) | | `ptr_offset_from`, `ptr_offset_from_unsigned`, `arith_offset` | Same-allocation / ordering `requires`; `arith_offset` checked for every base in [1, 2^52) and every offset whose result lands in [0, 2^52), which is every address CBMC can represent with CI's `--object-bits 12` | | `compare_bytes` | Whole-range readability `requires` (docs stress chunked reads); checked instances bounded to 64 bytes (`unwind(65)`), because Kani lowers the intrinsic to CBMC's built-in `memcmp` loop, which cannot take a loop invariant; the bound lives in the harness, not the contract | | `read_via_copy`, `write_via_move` | Read/write validity; `write_via_move` ensures dereferenceability post-state (the moved value cannot be re-read for generic `T`) | For the trait-object case, Kani has no "is a vtable" predicate, so (as for `vtable_size`/`vtable_align`) dereferenceability of the three metadata words is the stated approximation of the documented condition; the harnesses supply real compiler-produced vtables, so the precondition is discharged non-vacuously. Initialization: `ub_checks::can_dereference` checks that bytes are initialized only when Kani runs with `-Z uninit-checks`, and CI doesn't pass that flag. So in CI, the `requires` and `ensures` clauses that use it don't rule out uninitialized reads, and `check_copy_untyped` doesn't compare initialization state. In @feliperodri's run with the flag, 91 of the 394 `intrinsics::verify` harnesses stop on constructs Kani's uninit checking doesn't support yet (model-checking/kani#5151, model-checking/kani#5166), and none reports an uninitialized read. How solutions should treat this is open in model-checking#733. ## Part 2: std usage sites | Usage site | Proof | |---|---| | `mem::swap` | `proof_for_contract(swap)` + `stub_verified(typed_swap_nonoverlapping)`, so the intrinsic's `requires` become explicit call-site obligations | | `<[T]>::copy_from_slice` | Contract on the function; symbolic lengths 0..=32 across 5 element types, element equality asserted per type | | `mem::align_of_val` | 8 harnesses (Sized + slice tails); the precondition holds structurally for `&T` | | `MaybeUninit::zeroed` | 10 harnesses: the reached `write_bytes` is safe and all backing bytes are 0 | | `fmt::parse_u64_into` | Does not exist in the tree (finding above); its successor `u64::_fmt` is contracted and verified instead — the documented buffer-size safety condition as `requires`, digits-only/length `ensures`, plus a bounded value-fidelity harness. The contract lives on a `#[cfg(kani)]` wrapper because `_fmt` is macro-generated for every integer type; annotating it directly would touch them all | ## Part 3: raw-pointer functions Contracts + harnesses for `ptr::swap` (overlap-permitted path exercised), `ptr::write_bytes`, and `mem::align_of_val_raw` (including dangling-pointer harnesses for the documented always-safe `Sized` case). `copy_from_slice` doubles as its own Part 3 item. Wherever a harness restricts inputs with `kani::assume`, a `kani::cover` check confirms some input satisfies the restriction, so no proof passes vacuously; value-level properties that cannot be generic `ensures` clauses (no `PartialEq` bound) are asserted per concrete type. ## Relation to other work on this challenge model-checking#37 (merged) contributed the `typed_swap` contract this PR builds on and exercises via the `mem::swap` usage proof. model-checking#618 is an open partial solution covering 15 Part 1 intrinsics. This PR was developed independently and additionally covers the five volatile intrinsics, Part 2, and Part 3. Its review thread shaped two of this PR's contracts (per-case preconditions instead of a blanket `can_dereference`), and its author's now-merged Kani fixes (model-checking/kani#4672, model-checking/kani#4673) are what let this PR verify the five volatile intrinsics directly. model-checking#643 is another open full-table attempt, developed independently on the same wrapper pattern; this PR adopts its correct fix to the pre-existing `check_copy_untyped` spec helper (`src_data` was never offset by the chosen element), with all affected harnesses re-verified. Beyond that, this PR goes further on three fronts: - **Adversarial inputs.** Copy-family harnesses here generate byte-granular pointer offsets across several element types, so misaligned and overlapping inputs are produced by the solver rather than avoided; model-checking#643's are `u8`-only (alignment trivially 1) with a single fixed overlap shift, so its alignment precondition is never non-trivially exercised. - **Part 2 depth.** Both PRs touch all five usage sites; this PR proves each more deeply: 10 byte-level `zeroed` harnesses (model-checking#643 has 2, integer-only), `copy_from_slice` at symbolic lengths 0..=32 across 5 element types (model-checking#643: one `u8` harness at fixed length 4), and a `mem::swap` proof that `stub_verified`s the intrinsic contract so its `requires` become explicit call-site obligations (model-checking#643 asserts value exchange only). - **Part 3 coverage.** This PR contracts and verifies the exposing functions — `ptr::swap` (overlap-permitted path), `ptr::write_bytes`, `mem::align_of_val_raw` — as the challenge asks; in model-checking#643 this part is essentially absent (plain fixed-size harnesses without contracts, `align_of_val_raw` not covered). By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.
Implements three of the intrinsics still unchecked on the tracking issue #1163:
volatile_copy_memory,volatile_copy_nonoverlapping_memoryandvolatile_set_memory.Why the existing placeholders could not simply be un-gated
The two copy intrinsics already had arms, but behind
unstable_codegen!:unstable_codegen!is declared as($($tt:tt)*)and never expands its tokens — it always emits acodegen_unimplemented_expr. The bodies above were therefore never type-checked, and they have sincerotted:
codegen_intrinsic_copy!no longer exists anywhere inkani-compiler. Removing the gate alonedoes not compile, so both arms are rewritten rather than un-gated.
volatile_set_memoryhad noIntrinsicvariant at all and fell through to the unsupported catch-all.Argument order
The Rust intrinsics take the destination first:
whereas
codegen_copyconsumes source first (let src = fargs.remove(0); let dst = fargs.remove(0);)and indexes
farg_types[0]/farg_types[1]for thesrcanddstalignment checks respectively.Both
fargsandfarg_typesare therefore swapped before delegating. Without swapping both, the twoalignment assertions are silently applied to the wrong pointers — a discrepancy that a test using two
equally-aligned buffers would not detect.
volatile_set_memory(dst, val, count)matcheswrite_bytes(dst, val, count), so no swap is needed there.Soundness of reusing the non-volatile codegen
Volatility constrains what the optimizer may do — it must not elide, duplicate or reorder the access.
It is not a memory-safety property: the UB conditions for these three intrinsics are exactly those of
copy,copy_nonoverlappingandwrite_bytes. Kani's codegen performs no optimization that volatilityis meant to suppress, so there is nothing additional to model. This mirrors the existing treatment of
volatile_load/volatile_store, which already delegate to their non-volatile counterparts.Points-to analysis
Adding the
VolatileSetMemoryvariant required one further line.points_to_analysis.rsmatchesexhaustively over
Intrinsicwith a finalunimplemented!()wildcard;WriteBytesis protected from itby being listed in
is_identity_aliasing_intrinsic. Before this changevolatile_set_memoryreached theanalysis as
Intrinsic::Unimplemented { .. }, which is explicitly handled as a no-op. Introducing the newvariant would have routed it to the panicking wildcard instead, so it is listed alongside
WriteBytesinthe same way.
The other two visitors that match on
Intrinsic(
check_uninit/ptr_uninit/uninit_visitor.rs,check_uninit/delayed_ub/initial_target_visitor.rs) havenon-panicking fallbacks, so behaviour there is unchanged.
Tests
tests/kani/Intrinsics/Volatile/copy.rs— both copy intrinsics move the expected bytes, including anoverlapping case for
volatile_copy_memory(memmove semantics) to distinguish it from thenon-overlapping variant.
tests/kani/Intrinsics/Volatile/set.rs—volatile_set_memoryfills the destination, full and partial.tests/expected/intrinsics/volatile_copy/overlapping/—volatile_copy_nonoverlapping_memoryonoverlapping ranges fails, matching the existing
tests/expected/intrinsics/copy-nonoverlapping/copy-overlapping/test for the non-volatile intrinsic.tests/expected/intrinsics/volatile_copy/unaligned/— a misaligned pointer fails the alignment check.Test layout follows #1347, which added
volatile_loadsupport.Related
Towards #1163. The remaining unchecked volatile entries —
unaligned_volatile_loadandunaligned_volatile_store— are deliberately left out of this PR: the gated body forunaligned_volatile_loadis a plain dereference, which does not model the unaligned access itself, sothose two need a separate decision about how unaligned accesses should be represented.
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0
and MIT licenses.