Skip to content

Commit a43ef3d

Browse files
Challenge 2: memory safety of raw-pointer intrinsics (#649)
Towards #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 #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 #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 #37 (merged) contributed the `typed_swap` contract this PR builds on and exercises via the `mem::swap` usage proof. #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. #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; #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 (#643 has 2, integer-only), `copy_from_slice` at symbolic lengths 0..=32 across 5 element types (#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 (#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 #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.
1 parent 6079edc commit a43ef3d

6 files changed

Lines changed: 1486 additions & 37 deletions

File tree

‎library/core/src/fmt/num.rs‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -926,3 +926,79 @@ fn div_rem_1e16(n: u128) -> (u128, u64) {
926926
let rem = n - quot * D;
927927
(quot, rem as u64)
928928
}
929+
930+
#[cfg(kani)]
931+
#[unstable(feature = "kani", issue = "none")]
932+
mod verify {
933+
use safety::{ensures, requires};
934+
935+
use super::*;
936+
use crate::kani;
937+
938+
// ---------------------------------------------------------------------
939+
// `fmt::num::parse_u64_into` (the challenge's listed usage site) was
940+
// removed when decimal formatting was rewritten; `u64::_fmt` is its
941+
// successor and fills the tail of a `MaybeUninit<u8>` buffer with the
942+
// ASCII digits of `self` exactly as `parse_u64_into` did. Its documented
943+
// safety condition ("`buf` will always be big enough to contain all
944+
// digits") is stated as `requires` on this wrapper: `_fmt` is generated
945+
// by `impl_Display!` for every integer type, so annotating it directly
946+
// would touch the runtime definition of all of them (the approach #643
947+
// takes); the wrapper keeps the annotation surface at zero.
948+
// ---------------------------------------------------------------------
949+
950+
/// Digits of `u64::MAX` (= 20); any `u64` fits in this many bytes.
951+
const U64_MAX_DEC_N: usize = u64::MAX.ilog10() as usize + 1;
952+
953+
#[cfg(not(feature = "optimize_for_size"))]
954+
#[requires(buf.len() >= U64_MAX_DEC_N)]
955+
#[ensures(|result: &&str| !result.is_empty() && result.len() <= U64_MAX_DEC_N)]
956+
#[ensures(|result: &&str| result.as_bytes().iter().all(|b| b.is_ascii_digit()))]
957+
#[kani::modifies(crate::ptr::slice_from_raw_parts_mut(buf.as_mut_ptr(), buf.len()))]
958+
#[allow(dead_code)]
959+
fn u64_fmt_wrapper<'a>(n: u64, buf: &'a mut [MaybeUninit<u8>]) -> &'a str {
960+
// SAFETY: guaranteed by the precondition (`buf` holds any `u64`'s digits).
961+
unsafe { n._fmt(buf) }
962+
}
963+
964+
// Verifies the `ensures` plus the UB checks along `_fmt_inner`'s
965+
// buffer-filling walk and the final `slice_buffer_to_str` cast
966+
// (`get_unchecked`, `assume_init_ref`, `from_utf8_unchecked`).
967+
// Unwind: the digit loop runs at most 5 times (4 digits each), the
968+
// byte-level `ensures` scan up to `U64_MAX_DEC_N` times.
969+
#[cfg(not(feature = "optimize_for_size"))]
970+
#[kani::proof_for_contract(u64_fmt_wrapper)]
971+
#[kani::unwind(21)]
972+
fn check_u64_fmt() {
973+
let n: u64 = kani::any();
974+
let mut buf = [MaybeUninit::<u8>::uninit(); U64_MAX_DEC_N];
975+
let s = u64_fmt_wrapper(n, &mut buf);
976+
kani::cover(s.len() == 1, "single digit");
977+
kani::cover(s.len() > 1, "multiple digits");
978+
}
979+
980+
// Value-level fidelity on a bounded window (full 20-digit decimal
981+
// equality for arbitrary `u64` does not converge): below 100 the result
982+
// is exactly the one- or two-digit decimal of `n`, pinning the lookup
983+
// table path against, e.g., a swapped-pair mutant.
984+
#[cfg(not(feature = "optimize_for_size"))]
985+
#[kani::proof]
986+
#[kani::unwind(21)]
987+
fn check_u64_fmt_small_values() {
988+
let n: u64 = kani::any();
989+
kani::assume(n < 100);
990+
let mut buf = [MaybeUninit::<u8>::uninit(); U64_MAX_DEC_N];
991+
let s = unsafe { n._fmt(&mut buf) };
992+
let bytes = s.as_bytes();
993+
if n < 10 {
994+
assert_eq!(bytes.len(), 1);
995+
assert_eq!(bytes[0], b'0' + n as u8);
996+
} else {
997+
assert_eq!(bytes.len(), 2);
998+
assert_eq!(bytes[0], b'0' + (n / 10) as u8);
999+
assert_eq!(bytes[1], b'0' + (n % 10) as u8);
1000+
}
1001+
kani::cover(n < 10, "one digit");
1002+
kani::cover(n >= 10, "two digits");
1003+
}
1004+
}

0 commit comments

Comments
 (0)